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 ssh2_channel_check_close(struct ssh_channel *c);
370 static void ssh_channel_destroy(struct ssh_channel *c);
371 static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize);
372 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin);
375 * Buffer management constants. There are several of these for
376 * various different purposes:
378 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
379 * on a local data stream before we throttle the whole SSH
380 * connection (in SSH-1 only). Throttling the whole connection is
381 * pretty drastic so we set this high in the hope it won't
384 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
385 * on the SSH connection itself before we defensively throttle
386 * _all_ local data streams. This is pretty drastic too (though
387 * thankfully unlikely in SSH-2 since the window mechanism should
388 * ensure that the server never has any need to throttle its end
389 * of the connection), so we set this high as well.
391 * - OUR_V2_WINSIZE is the default window size we present on SSH-2
394 * - OUR_V2_BIGWIN is the window size we advertise for the only
395 * channel in a simple connection. It must be <= INT_MAX.
397 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
398 * to the remote side. This actually has nothing to do with the
399 * size of the _packet_, but is instead a limit on the amount
400 * of data we're willing to receive in a single SSH2 channel
403 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
404 * _packet_ we're prepared to cope with. It must be a multiple
405 * of the cipher block size, and must be at least 35000.
408 #define SSH1_BUFFER_LIMIT 32768
409 #define SSH_MAX_BACKLOG 32768
410 #define OUR_V2_WINSIZE 16384
411 #define OUR_V2_BIGWIN 0x7fffffff
412 #define OUR_V2_MAXPKT 0x4000UL
413 #define OUR_V2_PACKETLIMIT 0x9000UL
415 struct ssh_signkey_with_user_pref_id {
416 const struct ssh_signkey *alg;
419 const static struct ssh_signkey_with_user_pref_id hostkey_algs[] = {
420 { &ssh_ecdsa_ed25519, HK_ED25519 },
421 { &ssh_ecdsa_nistp256, HK_ECDSA },
422 { &ssh_ecdsa_nistp384, HK_ECDSA },
423 { &ssh_ecdsa_nistp521, HK_ECDSA },
424 { &ssh_dss, HK_DSA },
425 { &ssh_rsa, HK_RSA },
428 const static struct ssh_mac *const macs[] = {
429 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
431 const static struct ssh_mac *const buggymacs[] = {
432 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
435 static void *ssh_comp_none_init(void)
439 static void ssh_comp_none_cleanup(void *handle)
442 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
443 unsigned char **outblock, int *outlen)
447 static int ssh_comp_none_disable(void *handle)
451 const static struct ssh_compress ssh_comp_none = {
453 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
454 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
455 ssh_comp_none_disable, NULL
457 extern const struct ssh_compress ssh_zlib;
458 const static struct ssh_compress *const compressions[] = {
459 &ssh_zlib, &ssh_comp_none
462 enum { /* channel types */
468 * CHAN_SHARING indicates a channel which is tracked here on
469 * behalf of a connection-sharing downstream. We do almost nothing
470 * with these channels ourselves: all messages relating to them
471 * get thrown straight to sshshare.c and passed on almost
472 * unmodified to downstream.
476 * CHAN_ZOMBIE is used to indicate a channel for which we've
477 * already destroyed the local data source: for instance, if a
478 * forwarded port experiences a socket error on the local side, we
479 * immediately destroy its local socket and turn the SSH channel
485 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
486 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
487 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
490 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
493 struct outstanding_channel_request {
494 cchandler_fn_t handler;
496 struct outstanding_channel_request *next;
500 * 2-3-4 tree storing channels.
503 Ssh ssh; /* pointer back to main context */
504 unsigned remoteid, localid;
506 /* True if we opened this channel but server hasn't confirmed. */
509 * In SSH-1, this value contains four bits:
511 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
512 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
513 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
514 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
516 * A channel is completely finished with when all four bits are set.
518 * In SSH-2, the four bits mean:
520 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
521 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
522 * 4 We have received SSH2_MSG_CHANNEL_EOF.
523 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
525 * A channel is completely finished with when we have both sent
526 * and received CLOSE.
528 * The symbolic constants below use the SSH-2 terminology, which
529 * is a bit confusing in SSH-1, but we have to use _something_.
531 #define CLOSES_SENT_EOF 1
532 #define CLOSES_SENT_CLOSE 2
533 #define CLOSES_RCVD_EOF 4
534 #define CLOSES_RCVD_CLOSE 8
538 * This flag indicates that an EOF is pending on the outgoing side
539 * of the channel: that is, wherever we're getting the data for
540 * this channel has sent us some data followed by EOF. We can't
541 * actually send the EOF until we've finished sending the data, so
542 * we set this flag instead to remind us to do so once our buffer
548 * True if this channel is causing the underlying connection to be
553 struct ssh2_data_channel {
555 unsigned remwindow, remmaxpkt;
556 /* locwindow is signed so we can cope with excess data. */
557 int locwindow, locmaxwin;
559 * remlocwin is the amount of local window that we think
560 * the remote end had available to it after it sent the
561 * last data packet or window adjust ack.
565 * These store the list of channel requests that haven't
568 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
569 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
573 struct ssh_agent_channel {
574 unsigned char *message;
575 unsigned char msglen[4];
576 unsigned lensofar, totallen;
577 int outstanding_requests;
579 struct ssh_x11_channel {
580 struct X11Connection *xconn;
583 struct ssh_pfd_channel {
584 struct PortForwarding *pf;
586 struct ssh_sharing_channel {
593 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
594 * use this structure in different ways, reflecting SSH-2's
595 * altogether saner approach to port forwarding.
597 * In SSH-1, you arrange a remote forwarding by sending the server
598 * the remote port number, and the local destination host:port.
599 * When a connection comes in, the server sends you back that
600 * host:port pair, and you connect to it. This is a ready-made
601 * security hole if you're not on the ball: a malicious server
602 * could send you back _any_ host:port pair, so if you trustingly
603 * connect to the address it gives you then you've just opened the
604 * entire inside of your corporate network just by connecting
605 * through it to a dodgy SSH server. Hence, we must store a list of
606 * host:port pairs we _are_ trying to forward to, and reject a
607 * connection request from the server if it's not in the list.
609 * In SSH-2, each side of the connection minds its own business and
610 * doesn't send unnecessary information to the other. You arrange a
611 * remote forwarding by sending the server just the remote port
612 * number. When a connection comes in, the server tells you which
613 * of its ports was connected to; and _you_ have to remember what
614 * local host:port pair went with that port number.
616 * Hence, in SSH-1 this structure is indexed by destination
617 * host:port pair, whereas in SSH-2 it is indexed by source port.
619 struct ssh_portfwd; /* forward declaration */
621 struct ssh_rportfwd {
622 unsigned sport, dport;
626 struct ssh_portfwd *pfrec;
629 static void free_rportfwd(struct ssh_rportfwd *pf)
632 sfree(pf->sportdesc);
640 * Separately to the rportfwd tree (which is for looking up port
641 * open requests from the server), a tree of _these_ structures is
642 * used to keep track of all the currently open port forwardings,
643 * so that we can reconfigure in mid-session if the user requests
647 enum { DESTROY, KEEP, CREATE } status;
649 unsigned sport, dport;
652 struct ssh_rportfwd *remote;
654 struct PortListener *local;
656 #define free_portfwd(pf) ( \
657 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
658 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
661 long length; /* length of packet: see below */
662 long forcepad; /* SSH-2: force padding to at least this length */
663 int type; /* only used for incoming packets */
664 unsigned long sequence; /* SSH-2 incoming sequence number */
665 unsigned char *data; /* allocated storage */
666 unsigned char *body; /* offset of payload within `data' */
667 long savedpos; /* dual-purpose saved packet position: see below */
668 long maxlen; /* amount of storage allocated for `data' */
669 long encrypted_len; /* for SSH-2 total-size counting */
672 * A note on the 'length' and 'savedpos' fields above.
674 * Incoming packets are set up so that pkt->length is measured
675 * relative to pkt->body, which itself points to a few bytes after
676 * pkt->data (skipping some uninteresting header fields including
677 * the packet type code). The ssh_pkt_get* functions all expect
678 * this setup, and they also use pkt->savedpos to indicate how far
679 * through the packet being decoded they've got - and that, too,
680 * is an offset from pkt->body rather than pkt->data.
682 * During construction of an outgoing packet, however, pkt->length
683 * is measured relative to the base pointer pkt->data, and
684 * pkt->body is not really used for anything until the packet is
685 * ready for sending. In this mode, pkt->savedpos is reused as a
686 * temporary variable by the addstring functions, which write out
687 * a string length field and then keep going back and updating it
688 * as more data is appended to the subsequent string data field;
689 * pkt->savedpos stores the offset (again relative to pkt->data)
690 * of the start of the string data field.
693 /* Extra metadata used in SSH packet logging mode, allowing us to
694 * log in the packet header line that the packet came from a
695 * connection-sharing downstream and what if anything unusual was
696 * done to it. The additional_log_text field is expected to be a
697 * static string - it will not be freed. */
698 unsigned downstream_id;
699 const char *additional_log_text;
702 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
703 struct Packet *pktin);
704 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
705 struct Packet *pktin);
706 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
707 struct Packet *pktin);
708 static void ssh1_protocol_setup(Ssh ssh);
709 static void ssh2_protocol_setup(Ssh ssh);
710 static void ssh2_bare_connection_protocol_setup(Ssh ssh);
711 static void ssh_size(void *handle, int width, int height);
712 static void ssh_special(void *handle, Telnet_Special);
713 static int ssh2_try_send(struct ssh_channel *c);
714 static int ssh_send_channel_data(struct ssh_channel *c,
715 const char *buf, int len);
716 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
717 static void ssh2_set_window(struct ssh_channel *c, int newwin);
718 static int ssh_sendbuffer(void *handle);
719 static int ssh_do_close(Ssh ssh, int notify_exit);
720 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
721 static int ssh2_pkt_getbool(struct Packet *pkt);
722 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
723 static void ssh2_timer(void *ctx, unsigned long now);
724 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
725 struct Packet *pktin);
726 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
728 struct rdpkt1_state_tag {
729 long len, pad, biglen, to_read;
730 unsigned long realcrc, gotcrc;
734 struct Packet *pktin;
737 struct rdpkt2_state_tag {
738 long len, pad, payload, packetlen, maclen;
741 unsigned long incoming_sequence;
742 struct Packet *pktin;
745 struct rdpkt2_bare_state_tag {
749 unsigned long incoming_sequence;
750 struct Packet *pktin;
753 struct queued_handler;
754 struct queued_handler {
756 chandler_fn_t handler;
758 struct queued_handler *next;
762 const struct plug_function_table *fn;
763 /* the above field _must_ be first in the structure */
773 unsigned char session_key[32];
775 int v1_remote_protoflags;
776 int v1_local_protoflags;
777 int agentfwd_enabled;
780 const struct ssh_cipher *cipher;
783 const struct ssh2_cipher *cscipher, *sccipher;
784 void *cs_cipher_ctx, *sc_cipher_ctx;
785 const struct ssh_mac *csmac, *scmac;
786 int csmac_etm, scmac_etm;
787 void *cs_mac_ctx, *sc_mac_ctx;
788 const struct ssh_compress *cscomp, *sccomp;
789 void *cs_comp_ctx, *sc_comp_ctx;
790 const struct ssh_kex *kex;
791 const struct ssh_signkey *hostkey;
792 char *hostkey_str; /* string representation, for easy checking in rekeys */
793 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
794 int v2_session_id_len;
798 int attempting_connshare;
804 int echoing, editing;
809 int ospeed, ispeed; /* temporaries */
810 int term_width, term_height;
812 tree234 *channels; /* indexed by local id */
813 struct ssh_channel *mainchan; /* primary session channel */
814 int ncmode; /* is primary channel direct-tcpip? */
819 tree234 *rportfwds, *portfwds;
823 SSH_STATE_BEFORE_SIZE,
829 int size_needed, eof_needed;
830 int sent_console_eof;
831 int got_pty; /* affects EOF behaviour on main channel */
833 struct Packet **queue;
834 int queuelen, queuesize;
836 unsigned char *deferred_send_data;
837 int deferred_len, deferred_size;
840 * Gross hack: pscp will try to start SFTP but fall back to
841 * scp1 if that fails. This variable is the means by which
842 * scp.c can reach into the SSH code and find out which one it
847 bufchain banner; /* accumulates banners during do_ssh2_authconn */
852 struct X11Display *x11disp;
853 struct X11FakeAuth *x11auth;
854 tree234 *x11authtree;
857 int conn_throttle_count;
860 int v1_stdout_throttling;
861 unsigned long v2_outgoing_sequence;
863 int ssh1_rdpkt_crstate;
864 int ssh2_rdpkt_crstate;
865 int ssh2_bare_rdpkt_crstate;
866 int ssh_gotdata_crstate;
867 int do_ssh1_connection_crstate;
869 void *do_ssh_init_state;
870 void *do_ssh1_login_state;
871 void *do_ssh2_transport_state;
872 void *do_ssh2_authconn_state;
873 void *do_ssh_connection_init_state;
875 struct rdpkt1_state_tag rdpkt1_state;
876 struct rdpkt2_state_tag rdpkt2_state;
877 struct rdpkt2_bare_state_tag rdpkt2_bare_state;
879 /* SSH-1 and SSH-2 use this for different things, but both use it */
880 int protocol_initial_phase_done;
882 void (*protocol) (Ssh ssh, const void *vin, int inlen,
884 struct Packet *(*s_rdpkt) (Ssh ssh, const unsigned char **data,
886 int (*do_ssh_init)(Ssh ssh, unsigned char c);
889 * We maintain our own copy of a Conf structure here. That way,
890 * when we're passed a new one for reconfiguration, we can check
891 * the differences and potentially reconfigure port forwardings
892 * etc in mid-session.
897 * Values cached out of conf so as to avoid the tree234 lookup
898 * cost every time they're used.
903 * Dynamically allocated username string created during SSH
904 * login. Stored in here rather than in the coroutine state so
905 * that it'll be reliably freed if we shut down the SSH session
906 * at some unexpected moment.
911 * Used to transfer data back from async callbacks.
913 void *agent_response;
914 int agent_response_len;
918 * The SSH connection can be set as `frozen', meaning we are
919 * not currently accepting incoming data from the network. This
920 * is slightly more serious than setting the _socket_ as
921 * frozen, because we may already have had data passed to us
922 * from the network which we need to delay processing until
923 * after the freeze is lifted, so we also need a bufchain to
927 bufchain queued_incoming_data;
930 * Dispatch table for packet types that we may have to deal
933 handler_fn_t packet_dispatch[256];
936 * Queues of one-off handler functions for success/failure
937 * indications from a request.
939 struct queued_handler *qhead, *qtail;
940 handler_fn_t q_saved_handler1, q_saved_handler2;
943 * This module deals with sending keepalives.
948 * Track incoming and outgoing data sizes and time, for
951 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
952 unsigned long max_data_size;
954 unsigned long next_rekey, last_rekey;
955 const char *deferred_rekey_reason;
958 * Fully qualified host name, which we need if doing GSSAPI.
964 * GSSAPI libraries for this session.
966 struct ssh_gss_liblist *gsslibs;
970 * The last list returned from get_specials.
972 struct telnet_special *specials;
975 * List of host key algorithms for which we _don't_ have a stored
976 * host key. These are indices into the main hostkey_algs[] array
978 int uncert_hostkeys[lenof(hostkey_algs)];
979 int n_uncert_hostkeys;
982 * Flag indicating that the current rekey is intended to finish
983 * with a newly cross-certified host key.
985 int cross_certifying;
988 static const char *ssh_pkt_type(Ssh ssh, int type)
990 if (ssh->version == 1)
991 return ssh1_pkt_type(type);
993 return ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, type);
996 #define logevent(s) logevent(ssh->frontend, s)
998 /* logevent, only printf-formatted. */
999 static void logeventf(Ssh ssh, const char *fmt, ...)
1005 buf = dupvprintf(fmt, ap);
1011 static void bomb_out(Ssh ssh, char *text)
1013 ssh_do_close(ssh, FALSE);
1015 connection_fatal(ssh->frontend, "%s", text);
1019 #define bombout(msg) bomb_out(ssh, dupprintf msg)
1021 /* Helper function for common bits of parsing ttymodes. */
1022 static void parse_ttymodes(Ssh ssh,
1023 void (*do_mode)(void *data,
1024 const struct ssh_ttymode *mode,
1029 const struct ssh_ttymode *mode;
1031 char default_val[2];
1033 strcpy(default_val, "A");
1035 for (i = 0; i < lenof(ssh_ttymodes); i++) {
1036 mode = ssh_ttymodes + i;
1037 val = conf_get_str_str_opt(ssh->conf, CONF_ttymodes, mode->mode);
1042 * val[0] is either 'V', indicating that an explicit value
1043 * follows it, or 'A' indicating that we should pass the
1044 * value through from the local environment via get_ttymode.
1046 if (val[0] == 'A') {
1047 val = get_ttymode(ssh->frontend, mode->mode);
1049 do_mode(data, mode, val);
1053 do_mode(data, mode, val + 1); /* skip the 'V' */
1057 static int ssh_channelcmp(void *av, void *bv)
1059 struct ssh_channel *a = (struct ssh_channel *) av;
1060 struct ssh_channel *b = (struct ssh_channel *) bv;
1061 if (a->localid < b->localid)
1063 if (a->localid > b->localid)
1067 static int ssh_channelfind(void *av, void *bv)
1069 unsigned *a = (unsigned *) av;
1070 struct ssh_channel *b = (struct ssh_channel *) bv;
1071 if (*a < b->localid)
1073 if (*a > b->localid)
1078 static int ssh_rportcmp_ssh1(void *av, void *bv)
1080 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1081 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1083 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1084 return i < 0 ? -1 : +1;
1085 if (a->dport > b->dport)
1087 if (a->dport < b->dport)
1092 static int ssh_rportcmp_ssh2(void *av, void *bv)
1094 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1095 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1097 if ( (i = strcmp(a->shost, b->shost)) != 0)
1098 return i < 0 ? -1 : +1;
1099 if (a->sport > b->sport)
1101 if (a->sport < b->sport)
1107 * Special form of strcmp which can cope with NULL inputs. NULL is
1108 * defined to sort before even the empty string.
1110 static int nullstrcmp(const char *a, const char *b)
1112 if (a == NULL && b == NULL)
1118 return strcmp(a, b);
1121 static int ssh_portcmp(void *av, void *bv)
1123 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1124 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1126 if (a->type > b->type)
1128 if (a->type < b->type)
1130 if (a->addressfamily > b->addressfamily)
1132 if (a->addressfamily < b->addressfamily)
1134 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1135 return i < 0 ? -1 : +1;
1136 if (a->sport > b->sport)
1138 if (a->sport < b->sport)
1140 if (a->type != 'D') {
1141 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1142 return i < 0 ? -1 : +1;
1143 if (a->dport > b->dport)
1145 if (a->dport < b->dport)
1151 static int alloc_channel_id(Ssh ssh)
1153 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1154 unsigned low, high, mid;
1156 struct ssh_channel *c;
1159 * First-fit allocation of channel numbers: always pick the
1160 * lowest unused one. To do this, binary-search using the
1161 * counted B-tree to find the largest channel ID which is in a
1162 * contiguous sequence from the beginning. (Precisely
1163 * everything in that sequence must have ID equal to its tree
1164 * index plus CHANNEL_NUMBER_OFFSET.)
1166 tsize = count234(ssh->channels);
1170 while (high - low > 1) {
1171 mid = (high + low) / 2;
1172 c = index234(ssh->channels, mid);
1173 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1174 low = mid; /* this one is fine */
1176 high = mid; /* this one is past it */
1179 * Now low points to either -1, or the tree index of the
1180 * largest ID in the initial sequence.
1183 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1184 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1186 return low + 1 + CHANNEL_NUMBER_OFFSET;
1189 static void c_write_stderr(int trusted, const char *buf, int len)
1192 for (i = 0; i < len; i++)
1193 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1194 fputc(buf[i], stderr);
1197 static void c_write(Ssh ssh, const char *buf, int len)
1199 if (flags & FLAG_STDERR)
1200 c_write_stderr(1, buf, len);
1202 from_backend(ssh->frontend, 1, buf, len);
1205 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1207 if (flags & FLAG_STDERR)
1208 c_write_stderr(0, buf, len);
1210 from_backend_untrusted(ssh->frontend, buf, len);
1213 static void c_write_str(Ssh ssh, const char *buf)
1215 c_write(ssh, buf, strlen(buf));
1218 static void ssh_free_packet(struct Packet *pkt)
1223 static struct Packet *ssh_new_packet(void)
1225 struct Packet *pkt = snew(struct Packet);
1227 pkt->body = pkt->data = NULL;
1233 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1236 struct logblank_t blanks[4];
1242 if (ssh->logomitdata &&
1243 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1244 pkt->type == SSH1_SMSG_STDERR_DATA ||
1245 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1246 /* "Session data" packets - omit the data string. */
1247 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1248 ssh_pkt_getuint32(pkt); /* skip channel id */
1249 blanks[nblanks].offset = pkt->savedpos + 4;
1250 blanks[nblanks].type = PKTLOG_OMIT;
1251 ssh_pkt_getstring(pkt, &str, &slen);
1253 blanks[nblanks].len = slen;
1257 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1258 ssh1_pkt_type(pkt->type),
1259 pkt->body, pkt->length, nblanks, blanks, NULL,
1263 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1266 struct logblank_t blanks[4];
1271 * For outgoing packets, pkt->length represents the length of the
1272 * whole packet starting at pkt->data (including some header), and
1273 * pkt->body refers to the point within that where the log-worthy
1274 * payload begins. However, incoming packets expect pkt->length to
1275 * represent only the payload length (that is, it's measured from
1276 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1277 * packet to conform to the incoming-packet semantics, so that we
1278 * can analyse it with the ssh_pkt_get functions.
1280 pkt->length -= (pkt->body - pkt->data);
1283 if (ssh->logomitdata &&
1284 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1285 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1286 /* "Session data" packets - omit the data string. */
1287 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1288 ssh_pkt_getuint32(pkt); /* skip channel id */
1289 blanks[nblanks].offset = pkt->savedpos + 4;
1290 blanks[nblanks].type = PKTLOG_OMIT;
1291 ssh_pkt_getstring(pkt, &str, &slen);
1293 blanks[nblanks].len = slen;
1298 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1299 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1300 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1301 conf_get_int(ssh->conf, CONF_logomitpass)) {
1302 /* If this is a password or similar packet, blank the password(s). */
1303 blanks[nblanks].offset = 0;
1304 blanks[nblanks].len = pkt->length;
1305 blanks[nblanks].type = PKTLOG_BLANK;
1307 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1308 conf_get_int(ssh->conf, CONF_logomitpass)) {
1310 * If this is an X forwarding request packet, blank the fake
1313 * Note that while we blank the X authentication data here, we
1314 * don't take any special action to blank the start of an X11
1315 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1316 * an X connection without having session blanking enabled is
1317 * likely to leak your cookie into the log.
1320 ssh_pkt_getstring(pkt, &str, &slen);
1321 blanks[nblanks].offset = pkt->savedpos;
1322 blanks[nblanks].type = PKTLOG_BLANK;
1323 ssh_pkt_getstring(pkt, &str, &slen);
1325 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1330 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1331 ssh1_pkt_type(pkt->data[12]),
1332 pkt->body, pkt->length,
1333 nblanks, blanks, NULL, 0, NULL);
1336 * Undo the above adjustment of pkt->length, to put the packet
1337 * back in the state we found it.
1339 pkt->length += (pkt->body - pkt->data);
1343 * Collect incoming data in the incoming packet buffer.
1344 * Decipher and verify the packet when it is completely read.
1345 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1346 * Update the *data and *datalen variables.
1347 * Return a Packet structure when a packet is completed.
1349 static struct Packet *ssh1_rdpkt(Ssh ssh, const unsigned char **data,
1352 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1354 crBegin(ssh->ssh1_rdpkt_crstate);
1356 st->pktin = ssh_new_packet();
1358 st->pktin->type = 0;
1359 st->pktin->length = 0;
1361 for (st->i = st->len = 0; st->i < 4; st->i++) {
1362 while ((*datalen) == 0)
1364 st->len = (st->len << 8) + **data;
1365 (*data)++, (*datalen)--;
1368 st->pad = 8 - (st->len % 8);
1369 st->biglen = st->len + st->pad;
1370 st->pktin->length = st->len - 5;
1372 if (st->biglen < 0) {
1373 bombout(("Extremely large packet length from server suggests"
1374 " data stream corruption"));
1375 ssh_free_packet(st->pktin);
1379 st->pktin->maxlen = st->biglen;
1380 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1382 st->to_read = st->biglen;
1383 st->p = st->pktin->data;
1384 while (st->to_read > 0) {
1385 st->chunk = st->to_read;
1386 while ((*datalen) == 0)
1388 if (st->chunk > (*datalen))
1389 st->chunk = (*datalen);
1390 memcpy(st->p, *data, st->chunk);
1392 *datalen -= st->chunk;
1394 st->to_read -= st->chunk;
1397 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1398 st->biglen, NULL)) {
1399 bombout(("Network attack (CRC compensation) detected!"));
1400 ssh_free_packet(st->pktin);
1405 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1407 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1408 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1409 if (st->gotcrc != st->realcrc) {
1410 bombout(("Incorrect CRC received on packet"));
1411 ssh_free_packet(st->pktin);
1415 st->pktin->body = st->pktin->data + st->pad + 1;
1417 if (ssh->v1_compressing) {
1418 unsigned char *decompblk;
1420 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1421 st->pktin->body - 1, st->pktin->length + 1,
1422 &decompblk, &decomplen)) {
1423 bombout(("Zlib decompression encountered invalid data"));
1424 ssh_free_packet(st->pktin);
1428 if (st->pktin->maxlen < st->pad + decomplen) {
1429 st->pktin->maxlen = st->pad + decomplen;
1430 st->pktin->data = sresize(st->pktin->data,
1431 st->pktin->maxlen + APIEXTRA,
1433 st->pktin->body = st->pktin->data + st->pad + 1;
1436 memcpy(st->pktin->body - 1, decompblk, decomplen);
1438 st->pktin->length = decomplen - 1;
1441 st->pktin->type = st->pktin->body[-1];
1444 * Now pktin->body and pktin->length identify the semantic content
1445 * of the packet, excluding the initial type byte.
1449 ssh1_log_incoming_packet(ssh, st->pktin);
1451 st->pktin->savedpos = 0;
1453 crFinish(st->pktin);
1456 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1459 struct logblank_t blanks[4];
1465 if (ssh->logomitdata &&
1466 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1467 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1468 /* "Session data" packets - omit the data string. */
1469 ssh_pkt_getuint32(pkt); /* skip channel id */
1470 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1471 ssh_pkt_getuint32(pkt); /* skip extended data type */
1472 blanks[nblanks].offset = pkt->savedpos + 4;
1473 blanks[nblanks].type = PKTLOG_OMIT;
1474 ssh_pkt_getstring(pkt, &str, &slen);
1476 blanks[nblanks].len = slen;
1481 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1482 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1483 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1487 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1490 struct logblank_t blanks[4];
1495 * For outgoing packets, pkt->length represents the length of the
1496 * whole packet starting at pkt->data (including some header), and
1497 * pkt->body refers to the point within that where the log-worthy
1498 * payload begins. However, incoming packets expect pkt->length to
1499 * represent only the payload length (that is, it's measured from
1500 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1501 * packet to conform to the incoming-packet semantics, so that we
1502 * can analyse it with the ssh_pkt_get functions.
1504 pkt->length -= (pkt->body - pkt->data);
1507 if (ssh->logomitdata &&
1508 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1509 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1510 /* "Session data" packets - omit the data string. */
1511 ssh_pkt_getuint32(pkt); /* skip channel id */
1512 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1513 ssh_pkt_getuint32(pkt); /* skip extended data type */
1514 blanks[nblanks].offset = pkt->savedpos + 4;
1515 blanks[nblanks].type = PKTLOG_OMIT;
1516 ssh_pkt_getstring(pkt, &str, &slen);
1518 blanks[nblanks].len = slen;
1523 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1524 conf_get_int(ssh->conf, CONF_logomitpass)) {
1525 /* If this is a password packet, blank the password(s). */
1527 ssh_pkt_getstring(pkt, &str, &slen);
1528 ssh_pkt_getstring(pkt, &str, &slen);
1529 ssh_pkt_getstring(pkt, &str, &slen);
1530 if (slen == 8 && !memcmp(str, "password", 8)) {
1531 ssh2_pkt_getbool(pkt);
1532 /* Blank the password field. */
1533 blanks[nblanks].offset = pkt->savedpos;
1534 blanks[nblanks].type = PKTLOG_BLANK;
1535 ssh_pkt_getstring(pkt, &str, &slen);
1537 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1539 /* If there's another password field beyond it (change of
1540 * password), blank that too. */
1541 ssh_pkt_getstring(pkt, &str, &slen);
1543 blanks[nblanks-1].len =
1544 pkt->savedpos - blanks[nblanks].offset;
1547 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1548 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1549 conf_get_int(ssh->conf, CONF_logomitpass)) {
1550 /* If this is a keyboard-interactive response packet, blank
1553 ssh_pkt_getuint32(pkt);
1554 blanks[nblanks].offset = pkt->savedpos;
1555 blanks[nblanks].type = PKTLOG_BLANK;
1557 ssh_pkt_getstring(pkt, &str, &slen);
1561 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1563 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1564 conf_get_int(ssh->conf, CONF_logomitpass)) {
1566 * If this is an X forwarding request packet, blank the fake
1569 * Note that while we blank the X authentication data here, we
1570 * don't take any special action to blank the start of an X11
1571 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1572 * an X connection without having session blanking enabled is
1573 * likely to leak your cookie into the log.
1576 ssh_pkt_getuint32(pkt);
1577 ssh_pkt_getstring(pkt, &str, &slen);
1578 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1579 ssh2_pkt_getbool(pkt);
1580 ssh2_pkt_getbool(pkt);
1581 ssh_pkt_getstring(pkt, &str, &slen);
1582 blanks[nblanks].offset = pkt->savedpos;
1583 blanks[nblanks].type = PKTLOG_BLANK;
1584 ssh_pkt_getstring(pkt, &str, &slen);
1586 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1592 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1593 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1594 pkt->body, pkt->length, nblanks, blanks,
1595 &ssh->v2_outgoing_sequence,
1596 pkt->downstream_id, pkt->additional_log_text);
1599 * Undo the above adjustment of pkt->length, to put the packet
1600 * back in the state we found it.
1602 pkt->length += (pkt->body - pkt->data);
1605 static struct Packet *ssh2_rdpkt(Ssh ssh, const unsigned char **data,
1608 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1610 crBegin(ssh->ssh2_rdpkt_crstate);
1612 st->pktin = ssh_new_packet();
1614 st->pktin->type = 0;
1615 st->pktin->length = 0;
1617 st->cipherblk = ssh->sccipher->blksize;
1620 if (st->cipherblk < 8)
1622 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1624 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1625 ssh->scmac && !ssh->scmac_etm) {
1627 * When dealing with a CBC-mode cipher, we want to avoid the
1628 * possibility of an attacker's tweaking the ciphertext stream
1629 * so as to cause us to feed the same block to the block
1630 * cipher more than once and thus leak information
1631 * (VU#958563). The way we do this is not to take any
1632 * decisions on the basis of anything we've decrypted until
1633 * we've verified it with a MAC. That includes the packet
1634 * length, so we just read data and check the MAC repeatedly,
1635 * and when the MAC passes, see if the length we've got is
1638 * This defence is unnecessary in OpenSSH ETM mode, because
1639 * the whole point of ETM mode is that the attacker can't
1640 * tweak the ciphertext stream at all without the MAC
1641 * detecting it before we decrypt anything.
1644 /* May as well allocate the whole lot now. */
1645 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1648 /* Read an amount corresponding to the MAC. */
1649 for (st->i = 0; st->i < st->maclen; st->i++) {
1650 while ((*datalen) == 0)
1652 st->pktin->data[st->i] = *(*data)++;
1658 unsigned char seq[4];
1659 ssh->scmac->start(ssh->sc_mac_ctx);
1660 PUT_32BIT(seq, st->incoming_sequence);
1661 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1664 for (;;) { /* Once around this loop per cipher block. */
1665 /* Read another cipher-block's worth, and tack it onto the end. */
1666 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1667 while ((*datalen) == 0)
1669 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1672 /* Decrypt one more block (a little further back in the stream). */
1673 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1674 st->pktin->data + st->packetlen,
1676 /* Feed that block to the MAC. */
1677 ssh->scmac->bytes(ssh->sc_mac_ctx,
1678 st->pktin->data + st->packetlen, st->cipherblk);
1679 st->packetlen += st->cipherblk;
1680 /* See if that gives us a valid packet. */
1681 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1682 st->pktin->data + st->packetlen) &&
1683 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1686 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1687 bombout(("No valid incoming packet found"));
1688 ssh_free_packet(st->pktin);
1692 st->pktin->maxlen = st->packetlen + st->maclen;
1693 st->pktin->data = sresize(st->pktin->data,
1694 st->pktin->maxlen + APIEXTRA,
1696 } else if (ssh->scmac && ssh->scmac_etm) {
1697 st->pktin->data = snewn(4 + APIEXTRA, unsigned char);
1700 * OpenSSH encrypt-then-MAC mode: the packet length is
1701 * unencrypted, unless the cipher supports length encryption.
1703 for (st->i = st->len = 0; st->i < 4; st->i++) {
1704 while ((*datalen) == 0)
1706 st->pktin->data[st->i] = *(*data)++;
1709 /* Cipher supports length decryption, so do it */
1710 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
1711 /* Keep the packet the same though, so the MAC passes */
1712 unsigned char len[4];
1713 memcpy(len, st->pktin->data, 4);
1714 ssh->sccipher->decrypt_length(ssh->sc_cipher_ctx, len, 4, st->incoming_sequence);
1715 st->len = toint(GET_32BIT(len));
1717 st->len = toint(GET_32BIT(st->pktin->data));
1721 * _Completely_ silly lengths should be stomped on before they
1722 * do us any more damage.
1724 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1725 st->len % st->cipherblk != 0) {
1726 bombout(("Incoming packet length field was garbled"));
1727 ssh_free_packet(st->pktin);
1732 * So now we can work out the total packet length.
1734 st->packetlen = st->len + 4;
1737 * Allocate memory for the rest of the packet.
1739 st->pktin->maxlen = st->packetlen + st->maclen;
1740 st->pktin->data = sresize(st->pktin->data,
1741 st->pktin->maxlen + APIEXTRA,
1745 * Read the remainder of the packet.
1747 for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
1748 while ((*datalen) == 0)
1750 st->pktin->data[st->i] = *(*data)++;
1758 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1759 st->len + 4, st->incoming_sequence)) {
1760 bombout(("Incorrect MAC received on packet"));
1761 ssh_free_packet(st->pktin);
1765 /* Decrypt everything between the length field and the MAC. */
1767 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1768 st->pktin->data + 4,
1771 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1774 * Acquire and decrypt the first block of the packet. This will
1775 * contain the length and padding details.
1777 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1778 while ((*datalen) == 0)
1780 st->pktin->data[st->i] = *(*data)++;
1785 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1786 st->pktin->data, st->cipherblk);
1789 * Now get the length figure.
1791 st->len = toint(GET_32BIT(st->pktin->data));
1794 * _Completely_ silly lengths should be stomped on before they
1795 * do us any more damage.
1797 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1798 (st->len + 4) % st->cipherblk != 0) {
1799 bombout(("Incoming packet was garbled on decryption"));
1800 ssh_free_packet(st->pktin);
1805 * So now we can work out the total packet length.
1807 st->packetlen = st->len + 4;
1810 * Allocate memory for the rest of the packet.
1812 st->pktin->maxlen = st->packetlen + st->maclen;
1813 st->pktin->data = sresize(st->pktin->data,
1814 st->pktin->maxlen + APIEXTRA,
1818 * Read and decrypt the remainder of the packet.
1820 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1822 while ((*datalen) == 0)
1824 st->pktin->data[st->i] = *(*data)++;
1827 /* Decrypt everything _except_ the MAC. */
1829 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1830 st->pktin->data + st->cipherblk,
1831 st->packetlen - st->cipherblk);
1837 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1838 st->len + 4, st->incoming_sequence)) {
1839 bombout(("Incorrect MAC received on packet"));
1840 ssh_free_packet(st->pktin);
1844 /* Get and sanity-check the amount of random padding. */
1845 st->pad = st->pktin->data[4];
1846 if (st->pad < 4 || st->len - st->pad < 1) {
1847 bombout(("Invalid padding length on received packet"));
1848 ssh_free_packet(st->pktin);
1852 * This enables us to deduce the payload length.
1854 st->payload = st->len - st->pad - 1;
1856 st->pktin->length = st->payload + 5;
1857 st->pktin->encrypted_len = st->packetlen;
1859 st->pktin->sequence = st->incoming_sequence++;
1861 st->pktin->length = st->packetlen - st->pad;
1862 assert(st->pktin->length >= 0);
1865 * Decompress packet payload.
1868 unsigned char *newpayload;
1871 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1872 st->pktin->data + 5, st->pktin->length - 5,
1873 &newpayload, &newlen)) {
1874 if (st->pktin->maxlen < newlen + 5) {
1875 st->pktin->maxlen = newlen + 5;
1876 st->pktin->data = sresize(st->pktin->data,
1877 st->pktin->maxlen + APIEXTRA,
1880 st->pktin->length = 5 + newlen;
1881 memcpy(st->pktin->data + 5, newpayload, newlen);
1887 * RFC 4253 doesn't explicitly say that completely empty packets
1888 * with no type byte are forbidden, so treat them as deserving
1889 * an SSH_MSG_UNIMPLEMENTED.
1891 if (st->pktin->length <= 5) { /* == 5 we hope, but robustness */
1892 ssh2_msg_something_unimplemented(ssh, st->pktin);
1896 * pktin->body and pktin->length should identify the semantic
1897 * content of the packet, excluding the initial type byte.
1899 st->pktin->type = st->pktin->data[5];
1900 st->pktin->body = st->pktin->data + 6;
1901 st->pktin->length -= 6;
1902 assert(st->pktin->length >= 0); /* one last double-check */
1905 ssh2_log_incoming_packet(ssh, st->pktin);
1907 st->pktin->savedpos = 0;
1909 crFinish(st->pktin);
1912 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh,
1913 const unsigned char **data,
1916 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1918 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1921 * Read the packet length field.
1923 for (st->i = 0; st->i < 4; st->i++) {
1924 while ((*datalen) == 0)
1926 st->length[st->i] = *(*data)++;
1930 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1931 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1932 bombout(("Invalid packet length received"));
1936 st->pktin = ssh_new_packet();
1937 st->pktin->data = snewn(st->packetlen, unsigned char);
1939 st->pktin->encrypted_len = st->packetlen;
1941 st->pktin->sequence = st->incoming_sequence++;
1944 * Read the remainder of the packet.
1946 for (st->i = 0; st->i < st->packetlen; st->i++) {
1947 while ((*datalen) == 0)
1949 st->pktin->data[st->i] = *(*data)++;
1954 * pktin->body and pktin->length should identify the semantic
1955 * content of the packet, excluding the initial type byte.
1957 st->pktin->type = st->pktin->data[0];
1958 st->pktin->body = st->pktin->data + 1;
1959 st->pktin->length = st->packetlen - 1;
1962 * Log incoming packet, possibly omitting sensitive fields.
1965 ssh2_log_incoming_packet(ssh, st->pktin);
1967 st->pktin->savedpos = 0;
1969 crFinish(st->pktin);
1972 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1974 int pad, biglen, i, pktoffs;
1978 * XXX various versions of SC (including 8.8.4) screw up the
1979 * register allocation in this function and use the same register
1980 * (D6) for len and as a temporary, with predictable results. The
1981 * following sledgehammer prevents this.
1988 ssh1_log_outgoing_packet(ssh, pkt);
1990 if (ssh->v1_compressing) {
1991 unsigned char *compblk;
1993 zlib_compress_block(ssh->cs_comp_ctx,
1994 pkt->data + 12, pkt->length - 12,
1995 &compblk, &complen);
1996 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1997 memcpy(pkt->data + 12, compblk, complen);
1999 pkt->length = complen + 12;
2002 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
2004 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
2005 pad = 8 - (len % 8);
2007 biglen = len + pad; /* len(padding+type+data+CRC) */
2009 for (i = pktoffs; i < 4+8; i++)
2010 pkt->data[i] = random_byte();
2011 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
2012 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
2013 PUT_32BIT(pkt->data + pktoffs, len);
2016 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
2017 pkt->data + pktoffs + 4, biglen);
2019 if (offset_p) *offset_p = pktoffs;
2020 return biglen + 4; /* len(length+padding+type+data+CRC) */
2023 static int s_write(Ssh ssh, void *data, int len)
2026 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
2027 0, NULL, NULL, 0, NULL);
2030 return sk_write(ssh->s, (char *)data, len);
2033 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
2035 int len, backlog, offset;
2036 len = s_wrpkt_prepare(ssh, pkt, &offset);
2037 backlog = s_write(ssh, pkt->data + offset, len);
2038 if (backlog > SSH_MAX_BACKLOG)
2039 ssh_throttle_all(ssh, 1, backlog);
2040 ssh_free_packet(pkt);
2043 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
2046 len = s_wrpkt_prepare(ssh, pkt, &offset);
2047 if (ssh->deferred_len + len > ssh->deferred_size) {
2048 ssh->deferred_size = ssh->deferred_len + len + 128;
2049 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2053 memcpy(ssh->deferred_send_data + ssh->deferred_len,
2054 pkt->data + offset, len);
2055 ssh->deferred_len += len;
2056 ssh_free_packet(pkt);
2060 * Construct a SSH-1 packet with the specified contents.
2061 * (This all-at-once interface used to be the only one, but now SSH-1
2062 * packets can also be constructed incrementally.)
2064 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
2070 pkt = ssh1_pkt_init(pkttype);
2072 while ((argtype = va_arg(ap, int)) != PKT_END) {
2073 unsigned char *argp, argchar;
2075 unsigned long argint;
2078 /* Actual fields in the packet */
2080 argint = va_arg(ap, int);
2081 ssh_pkt_adduint32(pkt, argint);
2084 argchar = (unsigned char) va_arg(ap, int);
2085 ssh_pkt_addbyte(pkt, argchar);
2088 argp = va_arg(ap, unsigned char *);
2089 arglen = va_arg(ap, int);
2090 ssh_pkt_adddata(pkt, argp, arglen);
2093 sargp = va_arg(ap, char *);
2094 ssh_pkt_addstring(pkt, sargp);
2097 bn = va_arg(ap, Bignum);
2098 ssh1_pkt_addmp(pkt, bn);
2106 static void send_packet(Ssh ssh, int pkttype, ...)
2110 va_start(ap, pkttype);
2111 pkt = construct_packet(ssh, pkttype, ap);
2116 static void defer_packet(Ssh ssh, int pkttype, ...)
2120 va_start(ap, pkttype);
2121 pkt = construct_packet(ssh, pkttype, ap);
2123 s_wrpkt_defer(ssh, pkt);
2126 static int ssh_versioncmp(const char *a, const char *b)
2129 unsigned long av, bv;
2131 av = strtoul(a, &ae, 10);
2132 bv = strtoul(b, &be, 10);
2134 return (av < bv ? -1 : +1);
2139 av = strtoul(ae, &ae, 10);
2140 bv = strtoul(be, &be, 10);
2142 return (av < bv ? -1 : +1);
2147 * Utility routines for putting an SSH-protocol `string' and
2148 * `uint32' into a hash state.
2150 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2152 unsigned char lenblk[4];
2153 PUT_32BIT(lenblk, len);
2154 h->bytes(s, lenblk, 4);
2155 h->bytes(s, str, len);
2158 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2160 unsigned char intblk[4];
2161 PUT_32BIT(intblk, i);
2162 h->bytes(s, intblk, 4);
2166 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2168 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2170 if (pkt->maxlen < length) {
2171 unsigned char *body = pkt->body;
2172 int offset = body ? body - pkt->data : 0;
2173 pkt->maxlen = length + 256;
2174 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2175 if (body) pkt->body = pkt->data + offset;
2178 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2181 ssh_pkt_ensure(pkt, pkt->length);
2182 memcpy(pkt->data + pkt->length - len, data, len);
2184 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2186 ssh_pkt_adddata(pkt, &byte, 1);
2188 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2190 ssh_pkt_adddata(pkt, &value, 1);
2192 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2195 PUT_32BIT(x, value);
2196 ssh_pkt_adddata(pkt, x, 4);
2198 static void ssh_pkt_addstring_start(struct Packet *pkt)
2200 ssh_pkt_adduint32(pkt, 0);
2201 pkt->savedpos = pkt->length;
2203 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2206 ssh_pkt_adddata(pkt, data, len);
2207 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2209 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2211 ssh_pkt_addstring_data(pkt, data, strlen(data));
2213 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2215 ssh_pkt_addstring_start(pkt);
2216 ssh_pkt_addstring_str(pkt, data);
2218 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2220 int len = ssh1_bignum_length(b);
2221 unsigned char *data = snewn(len, unsigned char);
2222 (void) ssh1_write_bignum(data, b);
2223 ssh_pkt_adddata(pkt, data, len);
2226 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2229 int i, n = (bignum_bitcount(b) + 7) / 8;
2230 p = snewn(n + 1, unsigned char);
2232 for (i = 1; i <= n; i++)
2233 p[i] = bignum_byte(b, n - i);
2235 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2237 memmove(p, p + i, n + 1 - i);
2241 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2245 p = ssh2_mpint_fmt(b, &len);
2246 ssh_pkt_addstring_start(pkt);
2247 ssh_pkt_addstring_data(pkt, (char *)p, len);
2251 static struct Packet *ssh1_pkt_init(int pkt_type)
2253 struct Packet *pkt = ssh_new_packet();
2254 pkt->length = 4 + 8; /* space for length + max padding */
2255 ssh_pkt_addbyte(pkt, pkt_type);
2256 pkt->body = pkt->data + pkt->length;
2257 pkt->type = pkt_type;
2258 pkt->downstream_id = 0;
2259 pkt->additional_log_text = NULL;
2263 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2264 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2265 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2266 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2267 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2268 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2269 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2270 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2271 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2273 static struct Packet *ssh2_pkt_init(int pkt_type)
2275 struct Packet *pkt = ssh_new_packet();
2276 pkt->length = 5; /* space for packet length + padding length */
2278 pkt->type = pkt_type;
2279 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2280 pkt->body = pkt->data + pkt->length; /* after packet type */
2281 pkt->downstream_id = 0;
2282 pkt->additional_log_text = NULL;
2287 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2288 * put the MAC on it. Final packet, ready to be sent, is stored in
2289 * pkt->data. Total length is returned.
2291 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2293 int cipherblk, maclen, padding, unencrypted_prefix, i;
2296 ssh2_log_outgoing_packet(ssh, pkt);
2298 if (ssh->bare_connection) {
2300 * Trivial packet construction for the bare connection
2303 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2304 pkt->body = pkt->data + 1;
2305 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2306 return pkt->length - 1;
2310 * Compress packet payload.
2313 unsigned char *newpayload;
2316 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2318 &newpayload, &newlen)) {
2320 ssh2_pkt_adddata(pkt, newpayload, newlen);
2326 * Add padding. At least four bytes, and must also bring total
2327 * length (minus MAC) up to a multiple of the block size.
2328 * If pkt->forcepad is set, make sure the packet is at least that size
2331 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2332 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2334 unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
2335 if (pkt->length + padding < pkt->forcepad)
2336 padding = pkt->forcepad - pkt->length;
2338 (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
2340 assert(padding <= 255);
2341 maclen = ssh->csmac ? ssh->csmac->len : 0;
2342 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2343 pkt->data[4] = padding;
2344 for (i = 0; i < padding; i++)
2345 pkt->data[pkt->length + i] = random_byte();
2346 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2348 /* Encrypt length if the scheme requires it */
2349 if (ssh->cscipher && (ssh->cscipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
2350 ssh->cscipher->encrypt_length(ssh->cs_cipher_ctx, pkt->data, 4,
2351 ssh->v2_outgoing_sequence);
2354 if (ssh->csmac && ssh->csmac_etm) {
2356 * OpenSSH-defined encrypt-then-MAC protocol.
2359 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2360 pkt->data + 4, pkt->length + padding - 4);
2361 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2362 pkt->length + padding,
2363 ssh->v2_outgoing_sequence);
2366 * SSH-2 standard protocol.
2369 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2370 pkt->length + padding,
2371 ssh->v2_outgoing_sequence);
2373 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2374 pkt->data, pkt->length + padding);
2377 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2378 pkt->encrypted_len = pkt->length + padding;
2380 /* Ready-to-send packet starts at pkt->data. We return length. */
2381 pkt->body = pkt->data;
2382 return pkt->length + padding + maclen;
2386 * Routines called from the main SSH code to send packets. There
2387 * are quite a few of these, because we have two separate
2388 * mechanisms for delaying the sending of packets:
2390 * - In order to send an IGNORE message and a password message in
2391 * a single fixed-length blob, we require the ability to
2392 * concatenate the encrypted forms of those two packets _into_ a
2393 * single blob and then pass it to our <network.h> transport
2394 * layer in one go. Hence, there's a deferment mechanism which
2395 * works after packet encryption.
2397 * - In order to avoid sending any connection-layer messages
2398 * during repeat key exchange, we have to queue up any such
2399 * outgoing messages _before_ they are encrypted (and in
2400 * particular before they're allocated sequence numbers), and
2401 * then send them once we've finished.
2403 * I call these mechanisms `defer' and `queue' respectively, so as
2404 * to distinguish them reasonably easily.
2406 * The functions send_noqueue() and defer_noqueue() free the packet
2407 * structure they are passed. Every outgoing packet goes through
2408 * precisely one of these functions in its life; packets passed to
2409 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2410 * these or get queued, and then when the queue is later emptied
2411 * the packets are all passed to defer_noqueue().
2413 * When using a CBC-mode cipher, it's necessary to ensure that an
2414 * attacker can't provide data to be encrypted using an IV that they
2415 * know. We ensure this by prefixing each packet that might contain
2416 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2417 * mechanism, so in this case send_noqueue() ends up redirecting to
2418 * defer_noqueue(). If you don't like this inefficiency, don't use
2422 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2423 static void ssh_pkt_defersend(Ssh);
2426 * Send an SSH-2 packet immediately, without queuing or deferring.
2428 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2432 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2433 /* We need to send two packets, so use the deferral mechanism. */
2434 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2435 ssh_pkt_defersend(ssh);
2438 len = ssh2_pkt_construct(ssh, pkt);
2439 backlog = s_write(ssh, pkt->body, len);
2440 if (backlog > SSH_MAX_BACKLOG)
2441 ssh_throttle_all(ssh, 1, backlog);
2443 ssh->outgoing_data_size += pkt->encrypted_len;
2444 if (!ssh->kex_in_progress &&
2445 !ssh->bare_connection &&
2446 ssh->max_data_size != 0 &&
2447 ssh->outgoing_data_size > ssh->max_data_size)
2448 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2450 ssh_free_packet(pkt);
2454 * Defer an SSH-2 packet.
2456 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2459 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2460 ssh->deferred_len == 0 && !noignore &&
2461 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2463 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2464 * get encrypted with a known IV.
2466 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2467 ssh2_pkt_addstring_start(ipkt);
2468 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2470 len = ssh2_pkt_construct(ssh, pkt);
2471 if (ssh->deferred_len + len > ssh->deferred_size) {
2472 ssh->deferred_size = ssh->deferred_len + len + 128;
2473 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2477 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2478 ssh->deferred_len += len;
2479 ssh->deferred_data_size += pkt->encrypted_len;
2480 ssh_free_packet(pkt);
2484 * Queue an SSH-2 packet.
2486 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2488 assert(ssh->queueing);
2490 if (ssh->queuelen >= ssh->queuesize) {
2491 ssh->queuesize = ssh->queuelen + 32;
2492 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2495 ssh->queue[ssh->queuelen++] = pkt;
2499 * Either queue or send a packet, depending on whether queueing is
2502 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2505 ssh2_pkt_queue(ssh, pkt);
2507 ssh2_pkt_send_noqueue(ssh, pkt);
2511 * Either queue or defer a packet, depending on whether queueing is
2514 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2517 ssh2_pkt_queue(ssh, pkt);
2519 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2523 * Send the whole deferred data block constructed by
2524 * ssh2_pkt_defer() or SSH-1's defer_packet().
2526 * The expected use of the defer mechanism is that you call
2527 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2528 * not currently queueing, this simply sets up deferred_send_data
2529 * and then sends it. If we _are_ currently queueing, the calls to
2530 * ssh2_pkt_defer() put the deferred packets on to the queue
2531 * instead, and therefore ssh_pkt_defersend() has no deferred data
2532 * to send. Hence, there's no need to make it conditional on
2535 static void ssh_pkt_defersend(Ssh ssh)
2538 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2539 ssh->deferred_len = ssh->deferred_size = 0;
2540 sfree(ssh->deferred_send_data);
2541 ssh->deferred_send_data = NULL;
2542 if (backlog > SSH_MAX_BACKLOG)
2543 ssh_throttle_all(ssh, 1, backlog);
2545 if (ssh->version == 2) {
2546 ssh->outgoing_data_size += ssh->deferred_data_size;
2547 ssh->deferred_data_size = 0;
2548 if (!ssh->kex_in_progress &&
2549 !ssh->bare_connection &&
2550 ssh->max_data_size != 0 &&
2551 ssh->outgoing_data_size > ssh->max_data_size)
2552 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2557 * Send a packet whose length needs to be disguised (typically
2558 * passwords or keyboard-interactive responses).
2560 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2566 * The simplest way to do this is to adjust the
2567 * variable-length padding field in the outgoing packet.
2569 * Currently compiled out, because some Cisco SSH servers
2570 * don't like excessively padded packets (bah, why's it
2573 pkt->forcepad = padsize;
2574 ssh2_pkt_send(ssh, pkt);
2579 * If we can't do that, however, an alternative approach is
2580 * to use the pkt_defer mechanism to bundle the packet
2581 * tightly together with an SSH_MSG_IGNORE such that their
2582 * combined length is a constant. So first we construct the
2583 * final form of this packet and defer its sending.
2585 ssh2_pkt_defer(ssh, pkt);
2588 * Now construct an SSH_MSG_IGNORE which includes a string
2589 * that's an exact multiple of the cipher block size. (If
2590 * the cipher is NULL so that the block size is
2591 * unavailable, we don't do this trick at all, because we
2592 * gain nothing by it.)
2594 if (ssh->cscipher &&
2595 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2598 stringlen = (256 - ssh->deferred_len);
2599 stringlen += ssh->cscipher->blksize - 1;
2600 stringlen -= (stringlen % ssh->cscipher->blksize);
2603 * Temporarily disable actual compression, so we
2604 * can guarantee to get this string exactly the
2605 * length we want it. The compression-disabling
2606 * routine should return an integer indicating how
2607 * many bytes we should adjust our string length
2611 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2613 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2614 ssh2_pkt_addstring_start(pkt);
2615 for (i = 0; i < stringlen; i++) {
2616 char c = (char) random_byte();
2617 ssh2_pkt_addstring_data(pkt, &c, 1);
2619 ssh2_pkt_defer(ssh, pkt);
2621 ssh_pkt_defersend(ssh);
2626 * Send all queued SSH-2 packets. We send them by means of
2627 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2628 * packets that needed to be lumped together.
2630 static void ssh2_pkt_queuesend(Ssh ssh)
2634 assert(!ssh->queueing);
2636 for (i = 0; i < ssh->queuelen; i++)
2637 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2640 ssh_pkt_defersend(ssh);
2644 void bndebug(char *string, Bignum b)
2648 p = ssh2_mpint_fmt(b, &len);
2649 debug(("%s", string));
2650 for (i = 0; i < len; i++)
2651 debug((" %02x", p[i]));
2657 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2661 p = ssh2_mpint_fmt(b, &len);
2662 hash_string(h, s, p, len);
2667 * Packet decode functions for both SSH-1 and SSH-2.
2669 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2671 unsigned long value;
2672 if (pkt->length - pkt->savedpos < 4)
2673 return 0; /* arrgh, no way to decline (FIXME?) */
2674 value = GET_32BIT(pkt->body + pkt->savedpos);
2678 static int ssh2_pkt_getbool(struct Packet *pkt)
2680 unsigned long value;
2681 if (pkt->length - pkt->savedpos < 1)
2682 return 0; /* arrgh, no way to decline (FIXME?) */
2683 value = pkt->body[pkt->savedpos] != 0;
2687 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2692 if (pkt->length - pkt->savedpos < 4)
2694 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2699 if (pkt->length - pkt->savedpos < *length)
2701 *p = (char *)(pkt->body + pkt->savedpos);
2702 pkt->savedpos += *length;
2704 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2706 if (pkt->length - pkt->savedpos < length)
2708 pkt->savedpos += length;
2709 return pkt->body + (pkt->savedpos - length);
2711 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2712 const unsigned char **keystr)
2716 j = makekey(pkt->body + pkt->savedpos,
2717 pkt->length - pkt->savedpos,
2724 assert(pkt->savedpos < pkt->length);
2728 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2733 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2734 pkt->length - pkt->savedpos, &b);
2742 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2748 ssh_pkt_getstring(pkt, &p, &length);
2753 b = bignum_from_bytes((unsigned char *)p, length);
2758 * Helper function to add an SSH-2 signature blob to a packet.
2759 * Expects to be shown the public key blob as well as the signature
2760 * blob. Normally works just like ssh2_pkt_addstring, but will
2761 * fiddle with the signature packet if necessary for
2762 * BUG_SSH2_RSA_PADDING.
2764 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2765 void *pkblob_v, int pkblob_len,
2766 void *sigblob_v, int sigblob_len)
2768 unsigned char *pkblob = (unsigned char *)pkblob_v;
2769 unsigned char *sigblob = (unsigned char *)sigblob_v;
2771 /* dmemdump(pkblob, pkblob_len); */
2772 /* dmemdump(sigblob, sigblob_len); */
2775 * See if this is in fact an ssh-rsa signature and a buggy
2776 * server; otherwise we can just do this the easy way.
2778 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2779 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2780 int pos, len, siglen;
2783 * Find the byte length of the modulus.
2786 pos = 4+7; /* skip over "ssh-rsa" */
2787 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2788 if (len < 0 || len > pkblob_len - pos - 4)
2790 pos += 4 + len; /* skip over exponent */
2791 if (pkblob_len - pos < 4)
2793 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2794 if (len < 0 || len > pkblob_len - pos - 4)
2796 pos += 4; /* find modulus itself */
2797 while (len > 0 && pkblob[pos] == 0)
2799 /* debug(("modulus length is %d\n", len)); */
2802 * Now find the signature integer.
2804 pos = 4+7; /* skip over "ssh-rsa" */
2805 if (sigblob_len < pos+4)
2807 siglen = toint(GET_32BIT(sigblob+pos));
2808 if (siglen != sigblob_len - pos - 4)
2810 /* debug(("signature length is %d\n", siglen)); */
2812 if (len != siglen) {
2813 unsigned char newlen[4];
2814 ssh2_pkt_addstring_start(pkt);
2815 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2816 /* dmemdump(sigblob, pos); */
2817 pos += 4; /* point to start of actual sig */
2818 PUT_32BIT(newlen, len);
2819 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2820 /* dmemdump(newlen, 4); */
2822 while (len-- > siglen) {
2823 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2824 /* dmemdump(newlen, 1); */
2826 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2827 /* dmemdump(sigblob+pos, siglen); */
2831 /* Otherwise fall through and do it the easy way. We also come
2832 * here as a fallback if we discover above that the key blob
2833 * is misformatted in some way. */
2837 ssh2_pkt_addstring_start(pkt);
2838 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2842 * Examine the remote side's version string and compare it against
2843 * a list of known buggy implementations.
2845 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2847 char *imp; /* pointer to implementation part */
2849 imp += strcspn(imp, "-");
2851 imp += strcspn(imp, "-");
2854 ssh->remote_bugs = 0;
2857 * General notes on server version strings:
2858 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2859 * here -- in particular, we've heard of one that's perfectly happy
2860 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2861 * so we can't distinguish them.
2863 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2864 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2865 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2866 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2867 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2868 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2870 * These versions don't support SSH1_MSG_IGNORE, so we have
2871 * to use a different defence against password length
2874 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2875 logevent("We believe remote version has SSH-1 ignore bug");
2878 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2879 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2880 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2882 * These versions need a plain password sent; they can't
2883 * handle having a null and a random length of data after
2886 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2887 logevent("We believe remote version needs a plain SSH-1 password");
2890 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2891 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2892 (!strcmp(imp, "Cisco-1.25")))) {
2894 * These versions apparently have no clue whatever about
2895 * RSA authentication and will panic and die if they see
2896 * an AUTH_RSA message.
2898 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2899 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2902 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2903 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2904 !wc_match("* VShell", imp) &&
2905 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2906 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2907 wc_match("2.1 *", imp)))) {
2909 * These versions have the HMAC bug.
2911 ssh->remote_bugs |= BUG_SSH2_HMAC;
2912 logevent("We believe remote version has SSH-2 HMAC bug");
2915 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2916 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2917 !wc_match("* VShell", imp) &&
2918 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2920 * These versions have the key-derivation bug (failing to
2921 * include the literal shared secret in the hashes that
2922 * generate the keys).
2924 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2925 logevent("We believe remote version has SSH-2 key-derivation bug");
2928 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2929 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2930 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2931 wc_match("OpenSSH_3.[0-2]*", imp) ||
2932 wc_match("mod_sftp/0.[0-8]*", imp) ||
2933 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2935 * These versions have the SSH-2 RSA padding bug.
2937 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2938 logevent("We believe remote version has SSH-2 RSA padding bug");
2941 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2942 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2943 wc_match("OpenSSH_2.[0-2]*", imp))) {
2945 * These versions have the SSH-2 session-ID bug in
2946 * public-key authentication.
2948 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2949 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2952 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2953 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2954 (wc_match("DigiSSH_2.0", imp) ||
2955 wc_match("OpenSSH_2.[0-4]*", imp) ||
2956 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2957 wc_match("Sun_SSH_1.0", imp) ||
2958 wc_match("Sun_SSH_1.0.1", imp) ||
2959 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2960 wc_match("WeOnlyDo-*", imp)))) {
2962 * These versions have the SSH-2 rekey bug.
2964 ssh->remote_bugs |= BUG_SSH2_REKEY;
2965 logevent("We believe remote version has SSH-2 rekey bug");
2968 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2969 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2970 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2971 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2973 * This version ignores our makpkt and needs to be throttled.
2975 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2976 logevent("We believe remote version ignores SSH-2 maximum packet size");
2979 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2981 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2982 * none detected automatically.
2984 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2985 logevent("We believe remote version has SSH-2 ignore bug");
2988 if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
2989 (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
2990 (wc_match("OpenSSH_2.[235]*", imp)))) {
2992 * These versions only support the original (pre-RFC4419)
2993 * SSH-2 GEX request, and disconnect with a protocol error if
2994 * we use the newer version.
2996 ssh->remote_bugs |= BUG_SSH2_OLDGEX;
2997 logevent("We believe remote version has outdated SSH-2 GEX");
3000 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
3002 * Servers that don't support our winadj request for one
3003 * reason or another. Currently, none detected automatically.
3005 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
3006 logevent("We believe remote version has winadj bug");
3009 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
3010 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
3011 (wc_match("OpenSSH_[2-5].*", imp) ||
3012 wc_match("OpenSSH_6.[0-6]*", imp) ||
3013 wc_match("dropbear_0.[2-4][0-9]*", imp) ||
3014 wc_match("dropbear_0.5[01]*", imp)))) {
3016 * These versions have the SSH-2 channel request bug.
3017 * OpenSSH 6.7 and above do not:
3018 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
3019 * dropbear_0.52 and above do not:
3020 * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
3022 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
3023 logevent("We believe remote version has SSH-2 channel request bug");
3028 * The `software version' part of an SSH version string is required
3029 * to contain no spaces or minus signs.
3031 static void ssh_fix_verstring(char *str)
3033 /* Eat "<protoversion>-". */
3034 while (*str && *str != '-') str++;
3035 assert(*str == '-'); str++;
3037 /* Convert minus signs and spaces in the remaining string into
3040 if (*str == '-' || *str == ' ')
3047 * Send an appropriate SSH version string.
3049 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
3053 if (ssh->version == 2) {
3055 * Construct a v2 version string.
3057 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
3060 * Construct a v1 version string.
3062 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
3063 verstring = dupprintf("SSH-%s-%s\012",
3064 (ssh_versioncmp(svers, "1.5") <= 0 ?
3069 ssh_fix_verstring(verstring + strlen(protoname));
3071 /* FUZZING make PuTTY insecure, so make live use difficult. */
3075 if (ssh->version == 2) {
3078 * Record our version string.
3080 len = strcspn(verstring, "\015\012");
3081 ssh->v_c = snewn(len + 1, char);
3082 memcpy(ssh->v_c, verstring, len);
3086 logeventf(ssh, "We claim version: %.*s",
3087 strcspn(verstring, "\015\012"), verstring);
3088 s_write(ssh, verstring, strlen(verstring));
3092 static int do_ssh_init(Ssh ssh, unsigned char c)
3094 static const char protoname[] = "SSH-";
3096 struct do_ssh_init_state {
3105 crState(do_ssh_init_state);
3109 /* Search for a line beginning with the protocol name prefix in
3112 for (s->i = 0; protoname[s->i]; s->i++) {
3113 if ((char)c != protoname[s->i]) goto no;
3123 ssh->session_started = TRUE;
3125 s->vstrsize = sizeof(protoname) + 16;
3126 s->vstring = snewn(s->vstrsize, char);
3127 strcpy(s->vstring, protoname);
3128 s->vslen = strlen(protoname);
3131 if (s->vslen >= s->vstrsize - 1) {
3133 s->vstring = sresize(s->vstring, s->vstrsize, char);
3135 s->vstring[s->vslen++] = c;
3138 s->version[s->i] = '\0';
3140 } else if (s->i < sizeof(s->version) - 1)
3141 s->version[s->i++] = c;
3142 } else if (c == '\012')
3144 crReturn(1); /* get another char */
3147 ssh->agentfwd_enabled = FALSE;
3148 ssh->rdpkt2_state.incoming_sequence = 0;
3150 s->vstring[s->vslen] = 0;
3151 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3152 logeventf(ssh, "Server version: %s", s->vstring);
3153 ssh_detect_bugs(ssh, s->vstring);
3156 * Decide which SSH protocol version to support.
3159 /* Anything strictly below "2.0" means protocol 1 is supported. */
3160 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
3161 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
3162 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
3164 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3166 bombout(("SSH protocol version 1 required by our configuration "
3167 "but not provided by server"));
3170 } else if (conf_get_int(ssh->conf, CONF_sshprot) == 3) {
3172 bombout(("SSH protocol version 2 required by our configuration "
3173 "but server only provides (old, insecure) SSH-1"));
3177 /* No longer support values 1 or 2 for CONF_sshprot */
3178 assert(!"Unexpected value for CONF_sshprot");
3181 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
3186 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
3188 /* Send the version string, if we haven't already */
3189 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
3190 ssh_send_verstring(ssh, protoname, s->version);
3192 if (ssh->version == 2) {
3195 * Record their version string.
3197 len = strcspn(s->vstring, "\015\012");
3198 ssh->v_s = snewn(len + 1, char);
3199 memcpy(ssh->v_s, s->vstring, len);
3203 * Initialise SSH-2 protocol.
3205 ssh->protocol = ssh2_protocol;
3206 ssh2_protocol_setup(ssh);
3207 ssh->s_rdpkt = ssh2_rdpkt;
3210 * Initialise SSH-1 protocol.
3212 ssh->protocol = ssh1_protocol;
3213 ssh1_protocol_setup(ssh);
3214 ssh->s_rdpkt = ssh1_rdpkt;
3216 if (ssh->version == 2)
3217 do_ssh2_transport(ssh, NULL, -1, NULL);
3219 update_specials_menu(ssh->frontend);
3220 ssh->state = SSH_STATE_BEFORE_SIZE;
3221 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3228 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3231 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3232 * the ssh-connection part, extracted and given a trivial binary
3233 * packet protocol, so we replace 'SSH-' at the start with a new
3234 * name. In proper SSH style (though of course this part of the
3235 * proper SSH protocol _isn't_ subject to this kind of
3236 * DNS-domain-based extension), we define the new name in our
3239 static const char protoname[] =
3240 "SSHCONNECTION@putty.projects.tartarus.org-";
3242 struct do_ssh_connection_init_state {
3250 crState(do_ssh_connection_init_state);
3254 /* Search for a line beginning with the protocol name prefix in
3257 for (s->i = 0; protoname[s->i]; s->i++) {
3258 if ((char)c != protoname[s->i]) goto no;
3268 s->vstrsize = sizeof(protoname) + 16;
3269 s->vstring = snewn(s->vstrsize, char);
3270 strcpy(s->vstring, protoname);
3271 s->vslen = strlen(protoname);
3274 if (s->vslen >= s->vstrsize - 1) {
3276 s->vstring = sresize(s->vstring, s->vstrsize, char);
3278 s->vstring[s->vslen++] = c;
3281 s->version[s->i] = '\0';
3283 } else if (s->i < sizeof(s->version) - 1)
3284 s->version[s->i++] = c;
3285 } else if (c == '\012')
3287 crReturn(1); /* get another char */
3290 ssh->agentfwd_enabled = FALSE;
3291 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3293 s->vstring[s->vslen] = 0;
3294 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3295 logeventf(ssh, "Server version: %s", s->vstring);
3296 ssh_detect_bugs(ssh, s->vstring);
3299 * Decide which SSH protocol version to support. This is easy in
3300 * bare ssh-connection mode: only 2.0 is legal.
3302 if (ssh_versioncmp(s->version, "2.0") < 0) {
3303 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3306 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3307 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3313 logeventf(ssh, "Using bare ssh-connection protocol");
3315 /* Send the version string, if we haven't already */
3316 ssh_send_verstring(ssh, protoname, s->version);
3319 * Initialise bare connection protocol.
3321 ssh->protocol = ssh2_bare_connection_protocol;
3322 ssh2_bare_connection_protocol_setup(ssh);
3323 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3325 update_specials_menu(ssh->frontend);
3326 ssh->state = SSH_STATE_BEFORE_SIZE;
3327 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3330 * Get authconn (really just conn) under way.
3332 do_ssh2_authconn(ssh, NULL, 0, NULL);
3339 static void ssh_process_incoming_data(Ssh ssh,
3340 const unsigned char **data, int *datalen)
3342 struct Packet *pktin;
3344 pktin = ssh->s_rdpkt(ssh, data, datalen);
3346 ssh->protocol(ssh, NULL, 0, pktin);
3347 ssh_free_packet(pktin);
3351 static void ssh_queue_incoming_data(Ssh ssh,
3352 const unsigned char **data, int *datalen)
3354 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3359 static void ssh_process_queued_incoming_data(Ssh ssh)
3362 const unsigned char *data;
3365 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3366 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3370 while (!ssh->frozen && len > 0)
3371 ssh_process_incoming_data(ssh, &data, &len);
3374 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3378 static void ssh_set_frozen(Ssh ssh, int frozen)
3381 sk_set_frozen(ssh->s, frozen);
3382 ssh->frozen = frozen;
3385 static void ssh_gotdata(Ssh ssh, const unsigned char *data, int datalen)
3387 /* Log raw data, if we're in that mode. */
3389 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3390 0, NULL, NULL, 0, NULL);
3392 crBegin(ssh->ssh_gotdata_crstate);
3395 * To begin with, feed the characters one by one to the
3396 * protocol initialisation / selection function do_ssh_init().
3397 * When that returns 0, we're done with the initial greeting
3398 * exchange and can move on to packet discipline.
3401 int ret; /* need not be kept across crReturn */
3403 crReturnV; /* more data please */
3404 ret = ssh->do_ssh_init(ssh, *data);
3412 * We emerge from that loop when the initial negotiation is
3413 * over and we have selected an s_rdpkt function. Now pass
3414 * everything to s_rdpkt, and then pass the resulting packets
3415 * to the proper protocol handler.
3419 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3421 ssh_queue_incoming_data(ssh, &data, &datalen);
3422 /* This uses up all data and cannot cause anything interesting
3423 * to happen; indeed, for anything to happen at all, we must
3424 * return, so break out. */
3426 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3427 /* This uses up some or all data, and may freeze the
3429 ssh_process_queued_incoming_data(ssh);
3431 /* This uses up some or all data, and may freeze the
3433 ssh_process_incoming_data(ssh, &data, &datalen);
3435 /* FIXME this is probably EBW. */
3436 if (ssh->state == SSH_STATE_CLOSED)
3439 /* We're out of data. Go and get some more. */
3445 static int ssh_do_close(Ssh ssh, int notify_exit)
3448 struct ssh_channel *c;
3450 ssh->state = SSH_STATE_CLOSED;
3451 expire_timer_context(ssh);
3456 notify_remote_exit(ssh->frontend);
3461 * Now we must shut down any port- and X-forwarded channels going
3462 * through this connection.
3464 if (ssh->channels) {
3465 while (NULL != (c = index234(ssh->channels, 0))) {
3468 x11_close(c->u.x11.xconn);
3471 pfd_close(c->u.pfd.pf);
3474 del234(ssh->channels, c); /* moving next one to index 0 */
3475 if (ssh->version == 2)
3476 bufchain_clear(&c->v.v2.outbuffer);
3481 * Go through port-forwardings, and close any associated
3482 * listening sockets.
3484 if (ssh->portfwds) {
3485 struct ssh_portfwd *pf;
3486 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3487 /* Dispose of any listening socket. */
3489 pfl_terminate(pf->local);
3490 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3493 freetree234(ssh->portfwds);
3494 ssh->portfwds = NULL;
3498 * Also stop attempting to connection-share.
3500 if (ssh->connshare) {
3501 sharestate_free(ssh->connshare);
3502 ssh->connshare = NULL;
3508 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3509 const char *error_msg, int error_code)
3511 Ssh ssh = (Ssh) plug;
3514 * While we're attempting connection sharing, don't loudly log
3515 * everything that happens. Real TCP connections need to be logged
3516 * when we _start_ trying to connect, because it might be ages
3517 * before they respond if something goes wrong; but connection
3518 * sharing is local and quick to respond, and it's sufficient to
3519 * simply wait and see whether it worked afterwards.
3522 if (!ssh->attempting_connshare)
3523 backend_socket_log(ssh->frontend, type, addr, port,
3524 error_msg, error_code, ssh->conf,
3525 ssh->session_started);
3528 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3529 const char *ds_err, const char *us_err)
3531 if (event == SHARE_NONE) {
3532 /* In this case, 'logtext' is an error message indicating a
3533 * reason why connection sharing couldn't be set up _at all_.
3534 * Failing that, ds_err and us_err indicate why we couldn't be
3535 * a downstream and an upstream respectively. */
3537 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3540 logeventf(ssh, "Could not set up connection sharing"
3541 " as downstream: %s", ds_err);
3543 logeventf(ssh, "Could not set up connection sharing"
3544 " as upstream: %s", us_err);
3546 } else if (event == SHARE_DOWNSTREAM) {
3547 /* In this case, 'logtext' is a local endpoint address */
3548 logeventf(ssh, "Using existing shared connection at %s", logtext);
3549 /* Also we should mention this in the console window to avoid
3550 * confusing users as to why this window doesn't behave the
3552 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3553 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3555 } else if (event == SHARE_UPSTREAM) {
3556 /* In this case, 'logtext' is a local endpoint address too */
3557 logeventf(ssh, "Sharing this connection at %s", logtext);
3561 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3564 Ssh ssh = (Ssh) plug;
3565 int need_notify = ssh_do_close(ssh, FALSE);
3568 if (!ssh->close_expected)
3569 error_msg = "Server unexpectedly closed network connection";
3571 error_msg = "Server closed network connection";
3574 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3578 notify_remote_exit(ssh->frontend);
3581 logevent(error_msg);
3582 if (!ssh->close_expected || !ssh->clean_exit)
3583 connection_fatal(ssh->frontend, "%s", error_msg);
3587 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3589 Ssh ssh = (Ssh) plug;
3590 ssh_gotdata(ssh, (unsigned char *)data, len);
3591 if (ssh->state == SSH_STATE_CLOSED) {
3592 ssh_do_close(ssh, TRUE);
3598 static void ssh_sent(Plug plug, int bufsize)
3600 Ssh ssh = (Ssh) plug;
3602 * If the send backlog on the SSH socket itself clears, we
3603 * should unthrottle the whole world if it was throttled.
3605 if (bufsize < SSH_MAX_BACKLOG)
3606 ssh_throttle_all(ssh, 0, bufsize);
3609 static void ssh_hostport_setup(const char *host, int port, Conf *conf,
3610 char **savedhost, int *savedport,
3613 char *loghost = conf_get_str(conf, CONF_loghost);
3615 *loghost_ret = loghost;
3621 tmphost = dupstr(loghost);
3622 *savedport = 22; /* default ssh port */
3625 * A colon suffix on the hostname string also lets us affect
3626 * savedport. (Unless there are multiple colons, in which case
3627 * we assume this is an unbracketed IPv6 literal.)
3629 colon = host_strrchr(tmphost, ':');
3630 if (colon && colon == host_strchr(tmphost, ':')) {
3633 *savedport = atoi(colon);
3636 *savedhost = host_strduptrim(tmphost);
3639 *savedhost = host_strduptrim(host);
3641 port = 22; /* default ssh port */
3646 static int ssh_test_for_upstream(const char *host, int port, Conf *conf)
3652 random_ref(); /* platform may need this to determine share socket name */
3653 ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
3654 ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
3662 * Connect to specified host and port.
3663 * Returns an error message, or NULL on success.
3664 * Also places the canonical host name into `realhost'. It must be
3665 * freed by the caller.
3667 static const char *connect_to_host(Ssh ssh, const char *host, int port,
3668 char **realhost, int nodelay, int keepalive)
3670 static const struct plug_function_table fn_table = {
3681 int addressfamily, sshprot;
3683 ssh_hostport_setup(host, port, ssh->conf,
3684 &ssh->savedhost, &ssh->savedport, &loghost);
3686 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3689 * Try connection-sharing, in case that means we don't open a
3690 * socket after all. ssh_connection_sharing_init will connect to a
3691 * previously established upstream if it can, and failing that,
3692 * establish a listening socket for _us_ to be the upstream. In
3693 * the latter case it will return NULL just as if it had done
3694 * nothing, because here we only need to care if we're a
3695 * downstream and need to do our connection setup differently.
3697 ssh->connshare = NULL;
3698 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3699 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3700 ssh->conf, ssh, &ssh->connshare);
3701 ssh->attempting_connshare = FALSE;
3702 if (ssh->s != NULL) {
3704 * We are a downstream.
3706 ssh->bare_connection = TRUE;
3707 ssh->do_ssh_init = do_ssh_connection_init;
3708 ssh->fullhostname = NULL;
3709 *realhost = dupstr(host); /* best we can do */
3712 * We're not a downstream, so open a normal socket.
3714 ssh->do_ssh_init = do_ssh_init;
3719 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3720 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
3721 ssh->frontend, "SSH connection");
3722 if ((err = sk_addr_error(addr)) != NULL) {
3726 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3728 ssh->s = new_connection(addr, *realhost, port,
3729 0, 1, nodelay, keepalive,
3730 (Plug) ssh, ssh->conf);
3731 if ((err = sk_socket_error(ssh->s)) != NULL) {
3733 notify_remote_exit(ssh->frontend);
3739 * The SSH version number is always fixed (since we no longer support
3740 * fallback between versions), so set it now, and if it's SSH-2,
3741 * send the version string now too.
3743 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3744 assert(sshprot == 0 || sshprot == 3);
3748 if (sshprot == 3 && !ssh->bare_connection) {
3751 ssh_send_verstring(ssh, "SSH-", NULL);
3755 * loghost, if configured, overrides realhost.
3759 *realhost = dupstr(loghost);
3766 * Throttle or unthrottle the SSH connection.
3768 static void ssh_throttle_conn(Ssh ssh, int adjust)
3770 int old_count = ssh->conn_throttle_count;
3771 ssh->conn_throttle_count += adjust;
3772 assert(ssh->conn_throttle_count >= 0);
3773 if (ssh->conn_throttle_count && !old_count) {
3774 ssh_set_frozen(ssh, 1);
3775 } else if (!ssh->conn_throttle_count && old_count) {
3776 ssh_set_frozen(ssh, 0);
3781 * Throttle or unthrottle _all_ local data streams (for when sends
3782 * on the SSH connection itself back up).
3784 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3787 struct ssh_channel *c;
3789 if (enable == ssh->throttled_all)
3791 ssh->throttled_all = enable;
3792 ssh->overall_bufsize = bufsize;
3795 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3797 case CHAN_MAINSESSION:
3799 * This is treated separately, outside the switch.
3803 x11_override_throttle(c->u.x11.xconn, enable);
3806 /* Agent channels require no buffer management. */
3809 pfd_override_throttle(c->u.pfd.pf, enable);
3815 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3817 Ssh ssh = (Ssh) sshv;
3819 ssh->agent_response = reply;
3820 ssh->agent_response_len = replylen;
3822 if (ssh->version == 1)
3823 do_ssh1_login(ssh, NULL, -1, NULL);
3825 do_ssh2_authconn(ssh, NULL, -1, NULL);
3828 static void ssh_dialog_callback(void *sshv, int ret)
3830 Ssh ssh = (Ssh) sshv;
3832 ssh->user_response = ret;
3834 if (ssh->version == 1)
3835 do_ssh1_login(ssh, NULL, -1, NULL);
3837 do_ssh2_transport(ssh, NULL, -1, NULL);
3840 * This may have unfrozen the SSH connection, so do a
3843 ssh_process_queued_incoming_data(ssh);
3846 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3848 struct ssh_channel *c = (struct ssh_channel *)cv;
3849 const void *sentreply = reply;
3851 c->u.a.outstanding_requests--;
3853 /* Fake SSH_AGENT_FAILURE. */
3854 sentreply = "\0\0\0\1\5";
3857 ssh_send_channel_data(c, sentreply, replylen);
3861 * If we've already seen an incoming EOF but haven't sent an
3862 * outgoing one, this may be the moment to send it.
3864 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3865 sshfwd_write_eof(c);
3869 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3870 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3871 * => log `wire_reason'.
3873 static void ssh_disconnect(Ssh ssh, const char *client_reason,
3874 const char *wire_reason,
3875 int code, int clean_exit)
3879 client_reason = wire_reason;
3881 error = dupprintf("Disconnected: %s", client_reason);
3883 error = dupstr("Disconnected");
3885 if (ssh->version == 1) {
3886 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3888 } else if (ssh->version == 2) {
3889 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3890 ssh2_pkt_adduint32(pktout, code);
3891 ssh2_pkt_addstring(pktout, wire_reason);
3892 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3893 ssh2_pkt_send_noqueue(ssh, pktout);
3896 ssh->close_expected = TRUE;
3897 ssh->clean_exit = clean_exit;
3898 ssh_closing((Plug)ssh, error, 0, 0);
3902 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3903 const struct ssh_signkey *ssh2keytype,
3906 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3907 return -1; /* no manual keys configured */
3912 * The fingerprint string we've been given will have things
3913 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3914 * narrow down to just the colon-separated hex block at the
3915 * end of the string.
3917 const char *p = strrchr(fingerprint, ' ');
3918 fingerprint = p ? p+1 : fingerprint;
3919 /* Quick sanity checks, including making sure it's in lowercase */
3920 assert(strlen(fingerprint) == 16*3 - 1);
3921 assert(fingerprint[2] == ':');
3922 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3924 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3926 return 1; /* success */
3931 * Construct the base64-encoded public key blob and see if
3934 unsigned char *binblob;
3936 int binlen, atoms, i;
3937 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3938 atoms = (binlen + 2) / 3;
3939 base64blob = snewn(atoms * 4 + 1, char);
3940 for (i = 0; i < atoms; i++)
3941 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3942 base64blob[atoms * 4] = '\0';
3944 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3947 return 1; /* success */
3956 * Handle the key exchange and user authentication phases.
3958 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
3959 struct Packet *pktin)
3962 unsigned char cookie[8], *ptr;
3963 struct MD5Context md5c;
3964 struct do_ssh1_login_state {
3967 unsigned char *rsabuf;
3968 const unsigned char *keystr1, *keystr2;
3969 unsigned long supported_ciphers_mask, supported_auths_mask;
3970 int tried_publickey, tried_agent;
3971 int tis_auth_refused, ccard_auth_refused;
3972 unsigned char session_id[16];
3974 void *publickey_blob;
3975 int publickey_bloblen;
3976 char *publickey_comment;
3977 int privatekey_available, privatekey_encrypted;
3978 prompts_t *cur_prompt;
3981 unsigned char request[5], *response, *p;
3991 struct RSAKey servkey, hostkey;
3993 crState(do_ssh1_login_state);
4000 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
4001 bombout(("Public key packet not received"));
4005 logevent("Received public keys");
4007 ptr = ssh_pkt_getdata(pktin, 8);
4009 bombout(("SSH-1 public key packet stopped before random cookie"));
4012 memcpy(cookie, ptr, 8);
4014 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
4015 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
4016 bombout(("Failed to read SSH-1 public keys from public key packet"));
4021 * Log the host key fingerprint.
4025 logevent("Host key fingerprint is:");
4026 strcpy(logmsg, " ");
4027 s->hostkey.comment = NULL;
4028 rsa_fingerprint(logmsg + strlen(logmsg),
4029 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
4033 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
4034 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
4035 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
4036 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
4037 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
4039 ssh->v1_local_protoflags =
4040 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
4041 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
4044 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
4045 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
4046 MD5Update(&md5c, cookie, 8);
4047 MD5Final(s->session_id, &md5c);
4049 for (i = 0; i < 32; i++)
4050 ssh->session_key[i] = random_byte();
4053 * Verify that the `bits' and `bytes' parameters match.
4055 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
4056 s->servkey.bits > s->servkey.bytes * 8) {
4057 bombout(("SSH-1 public keys were badly formatted"));
4061 s->len = (s->hostkey.bytes > s->servkey.bytes ?
4062 s->hostkey.bytes : s->servkey.bytes);
4064 s->rsabuf = snewn(s->len, unsigned char);
4067 * Verify the host key.
4071 * First format the key into a string.
4073 int len = rsastr_len(&s->hostkey);
4074 char fingerprint[100];
4075 char *keystr = snewn(len, char);
4076 rsastr_fmt(keystr, &s->hostkey);
4077 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
4079 /* First check against manually configured host keys. */
4080 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
4081 if (s->dlgret == 0) { /* did not match */
4082 bombout(("Host key did not appear in manually configured list"));
4085 } else if (s->dlgret < 0) { /* none configured; use standard handling */
4086 ssh_set_frozen(ssh, 1);
4087 s->dlgret = verify_ssh_host_key(ssh->frontend,
4088 ssh->savedhost, ssh->savedport,
4089 "rsa", keystr, fingerprint,
4090 ssh_dialog_callback, ssh);
4095 if (s->dlgret < 0) {
4099 bombout(("Unexpected data from server while waiting"
4100 " for user host key response"));
4103 } while (pktin || inlen > 0);
4104 s->dlgret = ssh->user_response;
4106 ssh_set_frozen(ssh, 0);
4108 if (s->dlgret == 0) {
4109 ssh_disconnect(ssh, "User aborted at host key verification",
4118 for (i = 0; i < 32; i++) {
4119 s->rsabuf[i] = ssh->session_key[i];
4121 s->rsabuf[i] ^= s->session_id[i];
4124 if (s->hostkey.bytes > s->servkey.bytes) {
4125 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4127 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4129 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4131 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4134 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4138 logevent("Encrypted session key");
4141 int cipher_chosen = 0, warn = 0;
4142 const char *cipher_string = NULL;
4144 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4145 int next_cipher = conf_get_int_int(ssh->conf,
4146 CONF_ssh_cipherlist, i);
4147 if (next_cipher == CIPHER_WARN) {
4148 /* If/when we choose a cipher, warn about it */
4150 } else if (next_cipher == CIPHER_AES) {
4151 /* XXX Probably don't need to mention this. */
4152 logevent("AES not supported in SSH-1, skipping");
4154 switch (next_cipher) {
4155 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
4156 cipher_string = "3DES"; break;
4157 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4158 cipher_string = "Blowfish"; break;
4159 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
4160 cipher_string = "single-DES"; break;
4162 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4166 if (!cipher_chosen) {
4167 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4168 bombout(("Server violates SSH-1 protocol by not "
4169 "supporting 3DES encryption"));
4171 /* shouldn't happen */
4172 bombout(("No supported ciphers found"));
4176 /* Warn about chosen cipher if necessary. */
4178 ssh_set_frozen(ssh, 1);
4179 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4180 ssh_dialog_callback, ssh);
4181 if (s->dlgret < 0) {
4185 bombout(("Unexpected data from server while waiting"
4186 " for user response"));
4189 } while (pktin || inlen > 0);
4190 s->dlgret = ssh->user_response;
4192 ssh_set_frozen(ssh, 0);
4193 if (s->dlgret == 0) {
4194 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4201 switch (s->cipher_type) {
4202 case SSH_CIPHER_3DES:
4203 logevent("Using 3DES encryption");
4205 case SSH_CIPHER_DES:
4206 logevent("Using single-DES encryption");
4208 case SSH_CIPHER_BLOWFISH:
4209 logevent("Using Blowfish encryption");
4213 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4214 PKT_CHAR, s->cipher_type,
4215 PKT_DATA, cookie, 8,
4216 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4217 PKT_DATA, s->rsabuf, s->len,
4218 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4220 logevent("Trying to enable encryption...");
4224 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4225 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4227 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4228 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4229 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4231 ssh->crcda_ctx = crcda_make_context();
4232 logevent("Installing CRC compensation attack detector");
4234 if (s->servkey.modulus) {
4235 sfree(s->servkey.modulus);
4236 s->servkey.modulus = NULL;
4238 if (s->servkey.exponent) {
4239 sfree(s->servkey.exponent);
4240 s->servkey.exponent = NULL;
4242 if (s->hostkey.modulus) {
4243 sfree(s->hostkey.modulus);
4244 s->hostkey.modulus = NULL;
4246 if (s->hostkey.exponent) {
4247 sfree(s->hostkey.exponent);
4248 s->hostkey.exponent = NULL;
4252 if (pktin->type != SSH1_SMSG_SUCCESS) {
4253 bombout(("Encryption not successfully enabled"));
4257 logevent("Successfully started encryption");
4259 fflush(stdout); /* FIXME eh? */
4261 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4262 int ret; /* need not be kept over crReturn */
4263 s->cur_prompt = new_prompts(ssh->frontend);
4264 s->cur_prompt->to_server = TRUE;
4265 s->cur_prompt->name = dupstr("SSH login name");
4266 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4267 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4270 crWaitUntil(!pktin);
4271 ret = get_userpass_input(s->cur_prompt, in, inlen);
4276 * Failed to get a username. Terminate.
4278 free_prompts(s->cur_prompt);
4279 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4282 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4283 free_prompts(s->cur_prompt);
4286 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4288 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4290 if (flags & FLAG_INTERACTIVE &&
4291 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4292 c_write_str(ssh, userlog);
4293 c_write_str(ssh, "\r\n");
4301 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4302 /* We must not attempt PK auth. Pretend we've already tried it. */
4303 s->tried_publickey = s->tried_agent = 1;
4305 s->tried_publickey = s->tried_agent = 0;
4307 s->tis_auth_refused = s->ccard_auth_refused = 0;
4309 * Load the public half of any configured keyfile for later use.
4311 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4312 if (!filename_is_null(s->keyfile)) {
4314 logeventf(ssh, "Reading key file \"%.150s\"",
4315 filename_to_str(s->keyfile));
4316 keytype = key_type(s->keyfile);
4317 if (keytype == SSH_KEYTYPE_SSH1 ||
4318 keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
4320 if (rsakey_pubblob(s->keyfile,
4321 &s->publickey_blob, &s->publickey_bloblen,
4322 &s->publickey_comment, &error)) {
4323 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
4324 if (!s->privatekey_available)
4325 logeventf(ssh, "Key file contains public key only");
4326 s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
4330 logeventf(ssh, "Unable to load key (%s)", error);
4331 msgbuf = dupprintf("Unable to load key file "
4332 "\"%.150s\" (%s)\r\n",
4333 filename_to_str(s->keyfile),
4335 c_write_str(ssh, msgbuf);
4337 s->publickey_blob = NULL;
4341 logeventf(ssh, "Unable to use this key file (%s)",
4342 key_type_to_str(keytype));
4343 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4345 filename_to_str(s->keyfile),
4346 key_type_to_str(keytype));
4347 c_write_str(ssh, msgbuf);
4349 s->publickey_blob = NULL;
4352 s->publickey_blob = NULL;
4354 while (pktin->type == SSH1_SMSG_FAILURE) {
4355 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4357 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4359 * Attempt RSA authentication using Pageant.
4365 logevent("Pageant is running. Requesting keys.");
4367 /* Request the keys held by the agent. */
4368 PUT_32BIT(s->request, 1);
4369 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4370 if (!agent_query(s->request, 5, &r, &s->responselen,
4371 ssh_agent_callback, ssh)) {
4375 bombout(("Unexpected data from server while waiting"
4376 " for agent response"));
4379 } while (pktin || inlen > 0);
4380 r = ssh->agent_response;
4381 s->responselen = ssh->agent_response_len;
4383 s->response = (unsigned char *) r;
4384 if (s->response && s->responselen >= 5 &&
4385 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4386 s->p = s->response + 5;
4387 s->nkeys = toint(GET_32BIT(s->p));
4389 logeventf(ssh, "Pageant reported negative key count %d",
4394 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4395 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4396 unsigned char *pkblob = s->p;
4400 do { /* do while (0) to make breaking easy */
4401 n = ssh1_read_bignum
4402 (s->p, toint(s->responselen-(s->p-s->response)),
4407 n = ssh1_read_bignum
4408 (s->p, toint(s->responselen-(s->p-s->response)),
4413 if (s->responselen - (s->p-s->response) < 4)
4415 s->commentlen = toint(GET_32BIT(s->p));
4417 if (s->commentlen < 0 ||
4418 toint(s->responselen - (s->p-s->response)) <
4421 s->commentp = (char *)s->p;
4422 s->p += s->commentlen;
4426 logevent("Pageant key list packet was truncated");
4430 if (s->publickey_blob) {
4431 if (!memcmp(pkblob, s->publickey_blob,
4432 s->publickey_bloblen)) {
4433 logeventf(ssh, "Pageant key #%d matches "
4434 "configured key file", s->keyi);
4435 s->tried_publickey = 1;
4437 /* Skip non-configured key */
4440 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4441 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4442 PKT_BIGNUM, s->key.modulus, PKT_END);
4444 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4445 logevent("Key refused");
4448 logevent("Received RSA challenge");
4449 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4450 bombout(("Server's RSA challenge was badly formatted"));
4455 char *agentreq, *q, *ret;
4458 len = 1 + 4; /* message type, bit count */
4459 len += ssh1_bignum_length(s->key.exponent);
4460 len += ssh1_bignum_length(s->key.modulus);
4461 len += ssh1_bignum_length(s->challenge);
4462 len += 16; /* session id */
4463 len += 4; /* response format */
4464 agentreq = snewn(4 + len, char);
4465 PUT_32BIT(agentreq, len);
4467 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4468 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4470 q += ssh1_write_bignum(q, s->key.exponent);
4471 q += ssh1_write_bignum(q, s->key.modulus);
4472 q += ssh1_write_bignum(q, s->challenge);
4473 memcpy(q, s->session_id, 16);
4475 PUT_32BIT(q, 1); /* response format */
4476 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4477 ssh_agent_callback, ssh)) {
4482 bombout(("Unexpected data from server"
4483 " while waiting for agent"
4487 } while (pktin || inlen > 0);
4488 vret = ssh->agent_response;
4489 retlen = ssh->agent_response_len;
4494 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4495 logevent("Sending Pageant's response");
4496 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4497 PKT_DATA, ret + 5, 16,
4501 if (pktin->type == SSH1_SMSG_SUCCESS) {
4503 ("Pageant's response accepted");
4504 if (flags & FLAG_VERBOSE) {
4505 c_write_str(ssh, "Authenticated using"
4507 c_write(ssh, s->commentp,
4509 c_write_str(ssh, "\" from agent\r\n");
4514 ("Pageant's response not accepted");
4517 ("Pageant failed to answer challenge");
4521 logevent("No reply received from Pageant");
4524 freebn(s->key.exponent);
4525 freebn(s->key.modulus);
4526 freebn(s->challenge);
4531 if (s->publickey_blob && !s->tried_publickey)
4532 logevent("Configured key file not in Pageant");
4534 logevent("Failed to get reply from Pageant");
4539 if (s->publickey_blob && s->privatekey_available &&
4540 !s->tried_publickey) {
4542 * Try public key authentication with the specified
4545 int got_passphrase; /* need not be kept over crReturn */
4546 if (flags & FLAG_VERBOSE)
4547 c_write_str(ssh, "Trying public key authentication.\r\n");
4548 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4549 logeventf(ssh, "Trying public key \"%s\"",
4550 filename_to_str(s->keyfile));
4551 s->tried_publickey = 1;
4552 got_passphrase = FALSE;
4553 while (!got_passphrase) {
4555 * Get a passphrase, if necessary.
4557 char *passphrase = NULL; /* only written after crReturn */
4559 if (!s->privatekey_encrypted) {
4560 if (flags & FLAG_VERBOSE)
4561 c_write_str(ssh, "No passphrase required.\r\n");
4564 int ret; /* need not be kept over crReturn */
4565 s->cur_prompt = new_prompts(ssh->frontend);
4566 s->cur_prompt->to_server = FALSE;
4567 s->cur_prompt->name = dupstr("SSH key passphrase");
4568 add_prompt(s->cur_prompt,
4569 dupprintf("Passphrase for key \"%.100s\": ",
4570 s->publickey_comment), FALSE);
4571 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4574 crWaitUntil(!pktin);
4575 ret = get_userpass_input(s->cur_prompt, in, inlen);
4579 /* Failed to get a passphrase. Terminate. */
4580 free_prompts(s->cur_prompt);
4581 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4585 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4586 free_prompts(s->cur_prompt);
4589 * Try decrypting key with passphrase.
4591 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4592 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4595 smemclr(passphrase, strlen(passphrase));
4599 /* Correct passphrase. */
4600 got_passphrase = TRUE;
4601 } else if (ret == 0) {
4602 c_write_str(ssh, "Couldn't load private key from ");
4603 c_write_str(ssh, filename_to_str(s->keyfile));
4604 c_write_str(ssh, " (");
4605 c_write_str(ssh, error);
4606 c_write_str(ssh, ").\r\n");
4607 got_passphrase = FALSE;
4608 break; /* go and try something else */
4609 } else if (ret == -1) {
4610 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4611 got_passphrase = FALSE;
4614 assert(0 && "unexpected return from loadrsakey()");
4615 got_passphrase = FALSE; /* placate optimisers */
4619 if (got_passphrase) {
4622 * Send a public key attempt.
4624 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4625 PKT_BIGNUM, s->key.modulus, PKT_END);
4628 if (pktin->type == SSH1_SMSG_FAILURE) {
4629 c_write_str(ssh, "Server refused our public key.\r\n");
4630 continue; /* go and try something else */
4632 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4633 bombout(("Bizarre response to offer of public key"));
4639 unsigned char buffer[32];
4640 Bignum challenge, response;
4642 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4643 bombout(("Server's RSA challenge was badly formatted"));
4646 response = rsadecrypt(challenge, &s->key);
4647 freebn(s->key.private_exponent);/* burn the evidence */
4649 for (i = 0; i < 32; i++) {
4650 buffer[i] = bignum_byte(response, 31 - i);
4654 MD5Update(&md5c, buffer, 32);
4655 MD5Update(&md5c, s->session_id, 16);
4656 MD5Final(buffer, &md5c);
4658 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4659 PKT_DATA, buffer, 16, PKT_END);
4666 if (pktin->type == SSH1_SMSG_FAILURE) {
4667 if (flags & FLAG_VERBOSE)
4668 c_write_str(ssh, "Failed to authenticate with"
4669 " our public key.\r\n");
4670 continue; /* go and try something else */
4671 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4672 bombout(("Bizarre response to RSA authentication response"));
4676 break; /* we're through! */
4682 * Otherwise, try various forms of password-like authentication.
4684 s->cur_prompt = new_prompts(ssh->frontend);
4686 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4687 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4688 !s->tis_auth_refused) {
4689 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4690 logevent("Requested TIS authentication");
4691 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4693 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4694 logevent("TIS authentication declined");
4695 if (flags & FLAG_INTERACTIVE)
4696 c_write_str(ssh, "TIS authentication refused.\r\n");
4697 s->tis_auth_refused = 1;
4702 char *instr_suf, *prompt;
4704 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4706 bombout(("TIS challenge packet was badly formed"));
4709 logevent("Received TIS challenge");
4710 s->cur_prompt->to_server = TRUE;
4711 s->cur_prompt->name = dupstr("SSH TIS authentication");
4712 /* Prompt heuristic comes from OpenSSH */
4713 if (memchr(challenge, '\n', challengelen)) {
4714 instr_suf = dupstr("");
4715 prompt = dupprintf("%.*s", challengelen, challenge);
4717 instr_suf = dupprintf("%.*s", challengelen, challenge);
4718 prompt = dupstr("Response: ");
4720 s->cur_prompt->instruction =
4721 dupprintf("Using TIS authentication.%s%s",
4722 (*instr_suf) ? "\n" : "",
4724 s->cur_prompt->instr_reqd = TRUE;
4725 add_prompt(s->cur_prompt, prompt, FALSE);
4729 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4730 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4731 !s->ccard_auth_refused) {
4732 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4733 logevent("Requested CryptoCard authentication");
4734 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4736 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4737 logevent("CryptoCard authentication declined");
4738 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4739 s->ccard_auth_refused = 1;
4744 char *instr_suf, *prompt;
4746 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4748 bombout(("CryptoCard challenge packet was badly formed"));
4751 logevent("Received CryptoCard challenge");
4752 s->cur_prompt->to_server = TRUE;
4753 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4754 s->cur_prompt->name_reqd = FALSE;
4755 /* Prompt heuristic comes from OpenSSH */
4756 if (memchr(challenge, '\n', challengelen)) {
4757 instr_suf = dupstr("");
4758 prompt = dupprintf("%.*s", challengelen, challenge);
4760 instr_suf = dupprintf("%.*s", challengelen, challenge);
4761 prompt = dupstr("Response: ");
4763 s->cur_prompt->instruction =
4764 dupprintf("Using CryptoCard authentication.%s%s",
4765 (*instr_suf) ? "\n" : "",
4767 s->cur_prompt->instr_reqd = TRUE;
4768 add_prompt(s->cur_prompt, prompt, FALSE);
4772 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4773 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4774 bombout(("No supported authentication methods available"));
4777 s->cur_prompt->to_server = TRUE;
4778 s->cur_prompt->name = dupstr("SSH password");
4779 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4780 ssh->username, ssh->savedhost),
4785 * Show password prompt, having first obtained it via a TIS
4786 * or CryptoCard exchange if we're doing TIS or CryptoCard
4790 int ret; /* need not be kept over crReturn */
4791 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4794 crWaitUntil(!pktin);
4795 ret = get_userpass_input(s->cur_prompt, in, inlen);
4800 * Failed to get a password (for example
4801 * because one was supplied on the command line
4802 * which has already failed to work). Terminate.
4804 free_prompts(s->cur_prompt);
4805 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4810 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4812 * Defence against traffic analysis: we send a
4813 * whole bunch of packets containing strings of
4814 * different lengths. One of these strings is the
4815 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4816 * The others are all random data in
4817 * SSH1_MSG_IGNORE packets. This way a passive
4818 * listener can't tell which is the password, and
4819 * hence can't deduce the password length.
4821 * Anybody with a password length greater than 16
4822 * bytes is going to have enough entropy in their
4823 * password that a listener won't find it _that_
4824 * much help to know how long it is. So what we'll
4827 * - if password length < 16, we send 15 packets
4828 * containing string lengths 1 through 15
4830 * - otherwise, we let N be the nearest multiple
4831 * of 8 below the password length, and send 8
4832 * packets containing string lengths N through
4833 * N+7. This won't obscure the order of
4834 * magnitude of the password length, but it will
4835 * introduce a bit of extra uncertainty.
4837 * A few servers can't deal with SSH1_MSG_IGNORE, at
4838 * least in this context. For these servers, we need
4839 * an alternative defence. We make use of the fact
4840 * that the password is interpreted as a C string:
4841 * so we can append a NUL, then some random data.
4843 * A few servers can deal with neither SSH1_MSG_IGNORE
4844 * here _nor_ a padded password string.
4845 * For these servers we are left with no defences
4846 * against password length sniffing.
4848 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4849 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4851 * The server can deal with SSH1_MSG_IGNORE, so
4852 * we can use the primary defence.
4854 int bottom, top, pwlen, i;
4857 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4859 bottom = 0; /* zero length passwords are OK! :-) */
4862 bottom = pwlen & ~7;
4866 assert(pwlen >= bottom && pwlen <= top);
4868 randomstr = snewn(top + 1, char);
4870 for (i = bottom; i <= top; i++) {
4872 defer_packet(ssh, s->pwpkt_type,
4873 PKT_STR,s->cur_prompt->prompts[0]->result,
4876 for (j = 0; j < i; j++) {
4878 randomstr[j] = random_byte();
4879 } while (randomstr[j] == '\0');
4881 randomstr[i] = '\0';
4882 defer_packet(ssh, SSH1_MSG_IGNORE,
4883 PKT_STR, randomstr, PKT_END);
4886 logevent("Sending password with camouflage packets");
4887 ssh_pkt_defersend(ssh);
4890 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4892 * The server can't deal with SSH1_MSG_IGNORE
4893 * but can deal with padded passwords, so we
4894 * can use the secondary defence.
4900 len = strlen(s->cur_prompt->prompts[0]->result);
4901 if (len < sizeof(string)) {
4903 strcpy(string, s->cur_prompt->prompts[0]->result);
4904 len++; /* cover the zero byte */
4905 while (len < sizeof(string)) {
4906 string[len++] = (char) random_byte();
4909 ss = s->cur_prompt->prompts[0]->result;
4911 logevent("Sending length-padded password");
4912 send_packet(ssh, s->pwpkt_type,
4913 PKT_INT, len, PKT_DATA, ss, len,
4917 * The server is believed unable to cope with
4918 * any of our password camouflage methods.
4921 len = strlen(s->cur_prompt->prompts[0]->result);
4922 logevent("Sending unpadded password");
4923 send_packet(ssh, s->pwpkt_type,
4925 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4929 send_packet(ssh, s->pwpkt_type,
4930 PKT_STR, s->cur_prompt->prompts[0]->result,
4933 logevent("Sent password");
4934 free_prompts(s->cur_prompt);
4936 if (pktin->type == SSH1_SMSG_FAILURE) {
4937 if (flags & FLAG_VERBOSE)
4938 c_write_str(ssh, "Access denied\r\n");
4939 logevent("Authentication refused");
4940 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4941 bombout(("Strange packet received, type %d", pktin->type));
4947 if (s->publickey_blob) {
4948 sfree(s->publickey_blob);
4949 sfree(s->publickey_comment);
4952 logevent("Authentication successful");
4957 static void ssh_channel_try_eof(struct ssh_channel *c)
4960 assert(c->pending_eof); /* precondition for calling us */
4962 return; /* can't close: not even opened yet */
4963 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4964 return; /* can't send EOF: pending outgoing data */
4966 c->pending_eof = FALSE; /* we're about to send it */
4967 if (ssh->version == 1) {
4968 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4970 c->closes |= CLOSES_SENT_EOF;
4972 struct Packet *pktout;
4973 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4974 ssh2_pkt_adduint32(pktout, c->remoteid);
4975 ssh2_pkt_send(ssh, pktout);
4976 c->closes |= CLOSES_SENT_EOF;
4977 ssh2_channel_check_close(c);
4981 Conf *sshfwd_get_conf(struct ssh_channel *c)
4987 void sshfwd_write_eof(struct ssh_channel *c)
4991 if (ssh->state == SSH_STATE_CLOSED)
4994 if (c->closes & CLOSES_SENT_EOF)
4997 c->pending_eof = TRUE;
4998 ssh_channel_try_eof(c);
5001 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
5005 if (ssh->state == SSH_STATE_CLOSED)
5010 x11_close(c->u.x11.xconn);
5011 logeventf(ssh, "Forwarded X11 connection terminated due to local "
5015 pfd_close(c->u.pfd.pf);
5016 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
5019 c->type = CHAN_ZOMBIE;
5020 c->pending_eof = FALSE; /* this will confuse a zombie channel */
5022 ssh2_channel_check_close(c);
5025 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
5029 if (ssh->state == SSH_STATE_CLOSED)
5032 return ssh_send_channel_data(c, buf, len);
5035 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
5039 if (ssh->state == SSH_STATE_CLOSED)
5042 ssh_channel_unthrottle(c, bufsize);
5045 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
5047 struct queued_handler *qh = ssh->qhead;
5051 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
5054 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
5055 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
5058 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
5059 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
5063 ssh->qhead = qh->next;
5065 if (ssh->qhead->msg1 > 0) {
5066 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5067 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
5069 if (ssh->qhead->msg2 > 0) {
5070 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5071 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
5074 ssh->qhead = ssh->qtail = NULL;
5077 qh->handler(ssh, pktin, qh->ctx);
5082 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5083 chandler_fn_t handler, void *ctx)
5085 struct queued_handler *qh;
5087 qh = snew(struct queued_handler);
5090 qh->handler = handler;
5094 if (ssh->qtail == NULL) {
5098 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5099 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5102 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5103 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5106 ssh->qtail->next = qh;
5111 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5113 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5115 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5116 SSH2_MSG_REQUEST_SUCCESS)) {
5117 logeventf(ssh, "Remote port forwarding from %s enabled",
5120 logeventf(ssh, "Remote port forwarding from %s refused",
5123 rpf = del234(ssh->rportfwds, pf);
5125 pf->pfrec->remote = NULL;
5130 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5133 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5136 pf->share_ctx = share_ctx;
5137 pf->shost = dupstr(shost);
5139 pf->sportdesc = NULL;
5140 if (!ssh->rportfwds) {
5141 assert(ssh->version == 2);
5142 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5144 if (add234(ssh->rportfwds, pf) != pf) {
5152 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5155 share_got_pkt_from_server(ctx, pktin->type,
5156 pktin->body, pktin->length);
5159 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5161 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5162 ssh_sharing_global_request_response, share_ctx);
5165 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5167 struct ssh_portfwd *epf;
5171 if (!ssh->portfwds) {
5172 ssh->portfwds = newtree234(ssh_portcmp);
5175 * Go through the existing port forwardings and tag them
5176 * with status==DESTROY. Any that we want to keep will be
5177 * re-enabled (status==KEEP) as we go through the
5178 * configuration and find out which bits are the same as
5181 struct ssh_portfwd *epf;
5183 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5184 epf->status = DESTROY;
5187 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5189 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5190 char *kp, *kp2, *vp, *vp2;
5191 char address_family, type;
5192 int sport,dport,sserv,dserv;
5193 char *sports, *dports, *saddr, *host;
5197 address_family = 'A';
5199 if (*kp == 'A' || *kp == '4' || *kp == '6')
5200 address_family = *kp++;
5201 if (*kp == 'L' || *kp == 'R')
5204 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5206 * There's a colon in the middle of the source port
5207 * string, which means that the part before it is
5208 * actually a source address.
5210 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5211 saddr = host_strduptrim(saddr_tmp);
5218 sport = atoi(sports);
5222 sport = net_service_lookup(sports);
5224 logeventf(ssh, "Service lookup failed for source"
5225 " port \"%s\"", sports);
5229 if (type == 'L' && !strcmp(val, "D")) {
5230 /* dynamic forwarding */
5237 /* ordinary forwarding */
5239 vp2 = vp + host_strcspn(vp, ":");
5240 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5244 dport = atoi(dports);
5248 dport = net_service_lookup(dports);
5250 logeventf(ssh, "Service lookup failed for destination"
5251 " port \"%s\"", dports);
5256 if (sport && dport) {
5257 /* Set up a description of the source port. */
5258 struct ssh_portfwd *pfrec, *epfrec;
5260 pfrec = snew(struct ssh_portfwd);
5262 pfrec->saddr = saddr;
5263 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5264 pfrec->sport = sport;
5265 pfrec->daddr = host;
5266 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5267 pfrec->dport = dport;
5268 pfrec->local = NULL;
5269 pfrec->remote = NULL;
5270 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5271 address_family == '6' ? ADDRTYPE_IPV6 :
5274 epfrec = add234(ssh->portfwds, pfrec);
5275 if (epfrec != pfrec) {
5276 if (epfrec->status == DESTROY) {
5278 * We already have a port forwarding up and running
5279 * with precisely these parameters. Hence, no need
5280 * to do anything; simply re-tag the existing one
5283 epfrec->status = KEEP;
5286 * Anything else indicates that there was a duplicate
5287 * in our input, which we'll silently ignore.
5289 free_portfwd(pfrec);
5291 pfrec->status = CREATE;
5300 * Now go through and destroy any port forwardings which were
5303 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5304 if (epf->status == DESTROY) {
5307 message = dupprintf("%s port forwarding from %s%s%d",
5308 epf->type == 'L' ? "local" :
5309 epf->type == 'R' ? "remote" : "dynamic",
5310 epf->saddr ? epf->saddr : "",
5311 epf->saddr ? ":" : "",
5314 if (epf->type != 'D') {
5315 char *msg2 = dupprintf("%s to %s:%d", message,
5316 epf->daddr, epf->dport);
5321 logeventf(ssh, "Cancelling %s", message);
5324 /* epf->remote or epf->local may be NULL if setting up a
5325 * forwarding failed. */
5327 struct ssh_rportfwd *rpf = epf->remote;
5328 struct Packet *pktout;
5331 * Cancel the port forwarding at the server
5334 if (ssh->version == 1) {
5336 * We cannot cancel listening ports on the
5337 * server side in SSH-1! There's no message
5338 * to support it. Instead, we simply remove
5339 * the rportfwd record from the local end
5340 * so that any connections the server tries
5341 * to make on it are rejected.
5344 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5345 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5346 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5348 ssh2_pkt_addstring(pktout, epf->saddr);
5349 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5350 /* XXX: rport_acceptall may not represent
5351 * what was used to open the original connection,
5352 * since it's reconfigurable. */
5353 ssh2_pkt_addstring(pktout, "");
5355 ssh2_pkt_addstring(pktout, "localhost");
5357 ssh2_pkt_adduint32(pktout, epf->sport);
5358 ssh2_pkt_send(ssh, pktout);
5361 del234(ssh->rportfwds, rpf);
5363 } else if (epf->local) {
5364 pfl_terminate(epf->local);
5367 delpos234(ssh->portfwds, i);
5369 i--; /* so we don't skip one in the list */
5373 * And finally, set up any new port forwardings (status==CREATE).
5375 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5376 if (epf->status == CREATE) {
5377 char *sportdesc, *dportdesc;
5378 sportdesc = dupprintf("%s%s%s%s%d%s",
5379 epf->saddr ? epf->saddr : "",
5380 epf->saddr ? ":" : "",
5381 epf->sserv ? epf->sserv : "",
5382 epf->sserv ? "(" : "",
5384 epf->sserv ? ")" : "");
5385 if (epf->type == 'D') {
5388 dportdesc = dupprintf("%s:%s%s%d%s",
5390 epf->dserv ? epf->dserv : "",
5391 epf->dserv ? "(" : "",
5393 epf->dserv ? ")" : "");
5396 if (epf->type == 'L') {
5397 char *err = pfl_listen(epf->daddr, epf->dport,
5398 epf->saddr, epf->sport,
5399 ssh, conf, &epf->local,
5400 epf->addressfamily);
5402 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5403 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5404 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5405 sportdesc, dportdesc,
5406 err ? " failed: " : "", err ? err : "");
5409 } else if (epf->type == 'D') {
5410 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5411 ssh, conf, &epf->local,
5412 epf->addressfamily);
5414 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5415 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5416 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5418 err ? " failed: " : "", err ? err : "");
5423 struct ssh_rportfwd *pf;
5426 * Ensure the remote port forwardings tree exists.
5428 if (!ssh->rportfwds) {
5429 if (ssh->version == 1)
5430 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5432 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5435 pf = snew(struct ssh_rportfwd);
5436 pf->share_ctx = NULL;
5437 pf->dhost = dupstr(epf->daddr);
5438 pf->dport = epf->dport;
5440 pf->shost = dupstr(epf->saddr);
5441 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5442 pf->shost = dupstr("");
5444 pf->shost = dupstr("localhost");
5446 pf->sport = epf->sport;
5447 if (add234(ssh->rportfwds, pf) != pf) {
5448 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5449 epf->daddr, epf->dport);
5452 logeventf(ssh, "Requesting remote port %s"
5453 " forward to %s", sportdesc, dportdesc);
5455 pf->sportdesc = sportdesc;
5460 if (ssh->version == 1) {
5461 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5462 PKT_INT, epf->sport,
5463 PKT_STR, epf->daddr,
5464 PKT_INT, epf->dport,
5466 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5468 ssh_rportfwd_succfail, pf);
5470 struct Packet *pktout;
5471 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5472 ssh2_pkt_addstring(pktout, "tcpip-forward");
5473 ssh2_pkt_addbool(pktout, 1);/* want reply */
5474 ssh2_pkt_addstring(pktout, pf->shost);
5475 ssh2_pkt_adduint32(pktout, pf->sport);
5476 ssh2_pkt_send(ssh, pktout);
5478 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5479 SSH2_MSG_REQUEST_FAILURE,
5480 ssh_rportfwd_succfail, pf);
5489 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5492 int stringlen, bufsize;
5494 ssh_pkt_getstring(pktin, &string, &stringlen);
5495 if (string == NULL) {
5496 bombout(("Incoming terminal data packet was badly formed"));
5500 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5502 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5503 ssh->v1_stdout_throttling = 1;
5504 ssh_throttle_conn(ssh, +1);
5508 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5510 /* Remote side is trying to open a channel to talk to our
5511 * X-Server. Give them back a local channel number. */
5512 struct ssh_channel *c;
5513 int remoteid = ssh_pkt_getuint32(pktin);
5515 logevent("Received X11 connect request");
5516 /* Refuse if X11 forwarding is disabled. */
5517 if (!ssh->X11_fwd_enabled) {
5518 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5519 PKT_INT, remoteid, PKT_END);
5520 logevent("Rejected X11 connect request");
5522 c = snew(struct ssh_channel);
5525 ssh_channel_init(c);
5526 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5527 c->remoteid = remoteid;
5528 c->halfopen = FALSE;
5529 c->type = CHAN_X11; /* identify channel type */
5530 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5531 PKT_INT, c->remoteid, PKT_INT,
5532 c->localid, PKT_END);
5533 logevent("Opened X11 forward channel");
5537 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5539 /* Remote side is trying to open a channel to talk to our
5540 * agent. Give them back a local channel number. */
5541 struct ssh_channel *c;
5542 int remoteid = ssh_pkt_getuint32(pktin);
5544 /* Refuse if agent forwarding is disabled. */
5545 if (!ssh->agentfwd_enabled) {
5546 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5547 PKT_INT, remoteid, PKT_END);
5549 c = snew(struct ssh_channel);
5551 ssh_channel_init(c);
5552 c->remoteid = remoteid;
5553 c->halfopen = FALSE;
5554 c->type = CHAN_AGENT; /* identify channel type */
5555 c->u.a.lensofar = 0;
5556 c->u.a.message = NULL;
5557 c->u.a.outstanding_requests = 0;
5558 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5559 PKT_INT, c->remoteid, PKT_INT, c->localid,
5564 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5566 /* Remote side is trying to open a channel to talk to a
5567 * forwarded port. Give them back a local channel number. */
5568 struct ssh_rportfwd pf, *pfp;
5574 remoteid = ssh_pkt_getuint32(pktin);
5575 ssh_pkt_getstring(pktin, &host, &hostsize);
5576 port = ssh_pkt_getuint32(pktin);
5578 pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host));
5580 pfp = find234(ssh->rportfwds, &pf, NULL);
5583 logeventf(ssh, "Rejected remote port open request for %s:%d",
5585 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5586 PKT_INT, remoteid, PKT_END);
5588 struct ssh_channel *c = snew(struct ssh_channel);
5591 logeventf(ssh, "Received remote port open request for %s:%d",
5593 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5594 c, ssh->conf, pfp->pfrec->addressfamily);
5596 logeventf(ssh, "Port open failed: %s", err);
5599 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5600 PKT_INT, remoteid, PKT_END);
5602 ssh_channel_init(c);
5603 c->remoteid = remoteid;
5604 c->halfopen = FALSE;
5605 c->type = CHAN_SOCKDATA; /* identify channel type */
5606 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5607 PKT_INT, c->remoteid, PKT_INT,
5608 c->localid, PKT_END);
5609 logevent("Forwarded port opened successfully");
5616 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5618 struct ssh_channel *c;
5620 c = ssh_channel_msg(ssh, pktin);
5621 if (c && c->type == CHAN_SOCKDATA) {
5622 c->remoteid = ssh_pkt_getuint32(pktin);
5623 c->halfopen = FALSE;
5624 c->throttling_conn = 0;
5625 pfd_confirm(c->u.pfd.pf);
5628 if (c && c->pending_eof) {
5630 * We have a pending close on this channel,
5631 * which we decided on before the server acked
5632 * the channel open. So now we know the
5633 * remoteid, we can close it again.
5635 ssh_channel_try_eof(c);
5639 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5641 struct ssh_channel *c;
5643 c = ssh_channel_msg(ssh, pktin);
5644 if (c && c->type == CHAN_SOCKDATA) {
5645 logevent("Forwarded connection refused by server");
5646 pfd_close(c->u.pfd.pf);
5647 del234(ssh->channels, c);
5652 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5654 /* Remote side closes a channel. */
5655 struct ssh_channel *c;
5657 c = ssh_channel_msg(ssh, pktin);
5660 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5661 !(c->closes & CLOSES_RCVD_EOF)) {
5663 * Received CHANNEL_CLOSE, which we translate into
5666 int send_close = FALSE;
5668 c->closes |= CLOSES_RCVD_EOF;
5672 assert(c->u.x11.xconn != NULL);
5673 x11_send_eof(c->u.x11.xconn);
5676 assert(c->u.pfd.pf != NULL);
5677 pfd_send_eof(c->u.pfd.pf);
5684 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5685 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5687 c->closes |= CLOSES_SENT_EOF;
5691 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5692 !(c->closes & CLOSES_RCVD_CLOSE)) {
5694 if (!(c->closes & CLOSES_SENT_EOF)) {
5695 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %u"
5696 " for which we never sent CHANNEL_CLOSE\n",
5700 c->closes |= CLOSES_RCVD_CLOSE;
5703 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5704 !(c->closes & CLOSES_SENT_CLOSE)) {
5705 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5706 PKT_INT, c->remoteid, PKT_END);
5707 c->closes |= CLOSES_SENT_CLOSE;
5710 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5711 ssh_channel_destroy(c);
5716 * Handle incoming data on an SSH-1 or SSH-2 agent-forwarding channel.
5718 static int ssh_agent_channel_data(struct ssh_channel *c, char *data,
5721 while (length > 0) {
5722 if (c->u.a.lensofar < 4) {
5723 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)length);
5724 memcpy(c->u.a.msglen + c->u.a.lensofar, data, l);
5727 c->u.a.lensofar += l;
5729 if (c->u.a.lensofar == 4) {
5730 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
5731 c->u.a.message = snewn(c->u.a.totallen, unsigned char);
5732 memcpy(c->u.a.message, c->u.a.msglen, 4);
5734 if (c->u.a.lensofar >= 4 && length > 0) {
5735 unsigned int l = min(c->u.a.totallen - c->u.a.lensofar,
5737 memcpy(c->u.a.message + c->u.a.lensofar, data, l);
5740 c->u.a.lensofar += l;
5742 if (c->u.a.lensofar == c->u.a.totallen) {
5745 c->u.a.outstanding_requests++;
5746 if (agent_query(c->u.a.message, c->u.a.totallen, &reply, &replylen,
5747 ssh_agentf_callback, c))
5748 ssh_agentf_callback(c, reply, replylen);
5749 sfree(c->u.a.message);
5750 c->u.a.message = NULL;
5751 c->u.a.lensofar = 0;
5754 return 0; /* agent channels never back up */
5757 static int ssh_channel_data(struct ssh_channel *c, int is_stderr,
5758 char *data, int length)
5761 case CHAN_MAINSESSION:
5762 return from_backend(c->ssh->frontend, is_stderr, data, length);
5764 return x11_send(c->u.x11.xconn, data, length);
5766 return pfd_send(c->u.pfd.pf, data, length);
5768 return ssh_agent_channel_data(c, data, length);
5773 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5775 /* Data sent down one of our channels. */
5778 struct ssh_channel *c;
5780 c = ssh_channel_msg(ssh, pktin);
5781 ssh_pkt_getstring(pktin, &p, &len);
5784 int bufsize = ssh_channel_data(c, FALSE, p, len);
5785 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5786 c->throttling_conn = 1;
5787 ssh_throttle_conn(ssh, +1);
5792 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5794 ssh->exitcode = ssh_pkt_getuint32(pktin);
5795 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5796 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5798 * In case `helpful' firewalls or proxies tack
5799 * extra human-readable text on the end of the
5800 * session which we might mistake for another
5801 * encrypted packet, we close the session once
5802 * we've sent EXIT_CONFIRMATION.
5804 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5807 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5808 static void ssh1_send_ttymode(void *data,
5809 const struct ssh_ttymode *mode, char *val)
5811 struct Packet *pktout = (struct Packet *)data;
5812 unsigned int arg = 0;
5814 switch (mode->type) {
5816 arg = ssh_tty_parse_specchar(val);
5819 arg = ssh_tty_parse_boolean(val);
5822 ssh2_pkt_addbyte(pktout, mode->opcode);
5823 ssh2_pkt_addbyte(pktout, arg);
5826 int ssh_agent_forwarding_permitted(Ssh ssh)
5828 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5831 static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
5832 struct Packet *pktin)
5834 crBegin(ssh->do_ssh1_connection_crstate);
5836 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5837 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5838 ssh1_smsg_stdout_stderr_data;
5840 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5841 ssh1_msg_channel_open_confirmation;
5842 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5843 ssh1_msg_channel_open_failure;
5844 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5845 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5846 ssh1_msg_channel_close;
5847 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5848 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5850 if (ssh_agent_forwarding_permitted(ssh)) {
5851 logevent("Requesting agent forwarding");
5852 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5856 if (pktin->type != SSH1_SMSG_SUCCESS
5857 && pktin->type != SSH1_SMSG_FAILURE) {
5858 bombout(("Protocol confusion"));
5860 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5861 logevent("Agent forwarding refused");
5863 logevent("Agent forwarding enabled");
5864 ssh->agentfwd_enabled = TRUE;
5865 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5869 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5871 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5873 if (!ssh->x11disp) {
5874 /* FIXME: return an error message from x11_setup_display */
5875 logevent("X11 forwarding not enabled: unable to"
5876 " initialise X display");
5878 ssh->x11auth = x11_invent_fake_auth
5879 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5880 ssh->x11auth->disp = ssh->x11disp;
5882 logevent("Requesting X11 forwarding");
5883 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5884 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5885 PKT_STR, ssh->x11auth->protoname,
5886 PKT_STR, ssh->x11auth->datastring,
5887 PKT_INT, ssh->x11disp->screennum,
5890 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5891 PKT_STR, ssh->x11auth->protoname,
5892 PKT_STR, ssh->x11auth->datastring,
5898 if (pktin->type != SSH1_SMSG_SUCCESS
5899 && pktin->type != SSH1_SMSG_FAILURE) {
5900 bombout(("Protocol confusion"));
5902 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5903 logevent("X11 forwarding refused");
5905 logevent("X11 forwarding enabled");
5906 ssh->X11_fwd_enabled = TRUE;
5907 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5912 ssh_setup_portfwd(ssh, ssh->conf);
5913 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5915 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5917 /* Unpick the terminal-speed string. */
5918 /* XXX perhaps we should allow no speeds to be sent. */
5919 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5920 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5921 /* Send the pty request. */
5922 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5923 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5924 ssh_pkt_adduint32(pkt, ssh->term_height);
5925 ssh_pkt_adduint32(pkt, ssh->term_width);
5926 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5927 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5928 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5929 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5930 ssh_pkt_adduint32(pkt, ssh->ispeed);
5931 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5932 ssh_pkt_adduint32(pkt, ssh->ospeed);
5933 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5935 ssh->state = SSH_STATE_INTERMED;
5939 if (pktin->type != SSH1_SMSG_SUCCESS
5940 && pktin->type != SSH1_SMSG_FAILURE) {
5941 bombout(("Protocol confusion"));
5943 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5944 c_write_str(ssh, "Server refused to allocate pty\r\n");
5945 ssh->editing = ssh->echoing = 1;
5947 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5948 ssh->ospeed, ssh->ispeed);
5949 ssh->got_pty = TRUE;
5952 ssh->editing = ssh->echoing = 1;
5955 if (conf_get_int(ssh->conf, CONF_compression)) {
5956 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5960 if (pktin->type != SSH1_SMSG_SUCCESS
5961 && pktin->type != SSH1_SMSG_FAILURE) {
5962 bombout(("Protocol confusion"));
5964 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5965 c_write_str(ssh, "Server refused to compress\r\n");
5967 logevent("Started compression");
5968 ssh->v1_compressing = TRUE;
5969 ssh->cs_comp_ctx = zlib_compress_init();
5970 logevent("Initialised zlib (RFC1950) compression");
5971 ssh->sc_comp_ctx = zlib_decompress_init();
5972 logevent("Initialised zlib (RFC1950) decompression");
5976 * Start the shell or command.
5978 * Special case: if the first-choice command is an SSH-2
5979 * subsystem (hence not usable here) and the second choice
5980 * exists, we fall straight back to that.
5983 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5985 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5986 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5987 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5988 ssh->fallback_cmd = TRUE;
5991 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5993 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5994 logevent("Started session");
5997 ssh->state = SSH_STATE_SESSION;
5998 if (ssh->size_needed)
5999 ssh_size(ssh, ssh->term_width, ssh->term_height);
6000 if (ssh->eof_needed)
6001 ssh_special(ssh, TS_EOF);
6004 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
6006 ssh->channels = newtree234(ssh_channelcmp);
6010 * By this point, most incoming packets are already being
6011 * handled by the dispatch table, and we need only pay
6012 * attention to the unusual ones.
6017 if (pktin->type == SSH1_SMSG_SUCCESS) {
6018 /* may be from EXEC_SHELL on some servers */
6019 } else if (pktin->type == SSH1_SMSG_FAILURE) {
6020 /* may be from EXEC_SHELL on some servers
6021 * if no pty is available or in other odd cases. Ignore */
6023 bombout(("Strange packet received: type %d", pktin->type));
6028 int len = min(inlen, 512);
6029 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
6030 PKT_INT, len, PKT_DATA, in, len,
6042 * Handle the top-level SSH-2 protocol.
6044 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
6049 ssh_pkt_getstring(pktin, &msg, &msglen);
6050 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
6053 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
6055 /* log reason code in disconnect message */
6059 ssh_pkt_getstring(pktin, &msg, &msglen);
6060 bombout(("Server sent disconnect message:\n\"%.*s\"",
6061 msglen, NULLTOEMPTY(msg)));
6064 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6066 /* Do nothing, because we're ignoring it! Duhh. */
6069 static void ssh1_protocol_setup(Ssh ssh)
6074 * Most messages are handled by the coroutines.
6076 for (i = 0; i < 256; i++)
6077 ssh->packet_dispatch[i] = NULL;
6080 * These special message types we install handlers for.
6082 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6083 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6084 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6087 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
6088 struct Packet *pktin)
6090 const unsigned char *in = (const unsigned char *)vin;
6091 if (ssh->state == SSH_STATE_CLOSED)
6094 if (pktin && ssh->packet_dispatch[pktin->type]) {
6095 ssh->packet_dispatch[pktin->type](ssh, pktin);
6099 if (!ssh->protocol_initial_phase_done) {
6100 if (do_ssh1_login(ssh, in, inlen, pktin))
6101 ssh->protocol_initial_phase_done = TRUE;
6106 do_ssh1_connection(ssh, in, inlen, pktin);
6110 * Utility routines for decoding comma-separated strings in KEXINIT.
6112 static int first_in_commasep_string(char const *needle, char const *haystack,
6116 if (!needle || !haystack) /* protect against null pointers */
6118 needlen = strlen(needle);
6120 if (haylen >= needlen && /* haystack is long enough */
6121 !memcmp(needle, haystack, needlen) && /* initial match */
6122 (haylen == needlen || haystack[needlen] == ',')
6123 /* either , or EOS follows */
6129 static int in_commasep_string(char const *needle, char const *haystack,
6134 if (!needle || !haystack) /* protect against null pointers */
6137 * Is it at the start of the string?
6139 if (first_in_commasep_string(needle, haystack, haylen))
6142 * If not, search for the next comma and resume after that.
6143 * If no comma found, terminate.
6145 p = memchr(haystack, ',', haylen);
6147 /* + 1 to skip over comma */
6148 return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
6152 * Add a value to the comma-separated string at the end of the packet.
6154 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6156 if (pkt->length - pkt->savedpos > 0)
6157 ssh_pkt_addstring_str(pkt, ",");
6158 ssh_pkt_addstring_str(pkt, data);
6163 * SSH-2 key derivation (RFC 4253 section 7.2).
6165 static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
6166 char chr, int keylen)
6168 const struct ssh_hash *h = ssh->kex->hash;
6176 /* Round up to the next multiple of hash length. */
6177 keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
6179 key = snewn(keylen_padded, unsigned char);
6181 /* First hlen bytes. */
6183 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6184 hash_mpint(h, s, K);
6185 h->bytes(s, H, h->hlen);
6186 h->bytes(s, &chr, 1);
6187 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6190 /* Subsequent blocks of hlen bytes. */
6191 if (keylen_padded > h->hlen) {
6195 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6196 hash_mpint(h, s, K);
6197 h->bytes(s, H, h->hlen);
6199 for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
6200 h->bytes(s, key + offset - h->hlen, h->hlen);
6202 h->final(s2, key + offset);
6208 /* Now clear any extra bytes of key material beyond the length
6209 * we're officially returning, because the caller won't know to
6211 if (keylen_padded > keylen)
6212 smemclr(key + keylen, keylen_padded - keylen);
6218 * Structure for constructing KEXINIT algorithm lists.
6220 #define MAXKEXLIST 16
6221 struct kexinit_algorithm {
6225 const struct ssh_kex *kex;
6229 const struct ssh_signkey *hostkey;
6233 const struct ssh2_cipher *cipher;
6237 const struct ssh_mac *mac;
6240 const struct ssh_compress *comp;
6245 * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
6246 * If the algorithm is already in the list, return a pointer to its
6247 * entry, otherwise return an entry from the end of the list.
6248 * This assumes that every time a particular name is passed in, it
6249 * comes from the same string constant. If this isn't true, this
6250 * function may need to be rewritten to use strcmp() instead.
6252 static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
6253 *list, const char *name)
6257 for (i = 0; i < MAXKEXLIST; i++)
6258 if (list[i].name == NULL || list[i].name == name) {
6259 list[i].name = name;
6262 assert(!"No space in KEXINIT list");
6267 * Handle the SSH-2 transport layer.
6269 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
6270 struct Packet *pktin)
6272 const unsigned char *in = (const unsigned char *)vin;
6274 KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
6275 KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
6278 const char * kexlist_descr[NKEXLIST] = {
6279 "key exchange algorithm", "host key algorithm",
6280 "client-to-server cipher", "server-to-client cipher",
6281 "client-to-server MAC", "server-to-client MAC",
6282 "client-to-server compression method",
6283 "server-to-client compression method" };
6284 struct do_ssh2_transport_state {
6286 int nbits, pbits, warn_kex, warn_hk, warn_cscipher, warn_sccipher;
6287 Bignum p, g, e, f, K;
6290 int kex_init_value, kex_reply_value;
6291 const struct ssh_mac *const *maclist;
6293 const struct ssh2_cipher *cscipher_tobe;
6294 const struct ssh2_cipher *sccipher_tobe;
6295 const struct ssh_mac *csmac_tobe;
6296 const struct ssh_mac *scmac_tobe;
6297 int csmac_etm_tobe, scmac_etm_tobe;
6298 const struct ssh_compress *cscomp_tobe;
6299 const struct ssh_compress *sccomp_tobe;
6300 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6301 int hostkeylen, siglen, rsakeylen;
6302 void *hkey; /* actual host key */
6303 void *rsakey; /* for RSA kex */
6304 void *eckey; /* for ECDH kex */
6305 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6306 int n_preferred_kex;
6307 const struct ssh_kexes *preferred_kex[KEX_MAX];
6309 int preferred_hk[HK_MAX];
6310 int n_preferred_ciphers;
6311 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6312 const struct ssh_compress *preferred_comp;
6313 int userauth_succeeded; /* for delayed compression */
6314 int pending_compression;
6315 int got_session_id, activated_authconn;
6316 struct Packet *pktout;
6320 struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
6322 crState(do_ssh2_transport_state);
6324 assert(!ssh->bare_connection);
6325 assert(ssh->version == 2);
6329 s->cscipher_tobe = s->sccipher_tobe = NULL;
6330 s->csmac_tobe = s->scmac_tobe = NULL;
6331 s->cscomp_tobe = s->sccomp_tobe = NULL;
6333 s->got_session_id = s->activated_authconn = FALSE;
6334 s->userauth_succeeded = FALSE;
6335 s->pending_compression = FALSE;
6338 * Be prepared to work around the buggy MAC problem.
6340 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6341 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6343 s->maclist = macs, s->nmacs = lenof(macs);
6346 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6349 struct kexinit_algorithm *alg;
6352 * Set up the preferred key exchange. (NULL => warn below here)
6354 s->n_preferred_kex = 0;
6355 for (i = 0; i < KEX_MAX; i++) {
6356 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6358 s->preferred_kex[s->n_preferred_kex++] =
6359 &ssh_diffiehellman_gex;
6362 s->preferred_kex[s->n_preferred_kex++] =
6363 &ssh_diffiehellman_group14;
6366 s->preferred_kex[s->n_preferred_kex++] =
6367 &ssh_diffiehellman_group1;
6370 s->preferred_kex[s->n_preferred_kex++] =
6374 s->preferred_kex[s->n_preferred_kex++] =
6378 /* Flag for later. Don't bother if it's the last in
6380 if (i < KEX_MAX - 1) {
6381 s->preferred_kex[s->n_preferred_kex++] = NULL;
6388 * Set up the preferred host key types. These are just the ids
6389 * in the enum in putty.h, so 'warn below here' is indicated
6392 s->n_preferred_hk = 0;
6393 for (i = 0; i < HK_MAX; i++) {
6394 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, i);
6395 /* As above, don't bother with HK_WARN if it's last in the
6397 if (id != HK_WARN || i < HK_MAX - 1)
6398 s->preferred_hk[s->n_preferred_hk++] = id;
6402 * Set up the preferred ciphers. (NULL => warn below here)
6404 s->n_preferred_ciphers = 0;
6405 for (i = 0; i < CIPHER_MAX; i++) {
6406 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6407 case CIPHER_BLOWFISH:
6408 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6411 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6412 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6416 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6419 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6421 case CIPHER_ARCFOUR:
6422 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6424 case CIPHER_CHACHA20:
6425 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
6428 /* Flag for later. Don't bother if it's the last in
6430 if (i < CIPHER_MAX - 1) {
6431 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6438 * Set up preferred compression.
6440 if (conf_get_int(ssh->conf, CONF_compression))
6441 s->preferred_comp = &ssh_zlib;
6443 s->preferred_comp = &ssh_comp_none;
6446 * Enable queueing of outgoing auth- or connection-layer
6447 * packets while we are in the middle of a key exchange.
6449 ssh->queueing = TRUE;
6452 * Flag that KEX is in progress.
6454 ssh->kex_in_progress = TRUE;
6456 for (i = 0; i < NKEXLIST; i++)
6457 for (j = 0; j < MAXKEXLIST; j++)
6458 s->kexlists[i][j].name = NULL;
6459 /* List key exchange algorithms. */
6461 for (i = 0; i < s->n_preferred_kex; i++) {
6462 const struct ssh_kexes *k = s->preferred_kex[i];
6463 if (!k) warn = TRUE;
6464 else for (j = 0; j < k->nkexes; j++) {
6465 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
6467 alg->u.kex.kex = k->list[j];
6468 alg->u.kex.warn = warn;
6471 /* List server host key algorithms. */
6472 if (!s->got_session_id) {
6474 * In the first key exchange, we list all the algorithms
6475 * we're prepared to cope with, but prefer those algorithms
6476 * for which we have a host key for this host.
6478 * If the host key algorithm is below the warning
6479 * threshold, we warn even if we did already have a key
6480 * for it, on the basis that if the user has just
6481 * reconfigured that host key type to be warned about,
6482 * they surely _do_ want to be alerted that a server
6483 * they're actually connecting to is using it.
6486 for (i = 0; i < s->n_preferred_hk; i++) {
6487 if (s->preferred_hk[i] == HK_WARN)
6489 for (j = 0; j < lenof(hostkey_algs); j++) {
6490 if (hostkey_algs[j].id != s->preferred_hk[i])
6492 if (have_ssh_host_key(ssh->savedhost, ssh->savedport,
6493 hostkey_algs[j].alg->keytype)) {
6494 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6495 hostkey_algs[j].alg->name);
6496 alg->u.hk.hostkey = hostkey_algs[j].alg;
6497 alg->u.hk.warn = warn;
6502 for (i = 0; i < s->n_preferred_hk; i++) {
6503 if (s->preferred_hk[i] == HK_WARN)
6505 for (j = 0; j < lenof(hostkey_algs); j++) {
6506 if (hostkey_algs[j].id != s->preferred_hk[i])
6508 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6509 hostkey_algs[j].alg->name);
6510 alg->u.hk.hostkey = hostkey_algs[j].alg;
6511 alg->u.hk.warn = warn;
6516 * In subsequent key exchanges, we list only the kex
6517 * algorithm that was selected in the first key exchange,
6518 * so that we keep getting the same host key and hence
6519 * don't have to interrupt the user's session to ask for
6523 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6524 ssh->hostkey->name);
6525 alg->u.hk.hostkey = ssh->hostkey;
6526 alg->u.hk.warn = FALSE;
6528 /* List encryption algorithms (client->server then server->client). */
6529 for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
6532 alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
6533 alg->u.cipher.cipher = NULL;
6534 alg->u.cipher.warn = warn;
6535 #endif /* FUZZING */
6536 for (i = 0; i < s->n_preferred_ciphers; i++) {
6537 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6538 if (!c) warn = TRUE;
6539 else for (j = 0; j < c->nciphers; j++) {
6540 alg = ssh2_kexinit_addalg(s->kexlists[k],
6542 alg->u.cipher.cipher = c->list[j];
6543 alg->u.cipher.warn = warn;
6547 /* List MAC algorithms (client->server then server->client). */
6548 for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
6550 alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
6551 alg->u.mac.mac = NULL;
6552 alg->u.mac.etm = FALSE;
6553 #endif /* FUZZING */
6554 for (i = 0; i < s->nmacs; i++) {
6555 alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
6556 alg->u.mac.mac = s->maclist[i];
6557 alg->u.mac.etm = FALSE;
6559 for (i = 0; i < s->nmacs; i++)
6560 /* For each MAC, there may also be an ETM version,
6561 * which we list second. */
6562 if (s->maclist[i]->etm_name) {
6563 alg = ssh2_kexinit_addalg(s->kexlists[j],
6564 s->maclist[i]->etm_name);
6565 alg->u.mac.mac = s->maclist[i];
6566 alg->u.mac.etm = TRUE;
6569 /* List client->server compression algorithms,
6570 * then server->client compression algorithms. (We use the
6571 * same set twice.) */
6572 for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
6573 assert(lenof(compressions) > 1);
6574 /* Prefer non-delayed versions */
6575 alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
6576 alg->u.comp = s->preferred_comp;
6577 /* We don't even list delayed versions of algorithms until
6578 * they're allowed to be used, to avoid a race. See the end of
6580 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6581 alg = ssh2_kexinit_addalg(s->kexlists[j],
6582 s->preferred_comp->delayed_name);
6583 alg->u.comp = s->preferred_comp;
6585 for (i = 0; i < lenof(compressions); i++) {
6586 const struct ssh_compress *c = compressions[i];
6587 alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
6589 if (s->userauth_succeeded && c->delayed_name) {
6590 alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
6596 * Construct and send our key exchange packet.
6598 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6599 for (i = 0; i < 16; i++)
6600 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6601 for (i = 0; i < NKEXLIST; i++) {
6602 ssh2_pkt_addstring_start(s->pktout);
6603 for (j = 0; j < MAXKEXLIST; j++) {
6604 if (s->kexlists[i][j].name == NULL) break;
6605 ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
6608 /* List client->server languages. Empty list. */
6609 ssh2_pkt_addstring_start(s->pktout);
6610 /* List server->client languages. Empty list. */
6611 ssh2_pkt_addstring_start(s->pktout);
6612 /* First KEX packet does _not_ follow, because we're not that brave. */
6613 ssh2_pkt_addbool(s->pktout, FALSE);
6615 ssh2_pkt_adduint32(s->pktout, 0);
6618 s->our_kexinitlen = s->pktout->length - 5;
6619 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6620 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6622 ssh2_pkt_send_noqueue(ssh, s->pktout);
6625 crWaitUntilV(pktin);
6628 * Now examine the other side's KEXINIT to see what we're up
6635 if (pktin->type != SSH2_MSG_KEXINIT) {
6636 bombout(("expected key exchange packet from server"));
6640 ssh->hostkey = NULL;
6641 s->cscipher_tobe = NULL;
6642 s->sccipher_tobe = NULL;
6643 s->csmac_tobe = NULL;
6644 s->scmac_tobe = NULL;
6645 s->cscomp_tobe = NULL;
6646 s->sccomp_tobe = NULL;
6647 s->warn_kex = s->warn_hk = FALSE;
6648 s->warn_cscipher = s->warn_sccipher = FALSE;
6650 pktin->savedpos += 16; /* skip garbage cookie */
6653 for (i = 0; i < NKEXLIST; i++) {
6654 ssh_pkt_getstring(pktin, &str, &len);
6656 bombout(("KEXINIT packet was incomplete"));
6660 /* If we've already selected a cipher which requires a
6661 * particular MAC, then just select that, and don't even
6662 * bother looking through the server's KEXINIT string for
6664 if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
6665 s->cscipher_tobe->required_mac) {
6666 s->csmac_tobe = s->cscipher_tobe->required_mac;
6667 s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
6670 if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
6671 s->sccipher_tobe->required_mac) {
6672 s->scmac_tobe = s->sccipher_tobe->required_mac;
6673 s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
6677 for (j = 0; j < MAXKEXLIST; j++) {
6678 struct kexinit_algorithm *alg = &s->kexlists[i][j];
6679 if (alg->name == NULL) break;
6680 if (in_commasep_string(alg->name, str, len)) {
6681 /* We've found a matching algorithm. */
6682 if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
6683 /* Check if we might need to ignore first kex pkt */
6685 !first_in_commasep_string(alg->name, str, len))
6688 if (i == KEXLIST_KEX) {
6689 ssh->kex = alg->u.kex.kex;
6690 s->warn_kex = alg->u.kex.warn;
6691 } else if (i == KEXLIST_HOSTKEY) {
6692 ssh->hostkey = alg->u.hk.hostkey;
6693 s->warn_hk = alg->u.hk.warn;
6694 } else if (i == KEXLIST_CSCIPHER) {
6695 s->cscipher_tobe = alg->u.cipher.cipher;
6696 s->warn_cscipher = alg->u.cipher.warn;
6697 } else if (i == KEXLIST_SCCIPHER) {
6698 s->sccipher_tobe = alg->u.cipher.cipher;
6699 s->warn_sccipher = alg->u.cipher.warn;
6700 } else if (i == KEXLIST_CSMAC) {
6701 s->csmac_tobe = alg->u.mac.mac;
6702 s->csmac_etm_tobe = alg->u.mac.etm;
6703 } else if (i == KEXLIST_SCMAC) {
6704 s->scmac_tobe = alg->u.mac.mac;
6705 s->scmac_etm_tobe = alg->u.mac.etm;
6706 } else if (i == KEXLIST_CSCOMP) {
6707 s->cscomp_tobe = alg->u.comp;
6708 } else if (i == KEXLIST_SCCOMP) {
6709 s->sccomp_tobe = alg->u.comp;
6713 if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
6714 in_commasep_string(alg->u.comp->delayed_name, str, len))
6715 s->pending_compression = TRUE; /* try this later */
6717 bombout(("Couldn't agree a %s (available: %.*s)",
6718 kexlist_descr[i], len, str));
6722 if (i == KEXLIST_HOSTKEY) {
6726 * In addition to deciding which host key we're
6727 * actually going to use, we should make a list of the
6728 * host keys offered by the server which we _don't_
6729 * have cached. These will be offered as cross-
6730 * certification options by ssh_get_specials.
6732 * We also count the key we're currently using for KEX
6733 * as one we've already got, because by the time this
6734 * menu becomes visible, it will be.
6736 ssh->n_uncert_hostkeys = 0;
6738 for (j = 0; j < lenof(hostkey_algs); j++) {
6739 if (hostkey_algs[j].alg != ssh->hostkey &&
6740 in_commasep_string(hostkey_algs[j].alg->name,
6742 !have_ssh_host_key(ssh->savedhost, ssh->savedport,
6743 hostkey_algs[j].alg->keytype)) {
6744 ssh->uncert_hostkeys[ssh->n_uncert_hostkeys++] = j;
6750 if (s->pending_compression) {
6751 logevent("Server supports delayed compression; "
6752 "will try this later");
6754 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6755 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6756 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6758 ssh->exhash = ssh->kex->hash->init();
6759 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6760 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6761 hash_string(ssh->kex->hash, ssh->exhash,
6762 s->our_kexinit, s->our_kexinitlen);
6763 sfree(s->our_kexinit);
6764 /* Include the type byte in the hash of server's KEXINIT */
6765 hash_string(ssh->kex->hash, ssh->exhash,
6766 pktin->body - 1, pktin->length + 1);
6769 ssh_set_frozen(ssh, 1);
6770 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6772 ssh_dialog_callback, ssh);
6773 if (s->dlgret < 0) {
6777 bombout(("Unexpected data from server while"
6778 " waiting for user response"));
6781 } while (pktin || inlen > 0);
6782 s->dlgret = ssh->user_response;
6784 ssh_set_frozen(ssh, 0);
6785 if (s->dlgret == 0) {
6786 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6796 ssh_set_frozen(ssh, 1);
6799 * Change warning box wording depending on why we chose a
6800 * warning-level host key algorithm. If it's because
6801 * that's all we have *cached*, use the askhk mechanism,
6802 * and list the host keys we could usefully cross-certify.
6803 * Otherwise, use askalg for the standard wording.
6806 for (j = 0; j < ssh->n_uncert_hostkeys; j++) {
6807 const struct ssh_signkey_with_user_pref_id *hktype =
6808 &hostkey_algs[ssh->uncert_hostkeys[j]];
6810 for (k = 0; k < HK_MAX; k++) {
6811 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, k);
6812 if (id == HK_WARN) {
6814 } else if (id == hktype->id) {
6821 char *old_ba = betteralgs;
6822 betteralgs = dupcat(betteralgs, ",",
6824 (const char *)NULL);
6827 betteralgs = dupstr(hktype->alg->name);
6832 s->dlgret = askhk(ssh->frontend, ssh->hostkey->name,
6833 betteralgs, ssh_dialog_callback, ssh);
6836 s->dlgret = askalg(ssh->frontend, "host key type",
6838 ssh_dialog_callback, ssh);
6840 if (s->dlgret < 0) {
6844 bombout(("Unexpected data from server while"
6845 " waiting for user response"));
6848 } while (pktin || inlen > 0);
6849 s->dlgret = ssh->user_response;
6851 ssh_set_frozen(ssh, 0);
6852 if (s->dlgret == 0) {
6853 ssh_disconnect(ssh, "User aborted at host key warning", NULL,
6859 if (s->warn_cscipher) {
6860 ssh_set_frozen(ssh, 1);
6861 s->dlgret = askalg(ssh->frontend,
6862 "client-to-server cipher",
6863 s->cscipher_tobe->name,
6864 ssh_dialog_callback, ssh);
6865 if (s->dlgret < 0) {
6869 bombout(("Unexpected data from server while"
6870 " waiting for user response"));
6873 } while (pktin || inlen > 0);
6874 s->dlgret = ssh->user_response;
6876 ssh_set_frozen(ssh, 0);
6877 if (s->dlgret == 0) {
6878 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6884 if (s->warn_sccipher) {
6885 ssh_set_frozen(ssh, 1);
6886 s->dlgret = askalg(ssh->frontend,
6887 "server-to-client cipher",
6888 s->sccipher_tobe->name,
6889 ssh_dialog_callback, ssh);
6890 if (s->dlgret < 0) {
6894 bombout(("Unexpected data from server while"
6895 " waiting for user response"));
6898 } while (pktin || inlen > 0);
6899 s->dlgret = ssh->user_response;
6901 ssh_set_frozen(ssh, 0);
6902 if (s->dlgret == 0) {
6903 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6909 if (s->ignorepkt) /* first_kex_packet_follows */
6910 crWaitUntilV(pktin); /* Ignore packet */
6913 if (ssh->kex->main_type == KEXTYPE_DH) {
6915 * Work out the number of bits of key we will need from the
6916 * key exchange. We start with the maximum key length of
6922 csbits = s->cscipher_tobe ? s->cscipher_tobe->real_keybits : 0;
6923 scbits = s->sccipher_tobe ? s->sccipher_tobe->real_keybits : 0;
6924 s->nbits = (csbits > scbits ? csbits : scbits);
6926 /* The keys only have hlen-bit entropy, since they're based on
6927 * a hash. So cap the key size at hlen bits. */
6928 if (s->nbits > ssh->kex->hash->hlen * 8)
6929 s->nbits = ssh->kex->hash->hlen * 8;
6932 * If we're doing Diffie-Hellman group exchange, start by
6933 * requesting a group.
6935 if (dh_is_gex(ssh->kex)) {
6936 logevent("Doing Diffie-Hellman group exchange");
6937 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6939 * Work out how big a DH group we will need to allow that
6942 s->pbits = 512 << ((s->nbits - 1) / 64);
6943 if (s->pbits < DH_MIN_SIZE)
6944 s->pbits = DH_MIN_SIZE;
6945 if (s->pbits > DH_MAX_SIZE)
6946 s->pbits = DH_MAX_SIZE;
6947 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6948 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6949 ssh2_pkt_adduint32(s->pktout, s->pbits);
6951 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6952 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6953 ssh2_pkt_adduint32(s->pktout, s->pbits);
6954 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6956 ssh2_pkt_send_noqueue(ssh, s->pktout);
6958 crWaitUntilV(pktin);
6959 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6960 bombout(("expected key exchange group packet from server"));
6963 s->p = ssh2_pkt_getmp(pktin);
6964 s->g = ssh2_pkt_getmp(pktin);
6965 if (!s->p || !s->g) {
6966 bombout(("unable to read mp-ints from incoming group packet"));
6969 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6970 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6971 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6973 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6974 ssh->kex_ctx = dh_setup_group(ssh->kex);
6975 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6976 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6977 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6978 ssh->kex->groupname);
6981 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6982 ssh->kex->hash->text_name);
6984 * Now generate and send e for Diffie-Hellman.
6986 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6987 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6988 s->pktout = ssh2_pkt_init(s->kex_init_value);
6989 ssh2_pkt_addmp(s->pktout, s->e);
6990 ssh2_pkt_send_noqueue(ssh, s->pktout);
6992 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6993 crWaitUntilV(pktin);
6994 if (pktin->type != s->kex_reply_value) {
6995 bombout(("expected key exchange reply packet from server"));
6998 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6999 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7000 if (!s->hostkeydata) {
7001 bombout(("unable to parse key exchange reply packet"));
7004 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7005 s->hostkeydata, s->hostkeylen);
7006 s->f = ssh2_pkt_getmp(pktin);
7008 bombout(("unable to parse key exchange reply packet"));
7011 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7013 bombout(("unable to parse key exchange reply packet"));
7018 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
7020 bombout(("key exchange reply failed validation: %s", err));
7024 s->K = dh_find_K(ssh->kex_ctx, s->f);
7026 /* We assume everything from now on will be quick, and it might
7027 * involve user interaction. */
7028 set_busy_status(ssh->frontend, BUSY_NOT);
7030 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7031 if (dh_is_gex(ssh->kex)) {
7032 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7033 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
7034 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
7035 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7036 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
7037 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
7038 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
7040 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
7041 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
7043 dh_cleanup(ssh->kex_ctx);
7045 if (dh_is_gex(ssh->kex)) {
7049 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
7051 logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
7052 ssh_ecdhkex_curve_textname(ssh->kex),
7053 ssh->kex->hash->text_name);
7054 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
7056 s->eckey = ssh_ecdhkex_newkey(ssh->kex);
7058 bombout(("Unable to generate key for ECDH"));
7064 int publicPointLength;
7065 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7067 ssh_ecdhkex_freekey(s->eckey);
7068 bombout(("Unable to encode public key for ECDH"));
7071 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
7072 ssh2_pkt_addstring_start(s->pktout);
7073 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
7077 ssh2_pkt_send_noqueue(ssh, s->pktout);
7079 crWaitUntilV(pktin);
7080 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
7081 ssh_ecdhkex_freekey(s->eckey);
7082 bombout(("expected ECDH reply packet from server"));
7086 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7087 if (!s->hostkeydata) {
7088 bombout(("unable to parse ECDH reply packet"));
7091 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7092 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7093 s->hostkeydata, s->hostkeylen);
7097 int publicPointLength;
7098 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7100 ssh_ecdhkex_freekey(s->eckey);
7101 bombout(("Unable to encode public key for ECDH hash"));
7104 hash_string(ssh->kex->hash, ssh->exhash,
7105 publicPoint, publicPointLength);
7112 ssh_pkt_getstring(pktin, &keydata, &keylen);
7114 bombout(("unable to parse ECDH reply packet"));
7117 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
7118 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
7120 ssh_ecdhkex_freekey(s->eckey);
7121 bombout(("point received in ECDH was not valid"));
7126 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7128 bombout(("unable to parse key exchange reply packet"));
7132 ssh_ecdhkex_freekey(s->eckey);
7134 logeventf(ssh, "Doing RSA key exchange with hash %s",
7135 ssh->kex->hash->text_name);
7136 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
7138 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
7141 crWaitUntilV(pktin);
7142 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
7143 bombout(("expected RSA public key packet from server"));
7147 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7148 if (!s->hostkeydata) {
7149 bombout(("unable to parse RSA public key packet"));
7152 hash_string(ssh->kex->hash, ssh->exhash,
7153 s->hostkeydata, s->hostkeylen);
7154 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7155 s->hostkeydata, s->hostkeylen);
7159 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
7161 bombout(("unable to parse RSA public key packet"));
7164 s->rsakeydata = snewn(s->rsakeylen, char);
7165 memcpy(s->rsakeydata, keydata, s->rsakeylen);
7168 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
7170 sfree(s->rsakeydata);
7171 bombout(("unable to parse RSA public key from server"));
7175 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
7178 * Next, set up a shared secret K, of precisely KLEN -
7179 * 2*HLEN - 49 bits, where KLEN is the bit length of the
7180 * RSA key modulus and HLEN is the bit length of the hash
7184 int klen = ssh_rsakex_klen(s->rsakey);
7185 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
7187 unsigned char *kstr1, *kstr2, *outstr;
7188 int kstr1len, kstr2len, outstrlen;
7190 s->K = bn_power_2(nbits - 1);
7192 for (i = 0; i < nbits; i++) {
7194 byte = random_byte();
7196 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
7200 * Encode this as an mpint.
7202 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
7203 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
7204 PUT_32BIT(kstr2, kstr1len);
7205 memcpy(kstr2 + 4, kstr1, kstr1len);
7208 * Encrypt it with the given RSA key.
7210 outstrlen = (klen + 7) / 8;
7211 outstr = snewn(outstrlen, unsigned char);
7212 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
7213 outstr, outstrlen, s->rsakey);
7216 * And send it off in a return packet.
7218 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
7219 ssh2_pkt_addstring_start(s->pktout);
7220 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
7221 ssh2_pkt_send_noqueue(ssh, s->pktout);
7223 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7230 ssh_rsakex_freekey(s->rsakey);
7232 crWaitUntilV(pktin);
7233 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7234 sfree(s->rsakeydata);
7235 bombout(("expected signature packet from server"));
7239 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7241 bombout(("unable to parse signature packet"));
7245 sfree(s->rsakeydata);
7248 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7249 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7250 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7252 ssh->kex_ctx = NULL;
7255 debug(("Exchange hash is:\n"));
7256 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7260 bombout(("Server's host key is invalid"));
7264 if (!ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7265 (char *)s->exchange_hash,
7266 ssh->kex->hash->hlen)) {
7268 bombout(("Server's host key did not match the signature supplied"));
7273 s->keystr = ssh->hostkey->fmtkey(s->hkey);
7274 if (!s->got_session_id) {
7276 * Make a note of any other host key formats that are available.
7279 int i, j, nkeys = 0;
7281 for (i = 0; i < lenof(hostkey_algs); i++) {
7282 if (hostkey_algs[i].alg == ssh->hostkey)
7285 for (j = 0; j < ssh->n_uncert_hostkeys; j++)
7286 if (ssh->uncert_hostkeys[j] == i)
7289 if (j < ssh->n_uncert_hostkeys) {
7292 newlist = dupprintf("%s/%s", list,
7293 hostkey_algs[i].alg->name);
7295 newlist = dupprintf("%s", hostkey_algs[i].alg->name);
7303 "Server also has %s host key%s, but we "
7304 "don't know %s", list,
7305 nkeys > 1 ? "s" : "",
7306 nkeys > 1 ? "any of them" : "it");
7312 * Authenticate remote host: verify host key. (We've already
7313 * checked the signature of the exchange hash.)
7315 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7316 logevent("Host key fingerprint is:");
7317 logevent(s->fingerprint);
7318 /* First check against manually configured host keys. */
7319 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7320 ssh->hostkey, s->hkey);
7321 if (s->dlgret == 0) { /* did not match */
7322 bombout(("Host key did not appear in manually configured list"));
7324 } else if (s->dlgret < 0) { /* none configured; use standard handling */
7325 ssh_set_frozen(ssh, 1);
7326 s->dlgret = verify_ssh_host_key(ssh->frontend,
7327 ssh->savedhost, ssh->savedport,
7328 ssh->hostkey->keytype, s->keystr,
7330 ssh_dialog_callback, ssh);
7334 if (s->dlgret < 0) {
7338 bombout(("Unexpected data from server while waiting"
7339 " for user host key response"));
7342 } while (pktin || inlen > 0);
7343 s->dlgret = ssh->user_response;
7345 ssh_set_frozen(ssh, 0);
7346 if (s->dlgret == 0) {
7347 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7352 sfree(s->fingerprint);
7354 * Save this host key, to check against the one presented in
7355 * subsequent rekeys.
7357 ssh->hostkey_str = s->keystr;
7358 } else if (ssh->cross_certifying) {
7359 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7360 logevent("Storing additional host key for this host:");
7361 logevent(s->fingerprint);
7362 store_host_key(ssh->savedhost, ssh->savedport,
7363 ssh->hostkey->keytype, s->keystr);
7364 ssh->cross_certifying = FALSE;
7366 * Don't forget to store the new key as the one we'll be
7367 * re-checking in future normal rekeys.
7369 ssh->hostkey_str = s->keystr;
7372 * In a rekey, we never present an interactive host key
7373 * verification request to the user. Instead, we simply
7374 * enforce that the key we're seeing this time is identical to
7375 * the one we saw before.
7377 if (strcmp(ssh->hostkey_str, s->keystr)) {
7379 bombout(("Host key was different in repeat key exchange"));
7385 ssh->hostkey->freekey(s->hkey);
7388 * The exchange hash from the very first key exchange is also
7389 * the session id, used in session key construction and
7392 if (!s->got_session_id) {
7393 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7394 memcpy(ssh->v2_session_id, s->exchange_hash,
7395 sizeof(s->exchange_hash));
7396 ssh->v2_session_id_len = ssh->kex->hash->hlen;
7397 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7398 s->got_session_id = TRUE;
7402 * Send SSH2_MSG_NEWKEYS.
7404 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7405 ssh2_pkt_send_noqueue(ssh, s->pktout);
7406 ssh->outgoing_data_size = 0; /* start counting from here */
7409 * We've sent client NEWKEYS, so create and initialise
7410 * client-to-server session keys.
7412 if (ssh->cs_cipher_ctx)
7413 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7414 ssh->cscipher = s->cscipher_tobe;
7415 if (ssh->cscipher) ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7417 if (ssh->cs_mac_ctx)
7418 ssh->csmac->free_context(ssh->cs_mac_ctx);
7419 ssh->csmac = s->csmac_tobe;
7420 ssh->csmac_etm = s->csmac_etm_tobe;
7422 ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
7424 if (ssh->cs_comp_ctx)
7425 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7426 ssh->cscomp = s->cscomp_tobe;
7427 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7430 * Set IVs on client-to-server keys. Here we use the exchange
7431 * hash from the _first_ key exchange.
7433 if (ssh->cscipher) {
7436 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
7437 ssh->cscipher->padded_keybytes);
7438 ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
7439 smemclr(key, ssh->cscipher->padded_keybytes);
7442 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
7443 ssh->cscipher->blksize);
7444 ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
7445 smemclr(key, ssh->cscipher->blksize);
7451 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
7452 ssh->csmac->keylen);
7453 ssh->csmac->setkey(ssh->cs_mac_ctx, key);
7454 smemclr(key, ssh->csmac->keylen);
7459 logeventf(ssh, "Initialised %.200s client->server encryption",
7460 ssh->cscipher->text_name);
7462 logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
7463 ssh->csmac->text_name,
7464 ssh->csmac_etm ? " (in ETM mode)" : "",
7465 ssh->cscipher->required_mac ? " (required by cipher)" : "");
7466 if (ssh->cscomp->text_name)
7467 logeventf(ssh, "Initialised %s compression",
7468 ssh->cscomp->text_name);
7471 * Now our end of the key exchange is complete, we can send all
7472 * our queued higher-layer packets.
7474 ssh->queueing = FALSE;
7475 ssh2_pkt_queuesend(ssh);
7478 * Expect SSH2_MSG_NEWKEYS from server.
7480 crWaitUntilV(pktin);
7481 if (pktin->type != SSH2_MSG_NEWKEYS) {
7482 bombout(("expected new-keys packet from server"));
7485 ssh->incoming_data_size = 0; /* start counting from here */
7488 * We've seen server NEWKEYS, so create and initialise
7489 * server-to-client session keys.
7491 if (ssh->sc_cipher_ctx)
7492 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7493 if (s->sccipher_tobe) {
7494 ssh->sccipher = s->sccipher_tobe;
7495 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7498 if (ssh->sc_mac_ctx)
7499 ssh->scmac->free_context(ssh->sc_mac_ctx);
7500 if (s->scmac_tobe) {
7501 ssh->scmac = s->scmac_tobe;
7502 ssh->scmac_etm = s->scmac_etm_tobe;
7503 ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
7506 if (ssh->sc_comp_ctx)
7507 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7508 ssh->sccomp = s->sccomp_tobe;
7509 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7512 * Set IVs on server-to-client keys. Here we use the exchange
7513 * hash from the _first_ key exchange.
7515 if (ssh->sccipher) {
7518 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
7519 ssh->sccipher->padded_keybytes);
7520 ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
7521 smemclr(key, ssh->sccipher->padded_keybytes);
7524 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
7525 ssh->sccipher->blksize);
7526 ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
7527 smemclr(key, ssh->sccipher->blksize);
7533 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
7534 ssh->scmac->keylen);
7535 ssh->scmac->setkey(ssh->sc_mac_ctx, key);
7536 smemclr(key, ssh->scmac->keylen);
7540 logeventf(ssh, "Initialised %.200s server->client encryption",
7541 ssh->sccipher->text_name);
7543 logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
7544 ssh->scmac->text_name,
7545 ssh->scmac_etm ? " (in ETM mode)" : "",
7546 ssh->sccipher->required_mac ? " (required by cipher)" : "");
7547 if (ssh->sccomp->text_name)
7548 logeventf(ssh, "Initialised %s decompression",
7549 ssh->sccomp->text_name);
7552 * Free shared secret.
7557 * Update the specials menu to list the remaining uncertified host
7560 update_specials_menu(ssh->frontend);
7563 * Key exchange is over. Loop straight back round if we have a
7564 * deferred rekey reason.
7566 if (ssh->deferred_rekey_reason) {
7567 logevent(ssh->deferred_rekey_reason);
7569 ssh->deferred_rekey_reason = NULL;
7570 goto begin_key_exchange;
7574 * Otherwise, schedule a timer for our next rekey.
7576 ssh->kex_in_progress = FALSE;
7577 ssh->last_rekey = GETTICKCOUNT();
7578 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7579 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7583 * Now we're encrypting. Begin returning 1 to the protocol main
7584 * function so that other things can run on top of the
7585 * transport. If we ever see a KEXINIT, we must go back to the
7588 * We _also_ go back to the start if we see pktin==NULL and
7589 * inlen negative, because this is a special signal meaning
7590 * `initiate client-driven rekey', and `in' contains a message
7591 * giving the reason for the rekey.
7593 * inlen==-1 means always initiate a rekey;
7594 * inlen==-2 means that userauth has completed successfully and
7595 * we should consider rekeying (for delayed compression).
7597 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7598 (!pktin && inlen < 0))) {
7600 if (!ssh->protocol_initial_phase_done) {
7601 ssh->protocol_initial_phase_done = TRUE;
7603 * Allow authconn to initialise itself.
7605 do_ssh2_authconn(ssh, NULL, 0, NULL);
7610 logevent("Server initiated key re-exchange");
7614 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7615 * delayed compression, if it's available.
7617 * draft-miller-secsh-compression-delayed-00 says that you
7618 * negotiate delayed compression in the first key exchange, and
7619 * both sides start compressing when the server has sent
7620 * USERAUTH_SUCCESS. This has a race condition -- the server
7621 * can't know when the client has seen it, and thus which incoming
7622 * packets it should treat as compressed.
7624 * Instead, we do the initial key exchange without offering the
7625 * delayed methods, but note if the server offers them; when we
7626 * get here, if a delayed method was available that was higher
7627 * on our list than what we got, we initiate a rekey in which we
7628 * _do_ list the delayed methods (and hopefully get it as a
7629 * result). Subsequent rekeys will do the same.
7631 assert(!s->userauth_succeeded); /* should only happen once */
7632 s->userauth_succeeded = TRUE;
7633 if (!s->pending_compression)
7634 /* Can't see any point rekeying. */
7635 goto wait_for_rekey; /* this is utterly horrid */
7636 /* else fall through to rekey... */
7637 s->pending_compression = FALSE;
7640 * Now we've decided to rekey.
7642 * Special case: if the server bug is set that doesn't
7643 * allow rekeying, we give a different log message and
7644 * continue waiting. (If such a server _initiates_ a rekey,
7645 * we process it anyway!)
7647 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7648 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7650 /* Reset the counters, so that at least this message doesn't
7651 * hit the event log _too_ often. */
7652 ssh->outgoing_data_size = 0;
7653 ssh->incoming_data_size = 0;
7654 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7656 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7659 goto wait_for_rekey; /* this is still utterly horrid */
7661 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7664 goto begin_key_exchange;
7670 * Send data on an SSH channel. In SSH-2, this involves buffering it
7673 static int ssh_send_channel_data(struct ssh_channel *c, const char *buf,
7676 if (c->ssh->version == 2) {
7677 bufchain_add(&c->v.v2.outbuffer, buf, len);
7678 return ssh2_try_send(c);
7680 send_packet(c->ssh, SSH1_MSG_CHANNEL_DATA,
7681 PKT_INT, c->remoteid,
7686 * In SSH-1 we can return 0 here - implying that channels are
7687 * never individually throttled - because the only
7688 * circumstance that can cause throttling will be the whole
7689 * SSH connection backing up, in which case _everything_ will
7690 * be throttled as a whole.
7697 * Attempt to send data on an SSH-2 channel.
7699 static int ssh2_try_send(struct ssh_channel *c)
7702 struct Packet *pktout;
7705 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7708 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7709 if ((unsigned)len > c->v.v2.remwindow)
7710 len = c->v.v2.remwindow;
7711 if ((unsigned)len > c->v.v2.remmaxpkt)
7712 len = c->v.v2.remmaxpkt;
7713 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7714 ssh2_pkt_adduint32(pktout, c->remoteid);
7715 ssh2_pkt_addstring_start(pktout);
7716 ssh2_pkt_addstring_data(pktout, data, len);
7717 ssh2_pkt_send(ssh, pktout);
7718 bufchain_consume(&c->v.v2.outbuffer, len);
7719 c->v.v2.remwindow -= len;
7723 * After having sent as much data as we can, return the amount
7726 ret = bufchain_size(&c->v.v2.outbuffer);
7729 * And if there's no data pending but we need to send an EOF, send
7732 if (!ret && c->pending_eof)
7733 ssh_channel_try_eof(c);
7738 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7741 if (c->closes & CLOSES_SENT_EOF)
7742 return; /* don't send on channels we've EOFed */
7743 bufsize = ssh2_try_send(c);
7746 case CHAN_MAINSESSION:
7747 /* stdin need not receive an unthrottle
7748 * notification since it will be polled */
7751 x11_unthrottle(c->u.x11.xconn);
7754 /* agent sockets are request/response and need no
7755 * buffer management */
7758 pfd_unthrottle(c->u.pfd.pf);
7764 static int ssh_is_simple(Ssh ssh)
7767 * We use the 'simple' variant of the SSH protocol if we're asked
7768 * to, except not if we're also doing connection-sharing (either
7769 * tunnelling our packets over an upstream or expecting to be
7770 * tunnelled over ourselves), since then the assumption that we
7771 * have only one channel to worry about is not true after all.
7773 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7774 !ssh->bare_connection && !ssh->connshare);
7778 * Set up most of a new ssh_channel.
7780 static void ssh_channel_init(struct ssh_channel *c)
7783 c->localid = alloc_channel_id(ssh);
7785 c->pending_eof = FALSE;
7786 c->throttling_conn = FALSE;
7787 if (ssh->version == 2) {
7788 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7789 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7790 c->v.v2.chanreq_head = NULL;
7791 c->v.v2.throttle_state = UNTHROTTLED;
7792 bufchain_init(&c->v.v2.outbuffer);
7794 add234(ssh->channels, c);
7798 * Construct the common parts of a CHANNEL_OPEN.
7800 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
7803 struct Packet *pktout;
7805 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7806 ssh2_pkt_addstring(pktout, type);
7807 ssh2_pkt_adduint32(pktout, c->localid);
7808 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7809 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7814 * CHANNEL_FAILURE doesn't come with any indication of what message
7815 * caused it, so we have to keep track of the outstanding
7816 * CHANNEL_REQUESTs ourselves.
7818 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7819 cchandler_fn_t handler, void *ctx)
7821 struct outstanding_channel_request *ocr =
7822 snew(struct outstanding_channel_request);
7824 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7825 ocr->handler = handler;
7828 if (!c->v.v2.chanreq_head)
7829 c->v.v2.chanreq_head = ocr;
7831 c->v.v2.chanreq_tail->next = ocr;
7832 c->v.v2.chanreq_tail = ocr;
7836 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7837 * NULL then a reply will be requested and the handler will be called
7838 * when it arrives. The returned packet is ready to have any
7839 * request-specific data added and be sent. Note that if a handler is
7840 * provided, it's essential that the request actually be sent.
7842 * The handler will usually be passed the response packet in pktin. If
7843 * pktin is NULL, this means that no reply will ever be forthcoming
7844 * (e.g. because the entire connection is being destroyed, or because
7845 * the server initiated channel closure before we saw the response)
7846 * and the handler should free any storage it's holding.
7848 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
7850 cchandler_fn_t handler, void *ctx)
7852 struct Packet *pktout;
7854 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7855 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7856 ssh2_pkt_adduint32(pktout, c->remoteid);
7857 ssh2_pkt_addstring(pktout, type);
7858 ssh2_pkt_addbool(pktout, handler != NULL);
7859 if (handler != NULL)
7860 ssh2_queue_chanreq_handler(c, handler, ctx);
7864 static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize)
7869 if (ssh->version == 1) {
7870 buflimit = SSH1_BUFFER_LIMIT;
7872 if (ssh_is_simple(ssh))
7875 buflimit = c->v.v2.locmaxwin;
7876 if (bufsize < buflimit)
7877 ssh2_set_window(c, buflimit - bufsize);
7879 if (c->throttling_conn && bufsize <= buflimit) {
7880 c->throttling_conn = 0;
7881 ssh_throttle_conn(ssh, -1);
7886 * Potentially enlarge the window on an SSH-2 channel.
7888 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7890 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7895 * Never send WINDOW_ADJUST for a channel that the remote side has
7896 * already sent EOF on; there's no point, since it won't be
7897 * sending any more data anyway. Ditto if _we've_ already sent
7900 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7904 * Also, never widen the window for an X11 channel when we're
7905 * still waiting to see its initial auth and may yet hand it off
7908 if (c->type == CHAN_X11 && c->u.x11.initial)
7912 * If the remote end has a habit of ignoring maxpkt, limit the
7913 * window so that it has no choice (assuming it doesn't ignore the
7916 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7917 newwin = OUR_V2_MAXPKT;
7920 * Only send a WINDOW_ADJUST if there's significantly more window
7921 * available than the other end thinks there is. This saves us
7922 * sending a WINDOW_ADJUST for every character in a shell session.
7924 * "Significant" is arbitrarily defined as half the window size.
7926 if (newwin / 2 >= c->v.v2.locwindow) {
7927 struct Packet *pktout;
7931 * In order to keep track of how much window the client
7932 * actually has available, we'd like it to acknowledge each
7933 * WINDOW_ADJUST. We can't do that directly, so we accompany
7934 * it with a CHANNEL_REQUEST that has to be acknowledged.
7936 * This is only necessary if we're opening the window wide.
7937 * If we're not, then throughput is being constrained by
7938 * something other than the maximum window size anyway.
7940 if (newwin == c->v.v2.locmaxwin &&
7941 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7942 up = snew(unsigned);
7943 *up = newwin - c->v.v2.locwindow;
7944 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7945 ssh2_handle_winadj_response, up);
7946 ssh2_pkt_send(ssh, pktout);
7948 if (c->v.v2.throttle_state != UNTHROTTLED)
7949 c->v.v2.throttle_state = UNTHROTTLING;
7951 /* Pretend the WINDOW_ADJUST was acked immediately. */
7952 c->v.v2.remlocwin = newwin;
7953 c->v.v2.throttle_state = THROTTLED;
7955 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7956 ssh2_pkt_adduint32(pktout, c->remoteid);
7957 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7958 ssh2_pkt_send(ssh, pktout);
7959 c->v.v2.locwindow = newwin;
7964 * Find the channel associated with a message. If there's no channel,
7965 * or it's not properly open, make a noise about it and return NULL.
7966 * If the channel is shared, pass the message on to downstream and
7967 * also return NULL (meaning the caller should ignore this message).
7969 static struct ssh_channel *ssh_channel_msg(Ssh ssh, struct Packet *pktin)
7971 unsigned localid = ssh_pkt_getuint32(pktin);
7972 struct ssh_channel *c;
7975 /* Is this message OK on a half-open connection? */
7976 if (ssh->version == 1)
7977 halfopen_ok = (pktin->type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION ||
7978 pktin->type == SSH1_MSG_CHANNEL_OPEN_FAILURE);
7980 halfopen_ok = (pktin->type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION ||
7981 pktin->type == SSH2_MSG_CHANNEL_OPEN_FAILURE);
7982 c = find234(ssh->channels, &localid, ssh_channelfind);
7983 if (!c || (c->type != CHAN_SHARING && (c->halfopen != halfopen_ok))) {
7984 char *buf = dupprintf("Received %s for %s channel %u",
7985 ssh_pkt_type(ssh, pktin->type),
7986 !c ? "nonexistent" :
7987 c->halfopen ? "half-open" : "open",
7989 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7993 if (c->type == CHAN_SHARING) {
7994 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7995 pktin->body, pktin->length);
8001 static void ssh2_handle_winadj_response(struct ssh_channel *c,
8002 struct Packet *pktin, void *ctx)
8004 unsigned *sizep = ctx;
8007 * Winadj responses should always be failures. However, at least
8008 * one server ("boks_sshd") is known to return SUCCESS for channel
8009 * requests it's never heard of, such as "winadj@putty". Raised
8010 * with foxt.com as bug 090916-090424, but for the sake of a quiet
8011 * life, we don't worry about what kind of response we got.
8014 c->v.v2.remlocwin += *sizep;
8017 * winadj messages are only sent when the window is fully open, so
8018 * if we get an ack of one, we know any pending unthrottle is
8021 if (c->v.v2.throttle_state == UNTHROTTLING)
8022 c->v.v2.throttle_state = UNTHROTTLED;
8025 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
8027 struct ssh_channel *c = ssh_channel_msg(ssh, pktin);
8028 struct outstanding_channel_request *ocr;
8031 ocr = c->v.v2.chanreq_head;
8033 ssh2_msg_unexpected(ssh, pktin);
8036 ocr->handler(c, pktin, ocr->ctx);
8037 c->v.v2.chanreq_head = ocr->next;
8040 * We may now initiate channel-closing procedures, if that
8041 * CHANNEL_REQUEST was the last thing outstanding before we send
8044 ssh2_channel_check_close(c);
8047 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
8049 struct ssh_channel *c;
8050 c = ssh_channel_msg(ssh, pktin);
8053 if (!(c->closes & CLOSES_SENT_EOF)) {
8054 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
8055 ssh2_try_send_and_unthrottle(ssh, c);
8059 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
8063 unsigned ext_type = 0; /* 0 means not extended */
8064 struct ssh_channel *c;
8065 c = ssh_channel_msg(ssh, pktin);
8068 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
8069 ext_type = ssh_pkt_getuint32(pktin);
8070 ssh_pkt_getstring(pktin, &data, &length);
8073 c->v.v2.locwindow -= length;
8074 c->v.v2.remlocwin -= length;
8075 if (ext_type != 0 && ext_type != SSH2_EXTENDED_DATA_STDERR)
8076 length = 0; /* Don't do anything with unknown extended data. */
8077 bufsize = ssh_channel_data(c, ext_type == SSH2_EXTENDED_DATA_STDERR,
8080 * If it looks like the remote end hit the end of its window,
8081 * and we didn't want it to do that, think about using a
8084 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
8085 c->v.v2.locmaxwin < 0x40000000)
8086 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
8088 * If we are not buffering too much data,
8089 * enlarge the window again at the remote side.
8090 * If we are buffering too much, we may still
8091 * need to adjust the window if the server's
8094 if (bufsize < c->v.v2.locmaxwin)
8095 ssh2_set_window(c, c->v.v2.locmaxwin - bufsize);
8097 * If we're either buffering way too much data, or if we're
8098 * buffering anything at all and we're in "simple" mode,
8099 * throttle the whole channel.
8101 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
8102 && !c->throttling_conn) {
8103 c->throttling_conn = 1;
8104 ssh_throttle_conn(ssh, +1);
8109 static void ssh_check_termination(Ssh ssh)
8111 if (ssh->version == 2 &&
8112 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
8113 (ssh->channels && count234(ssh->channels) == 0) &&
8114 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
8116 * We used to send SSH_MSG_DISCONNECT here, because I'd
8117 * believed that _every_ conforming SSH-2 connection had to
8118 * end with a disconnect being sent by at least one side;
8119 * apparently I was wrong and it's perfectly OK to
8120 * unceremoniously slam the connection shut when you're done,
8121 * and indeed OpenSSH feels this is more polite than sending a
8122 * DISCONNECT. So now we don't.
8124 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
8128 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
8129 const char *peerinfo)
8132 logeventf(ssh, "Connection sharing downstream #%u connected from %s",
8135 logeventf(ssh, "Connection sharing downstream #%u connected", id);
8138 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
8140 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
8141 ssh_check_termination(ssh);
8144 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
8149 va_start(ap, logfmt);
8150 buf = dupvprintf(logfmt, ap);
8153 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
8155 logeventf(ssh, "Connection sharing: %s", buf);
8159 static void ssh_channel_destroy(struct ssh_channel *c)
8164 case CHAN_MAINSESSION:
8165 ssh->mainchan = NULL;
8166 update_specials_menu(ssh->frontend);
8169 assert(c->u.x11.xconn != NULL);
8170 x11_close(c->u.x11.xconn);
8171 logevent("Forwarded X11 connection terminated");
8174 sfree(c->u.a.message);
8177 assert(c->u.pfd.pf != NULL);
8178 pfd_close(c->u.pfd.pf);
8179 logevent("Forwarded port closed");
8183 del234(ssh->channels, c);
8184 if (ssh->version == 2) {
8185 bufchain_clear(&c->v.v2.outbuffer);
8186 assert(c->v.v2.chanreq_head == NULL);
8191 * If that was the last channel left open, we might need to
8194 ssh_check_termination(ssh);
8197 static void ssh2_channel_check_close(struct ssh_channel *c)
8200 struct Packet *pktout;
8202 assert(ssh->version == 2);
8205 * If we've sent out our own CHANNEL_OPEN but not yet seen
8206 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
8207 * it's too early to be sending close messages of any kind.
8212 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
8213 c->type == CHAN_ZOMBIE) &&
8214 !c->v.v2.chanreq_head &&
8215 !(c->closes & CLOSES_SENT_CLOSE)) {
8217 * We have both sent and received EOF (or the channel is a
8218 * zombie), and we have no outstanding channel requests, which
8219 * means the channel is in final wind-up. But we haven't sent
8220 * CLOSE, so let's do so now.
8222 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
8223 ssh2_pkt_adduint32(pktout, c->remoteid);
8224 ssh2_pkt_send(ssh, pktout);
8225 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
8228 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
8229 assert(c->v.v2.chanreq_head == NULL);
8231 * We have both sent and received CLOSE, which means we're
8232 * completely done with the channel.
8234 ssh_channel_destroy(c);
8238 static void ssh2_channel_got_eof(struct ssh_channel *c)
8240 if (c->closes & CLOSES_RCVD_EOF)
8241 return; /* already seen EOF */
8242 c->closes |= CLOSES_RCVD_EOF;
8244 if (c->type == CHAN_X11) {
8245 x11_send_eof(c->u.x11.xconn);
8246 } else if (c->type == CHAN_AGENT) {
8247 if (c->u.a.outstanding_requests == 0) {
8248 /* Manufacture an outgoing EOF in response to the incoming one. */
8249 sshfwd_write_eof(c);
8251 } else if (c->type == CHAN_SOCKDATA) {
8252 pfd_send_eof(c->u.pfd.pf);
8253 } else if (c->type == CHAN_MAINSESSION) {
8256 if (!ssh->sent_console_eof &&
8257 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
8259 * Either from_backend_eof told us that the front end
8260 * wants us to close the outgoing side of the connection
8261 * as soon as we see EOF from the far end, or else we've
8262 * unilaterally decided to do that because we've allocated
8263 * a remote pty and hence EOF isn't a particularly
8264 * meaningful concept.
8266 sshfwd_write_eof(c);
8268 ssh->sent_console_eof = TRUE;
8271 ssh2_channel_check_close(c);
8274 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
8276 struct ssh_channel *c;
8278 c = ssh_channel_msg(ssh, pktin);
8281 ssh2_channel_got_eof(c);
8284 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
8286 struct ssh_channel *c;
8288 c = ssh_channel_msg(ssh, pktin);
8293 * When we receive CLOSE on a channel, we assume it comes with an
8294 * implied EOF if we haven't seen EOF yet.
8296 ssh2_channel_got_eof(c);
8298 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
8300 * It also means we stop expecting to see replies to any
8301 * outstanding channel requests, so clean those up too.
8302 * (ssh_chanreq_init will enforce by assertion that we don't
8303 * subsequently put anything back on this list.)
8305 while (c->v.v2.chanreq_head) {
8306 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8307 ocr->handler(c, NULL, ocr->ctx);
8308 c->v.v2.chanreq_head = ocr->next;
8314 * And we also send an outgoing EOF, if we haven't already, on the
8315 * assumption that CLOSE is a pretty forceful announcement that
8316 * the remote side is doing away with the entire channel. (If it
8317 * had wanted to send us EOF and continue receiving data from us,
8318 * it would have just sent CHANNEL_EOF.)
8320 if (!(c->closes & CLOSES_SENT_EOF)) {
8322 * Make sure we don't read any more from whatever our local
8323 * data source is for this channel.
8326 case CHAN_MAINSESSION:
8327 ssh->send_ok = 0; /* stop trying to read from stdin */
8330 x11_override_throttle(c->u.x11.xconn, 1);
8333 pfd_override_throttle(c->u.pfd.pf, 1);
8338 * Abandon any buffered data we still wanted to send to this
8339 * channel. Receiving a CHANNEL_CLOSE is an indication that
8340 * the server really wants to get on and _destroy_ this
8341 * channel, and it isn't going to send us any further
8342 * WINDOW_ADJUSTs to permit us to send pending stuff.
8344 bufchain_clear(&c->v.v2.outbuffer);
8347 * Send outgoing EOF.
8349 sshfwd_write_eof(c);
8353 * Now process the actual close.
8355 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8356 c->closes |= CLOSES_RCVD_CLOSE;
8357 ssh2_channel_check_close(c);
8361 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8363 struct ssh_channel *c;
8365 c = ssh_channel_msg(ssh, pktin);
8368 assert(c->halfopen); /* ssh_channel_msg will have enforced this */
8369 c->remoteid = ssh_pkt_getuint32(pktin);
8370 c->halfopen = FALSE;
8371 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8372 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8374 if (c->type == CHAN_SOCKDATA) {
8375 assert(c->u.pfd.pf != NULL);
8376 pfd_confirm(c->u.pfd.pf);
8377 } else if (c->type == CHAN_ZOMBIE) {
8379 * This case can occur if a local socket error occurred
8380 * between us sending out CHANNEL_OPEN and receiving
8381 * OPEN_CONFIRMATION. In this case, all we can do is
8382 * immediately initiate close proceedings now that we know the
8383 * server's id to put in the close message.
8385 ssh2_channel_check_close(c);
8388 * We never expect to receive OPEN_CONFIRMATION for any
8389 * *other* channel type (since only local-to-remote port
8390 * forwardings cause us to send CHANNEL_OPEN after the main
8391 * channel is live - all other auxiliary channel types are
8392 * initiated from the server end). It's safe to enforce this
8393 * by assertion rather than by ssh_disconnect, because the
8394 * real point is that we never constructed a half-open channel
8395 * structure in the first place with any type other than the
8398 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8402 ssh_channel_try_eof(c); /* in case we had a pending EOF */
8405 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8407 static const char *const reasons[] = {
8408 "<unknown reason code>",
8409 "Administratively prohibited",
8411 "Unknown channel type",
8412 "Resource shortage",
8414 unsigned reason_code;
8415 char *reason_string;
8417 struct ssh_channel *c;
8419 c = ssh_channel_msg(ssh, pktin);
8422 assert(c->halfopen); /* ssh_channel_msg will have enforced this */
8424 if (c->type == CHAN_SOCKDATA) {
8425 reason_code = ssh_pkt_getuint32(pktin);
8426 if (reason_code >= lenof(reasons))
8427 reason_code = 0; /* ensure reasons[reason_code] in range */
8428 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8429 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8430 reasons[reason_code], reason_length,
8431 NULLTOEMPTY(reason_string));
8433 pfd_close(c->u.pfd.pf);
8434 } else if (c->type == CHAN_ZOMBIE) {
8436 * This case can occur if a local socket error occurred
8437 * between us sending out CHANNEL_OPEN and receiving
8438 * OPEN_FAILURE. In this case, we need do nothing except allow
8439 * the code below to throw the half-open channel away.
8443 * We never expect to receive OPEN_FAILURE for any *other*
8444 * channel type (since only local-to-remote port forwardings
8445 * cause us to send CHANNEL_OPEN after the main channel is
8446 * live - all other auxiliary channel types are initiated from
8447 * the server end). It's safe to enforce this by assertion
8448 * rather than by ssh_disconnect, because the real point is
8449 * that we never constructed a half-open channel structure in
8450 * the first place with any type other than the above.
8452 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8455 del234(ssh->channels, c);
8459 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8462 int typelen, want_reply;
8463 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8464 struct ssh_channel *c;
8465 struct Packet *pktout;
8467 c = ssh_channel_msg(ssh, pktin);
8470 ssh_pkt_getstring(pktin, &type, &typelen);
8471 want_reply = ssh2_pkt_getbool(pktin);
8473 if (c->closes & CLOSES_SENT_CLOSE) {
8475 * We don't reply to channel requests after we've sent
8476 * CHANNEL_CLOSE for the channel, because our reply might
8477 * cross in the network with the other side's CHANNEL_CLOSE
8478 * and arrive after they have wound the channel up completely.
8484 * Having got the channel number, we now look at
8485 * the request type string to see if it's something
8488 if (c == ssh->mainchan) {
8490 * We recognise "exit-status" and "exit-signal" on
8491 * the primary channel.
8493 if (typelen == 11 &&
8494 !memcmp(type, "exit-status", 11)) {
8496 ssh->exitcode = ssh_pkt_getuint32(pktin);
8497 logeventf(ssh, "Server sent command exit status %d",
8499 reply = SSH2_MSG_CHANNEL_SUCCESS;
8501 } else if (typelen == 11 &&
8502 !memcmp(type, "exit-signal", 11)) {
8504 int is_plausible = TRUE, is_int = FALSE;
8505 char *fmt_sig = NULL, *fmt_msg = NULL;
8507 int msglen = 0, core = FALSE;
8508 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8509 * provide an `int' for the signal, despite its
8510 * having been a `string' in the drafts of RFC 4254 since at
8511 * least 2001. (Fixed in session.c 1.147.) Try to
8512 * infer which we can safely parse it as. */
8514 unsigned char *p = pktin->body +
8516 long len = pktin->length - pktin->savedpos;
8517 unsigned long num = GET_32BIT(p); /* what is it? */
8518 /* If it's 0, it hardly matters; assume string */
8522 int maybe_int = FALSE, maybe_str = FALSE;
8523 #define CHECK_HYPOTHESIS(offset, result) \
8526 int q = toint(offset); \
8527 if (q >= 0 && q+4 <= len) { \
8528 q = toint(q + 4 + GET_32BIT(p+q)); \
8529 if (q >= 0 && q+4 <= len && \
8530 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8535 CHECK_HYPOTHESIS(4+1, maybe_int);
8536 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8537 #undef CHECK_HYPOTHESIS
8538 if (maybe_int && !maybe_str)
8540 else if (!maybe_int && maybe_str)
8543 /* Crikey. Either or neither. Panic. */
8544 is_plausible = FALSE;
8547 ssh->exitcode = 128; /* means `unknown signal' */
8550 /* Old non-standard OpenSSH. */
8551 int signum = ssh_pkt_getuint32(pktin);
8552 fmt_sig = dupprintf(" %d", signum);
8553 ssh->exitcode = 128 + signum;
8555 /* As per RFC 4254. */
8558 ssh_pkt_getstring(pktin, &sig, &siglen);
8559 /* Signal name isn't supposed to be blank, but
8560 * let's cope gracefully if it is. */
8562 fmt_sig = dupprintf(" \"%.*s\"",
8567 * Really hideous method of translating the
8568 * signal description back into a locally
8569 * meaningful number.
8574 #define TRANSLATE_SIGNAL(s) \
8575 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8576 ssh->exitcode = 128 + SIG ## s
8578 TRANSLATE_SIGNAL(ABRT);
8581 TRANSLATE_SIGNAL(ALRM);
8584 TRANSLATE_SIGNAL(FPE);
8587 TRANSLATE_SIGNAL(HUP);
8590 TRANSLATE_SIGNAL(ILL);
8593 TRANSLATE_SIGNAL(INT);
8596 TRANSLATE_SIGNAL(KILL);
8599 TRANSLATE_SIGNAL(PIPE);
8602 TRANSLATE_SIGNAL(QUIT);
8605 TRANSLATE_SIGNAL(SEGV);
8608 TRANSLATE_SIGNAL(TERM);
8611 TRANSLATE_SIGNAL(USR1);
8614 TRANSLATE_SIGNAL(USR2);
8616 #undef TRANSLATE_SIGNAL
8618 ssh->exitcode = 128;
8620 core = ssh2_pkt_getbool(pktin);
8621 ssh_pkt_getstring(pktin, &msg, &msglen);
8623 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8625 /* ignore lang tag */
8626 } /* else don't attempt to parse */
8627 logeventf(ssh, "Server exited on signal%s%s%s",
8628 fmt_sig ? fmt_sig : "",
8629 core ? " (core dumped)" : "",
8630 fmt_msg ? fmt_msg : "");
8633 reply = SSH2_MSG_CHANNEL_SUCCESS;
8638 * This is a channel request we don't know
8639 * about, so we now either ignore the request
8640 * or respond with CHANNEL_FAILURE, depending
8643 reply = SSH2_MSG_CHANNEL_FAILURE;
8646 pktout = ssh2_pkt_init(reply);
8647 ssh2_pkt_adduint32(pktout, c->remoteid);
8648 ssh2_pkt_send(ssh, pktout);
8652 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8655 int typelen, want_reply;
8656 struct Packet *pktout;
8658 ssh_pkt_getstring(pktin, &type, &typelen);
8659 want_reply = ssh2_pkt_getbool(pktin);
8662 * We currently don't support any global requests
8663 * at all, so we either ignore the request or
8664 * respond with REQUEST_FAILURE, depending on
8668 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8669 ssh2_pkt_send(ssh, pktout);
8673 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8677 struct X11FakeAuth *auth;
8680 * Make up a new set of fake X11 auth data, and add it to the tree
8681 * of currently valid ones with an indication of the sharing
8682 * context that it's relevant to.
8684 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8685 auth->share_cs = share_cs;
8686 auth->share_chan = share_chan;
8691 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8693 del234(ssh->x11authtree, auth);
8694 x11_free_fake_auth(auth);
8697 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8704 const char *error = NULL;
8705 struct ssh_channel *c;
8706 unsigned remid, winsize, pktsize;
8707 unsigned our_winsize_override = 0;
8708 struct Packet *pktout;
8710 ssh_pkt_getstring(pktin, &type, &typelen);
8711 c = snew(struct ssh_channel);
8714 remid = ssh_pkt_getuint32(pktin);
8715 winsize = ssh_pkt_getuint32(pktin);
8716 pktsize = ssh_pkt_getuint32(pktin);
8718 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8721 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8722 addrstr = dupprintf("%.*s", peeraddrlen, NULLTOEMPTY(peeraddr));
8723 peerport = ssh_pkt_getuint32(pktin);
8725 logeventf(ssh, "Received X11 connect request from %s:%d",
8728 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8729 error = "X11 forwarding is not enabled";
8731 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8734 c->u.x11.initial = TRUE;
8737 * If we are a connection-sharing upstream, then we should
8738 * initially present a very small window, adequate to take
8739 * the X11 initial authorisation packet but not much more.
8740 * Downstream will then present us a larger window (by
8741 * fiat of the connection-sharing protocol) and we can
8742 * guarantee to send a positive-valued WINDOW_ADJUST.
8745 our_winsize_override = 128;
8747 logevent("Opened X11 forward channel");
8751 } else if (typelen == 15 &&
8752 !memcmp(type, "forwarded-tcpip", 15)) {
8753 struct ssh_rportfwd pf, *realpf;
8756 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8757 pf.shost = dupprintf("%.*s", shostlen, NULLTOEMPTY(shost));
8758 pf.sport = ssh_pkt_getuint32(pktin);
8759 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8760 peerport = ssh_pkt_getuint32(pktin);
8761 realpf = find234(ssh->rportfwds, &pf, NULL);
8762 logeventf(ssh, "Received remote port %s:%d open request "
8763 "from %.*s:%d", pf.shost, pf.sport,
8764 peeraddrlen, NULLTOEMPTY(peeraddr), peerport);
8767 if (realpf == NULL) {
8768 error = "Remote port is not recognised";
8772 if (realpf->share_ctx) {
8774 * This port forwarding is on behalf of a
8775 * connection-sharing downstream, so abandon our own
8776 * channel-open procedure and just pass the message on
8779 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8780 pktin->body, pktin->length);
8785 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8786 c, ssh->conf, realpf->pfrec->addressfamily);
8787 logeventf(ssh, "Attempting to forward remote port to "
8788 "%s:%d", realpf->dhost, realpf->dport);
8790 logeventf(ssh, "Port open failed: %s", err);
8792 error = "Port open failed";
8794 logevent("Forwarded port opened successfully");
8795 c->type = CHAN_SOCKDATA;
8798 } else if (typelen == 22 &&
8799 !memcmp(type, "auth-agent@openssh.com", 22)) {
8800 if (!ssh->agentfwd_enabled)
8801 error = "Agent forwarding is not enabled";
8803 c->type = CHAN_AGENT; /* identify channel type */
8804 c->u.a.lensofar = 0;
8805 c->u.a.message = NULL;
8806 c->u.a.outstanding_requests = 0;
8809 error = "Unsupported channel type requested";
8812 c->remoteid = remid;
8813 c->halfopen = FALSE;
8815 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8816 ssh2_pkt_adduint32(pktout, c->remoteid);
8817 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8818 ssh2_pkt_addstring(pktout, error);
8819 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8820 ssh2_pkt_send(ssh, pktout);
8821 logeventf(ssh, "Rejected channel open: %s", error);
8824 ssh_channel_init(c);
8825 c->v.v2.remwindow = winsize;
8826 c->v.v2.remmaxpkt = pktsize;
8827 if (our_winsize_override) {
8828 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8829 our_winsize_override;
8831 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8832 ssh2_pkt_adduint32(pktout, c->remoteid);
8833 ssh2_pkt_adduint32(pktout, c->localid);
8834 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8835 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8836 ssh2_pkt_send(ssh, pktout);
8840 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8841 void *share_cs, void *share_chan,
8842 const char *peer_addr, int peer_port,
8843 int endian, int protomajor, int protominor,
8844 const void *initial_data, int initial_len)
8847 * This function is called when we've just discovered that an X
8848 * forwarding channel on which we'd been handling the initial auth
8849 * ourselves turns out to be destined for a connection-sharing
8850 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8851 * that we completely stop tracking windows and buffering data and
8852 * just pass more or less unmodified SSH messages back and forth.
8854 c->type = CHAN_SHARING;
8855 c->u.sharing.ctx = share_cs;
8856 share_setup_x11_channel(share_cs, share_chan,
8857 c->localid, c->remoteid, c->v.v2.remwindow,
8858 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8859 peer_addr, peer_port, endian,
8860 protomajor, protominor,
8861 initial_data, initial_len);
8864 void sshfwd_x11_is_local(struct ssh_channel *c)
8867 * This function is called when we've just discovered that an X
8868 * forwarding channel is _not_ destined for a connection-sharing
8869 * downstream but we're going to handle it ourselves. We stop
8870 * presenting a cautiously small window and go into ordinary data
8873 c->u.x11.initial = FALSE;
8874 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8878 * Buffer banner messages for later display at some convenient point,
8879 * if we're going to display them.
8881 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8883 /* Arbitrary limit to prevent unbounded inflation of buffer */
8884 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8885 bufchain_size(&ssh->banner) <= 131072) {
8886 char *banner = NULL;
8888 ssh_pkt_getstring(pktin, &banner, &size);
8890 bufchain_add(&ssh->banner, banner, size);
8894 /* Helper function to deal with sending tty modes for "pty-req" */
8895 static void ssh2_send_ttymode(void *data,
8896 const struct ssh_ttymode *mode, char *val)
8898 struct Packet *pktout = (struct Packet *)data;
8899 unsigned int arg = 0;
8901 switch (mode->type) {
8903 arg = ssh_tty_parse_specchar(val);
8906 arg = ssh_tty_parse_boolean(val);
8909 ssh2_pkt_addbyte(pktout, mode->opcode);
8910 ssh2_pkt_adduint32(pktout, arg);
8913 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8916 struct ssh2_setup_x11_state {
8920 struct Packet *pktout;
8921 crStateP(ssh2_setup_x11_state, ctx);
8925 logevent("Requesting X11 forwarding");
8926 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8928 ssh2_pkt_addbool(pktout, 0); /* many connections */
8929 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8930 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8931 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8932 ssh2_pkt_send(ssh, pktout);
8934 /* Wait to be called back with either a response packet, or NULL
8935 * meaning clean up and free our data */
8939 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8940 logevent("X11 forwarding enabled");
8941 ssh->X11_fwd_enabled = TRUE;
8943 logevent("X11 forwarding refused");
8949 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8952 struct ssh2_setup_agent_state {
8956 struct Packet *pktout;
8957 crStateP(ssh2_setup_agent_state, ctx);
8961 logevent("Requesting OpenSSH-style agent forwarding");
8962 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
8963 ssh2_setup_agent, s);
8964 ssh2_pkt_send(ssh, pktout);
8966 /* Wait to be called back with either a response packet, or NULL
8967 * meaning clean up and free our data */
8971 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8972 logevent("Agent forwarding enabled");
8973 ssh->agentfwd_enabled = TRUE;
8975 logevent("Agent forwarding refused");
8981 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
8984 struct ssh2_setup_pty_state {
8988 struct Packet *pktout;
8989 crStateP(ssh2_setup_pty_state, ctx);
8993 /* Unpick the terminal-speed string. */
8994 /* XXX perhaps we should allow no speeds to be sent. */
8995 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8996 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
8997 /* Build the pty request. */
8998 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
9000 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
9001 ssh2_pkt_adduint32(pktout, ssh->term_width);
9002 ssh2_pkt_adduint32(pktout, ssh->term_height);
9003 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
9004 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
9005 ssh2_pkt_addstring_start(pktout);
9006 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
9007 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
9008 ssh2_pkt_adduint32(pktout, ssh->ispeed);
9009 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
9010 ssh2_pkt_adduint32(pktout, ssh->ospeed);
9011 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
9012 ssh2_pkt_send(ssh, pktout);
9013 ssh->state = SSH_STATE_INTERMED;
9015 /* Wait to be called back with either a response packet, or NULL
9016 * meaning clean up and free our data */
9020 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9021 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9022 ssh->ospeed, ssh->ispeed);
9023 ssh->got_pty = TRUE;
9025 c_write_str(ssh, "Server refused to allocate pty\r\n");
9026 ssh->editing = ssh->echoing = 1;
9033 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
9036 struct ssh2_setup_env_state {
9038 int num_env, env_left, env_ok;
9041 struct Packet *pktout;
9042 crStateP(ssh2_setup_env_state, ctx);
9047 * Send environment variables.
9049 * Simplest thing here is to send all the requests at once, and
9050 * then wait for a whole bunch of successes or failures.
9056 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9058 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9059 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
9060 ssh2_pkt_addstring(pktout, key);
9061 ssh2_pkt_addstring(pktout, val);
9062 ssh2_pkt_send(ssh, pktout);
9067 logeventf(ssh, "Sent %d environment variables", s->num_env);
9072 s->env_left = s->num_env;
9074 while (s->env_left > 0) {
9075 /* Wait to be called back with either a response packet,
9076 * or NULL meaning clean up and free our data */
9078 if (!pktin) goto out;
9079 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
9084 if (s->env_ok == s->num_env) {
9085 logevent("All environment variables successfully set");
9086 } else if (s->env_ok == 0) {
9087 logevent("All environment variables refused");
9088 c_write_str(ssh, "Server refused to set environment variables\r\n");
9090 logeventf(ssh, "%d environment variables refused",
9091 s->num_env - s->env_ok);
9092 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9100 * Handle the SSH-2 userauth and connection layers.
9102 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
9104 do_ssh2_authconn(ssh, NULL, 0, pktin);
9107 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
9111 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
9114 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
9115 struct Packet *pktin)
9117 struct do_ssh2_authconn_state {
9121 AUTH_TYPE_PUBLICKEY,
9122 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
9123 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
9125 AUTH_TYPE_GSSAPI, /* always QUIET */
9126 AUTH_TYPE_KEYBOARD_INTERACTIVE,
9127 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
9129 int done_service_req;
9130 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
9131 int tried_pubkey_config, done_agent;
9136 int kbd_inter_refused;
9137 int we_are_in, userauth_success;
9138 prompts_t *cur_prompt;
9143 void *publickey_blob;
9144 int publickey_bloblen;
9145 int privatekey_available, privatekey_encrypted;
9146 char *publickey_algorithm;
9147 char *publickey_comment;
9148 unsigned char agent_request[5], *agent_response, *agentp;
9149 int agent_responselen;
9150 unsigned char *pkblob_in_agent;
9152 char *pkblob, *alg, *commentp;
9153 int pklen, alglen, commentlen;
9154 int siglen, retlen, len;
9155 char *q, *agentreq, *ret;
9156 struct Packet *pktout;
9159 struct ssh_gss_library *gsslib;
9160 Ssh_gss_ctx gss_ctx;
9161 Ssh_gss_buf gss_buf;
9162 Ssh_gss_buf gss_rcvtok, gss_sndtok;
9163 Ssh_gss_name gss_srv_name;
9164 Ssh_gss_stat gss_stat;
9167 crState(do_ssh2_authconn_state);
9171 /* Register as a handler for all the messages this coroutine handles. */
9172 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
9173 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
9174 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
9175 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
9176 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
9177 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
9178 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
9179 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
9180 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
9181 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
9182 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
9183 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
9184 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
9185 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
9186 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
9187 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
9188 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
9189 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
9190 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
9191 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
9193 s->done_service_req = FALSE;
9194 s->we_are_in = s->userauth_success = FALSE;
9195 s->agent_response = NULL;
9197 s->tried_gssapi = FALSE;
9200 if (!ssh->bare_connection) {
9201 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
9203 * Request userauth protocol, and await a response to it.
9205 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9206 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
9207 ssh2_pkt_send(ssh, s->pktout);
9208 crWaitUntilV(pktin);
9209 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
9210 s->done_service_req = TRUE;
9212 if (!s->done_service_req) {
9214 * Request connection protocol directly, without authentication.
9216 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9217 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9218 ssh2_pkt_send(ssh, s->pktout);
9219 crWaitUntilV(pktin);
9220 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
9221 s->we_are_in = TRUE; /* no auth required */
9223 bombout(("Server refused service request"));
9228 s->we_are_in = TRUE;
9231 /* Arrange to be able to deal with any BANNERs that come in.
9232 * (We do this now as packets may come in during the next bit.) */
9233 bufchain_init(&ssh->banner);
9234 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
9235 ssh2_msg_userauth_banner;
9238 * Misc one-time setup for authentication.
9240 s->publickey_blob = NULL;
9241 if (!s->we_are_in) {
9244 * Load the public half of any configured public key file
9247 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9248 if (!filename_is_null(s->keyfile)) {
9250 logeventf(ssh, "Reading key file \"%.150s\"",
9251 filename_to_str(s->keyfile));
9252 keytype = key_type(s->keyfile);
9253 if (keytype == SSH_KEYTYPE_SSH2 ||
9254 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
9255 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
9258 ssh2_userkey_loadpub(s->keyfile,
9259 &s->publickey_algorithm,
9260 &s->publickey_bloblen,
9261 &s->publickey_comment, &error);
9262 if (s->publickey_blob) {
9263 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
9264 if (!s->privatekey_available)
9265 logeventf(ssh, "Key file contains public key only");
9266 s->privatekey_encrypted =
9267 ssh2_userkey_encrypted(s->keyfile, NULL);
9270 logeventf(ssh, "Unable to load key (%s)",
9272 msgbuf = dupprintf("Unable to load key file "
9273 "\"%.150s\" (%s)\r\n",
9274 filename_to_str(s->keyfile),
9276 c_write_str(ssh, msgbuf);
9281 logeventf(ssh, "Unable to use this key file (%s)",
9282 key_type_to_str(keytype));
9283 msgbuf = dupprintf("Unable to use key file \"%.150s\""
9285 filename_to_str(s->keyfile),
9286 key_type_to_str(keytype));
9287 c_write_str(ssh, msgbuf);
9289 s->publickey_blob = NULL;
9294 * Find out about any keys Pageant has (but if there's a
9295 * public key configured, filter out all others).
9298 s->agent_response = NULL;
9299 s->pkblob_in_agent = NULL;
9300 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9304 logevent("Pageant is running. Requesting keys.");
9306 /* Request the keys held by the agent. */
9307 PUT_32BIT(s->agent_request, 1);
9308 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9309 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
9310 ssh_agent_callback, ssh)) {
9314 bombout(("Unexpected data from server while"
9315 " waiting for agent response"));
9318 } while (pktin || inlen > 0);
9319 r = ssh->agent_response;
9320 s->agent_responselen = ssh->agent_response_len;
9322 s->agent_response = (unsigned char *) r;
9323 if (s->agent_response && s->agent_responselen >= 5 &&
9324 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9327 p = s->agent_response + 5;
9328 s->nkeys = toint(GET_32BIT(p));
9331 * Vet the Pageant response to ensure that the key
9332 * count and blob lengths make sense.
9335 logeventf(ssh, "Pageant response contained a negative"
9336 " key count %d", s->nkeys);
9338 goto done_agent_query;
9340 unsigned char *q = p + 4;
9341 int lenleft = s->agent_responselen - 5 - 4;
9343 for (keyi = 0; keyi < s->nkeys; keyi++) {
9344 int bloblen, commentlen;
9346 logeventf(ssh, "Pageant response was truncated");
9348 goto done_agent_query;
9350 bloblen = toint(GET_32BIT(q));
9351 if (bloblen < 0 || bloblen > lenleft) {
9352 logeventf(ssh, "Pageant response was truncated");
9354 goto done_agent_query;
9356 lenleft -= 4 + bloblen;
9358 commentlen = toint(GET_32BIT(q));
9359 if (commentlen < 0 || commentlen > lenleft) {
9360 logeventf(ssh, "Pageant response was truncated");
9362 goto done_agent_query;
9364 lenleft -= 4 + commentlen;
9365 q += 4 + commentlen;
9370 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9371 if (s->publickey_blob) {
9372 /* See if configured key is in agent. */
9373 for (keyi = 0; keyi < s->nkeys; keyi++) {
9374 s->pklen = toint(GET_32BIT(p));
9375 if (s->pklen == s->publickey_bloblen &&
9376 !memcmp(p+4, s->publickey_blob,
9377 s->publickey_bloblen)) {
9378 logeventf(ssh, "Pageant key #%d matches "
9379 "configured key file", keyi);
9381 s->pkblob_in_agent = p;
9385 p += toint(GET_32BIT(p)) + 4; /* comment */
9387 if (!s->pkblob_in_agent) {
9388 logevent("Configured key file not in Pageant");
9393 logevent("Failed to get reply from Pageant");
9401 * We repeat this whole loop, including the username prompt,
9402 * until we manage a successful authentication. If the user
9403 * types the wrong _password_, they can be sent back to the
9404 * beginning to try another username, if this is configured on.
9405 * (If they specify a username in the config, they are never
9406 * asked, even if they do give a wrong password.)
9408 * I think this best serves the needs of
9410 * - the people who have no configuration, no keys, and just
9411 * want to try repeated (username,password) pairs until they
9412 * type both correctly
9414 * - people who have keys and configuration but occasionally
9415 * need to fall back to passwords
9417 * - people with a key held in Pageant, who might not have
9418 * logged in to a particular machine before; so they want to
9419 * type a username, and then _either_ their key will be
9420 * accepted, _or_ they will type a password. If they mistype
9421 * the username they will want to be able to get back and
9424 s->got_username = FALSE;
9425 while (!s->we_are_in) {
9429 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9431 * We got a username last time round this loop, and
9432 * with change_username turned off we don't try to get
9435 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9436 int ret; /* need not be kept over crReturn */
9437 s->cur_prompt = new_prompts(ssh->frontend);
9438 s->cur_prompt->to_server = TRUE;
9439 s->cur_prompt->name = dupstr("SSH login name");
9440 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9441 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9444 crWaitUntilV(!pktin);
9445 ret = get_userpass_input(s->cur_prompt, in, inlen);
9450 * get_userpass_input() failed to get a username.
9453 free_prompts(s->cur_prompt);
9454 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9457 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9458 free_prompts(s->cur_prompt);
9461 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9462 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9463 c_write_str(ssh, stuff);
9467 s->got_username = TRUE;
9470 * Send an authentication request using method "none": (a)
9471 * just in case it succeeds, and (b) so that we know what
9472 * authentication methods we can usefully try next.
9474 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9476 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9477 ssh2_pkt_addstring(s->pktout, ssh->username);
9478 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9479 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9480 ssh2_pkt_send(ssh, s->pktout);
9481 s->type = AUTH_TYPE_NONE;
9483 s->we_are_in = FALSE;
9485 s->tried_pubkey_config = FALSE;
9486 s->kbd_inter_refused = FALSE;
9488 /* Reset agent request state. */
9489 s->done_agent = FALSE;
9490 if (s->agent_response) {
9491 if (s->pkblob_in_agent) {
9492 s->agentp = s->pkblob_in_agent;
9494 s->agentp = s->agent_response + 5 + 4;
9500 char *methods = NULL;
9504 * Wait for the result of the last authentication request.
9507 crWaitUntilV(pktin);
9509 * Now is a convenient point to spew any banner material
9510 * that we've accumulated. (This should ensure that when
9511 * we exit the auth loop, we haven't any left to deal
9515 int size = bufchain_size(&ssh->banner);
9517 * Don't show the banner if we're operating in
9518 * non-verbose non-interactive mode. (It's probably
9519 * a script, which means nobody will read the
9520 * banner _anyway_, and moreover the printing of
9521 * the banner will screw up processing on the
9522 * output of (say) plink.)
9524 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9525 char *banner = snewn(size, char);
9526 bufchain_fetch(&ssh->banner, banner, size);
9527 c_write_untrusted(ssh, banner, size);
9530 bufchain_clear(&ssh->banner);
9532 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9533 logevent("Access granted");
9534 s->we_are_in = s->userauth_success = TRUE;
9538 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9539 bombout(("Strange packet received during authentication: "
9540 "type %d", pktin->type));
9547 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9548 * we can look at the string in it and know what we can
9549 * helpfully try next.
9551 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9552 ssh_pkt_getstring(pktin, &methods, &methlen);
9553 if (!ssh2_pkt_getbool(pktin)) {
9555 * We have received an unequivocal Access
9556 * Denied. This can translate to a variety of
9557 * messages, or no message at all.
9559 * For forms of authentication which are attempted
9560 * implicitly, by which I mean without printing
9561 * anything in the window indicating that we're
9562 * trying them, we should never print 'Access
9565 * If we do print a message saying that we're
9566 * attempting some kind of authentication, it's OK
9567 * to print a followup message saying it failed -
9568 * but the message may sometimes be more specific
9569 * than simply 'Access denied'.
9571 * Additionally, if we'd just tried password
9572 * authentication, we should break out of this
9573 * whole loop so as to go back to the username
9574 * prompt (iff we're configured to allow
9575 * username change attempts).
9577 if (s->type == AUTH_TYPE_NONE) {
9579 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9580 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9581 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9582 c_write_str(ssh, "Server refused our key\r\n");
9583 logevent("Server refused our key");
9584 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9585 /* This _shouldn't_ happen except by a
9586 * protocol bug causing client and server to
9587 * disagree on what is a correct signature. */
9588 c_write_str(ssh, "Server refused public-key signature"
9589 " despite accepting key!\r\n");
9590 logevent("Server refused public-key signature"
9591 " despite accepting key!");
9592 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9593 /* quiet, so no c_write */
9594 logevent("Server refused keyboard-interactive authentication");
9595 } else if (s->type==AUTH_TYPE_GSSAPI) {
9596 /* always quiet, so no c_write */
9597 /* also, the code down in the GSSAPI block has
9598 * already logged this in the Event Log */
9599 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9600 logevent("Keyboard-interactive authentication failed");
9601 c_write_str(ssh, "Access denied\r\n");
9603 assert(s->type == AUTH_TYPE_PASSWORD);
9604 logevent("Password authentication failed");
9605 c_write_str(ssh, "Access denied\r\n");
9607 if (conf_get_int(ssh->conf, CONF_change_username)) {
9608 /* XXX perhaps we should allow
9609 * keyboard-interactive to do this too? */
9610 s->we_are_in = FALSE;
9615 c_write_str(ssh, "Further authentication required\r\n");
9616 logevent("Further authentication required");
9620 in_commasep_string("publickey", methods, methlen);
9622 in_commasep_string("password", methods, methlen);
9623 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9624 in_commasep_string("keyboard-interactive", methods, methlen);
9626 if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9627 in_commasep_string("gssapi-with-mic", methods, methlen)) {
9628 /* Try loading the GSS libraries and see if we
9631 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9632 s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
9634 /* No point in even bothering to try to load the
9635 * GSS libraries, if the user configuration and
9636 * server aren't both prepared to attempt GSSAPI
9637 * auth in the first place. */
9638 s->can_gssapi = FALSE;
9643 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9645 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9648 * Attempt public-key authentication using a key from Pageant.
9651 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9653 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9655 /* Unpack key from agent response */
9656 s->pklen = toint(GET_32BIT(s->agentp));
9658 s->pkblob = (char *)s->agentp;
9659 s->agentp += s->pklen;
9660 s->alglen = toint(GET_32BIT(s->pkblob));
9661 s->alg = s->pkblob + 4;
9662 s->commentlen = toint(GET_32BIT(s->agentp));
9664 s->commentp = (char *)s->agentp;
9665 s->agentp += s->commentlen;
9666 /* s->agentp now points at next key, if any */
9668 /* See if server will accept it */
9669 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9670 ssh2_pkt_addstring(s->pktout, ssh->username);
9671 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9672 /* service requested */
9673 ssh2_pkt_addstring(s->pktout, "publickey");
9675 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9676 ssh2_pkt_addstring_start(s->pktout);
9677 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9678 ssh2_pkt_addstring_start(s->pktout);
9679 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9680 ssh2_pkt_send(ssh, s->pktout);
9681 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9683 crWaitUntilV(pktin);
9684 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9686 /* Offer of key refused. */
9693 if (flags & FLAG_VERBOSE) {
9694 c_write_str(ssh, "Authenticating with "
9696 c_write(ssh, s->commentp, s->commentlen);
9697 c_write_str(ssh, "\" from agent\r\n");
9701 * Server is willing to accept the key.
9702 * Construct a SIGN_REQUEST.
9704 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9705 ssh2_pkt_addstring(s->pktout, ssh->username);
9706 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9707 /* service requested */
9708 ssh2_pkt_addstring(s->pktout, "publickey");
9710 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9711 ssh2_pkt_addstring_start(s->pktout);
9712 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9713 ssh2_pkt_addstring_start(s->pktout);
9714 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9716 /* Ask agent for signature. */
9717 s->siglen = s->pktout->length - 5 + 4 +
9718 ssh->v2_session_id_len;
9719 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9721 s->len = 1; /* message type */
9722 s->len += 4 + s->pklen; /* key blob */
9723 s->len += 4 + s->siglen; /* data to sign */
9724 s->len += 4; /* flags */
9725 s->agentreq = snewn(4 + s->len, char);
9726 PUT_32BIT(s->agentreq, s->len);
9727 s->q = s->agentreq + 4;
9728 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9729 PUT_32BIT(s->q, s->pklen);
9731 memcpy(s->q, s->pkblob, s->pklen);
9733 PUT_32BIT(s->q, s->siglen);
9735 /* Now the data to be signed... */
9736 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9737 PUT_32BIT(s->q, ssh->v2_session_id_len);
9740 memcpy(s->q, ssh->v2_session_id,
9741 ssh->v2_session_id_len);
9742 s->q += ssh->v2_session_id_len;
9743 memcpy(s->q, s->pktout->data + 5,
9744 s->pktout->length - 5);
9745 s->q += s->pktout->length - 5;
9746 /* And finally the (zero) flags word. */
9748 if (!agent_query(s->agentreq, s->len + 4,
9750 ssh_agent_callback, ssh)) {
9754 bombout(("Unexpected data from server"
9755 " while waiting for agent"
9759 } while (pktin || inlen > 0);
9760 vret = ssh->agent_response;
9761 s->retlen = ssh->agent_response_len;
9766 if (s->retlen >= 9 &&
9767 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9768 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9769 logevent("Sending Pageant's response");
9770 ssh2_add_sigblob(ssh, s->pktout,
9771 s->pkblob, s->pklen,
9773 GET_32BIT(s->ret + 5));
9774 ssh2_pkt_send(ssh, s->pktout);
9775 s->type = AUTH_TYPE_PUBLICKEY;
9777 /* FIXME: less drastic response */
9778 bombout(("Pageant failed to answer challenge"));
9784 /* Do we have any keys left to try? */
9785 if (s->pkblob_in_agent) {
9786 s->done_agent = TRUE;
9787 s->tried_pubkey_config = TRUE;
9790 if (s->keyi >= s->nkeys)
9791 s->done_agent = TRUE;
9794 } else if (s->can_pubkey && s->publickey_blob &&
9795 s->privatekey_available && !s->tried_pubkey_config) {
9797 struct ssh2_userkey *key; /* not live over crReturn */
9798 char *passphrase; /* not live over crReturn */
9800 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9802 s->tried_pubkey_config = TRUE;
9805 * Try the public key supplied in the configuration.
9807 * First, offer the public blob to see if the server is
9808 * willing to accept it.
9810 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9811 ssh2_pkt_addstring(s->pktout, ssh->username);
9812 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9813 /* service requested */
9814 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9815 ssh2_pkt_addbool(s->pktout, FALSE);
9816 /* no signature included */
9817 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9818 ssh2_pkt_addstring_start(s->pktout);
9819 ssh2_pkt_addstring_data(s->pktout,
9820 (char *)s->publickey_blob,
9821 s->publickey_bloblen);
9822 ssh2_pkt_send(ssh, s->pktout);
9823 logevent("Offered public key");
9825 crWaitUntilV(pktin);
9826 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9827 /* Key refused. Give up. */
9828 s->gotit = TRUE; /* reconsider message next loop */
9829 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9830 continue; /* process this new message */
9832 logevent("Offer of public key accepted");
9835 * Actually attempt a serious authentication using
9838 if (flags & FLAG_VERBOSE) {
9839 c_write_str(ssh, "Authenticating with public key \"");
9840 c_write_str(ssh, s->publickey_comment);
9841 c_write_str(ssh, "\"\r\n");
9845 const char *error; /* not live over crReturn */
9846 if (s->privatekey_encrypted) {
9848 * Get a passphrase from the user.
9850 int ret; /* need not be kept over crReturn */
9851 s->cur_prompt = new_prompts(ssh->frontend);
9852 s->cur_prompt->to_server = FALSE;
9853 s->cur_prompt->name = dupstr("SSH key passphrase");
9854 add_prompt(s->cur_prompt,
9855 dupprintf("Passphrase for key \"%.100s\": ",
9856 s->publickey_comment),
9858 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9861 crWaitUntilV(!pktin);
9862 ret = get_userpass_input(s->cur_prompt,
9867 /* Failed to get a passphrase. Terminate. */
9868 free_prompts(s->cur_prompt);
9869 ssh_disconnect(ssh, NULL,
9870 "Unable to authenticate",
9871 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9876 dupstr(s->cur_prompt->prompts[0]->result);
9877 free_prompts(s->cur_prompt);
9879 passphrase = NULL; /* no passphrase needed */
9883 * Try decrypting the key.
9885 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9886 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9888 /* burn the evidence */
9889 smemclr(passphrase, strlen(passphrase));
9892 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9894 (key == SSH2_WRONG_PASSPHRASE)) {
9895 c_write_str(ssh, "Wrong passphrase\r\n");
9897 /* and loop again */
9899 c_write_str(ssh, "Unable to load private key (");
9900 c_write_str(ssh, error);
9901 c_write_str(ssh, ")\r\n");
9903 break; /* try something else */
9909 unsigned char *pkblob, *sigblob, *sigdata;
9910 int pkblob_len, sigblob_len, sigdata_len;
9914 * We have loaded the private key and the server
9915 * has announced that it's willing to accept it.
9916 * Hallelujah. Generate a signature and send it.
9918 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9919 ssh2_pkt_addstring(s->pktout, ssh->username);
9920 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9921 /* service requested */
9922 ssh2_pkt_addstring(s->pktout, "publickey");
9924 ssh2_pkt_addbool(s->pktout, TRUE);
9925 /* signature follows */
9926 ssh2_pkt_addstring(s->pktout, key->alg->name);
9927 pkblob = key->alg->public_blob(key->data,
9929 ssh2_pkt_addstring_start(s->pktout);
9930 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9934 * The data to be signed is:
9938 * followed by everything so far placed in the
9941 sigdata_len = s->pktout->length - 5 + 4 +
9942 ssh->v2_session_id_len;
9943 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9945 sigdata = snewn(sigdata_len, unsigned char);
9947 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9948 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9951 memcpy(sigdata+p, ssh->v2_session_id,
9952 ssh->v2_session_id_len);
9953 p += ssh->v2_session_id_len;
9954 memcpy(sigdata+p, s->pktout->data + 5,
9955 s->pktout->length - 5);
9956 p += s->pktout->length - 5;
9957 assert(p == sigdata_len);
9958 sigblob = key->alg->sign(key->data, (char *)sigdata,
9959 sigdata_len, &sigblob_len);
9960 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
9961 sigblob, sigblob_len);
9966 ssh2_pkt_send(ssh, s->pktout);
9967 logevent("Sent public key signature");
9968 s->type = AUTH_TYPE_PUBLICKEY;
9969 key->alg->freekey(key->data);
9970 sfree(key->comment);
9975 } else if (s->can_gssapi && !s->tried_gssapi) {
9977 /* GSSAPI Authentication */
9982 s->type = AUTH_TYPE_GSSAPI;
9983 s->tried_gssapi = TRUE;
9985 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
9988 * Pick the highest GSS library on the preference
9994 for (i = 0; i < ngsslibs; i++) {
9995 int want_id = conf_get_int_int(ssh->conf,
9996 CONF_ssh_gsslist, i);
9997 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
9998 if (ssh->gsslibs->libraries[j].id == want_id) {
9999 s->gsslib = &ssh->gsslibs->libraries[j];
10000 goto got_gsslib; /* double break */
10005 * We always expect to have found something in
10006 * the above loop: we only came here if there
10007 * was at least one viable GSS library, and the
10008 * preference list should always mention
10009 * everything and only change the order.
10014 if (s->gsslib->gsslogmsg)
10015 logevent(s->gsslib->gsslogmsg);
10017 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
10018 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10019 ssh2_pkt_addstring(s->pktout, ssh->username);
10020 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10021 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
10022 logevent("Attempting GSSAPI authentication");
10024 /* add mechanism info */
10025 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
10027 /* number of GSSAPI mechanisms */
10028 ssh2_pkt_adduint32(s->pktout,1);
10030 /* length of OID + 2 */
10031 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
10032 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
10034 /* length of OID */
10035 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
10037 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
10038 s->gss_buf.length);
10039 ssh2_pkt_send(ssh, s->pktout);
10040 crWaitUntilV(pktin);
10041 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
10042 logevent("GSSAPI authentication request refused");
10046 /* check returned packet ... */
10048 ssh_pkt_getstring(pktin, &data, &len);
10049 s->gss_rcvtok.value = data;
10050 s->gss_rcvtok.length = len;
10051 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
10052 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
10053 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
10054 memcmp((char *)s->gss_rcvtok.value + 2,
10055 s->gss_buf.value,s->gss_buf.length) ) {
10056 logevent("GSSAPI authentication - wrong response from server");
10060 /* now start running */
10061 s->gss_stat = s->gsslib->import_name(s->gsslib,
10064 if (s->gss_stat != SSH_GSS_OK) {
10065 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
10066 logevent("GSSAPI import name failed - Bad service name");
10068 logevent("GSSAPI import name failed");
10072 /* fetch TGT into GSS engine */
10073 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
10075 if (s->gss_stat != SSH_GSS_OK) {
10076 logevent("GSSAPI authentication failed to get credentials");
10077 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10081 /* initial tokens are empty */
10082 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
10083 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
10085 /* now enter the loop */
10087 s->gss_stat = s->gsslib->init_sec_context
10091 conf_get_int(ssh->conf, CONF_gssapifwd),
10095 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
10096 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
10097 logevent("GSSAPI authentication initialisation failed");
10099 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
10100 &s->gss_buf) == SSH_GSS_OK) {
10101 logevent(s->gss_buf.value);
10102 sfree(s->gss_buf.value);
10107 logevent("GSSAPI authentication initialised");
10109 /* Client and server now exchange tokens until GSSAPI
10110 * no longer says CONTINUE_NEEDED */
10112 if (s->gss_sndtok.length != 0) {
10113 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
10114 ssh_pkt_addstring_start(s->pktout);
10115 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
10116 ssh2_pkt_send(ssh, s->pktout);
10117 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
10120 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
10121 crWaitUntilV(pktin);
10122 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
10123 logevent("GSSAPI authentication - bad server response");
10124 s->gss_stat = SSH_GSS_FAILURE;
10127 ssh_pkt_getstring(pktin, &data, &len);
10128 s->gss_rcvtok.value = data;
10129 s->gss_rcvtok.length = len;
10131 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
10133 if (s->gss_stat != SSH_GSS_OK) {
10134 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10135 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10138 logevent("GSSAPI authentication loop finished OK");
10140 /* Now send the MIC */
10142 s->pktout = ssh2_pkt_init(0);
10143 micoffset = s->pktout->length;
10144 ssh_pkt_addstring_start(s->pktout);
10145 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
10146 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
10147 ssh_pkt_addstring(s->pktout, ssh->username);
10148 ssh_pkt_addstring(s->pktout, "ssh-connection");
10149 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
10151 s->gss_buf.value = (char *)s->pktout->data + micoffset;
10152 s->gss_buf.length = s->pktout->length - micoffset;
10154 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
10155 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
10156 ssh_pkt_addstring_start(s->pktout);
10157 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
10158 ssh2_pkt_send(ssh, s->pktout);
10159 s->gsslib->free_mic(s->gsslib, &mic);
10163 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10164 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10167 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
10170 * Keyboard-interactive authentication.
10173 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
10175 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
10177 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10178 ssh2_pkt_addstring(s->pktout, ssh->username);
10179 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10180 /* service requested */
10181 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
10183 ssh2_pkt_addstring(s->pktout, ""); /* lang */
10184 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
10185 ssh2_pkt_send(ssh, s->pktout);
10187 logevent("Attempting keyboard-interactive authentication");
10189 crWaitUntilV(pktin);
10190 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
10191 /* Server is not willing to do keyboard-interactive
10192 * at all (or, bizarrely but legally, accepts the
10193 * user without actually issuing any prompts).
10194 * Give up on it entirely. */
10196 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
10197 s->kbd_inter_refused = TRUE; /* don't try it again */
10202 * Loop while the server continues to send INFO_REQUESTs.
10204 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
10206 char *name, *inst, *lang;
10207 int name_len, inst_len, lang_len;
10211 * We've got a fresh USERAUTH_INFO_REQUEST.
10212 * Get the preamble and start building a prompt.
10214 ssh_pkt_getstring(pktin, &name, &name_len);
10215 ssh_pkt_getstring(pktin, &inst, &inst_len);
10216 ssh_pkt_getstring(pktin, &lang, &lang_len);
10217 s->cur_prompt = new_prompts(ssh->frontend);
10218 s->cur_prompt->to_server = TRUE;
10221 * Get any prompt(s) from the packet.
10223 s->num_prompts = ssh_pkt_getuint32(pktin);
10224 for (i = 0; i < s->num_prompts; i++) {
10228 static char noprompt[] =
10229 "<server failed to send prompt>: ";
10231 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10232 echo = ssh2_pkt_getbool(pktin);
10235 prompt_len = lenof(noprompt)-1;
10237 add_prompt(s->cur_prompt,
10238 dupprintf("%.*s", prompt_len, prompt),
10243 /* FIXME: better prefix to distinguish from
10244 * local prompts? */
10245 s->cur_prompt->name =
10246 dupprintf("SSH server: %.*s", name_len, name);
10247 s->cur_prompt->name_reqd = TRUE;
10249 s->cur_prompt->name =
10250 dupstr("SSH server authentication");
10251 s->cur_prompt->name_reqd = FALSE;
10253 /* We add a prefix to try to make it clear that a prompt
10254 * has come from the server.
10255 * FIXME: ugly to print "Using..." in prompt _every_
10256 * time round. Can this be done more subtly? */
10257 /* Special case: for reasons best known to themselves,
10258 * some servers send k-i requests with no prompts and
10259 * nothing to display. Keep quiet in this case. */
10260 if (s->num_prompts || name_len || inst_len) {
10261 s->cur_prompt->instruction =
10262 dupprintf("Using keyboard-interactive authentication.%s%.*s",
10263 inst_len ? "\n" : "", inst_len, inst);
10264 s->cur_prompt->instr_reqd = TRUE;
10266 s->cur_prompt->instr_reqd = FALSE;
10270 * Display any instructions, and get the user's
10274 int ret; /* not live over crReturn */
10275 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10278 crWaitUntilV(!pktin);
10279 ret = get_userpass_input(s->cur_prompt, in, inlen);
10284 * Failed to get responses. Terminate.
10286 free_prompts(s->cur_prompt);
10287 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10288 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10295 * Send the response(s) to the server.
10297 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
10298 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
10299 for (i=0; i < s->num_prompts; i++) {
10300 ssh2_pkt_addstring(s->pktout,
10301 s->cur_prompt->prompts[i]->result);
10303 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10306 * Free the prompts structure from this iteration.
10307 * If there's another, a new one will be allocated
10308 * when we return to the top of this while loop.
10310 free_prompts(s->cur_prompt);
10313 * Get the next packet in case it's another
10316 crWaitUntilV(pktin);
10321 * We should have SUCCESS or FAILURE now.
10325 } else if (s->can_passwd) {
10328 * Plain old password authentication.
10330 int ret; /* not live over crReturn */
10331 int changereq_first_time; /* not live over crReturn */
10333 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10335 s->cur_prompt = new_prompts(ssh->frontend);
10336 s->cur_prompt->to_server = TRUE;
10337 s->cur_prompt->name = dupstr("SSH password");
10338 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10343 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10346 crWaitUntilV(!pktin);
10347 ret = get_userpass_input(s->cur_prompt, in, inlen);
10352 * Failed to get responses. Terminate.
10354 free_prompts(s->cur_prompt);
10355 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10356 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10361 * Squirrel away the password. (We may need it later if
10362 * asked to change it.)
10364 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10365 free_prompts(s->cur_prompt);
10368 * Send the password packet.
10370 * We pad out the password packet to 256 bytes to make
10371 * it harder for an attacker to find the length of the
10374 * Anyone using a password longer than 256 bytes
10375 * probably doesn't have much to worry about from
10376 * people who find out how long their password is!
10378 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10379 ssh2_pkt_addstring(s->pktout, ssh->username);
10380 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10381 /* service requested */
10382 ssh2_pkt_addstring(s->pktout, "password");
10383 ssh2_pkt_addbool(s->pktout, FALSE);
10384 ssh2_pkt_addstring(s->pktout, s->password);
10385 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10386 logevent("Sent password");
10387 s->type = AUTH_TYPE_PASSWORD;
10390 * Wait for next packet, in case it's a password change
10393 crWaitUntilV(pktin);
10394 changereq_first_time = TRUE;
10396 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10399 * We're being asked for a new password
10400 * (perhaps not for the first time).
10401 * Loop until the server accepts it.
10404 int got_new = FALSE; /* not live over crReturn */
10405 char *prompt; /* not live over crReturn */
10406 int prompt_len; /* not live over crReturn */
10410 if (changereq_first_time)
10411 msg = "Server requested password change";
10413 msg = "Server rejected new password";
10415 c_write_str(ssh, msg);
10416 c_write_str(ssh, "\r\n");
10419 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10421 s->cur_prompt = new_prompts(ssh->frontend);
10422 s->cur_prompt->to_server = TRUE;
10423 s->cur_prompt->name = dupstr("New SSH password");
10424 s->cur_prompt->instruction =
10425 dupprintf("%.*s", prompt_len, NULLTOEMPTY(prompt));
10426 s->cur_prompt->instr_reqd = TRUE;
10428 * There's no explicit requirement in the protocol
10429 * for the "old" passwords in the original and
10430 * password-change messages to be the same, and
10431 * apparently some Cisco kit supports password change
10432 * by the user entering a blank password originally
10433 * and the real password subsequently, so,
10434 * reluctantly, we prompt for the old password again.
10436 * (On the other hand, some servers don't even bother
10437 * to check this field.)
10439 add_prompt(s->cur_prompt,
10440 dupstr("Current password (blank for previously entered password): "),
10442 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10444 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10448 * Loop until the user manages to enter the same
10453 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10456 crWaitUntilV(!pktin);
10457 ret = get_userpass_input(s->cur_prompt, in, inlen);
10462 * Failed to get responses. Terminate.
10464 /* burn the evidence */
10465 free_prompts(s->cur_prompt);
10466 smemclr(s->password, strlen(s->password));
10467 sfree(s->password);
10468 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10469 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10475 * If the user specified a new original password
10476 * (IYSWIM), overwrite any previously specified
10478 * (A side effect is that the user doesn't have to
10479 * re-enter it if they louse up the new password.)
10481 if (s->cur_prompt->prompts[0]->result[0]) {
10482 smemclr(s->password, strlen(s->password));
10483 /* burn the evidence */
10484 sfree(s->password);
10486 dupstr(s->cur_prompt->prompts[0]->result);
10490 * Check the two new passwords match.
10492 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10493 s->cur_prompt->prompts[2]->result)
10496 /* They don't. Silly user. */
10497 c_write_str(ssh, "Passwords do not match\r\n");
10502 * Send the new password (along with the old one).
10503 * (see above for padding rationale)
10505 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10506 ssh2_pkt_addstring(s->pktout, ssh->username);
10507 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10508 /* service requested */
10509 ssh2_pkt_addstring(s->pktout, "password");
10510 ssh2_pkt_addbool(s->pktout, TRUE);
10511 ssh2_pkt_addstring(s->pktout, s->password);
10512 ssh2_pkt_addstring(s->pktout,
10513 s->cur_prompt->prompts[1]->result);
10514 free_prompts(s->cur_prompt);
10515 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10516 logevent("Sent new password");
10519 * Now see what the server has to say about it.
10520 * (If it's CHANGEREQ again, it's not happy with the
10523 crWaitUntilV(pktin);
10524 changereq_first_time = FALSE;
10529 * We need to reexamine the current pktin at the top
10530 * of the loop. Either:
10531 * - we weren't asked to change password at all, in
10532 * which case it's a SUCCESS or FAILURE with the
10534 * - we sent a new password, and the server was
10535 * either OK with it (SUCCESS or FAILURE w/partial
10536 * success) or unhappy with the _old_ password
10537 * (FAILURE w/o partial success)
10538 * In any of these cases, we go back to the top of
10539 * the loop and start again.
10544 * We don't need the old password any more, in any
10545 * case. Burn the evidence.
10547 smemclr(s->password, strlen(s->password));
10548 sfree(s->password);
10551 char *str = dupprintf("No supported authentication methods available"
10552 " (server sent: %.*s)",
10555 ssh_disconnect(ssh, str,
10556 "No supported authentication methods available",
10557 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10567 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10569 /* Clear up various bits and pieces from authentication. */
10570 if (s->publickey_blob) {
10571 sfree(s->publickey_algorithm);
10572 sfree(s->publickey_blob);
10573 sfree(s->publickey_comment);
10575 if (s->agent_response)
10576 sfree(s->agent_response);
10578 if (s->userauth_success && !ssh->bare_connection) {
10580 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10581 * packets since. Signal the transport layer to consider enacting
10582 * delayed compression.
10584 * (Relying on we_are_in is not sufficient, as
10585 * draft-miller-secsh-compression-delayed is quite clear that it
10586 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10587 * become set for other reasons.)
10589 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10592 ssh->channels = newtree234(ssh_channelcmp);
10595 * Set up handlers for some connection protocol messages, so we
10596 * don't have to handle them repeatedly in this coroutine.
10598 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10599 ssh2_msg_channel_window_adjust;
10600 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10601 ssh2_msg_global_request;
10604 * Create the main session channel.
10606 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10607 ssh->mainchan = NULL;
10609 ssh->mainchan = snew(struct ssh_channel);
10610 ssh->mainchan->ssh = ssh;
10611 ssh_channel_init(ssh->mainchan);
10613 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10615 * Just start a direct-tcpip channel and use it as the main
10618 ssh_send_port_open(ssh->mainchan,
10619 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10620 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10622 ssh->ncmode = TRUE;
10624 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10625 logevent("Opening session as main channel");
10626 ssh2_pkt_send(ssh, s->pktout);
10627 ssh->ncmode = FALSE;
10629 crWaitUntilV(pktin);
10630 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10631 bombout(("Server refused to open channel"));
10633 /* FIXME: error data comes back in FAILURE packet */
10635 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10636 bombout(("Server's channel confirmation cited wrong channel"));
10639 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10640 ssh->mainchan->halfopen = FALSE;
10641 ssh->mainchan->type = CHAN_MAINSESSION;
10642 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10643 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10644 update_specials_menu(ssh->frontend);
10645 logevent("Opened main channel");
10649 * Now we have a channel, make dispatch table entries for
10650 * general channel-based messages.
10652 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10653 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10654 ssh2_msg_channel_data;
10655 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10656 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10657 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10658 ssh2_msg_channel_open_confirmation;
10659 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10660 ssh2_msg_channel_open_failure;
10661 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10662 ssh2_msg_channel_request;
10663 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10664 ssh2_msg_channel_open;
10665 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10666 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10669 * Now the connection protocol is properly up and running, with
10670 * all those dispatch table entries, so it's safe to let
10671 * downstreams start trying to open extra channels through us.
10673 if (ssh->connshare)
10674 share_activate(ssh->connshare, ssh->v_s);
10676 if (ssh->mainchan && ssh_is_simple(ssh)) {
10678 * This message indicates to the server that we promise
10679 * not to try to run any other channel in parallel with
10680 * this one, so it's safe for it to advertise a very large
10681 * window and leave the flow control to TCP.
10683 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10684 "simple@putty.projects.tartarus.org",
10686 ssh2_pkt_send(ssh, s->pktout);
10690 * Enable port forwardings.
10692 ssh_setup_portfwd(ssh, ssh->conf);
10694 if (ssh->mainchan && !ssh->ncmode) {
10696 * Send the CHANNEL_REQUESTS for the main session channel.
10697 * Each one is handled by its own little asynchronous
10701 /* Potentially enable X11 forwarding. */
10702 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10704 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10706 if (!ssh->x11disp) {
10707 /* FIXME: return an error message from x11_setup_display */
10708 logevent("X11 forwarding not enabled: unable to"
10709 " initialise X display");
10711 ssh->x11auth = x11_invent_fake_auth
10712 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10713 ssh->x11auth->disp = ssh->x11disp;
10715 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10719 /* Potentially enable agent forwarding. */
10720 if (ssh_agent_forwarding_permitted(ssh))
10721 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10723 /* Now allocate a pty for the session. */
10724 if (!conf_get_int(ssh->conf, CONF_nopty))
10725 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10727 /* Send environment variables. */
10728 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10731 * Start a shell or a remote command. We may have to attempt
10732 * this twice if the config data has provided a second choice
10739 if (ssh->fallback_cmd) {
10740 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10741 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10743 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10744 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10748 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10749 ssh2_response_authconn, NULL);
10750 ssh2_pkt_addstring(s->pktout, cmd);
10752 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10753 ssh2_response_authconn, NULL);
10754 ssh2_pkt_addstring(s->pktout, cmd);
10756 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10757 ssh2_response_authconn, NULL);
10759 ssh2_pkt_send(ssh, s->pktout);
10761 crWaitUntilV(pktin);
10763 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10764 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10765 bombout(("Unexpected response to shell/command request:"
10766 " packet type %d", pktin->type));
10770 * We failed to start the command. If this is the
10771 * fallback command, we really are finished; if it's
10772 * not, and if the fallback command exists, try falling
10773 * back to it before complaining.
10775 if (!ssh->fallback_cmd &&
10776 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10777 logevent("Primary command failed; attempting fallback");
10778 ssh->fallback_cmd = TRUE;
10781 bombout(("Server refused to start a shell/command"));
10784 logevent("Started a shell/command");
10789 ssh->editing = ssh->echoing = TRUE;
10792 ssh->state = SSH_STATE_SESSION;
10793 if (ssh->size_needed)
10794 ssh_size(ssh, ssh->term_width, ssh->term_height);
10795 if (ssh->eof_needed)
10796 ssh_special(ssh, TS_EOF);
10802 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10810 * _All_ the connection-layer packets we expect to
10811 * receive are now handled by the dispatch table.
10812 * Anything that reaches here must be bogus.
10815 bombout(("Strange packet received: type %d", pktin->type));
10817 } else if (ssh->mainchan) {
10819 * We have spare data. Add it to the channel buffer.
10821 ssh_send_channel_data(ssh->mainchan, (char *)in, inlen);
10829 * Handlers for SSH-2 messages that might arrive at any moment.
10831 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10833 /* log reason code in disconnect message */
10835 int reason, msglen;
10837 reason = ssh_pkt_getuint32(pktin);
10838 ssh_pkt_getstring(pktin, &msg, &msglen);
10840 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10841 buf = dupprintf("Received disconnect message (%s)",
10842 ssh2_disconnect_reasons[reason]);
10844 buf = dupprintf("Received disconnect message (unknown"
10845 " type %d)", reason);
10849 buf = dupprintf("Disconnection message text: %.*s",
10850 msglen, NULLTOEMPTY(msg));
10852 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10854 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10855 ssh2_disconnect_reasons[reason] : "unknown",
10856 msglen, NULLTOEMPTY(msg)));
10860 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10862 /* log the debug message */
10866 /* XXX maybe we should actually take notice of the return value */
10867 ssh2_pkt_getbool(pktin);
10868 ssh_pkt_getstring(pktin, &msg, &msglen);
10870 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
10873 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10875 do_ssh2_transport(ssh, NULL, 0, pktin);
10879 * Called if we receive a packet that isn't allowed by the protocol.
10880 * This only applies to packets whose meaning PuTTY understands.
10881 * Entirely unknown packets are handled below.
10883 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10885 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10886 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10888 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10892 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10894 struct Packet *pktout;
10895 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10896 ssh2_pkt_adduint32(pktout, pktin->sequence);
10898 * UNIMPLEMENTED messages MUST appear in the same order as the
10899 * messages they respond to. Hence, never queue them.
10901 ssh2_pkt_send_noqueue(ssh, pktout);
10905 * Handle the top-level SSH-2 protocol.
10907 static void ssh2_protocol_setup(Ssh ssh)
10912 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10914 for (i = 0; i < 256; i++)
10915 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10918 * Initially, we only accept transport messages (and a few generic
10919 * ones). do_ssh2_authconn will add more when it starts.
10920 * Messages that are understood but not currently acceptable go to
10921 * ssh2_msg_unexpected.
10923 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10924 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10925 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10926 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10927 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10928 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10929 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10930 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10931 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10932 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10933 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10934 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10935 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10936 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10937 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10938 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10939 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10940 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10941 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10942 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10943 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10944 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10945 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10946 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10947 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10948 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10949 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10950 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10951 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10952 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10953 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10954 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10955 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10958 * These messages have a special handler from the start.
10960 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10961 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
10962 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10965 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
10970 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10972 for (i = 0; i < 256; i++)
10973 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10976 * Initially, we set all ssh-connection messages to 'unexpected';
10977 * do_ssh2_authconn will fill things in properly. We also handle a
10978 * couple of messages from the transport protocol which aren't
10979 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
10982 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10983 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10984 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10985 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10986 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10987 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10988 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10989 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10990 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10991 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10992 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10993 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10994 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10995 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10997 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
11000 * These messages have a special handler from the start.
11002 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11003 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
11004 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11007 static void ssh2_timer(void *ctx, unsigned long now)
11009 Ssh ssh = (Ssh)ctx;
11011 if (ssh->state == SSH_STATE_CLOSED)
11014 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11015 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
11016 now == ssh->next_rekey) {
11017 do_ssh2_transport(ssh, "timeout", -1, NULL);
11021 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
11022 struct Packet *pktin)
11024 const unsigned char *in = (const unsigned char *)vin;
11025 if (ssh->state == SSH_STATE_CLOSED)
11029 ssh->incoming_data_size += pktin->encrypted_len;
11030 if (!ssh->kex_in_progress &&
11031 ssh->max_data_size != 0 &&
11032 ssh->incoming_data_size > ssh->max_data_size)
11033 do_ssh2_transport(ssh, "too much data received", -1, NULL);
11037 ssh->packet_dispatch[pktin->type](ssh, pktin);
11038 else if (!ssh->protocol_initial_phase_done)
11039 do_ssh2_transport(ssh, in, inlen, pktin);
11041 do_ssh2_authconn(ssh, in, inlen, pktin);
11044 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
11045 struct Packet *pktin)
11047 const unsigned char *in = (const unsigned char *)vin;
11048 if (ssh->state == SSH_STATE_CLOSED)
11052 ssh->packet_dispatch[pktin->type](ssh, pktin);
11054 do_ssh2_authconn(ssh, in, inlen, pktin);
11057 static void ssh_cache_conf_values(Ssh ssh)
11059 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
11063 * Called to set up the connection.
11065 * Returns an error message, or NULL on success.
11067 static const char *ssh_init(void *frontend_handle, void **backend_handle,
11069 const char *host, int port, char **realhost,
11070 int nodelay, int keepalive)
11075 ssh = snew(struct ssh_tag);
11076 ssh->conf = conf_copy(conf);
11077 ssh_cache_conf_values(ssh);
11078 ssh->version = 0; /* when not ready yet */
11080 ssh->cipher = NULL;
11081 ssh->v1_cipher_ctx = NULL;
11082 ssh->crcda_ctx = NULL;
11083 ssh->cscipher = NULL;
11084 ssh->cs_cipher_ctx = NULL;
11085 ssh->sccipher = NULL;
11086 ssh->sc_cipher_ctx = NULL;
11088 ssh->cs_mac_ctx = NULL;
11090 ssh->sc_mac_ctx = NULL;
11091 ssh->cscomp = NULL;
11092 ssh->cs_comp_ctx = NULL;
11093 ssh->sccomp = NULL;
11094 ssh->sc_comp_ctx = NULL;
11096 ssh->kex_ctx = NULL;
11097 ssh->hostkey = NULL;
11098 ssh->hostkey_str = NULL;
11099 ssh->exitcode = -1;
11100 ssh->close_expected = FALSE;
11101 ssh->clean_exit = FALSE;
11102 ssh->state = SSH_STATE_PREPACKET;
11103 ssh->size_needed = FALSE;
11104 ssh->eof_needed = FALSE;
11106 ssh->logctx = NULL;
11107 ssh->deferred_send_data = NULL;
11108 ssh->deferred_len = 0;
11109 ssh->deferred_size = 0;
11110 ssh->fallback_cmd = 0;
11111 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
11112 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
11113 ssh->x11disp = NULL;
11114 ssh->x11auth = NULL;
11115 ssh->x11authtree = newtree234(x11_authcmp);
11116 ssh->v1_compressing = FALSE;
11117 ssh->v2_outgoing_sequence = 0;
11118 ssh->ssh1_rdpkt_crstate = 0;
11119 ssh->ssh2_rdpkt_crstate = 0;
11120 ssh->ssh2_bare_rdpkt_crstate = 0;
11121 ssh->ssh_gotdata_crstate = 0;
11122 ssh->do_ssh1_connection_crstate = 0;
11123 ssh->do_ssh_init_state = NULL;
11124 ssh->do_ssh_connection_init_state = NULL;
11125 ssh->do_ssh1_login_state = NULL;
11126 ssh->do_ssh2_transport_state = NULL;
11127 ssh->do_ssh2_authconn_state = NULL;
11130 ssh->mainchan = NULL;
11131 ssh->throttled_all = 0;
11132 ssh->v1_stdout_throttling = 0;
11134 ssh->queuelen = ssh->queuesize = 0;
11135 ssh->queueing = FALSE;
11136 ssh->qhead = ssh->qtail = NULL;
11137 ssh->deferred_rekey_reason = NULL;
11138 bufchain_init(&ssh->queued_incoming_data);
11139 ssh->frozen = FALSE;
11140 ssh->username = NULL;
11141 ssh->sent_console_eof = FALSE;
11142 ssh->got_pty = FALSE;
11143 ssh->bare_connection = FALSE;
11144 ssh->X11_fwd_enabled = FALSE;
11145 ssh->connshare = NULL;
11146 ssh->attempting_connshare = FALSE;
11147 ssh->session_started = FALSE;
11148 ssh->specials = NULL;
11149 ssh->n_uncert_hostkeys = 0;
11150 ssh->cross_certifying = FALSE;
11152 *backend_handle = ssh;
11155 if (crypto_startup() == 0)
11156 return "Microsoft high encryption pack not installed!";
11159 ssh->frontend = frontend_handle;
11160 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
11161 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
11163 ssh->channels = NULL;
11164 ssh->rportfwds = NULL;
11165 ssh->portfwds = NULL;
11170 ssh->conn_throttle_count = 0;
11171 ssh->overall_bufsize = 0;
11172 ssh->fallback_cmd = 0;
11174 ssh->protocol = NULL;
11176 ssh->protocol_initial_phase_done = FALSE;
11178 ssh->pinger = NULL;
11180 ssh->incoming_data_size = ssh->outgoing_data_size =
11181 ssh->deferred_data_size = 0L;
11182 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11183 CONF_ssh_rekey_data));
11184 ssh->kex_in_progress = FALSE;
11187 ssh->gsslibs = NULL;
11190 random_ref(); /* do this now - may be needed by sharing setup code */
11192 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
11201 static void ssh_free(void *handle)
11203 Ssh ssh = (Ssh) handle;
11204 struct ssh_channel *c;
11205 struct ssh_rportfwd *pf;
11206 struct X11FakeAuth *auth;
11208 if (ssh->v1_cipher_ctx)
11209 ssh->cipher->free_context(ssh->v1_cipher_ctx);
11210 if (ssh->cs_cipher_ctx)
11211 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
11212 if (ssh->sc_cipher_ctx)
11213 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
11214 if (ssh->cs_mac_ctx)
11215 ssh->csmac->free_context(ssh->cs_mac_ctx);
11216 if (ssh->sc_mac_ctx)
11217 ssh->scmac->free_context(ssh->sc_mac_ctx);
11218 if (ssh->cs_comp_ctx) {
11220 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
11222 zlib_compress_cleanup(ssh->cs_comp_ctx);
11224 if (ssh->sc_comp_ctx) {
11226 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
11228 zlib_decompress_cleanup(ssh->sc_comp_ctx);
11231 dh_cleanup(ssh->kex_ctx);
11232 sfree(ssh->savedhost);
11234 while (ssh->queuelen-- > 0)
11235 ssh_free_packet(ssh->queue[ssh->queuelen]);
11238 while (ssh->qhead) {
11239 struct queued_handler *qh = ssh->qhead;
11240 ssh->qhead = qh->next;
11243 ssh->qhead = ssh->qtail = NULL;
11245 if (ssh->channels) {
11246 while ((c = delpos234(ssh->channels, 0)) != NULL) {
11249 assert(c->u.x11.xconn != NULL);
11250 x11_close(c->u.x11.xconn);
11252 case CHAN_SOCKDATA:
11253 assert(c->u.pfd.pf != NULL);
11254 pfd_close(c->u.pfd.pf);
11257 if (ssh->version == 2) {
11258 struct outstanding_channel_request *ocr, *nocr;
11259 ocr = c->v.v2.chanreq_head;
11261 ocr->handler(c, NULL, ocr->ctx);
11266 bufchain_clear(&c->v.v2.outbuffer);
11270 freetree234(ssh->channels);
11271 ssh->channels = NULL;
11274 if (ssh->connshare)
11275 sharestate_free(ssh->connshare);
11277 if (ssh->rportfwds) {
11278 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
11280 freetree234(ssh->rportfwds);
11281 ssh->rportfwds = NULL;
11283 sfree(ssh->deferred_send_data);
11285 x11_free_display(ssh->x11disp);
11286 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
11287 x11_free_fake_auth(auth);
11288 freetree234(ssh->x11authtree);
11289 sfree(ssh->do_ssh_init_state);
11290 sfree(ssh->do_ssh1_login_state);
11291 sfree(ssh->do_ssh2_transport_state);
11292 sfree(ssh->do_ssh2_authconn_state);
11295 sfree(ssh->fullhostname);
11296 sfree(ssh->hostkey_str);
11297 sfree(ssh->specials);
11298 if (ssh->crcda_ctx) {
11299 crcda_free_context(ssh->crcda_ctx);
11300 ssh->crcda_ctx = NULL;
11303 ssh_do_close(ssh, TRUE);
11304 expire_timer_context(ssh);
11306 pinger_free(ssh->pinger);
11307 bufchain_clear(&ssh->queued_incoming_data);
11308 sfree(ssh->username);
11309 conf_free(ssh->conf);
11312 ssh_gss_cleanup(ssh->gsslibs);
11320 * Reconfigure the SSH backend.
11322 static void ssh_reconfig(void *handle, Conf *conf)
11324 Ssh ssh = (Ssh) handle;
11325 const char *rekeying = NULL;
11326 int rekey_mandatory = FALSE;
11327 unsigned long old_max_data_size;
11330 pinger_reconfig(ssh->pinger, ssh->conf, conf);
11332 ssh_setup_portfwd(ssh, conf);
11334 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11335 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11337 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11338 unsigned long now = GETTICKCOUNT();
11340 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11341 rekeying = "timeout shortened";
11343 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11347 old_max_data_size = ssh->max_data_size;
11348 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11349 CONF_ssh_rekey_data));
11350 if (old_max_data_size != ssh->max_data_size &&
11351 ssh->max_data_size != 0) {
11352 if (ssh->outgoing_data_size > ssh->max_data_size ||
11353 ssh->incoming_data_size > ssh->max_data_size)
11354 rekeying = "data limit lowered";
11357 if (conf_get_int(ssh->conf, CONF_compression) !=
11358 conf_get_int(conf, CONF_compression)) {
11359 rekeying = "compression setting changed";
11360 rekey_mandatory = TRUE;
11363 for (i = 0; i < CIPHER_MAX; i++)
11364 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11365 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11366 rekeying = "cipher settings changed";
11367 rekey_mandatory = TRUE;
11369 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11370 conf_get_int(conf, CONF_ssh2_des_cbc)) {
11371 rekeying = "cipher settings changed";
11372 rekey_mandatory = TRUE;
11375 conf_free(ssh->conf);
11376 ssh->conf = conf_copy(conf);
11377 ssh_cache_conf_values(ssh);
11379 if (!ssh->bare_connection && rekeying) {
11380 if (!ssh->kex_in_progress) {
11381 do_ssh2_transport(ssh, rekeying, -1, NULL);
11382 } else if (rekey_mandatory) {
11383 ssh->deferred_rekey_reason = rekeying;
11389 * Called to send data down the SSH connection.
11391 static int ssh_send(void *handle, const char *buf, int len)
11393 Ssh ssh = (Ssh) handle;
11395 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11398 ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
11400 return ssh_sendbuffer(ssh);
11404 * Called to query the current amount of buffered stdin data.
11406 static int ssh_sendbuffer(void *handle)
11408 Ssh ssh = (Ssh) handle;
11409 int override_value;
11411 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11415 * If the SSH socket itself has backed up, add the total backup
11416 * size on that to any individual buffer on the stdin channel.
11418 override_value = 0;
11419 if (ssh->throttled_all)
11420 override_value = ssh->overall_bufsize;
11422 if (ssh->version == 1) {
11423 return override_value;
11424 } else if (ssh->version == 2) {
11425 if (!ssh->mainchan)
11426 return override_value;
11428 return (override_value +
11429 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11436 * Called to set the size of the window from SSH's POV.
11438 static void ssh_size(void *handle, int width, int height)
11440 Ssh ssh = (Ssh) handle;
11441 struct Packet *pktout;
11443 ssh->term_width = width;
11444 ssh->term_height = height;
11446 switch (ssh->state) {
11447 case SSH_STATE_BEFORE_SIZE:
11448 case SSH_STATE_PREPACKET:
11449 case SSH_STATE_CLOSED:
11450 break; /* do nothing */
11451 case SSH_STATE_INTERMED:
11452 ssh->size_needed = TRUE; /* buffer for later */
11454 case SSH_STATE_SESSION:
11455 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11456 if (ssh->version == 1) {
11457 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11458 PKT_INT, ssh->term_height,
11459 PKT_INT, ssh->term_width,
11460 PKT_INT, 0, PKT_INT, 0, PKT_END);
11461 } else if (ssh->mainchan) {
11462 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11464 ssh2_pkt_adduint32(pktout, ssh->term_width);
11465 ssh2_pkt_adduint32(pktout, ssh->term_height);
11466 ssh2_pkt_adduint32(pktout, 0);
11467 ssh2_pkt_adduint32(pktout, 0);
11468 ssh2_pkt_send(ssh, pktout);
11476 * Return a list of the special codes that make sense in this
11479 static const struct telnet_special *ssh_get_specials(void *handle)
11481 static const struct telnet_special ssh1_ignore_special[] = {
11482 {"IGNORE message", TS_NOP}
11484 static const struct telnet_special ssh2_ignore_special[] = {
11485 {"IGNORE message", TS_NOP},
11487 static const struct telnet_special ssh2_rekey_special[] = {
11488 {"Repeat key exchange", TS_REKEY},
11490 static const struct telnet_special ssh2_session_specials[] = {
11493 /* These are the signal names defined by RFC 4254.
11494 * They include all the ISO C signals, but are a subset of the POSIX
11495 * required signals. */
11496 {"SIGINT (Interrupt)", TS_SIGINT},
11497 {"SIGTERM (Terminate)", TS_SIGTERM},
11498 {"SIGKILL (Kill)", TS_SIGKILL},
11499 {"SIGQUIT (Quit)", TS_SIGQUIT},
11500 {"SIGHUP (Hangup)", TS_SIGHUP},
11501 {"More signals", TS_SUBMENU},
11502 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11503 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11504 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11505 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11506 {NULL, TS_EXITMENU}
11508 static const struct telnet_special specials_end[] = {
11509 {NULL, TS_EXITMENU}
11512 struct telnet_special *specials = NULL;
11513 int nspecials = 0, specialsize = 0;
11515 Ssh ssh = (Ssh) handle;
11517 sfree(ssh->specials);
11519 #define ADD_SPECIALS(name) do \
11521 int len = lenof(name); \
11522 if (nspecials + len > specialsize) { \
11523 specialsize = (nspecials + len) * 5 / 4 + 32; \
11524 specials = sresize(specials, specialsize, struct telnet_special); \
11526 memcpy(specials+nspecials, name, len*sizeof(struct telnet_special)); \
11527 nspecials += len; \
11530 if (ssh->version == 1) {
11531 /* Don't bother offering IGNORE if we've decided the remote
11532 * won't cope with it, since we wouldn't bother sending it if
11534 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11535 ADD_SPECIALS(ssh1_ignore_special);
11536 } else if (ssh->version == 2) {
11537 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11538 ADD_SPECIALS(ssh2_ignore_special);
11539 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11540 ADD_SPECIALS(ssh2_rekey_special);
11542 ADD_SPECIALS(ssh2_session_specials);
11544 if (ssh->n_uncert_hostkeys) {
11545 static const struct telnet_special uncert_start[] = {
11547 {"Cache new host key type", TS_SUBMENU},
11549 static const struct telnet_special uncert_end[] = {
11550 {NULL, TS_EXITMENU},
11554 ADD_SPECIALS(uncert_start);
11555 for (i = 0; i < ssh->n_uncert_hostkeys; i++) {
11556 struct telnet_special uncert[1];
11557 const struct ssh_signkey *alg =
11558 hostkey_algs[ssh->uncert_hostkeys[i]].alg;
11559 uncert[0].name = alg->name;
11560 uncert[0].code = TS_LOCALSTART + ssh->uncert_hostkeys[i];
11561 ADD_SPECIALS(uncert);
11563 ADD_SPECIALS(uncert_end);
11565 } /* else we're not ready yet */
11568 ADD_SPECIALS(specials_end);
11570 ssh->specials = specials;
11577 #undef ADD_SPECIALS
11581 * Send special codes. TS_EOF is useful for `plink', so you
11582 * can send an EOF and collect resulting output (e.g. `plink
11585 static void ssh_special(void *handle, Telnet_Special code)
11587 Ssh ssh = (Ssh) handle;
11588 struct Packet *pktout;
11590 if (code == TS_EOF) {
11591 if (ssh->state != SSH_STATE_SESSION) {
11593 * Buffer the EOF in case we are pre-SESSION, so we can
11594 * send it as soon as we reach SESSION.
11596 if (code == TS_EOF)
11597 ssh->eof_needed = TRUE;
11600 if (ssh->version == 1) {
11601 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11602 } else if (ssh->mainchan) {
11603 sshfwd_write_eof(ssh->mainchan);
11604 ssh->send_ok = 0; /* now stop trying to read from stdin */
11606 logevent("Sent EOF message");
11607 } else if (code == TS_PING || code == TS_NOP) {
11608 if (ssh->state == SSH_STATE_CLOSED
11609 || ssh->state == SSH_STATE_PREPACKET) return;
11610 if (ssh->version == 1) {
11611 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11612 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11614 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11615 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11616 ssh2_pkt_addstring_start(pktout);
11617 ssh2_pkt_send_noqueue(ssh, pktout);
11620 } else if (code == TS_REKEY) {
11621 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11622 ssh->version == 2) {
11623 do_ssh2_transport(ssh, "at user request", -1, NULL);
11625 } else if (code >= TS_LOCALSTART) {
11626 ssh->hostkey = hostkey_algs[code - TS_LOCALSTART].alg;
11627 ssh->cross_certifying = TRUE;
11628 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11629 ssh->version == 2) {
11630 do_ssh2_transport(ssh, "cross-certifying new host key", -1, NULL);
11632 } else if (code == TS_BRK) {
11633 if (ssh->state == SSH_STATE_CLOSED
11634 || ssh->state == SSH_STATE_PREPACKET) return;
11635 if (ssh->version == 1) {
11636 logevent("Unable to send BREAK signal in SSH-1");
11637 } else if (ssh->mainchan) {
11638 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11639 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11640 ssh2_pkt_send(ssh, pktout);
11643 /* Is is a POSIX signal? */
11644 const char *signame = NULL;
11645 if (code == TS_SIGABRT) signame = "ABRT";
11646 if (code == TS_SIGALRM) signame = "ALRM";
11647 if (code == TS_SIGFPE) signame = "FPE";
11648 if (code == TS_SIGHUP) signame = "HUP";
11649 if (code == TS_SIGILL) signame = "ILL";
11650 if (code == TS_SIGINT) signame = "INT";
11651 if (code == TS_SIGKILL) signame = "KILL";
11652 if (code == TS_SIGPIPE) signame = "PIPE";
11653 if (code == TS_SIGQUIT) signame = "QUIT";
11654 if (code == TS_SIGSEGV) signame = "SEGV";
11655 if (code == TS_SIGTERM) signame = "TERM";
11656 if (code == TS_SIGUSR1) signame = "USR1";
11657 if (code == TS_SIGUSR2) signame = "USR2";
11658 /* The SSH-2 protocol does in principle support arbitrary named
11659 * signals, including signame@domain, but we don't support those. */
11661 /* It's a signal. */
11662 if (ssh->version == 2 && ssh->mainchan) {
11663 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11664 ssh2_pkt_addstring(pktout, signame);
11665 ssh2_pkt_send(ssh, pktout);
11666 logeventf(ssh, "Sent signal SIG%s", signame);
11669 /* Never heard of it. Do nothing */
11674 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11676 Ssh ssh = (Ssh) handle;
11677 struct ssh_channel *c;
11678 c = snew(struct ssh_channel);
11681 ssh_channel_init(c);
11682 c->halfopen = TRUE;
11683 c->type = CHAN_SOCKDATA;/* identify channel type */
11688 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11690 struct ssh_channel *c;
11691 c = snew(struct ssh_channel);
11694 ssh_channel_init(c);
11695 c->type = CHAN_SHARING;
11696 c->u.sharing.ctx = sharing_ctx;
11700 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11702 struct ssh_channel *c;
11704 c = find234(ssh->channels, &localid, ssh_channelfind);
11706 ssh_channel_destroy(c);
11709 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11710 const void *data, int datalen,
11711 const char *additional_log_text)
11713 struct Packet *pkt;
11715 pkt = ssh2_pkt_init(type);
11716 pkt->downstream_id = id;
11717 pkt->additional_log_text = additional_log_text;
11718 ssh2_pkt_adddata(pkt, data, datalen);
11719 ssh2_pkt_send(ssh, pkt);
11723 * This is called when stdout/stderr (the entity to which
11724 * from_backend sends data) manages to clear some backlog.
11726 static void ssh_unthrottle(void *handle, int bufsize)
11728 Ssh ssh = (Ssh) handle;
11730 if (ssh->version == 1) {
11731 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11732 ssh->v1_stdout_throttling = 0;
11733 ssh_throttle_conn(ssh, -1);
11737 ssh_channel_unthrottle(ssh->mainchan, bufsize);
11741 * Now process any SSH connection data that was stashed in our
11742 * queue while we were frozen.
11744 ssh_process_queued_incoming_data(ssh);
11747 void ssh_send_port_open(void *channel, const char *hostname, int port,
11750 struct ssh_channel *c = (struct ssh_channel *)channel;
11752 struct Packet *pktout;
11754 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11756 if (ssh->version == 1) {
11757 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11758 PKT_INT, c->localid,
11761 /* PKT_STR, <org:orgport>, */
11764 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11766 char *trimmed_host = host_strduptrim(hostname);
11767 ssh2_pkt_addstring(pktout, trimmed_host);
11768 sfree(trimmed_host);
11770 ssh2_pkt_adduint32(pktout, port);
11772 * We make up values for the originator data; partly it's
11773 * too much hassle to keep track, and partly I'm not
11774 * convinced the server should be told details like that
11775 * about my local network configuration.
11776 * The "originator IP address" is syntactically a numeric
11777 * IP address, and some servers (e.g., Tectia) get upset
11778 * if it doesn't match this syntax.
11780 ssh2_pkt_addstring(pktout, "0.0.0.0");
11781 ssh2_pkt_adduint32(pktout, 0);
11782 ssh2_pkt_send(ssh, pktout);
11786 static int ssh_connected(void *handle)
11788 Ssh ssh = (Ssh) handle;
11789 return ssh->s != NULL;
11792 static int ssh_sendok(void *handle)
11794 Ssh ssh = (Ssh) handle;
11795 return ssh->send_ok;
11798 static int ssh_ldisc(void *handle, int option)
11800 Ssh ssh = (Ssh) handle;
11801 if (option == LD_ECHO)
11802 return ssh->echoing;
11803 if (option == LD_EDIT)
11804 return ssh->editing;
11808 static void ssh_provide_ldisc(void *handle, void *ldisc)
11810 Ssh ssh = (Ssh) handle;
11811 ssh->ldisc = ldisc;
11814 static void ssh_provide_logctx(void *handle, void *logctx)
11816 Ssh ssh = (Ssh) handle;
11817 ssh->logctx = logctx;
11820 static int ssh_return_exitcode(void *handle)
11822 Ssh ssh = (Ssh) handle;
11823 if (ssh->s != NULL)
11826 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11830 * cfg_info for SSH is the protocol running in this session.
11831 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11832 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11834 static int ssh_cfg_info(void *handle)
11836 Ssh ssh = (Ssh) handle;
11837 if (ssh->version == 0)
11838 return 0; /* don't know yet */
11839 else if (ssh->bare_connection)
11842 return ssh->version;
11846 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11847 * that fails. This variable is the means by which scp.c can reach
11848 * into the SSH code and find out which one it got.
11850 extern int ssh_fallback_cmd(void *handle)
11852 Ssh ssh = (Ssh) handle;
11853 return ssh->fallback_cmd;
11856 Backend ssh_backend = {
11866 ssh_return_exitcode,
11870 ssh_provide_logctx,
11873 ssh_test_for_upstream,