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 void ssh2_channel_check_close(struct ssh_channel *c);
369 static void ssh_channel_destroy(struct ssh_channel *c);
370 static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize);
371 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin);
374 * Buffer management constants. There are several of these for
375 * various different purposes:
377 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
378 * on a local data stream before we throttle the whole SSH
379 * connection (in SSH-1 only). Throttling the whole connection is
380 * pretty drastic so we set this high in the hope it won't
383 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
384 * on the SSH connection itself before we defensively throttle
385 * _all_ local data streams. This is pretty drastic too (though
386 * thankfully unlikely in SSH-2 since the window mechanism should
387 * ensure that the server never has any need to throttle its end
388 * of the connection), so we set this high as well.
390 * - OUR_V2_WINSIZE is the default window size we present on SSH-2
393 * - OUR_V2_BIGWIN is the window size we advertise for the only
394 * channel in a simple connection. It must be <= INT_MAX.
396 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
397 * to the remote side. This actually has nothing to do with the
398 * size of the _packet_, but is instead a limit on the amount
399 * of data we're willing to receive in a single SSH2 channel
402 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
403 * _packet_ we're prepared to cope with. It must be a multiple
404 * of the cipher block size, and must be at least 35000.
407 #define SSH1_BUFFER_LIMIT 32768
408 #define SSH_MAX_BACKLOG 32768
409 #define OUR_V2_WINSIZE 16384
410 #define OUR_V2_BIGWIN 0x7fffffff
411 #define OUR_V2_MAXPKT 0x4000UL
412 #define OUR_V2_PACKETLIMIT 0x9000UL
414 struct ssh_signkey_with_user_pref_id {
415 const struct ssh_signkey *alg;
418 const static struct ssh_signkey_with_user_pref_id hostkey_algs[] = {
419 { &ssh_ecdsa_ed25519, HK_ED25519 },
420 { &ssh_ecdsa_nistp256, HK_ECDSA },
421 { &ssh_ecdsa_nistp384, HK_ECDSA },
422 { &ssh_ecdsa_nistp521, HK_ECDSA },
423 { &ssh_dss, HK_DSA },
424 { &ssh_rsa, HK_RSA },
427 const static struct ssh_mac *const macs[] = {
428 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
430 const static struct ssh_mac *const buggymacs[] = {
431 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
434 static void *ssh_comp_none_init(void)
438 static void ssh_comp_none_cleanup(void *handle)
441 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
442 unsigned char **outblock, int *outlen)
446 static int ssh_comp_none_disable(void *handle)
450 const static struct ssh_compress ssh_comp_none = {
452 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
453 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
454 ssh_comp_none_disable, NULL
456 extern const struct ssh_compress ssh_zlib;
457 const static struct ssh_compress *const compressions[] = {
458 &ssh_zlib, &ssh_comp_none
461 enum { /* channel types */
466 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
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 #define logevent(s) logevent(ssh->frontend, s)
990 /* logevent, only printf-formatted. */
991 static void logeventf(Ssh ssh, const char *fmt, ...)
997 buf = dupvprintf(fmt, ap);
1003 static void bomb_out(Ssh ssh, char *text)
1005 ssh_do_close(ssh, FALSE);
1007 connection_fatal(ssh->frontend, "%s", text);
1011 #define bombout(msg) bomb_out(ssh, dupprintf msg)
1013 /* Helper function for common bits of parsing ttymodes. */
1014 static void parse_ttymodes(Ssh ssh,
1015 void (*do_mode)(void *data,
1016 const struct ssh_ttymode *mode,
1021 const struct ssh_ttymode *mode;
1023 char default_val[2];
1025 strcpy(default_val, "A");
1027 for (i = 0; i < lenof(ssh_ttymodes); i++) {
1028 mode = ssh_ttymodes + i;
1029 val = conf_get_str_str_opt(ssh->conf, CONF_ttymodes, mode->mode);
1034 * val[0] is either 'V', indicating that an explicit value
1035 * follows it, or 'A' indicating that we should pass the
1036 * value through from the local environment via get_ttymode.
1038 if (val[0] == 'A') {
1039 val = get_ttymode(ssh->frontend, mode->mode);
1041 do_mode(data, mode, val);
1045 do_mode(data, mode, val + 1); /* skip the 'V' */
1049 static int ssh_channelcmp(void *av, void *bv)
1051 struct ssh_channel *a = (struct ssh_channel *) av;
1052 struct ssh_channel *b = (struct ssh_channel *) bv;
1053 if (a->localid < b->localid)
1055 if (a->localid > b->localid)
1059 static int ssh_channelfind(void *av, void *bv)
1061 unsigned *a = (unsigned *) av;
1062 struct ssh_channel *b = (struct ssh_channel *) bv;
1063 if (*a < b->localid)
1065 if (*a > b->localid)
1070 static int ssh_rportcmp_ssh1(void *av, void *bv)
1072 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1073 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1075 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1076 return i < 0 ? -1 : +1;
1077 if (a->dport > b->dport)
1079 if (a->dport < b->dport)
1084 static int ssh_rportcmp_ssh2(void *av, void *bv)
1086 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1087 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1089 if ( (i = strcmp(a->shost, b->shost)) != 0)
1090 return i < 0 ? -1 : +1;
1091 if (a->sport > b->sport)
1093 if (a->sport < b->sport)
1099 * Special form of strcmp which can cope with NULL inputs. NULL is
1100 * defined to sort before even the empty string.
1102 static int nullstrcmp(const char *a, const char *b)
1104 if (a == NULL && b == NULL)
1110 return strcmp(a, b);
1113 static int ssh_portcmp(void *av, void *bv)
1115 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1116 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1118 if (a->type > b->type)
1120 if (a->type < b->type)
1122 if (a->addressfamily > b->addressfamily)
1124 if (a->addressfamily < b->addressfamily)
1126 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1127 return i < 0 ? -1 : +1;
1128 if (a->sport > b->sport)
1130 if (a->sport < b->sport)
1132 if (a->type != 'D') {
1133 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1134 return i < 0 ? -1 : +1;
1135 if (a->dport > b->dport)
1137 if (a->dport < b->dport)
1143 static int alloc_channel_id(Ssh ssh)
1145 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1146 unsigned low, high, mid;
1148 struct ssh_channel *c;
1151 * First-fit allocation of channel numbers: always pick the
1152 * lowest unused one. To do this, binary-search using the
1153 * counted B-tree to find the largest channel ID which is in a
1154 * contiguous sequence from the beginning. (Precisely
1155 * everything in that sequence must have ID equal to its tree
1156 * index plus CHANNEL_NUMBER_OFFSET.)
1158 tsize = count234(ssh->channels);
1162 while (high - low > 1) {
1163 mid = (high + low) / 2;
1164 c = index234(ssh->channels, mid);
1165 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1166 low = mid; /* this one is fine */
1168 high = mid; /* this one is past it */
1171 * Now low points to either -1, or the tree index of the
1172 * largest ID in the initial sequence.
1175 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1176 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1178 return low + 1 + CHANNEL_NUMBER_OFFSET;
1181 static void c_write_stderr(int trusted, const char *buf, int len)
1184 for (i = 0; i < len; i++)
1185 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1186 fputc(buf[i], stderr);
1189 static void c_write(Ssh ssh, const char *buf, int len)
1191 if (flags & FLAG_STDERR)
1192 c_write_stderr(1, buf, len);
1194 from_backend(ssh->frontend, 1, buf, len);
1197 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1199 if (flags & FLAG_STDERR)
1200 c_write_stderr(0, buf, len);
1202 from_backend_untrusted(ssh->frontend, buf, len);
1205 static void c_write_str(Ssh ssh, const char *buf)
1207 c_write(ssh, buf, strlen(buf));
1210 static void ssh_free_packet(struct Packet *pkt)
1215 static struct Packet *ssh_new_packet(void)
1217 struct Packet *pkt = snew(struct Packet);
1219 pkt->body = pkt->data = NULL;
1225 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1228 struct logblank_t blanks[4];
1234 if (ssh->logomitdata &&
1235 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1236 pkt->type == SSH1_SMSG_STDERR_DATA ||
1237 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1238 /* "Session data" packets - omit the data string. */
1239 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1240 ssh_pkt_getuint32(pkt); /* skip channel id */
1241 blanks[nblanks].offset = pkt->savedpos + 4;
1242 blanks[nblanks].type = PKTLOG_OMIT;
1243 ssh_pkt_getstring(pkt, &str, &slen);
1245 blanks[nblanks].len = slen;
1249 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1250 ssh1_pkt_type(pkt->type),
1251 pkt->body, pkt->length, nblanks, blanks, NULL,
1255 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1258 struct logblank_t blanks[4];
1263 * For outgoing packets, pkt->length represents the length of the
1264 * whole packet starting at pkt->data (including some header), and
1265 * pkt->body refers to the point within that where the log-worthy
1266 * payload begins. However, incoming packets expect pkt->length to
1267 * represent only the payload length (that is, it's measured from
1268 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1269 * packet to conform to the incoming-packet semantics, so that we
1270 * can analyse it with the ssh_pkt_get functions.
1272 pkt->length -= (pkt->body - pkt->data);
1275 if (ssh->logomitdata &&
1276 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1277 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1278 /* "Session data" packets - omit the data string. */
1279 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1280 ssh_pkt_getuint32(pkt); /* skip channel id */
1281 blanks[nblanks].offset = pkt->savedpos + 4;
1282 blanks[nblanks].type = PKTLOG_OMIT;
1283 ssh_pkt_getstring(pkt, &str, &slen);
1285 blanks[nblanks].len = slen;
1290 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1291 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1292 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1293 conf_get_int(ssh->conf, CONF_logomitpass)) {
1294 /* If this is a password or similar packet, blank the password(s). */
1295 blanks[nblanks].offset = 0;
1296 blanks[nblanks].len = pkt->length;
1297 blanks[nblanks].type = PKTLOG_BLANK;
1299 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1300 conf_get_int(ssh->conf, CONF_logomitpass)) {
1302 * If this is an X forwarding request packet, blank the fake
1305 * Note that while we blank the X authentication data here, we
1306 * don't take any special action to blank the start of an X11
1307 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1308 * an X connection without having session blanking enabled is
1309 * likely to leak your cookie into the log.
1312 ssh_pkt_getstring(pkt, &str, &slen);
1313 blanks[nblanks].offset = pkt->savedpos;
1314 blanks[nblanks].type = PKTLOG_BLANK;
1315 ssh_pkt_getstring(pkt, &str, &slen);
1317 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1322 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1323 ssh1_pkt_type(pkt->data[12]),
1324 pkt->body, pkt->length,
1325 nblanks, blanks, NULL, 0, NULL);
1328 * Undo the above adjustment of pkt->length, to put the packet
1329 * back in the state we found it.
1331 pkt->length += (pkt->body - pkt->data);
1335 * Collect incoming data in the incoming packet buffer.
1336 * Decipher and verify the packet when it is completely read.
1337 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1338 * Update the *data and *datalen variables.
1339 * Return a Packet structure when a packet is completed.
1341 static struct Packet *ssh1_rdpkt(Ssh ssh, const unsigned char **data,
1344 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1346 crBegin(ssh->ssh1_rdpkt_crstate);
1348 st->pktin = ssh_new_packet();
1350 st->pktin->type = 0;
1351 st->pktin->length = 0;
1353 for (st->i = st->len = 0; st->i < 4; st->i++) {
1354 while ((*datalen) == 0)
1356 st->len = (st->len << 8) + **data;
1357 (*data)++, (*datalen)--;
1360 st->pad = 8 - (st->len % 8);
1361 st->biglen = st->len + st->pad;
1362 st->pktin->length = st->len - 5;
1364 if (st->biglen < 0) {
1365 bombout(("Extremely large packet length from server suggests"
1366 " data stream corruption"));
1367 ssh_free_packet(st->pktin);
1371 st->pktin->maxlen = st->biglen;
1372 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1374 st->to_read = st->biglen;
1375 st->p = st->pktin->data;
1376 while (st->to_read > 0) {
1377 st->chunk = st->to_read;
1378 while ((*datalen) == 0)
1380 if (st->chunk > (*datalen))
1381 st->chunk = (*datalen);
1382 memcpy(st->p, *data, st->chunk);
1384 *datalen -= st->chunk;
1386 st->to_read -= st->chunk;
1389 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1390 st->biglen, NULL)) {
1391 bombout(("Network attack (CRC compensation) detected!"));
1392 ssh_free_packet(st->pktin);
1397 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1399 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1400 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1401 if (st->gotcrc != st->realcrc) {
1402 bombout(("Incorrect CRC received on packet"));
1403 ssh_free_packet(st->pktin);
1407 st->pktin->body = st->pktin->data + st->pad + 1;
1409 if (ssh->v1_compressing) {
1410 unsigned char *decompblk;
1412 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1413 st->pktin->body - 1, st->pktin->length + 1,
1414 &decompblk, &decomplen)) {
1415 bombout(("Zlib decompression encountered invalid data"));
1416 ssh_free_packet(st->pktin);
1420 if (st->pktin->maxlen < st->pad + decomplen) {
1421 st->pktin->maxlen = st->pad + decomplen;
1422 st->pktin->data = sresize(st->pktin->data,
1423 st->pktin->maxlen + APIEXTRA,
1425 st->pktin->body = st->pktin->data + st->pad + 1;
1428 memcpy(st->pktin->body - 1, decompblk, decomplen);
1430 st->pktin->length = decomplen - 1;
1433 st->pktin->type = st->pktin->body[-1];
1436 * Now pktin->body and pktin->length identify the semantic content
1437 * of the packet, excluding the initial type byte.
1441 ssh1_log_incoming_packet(ssh, st->pktin);
1443 st->pktin->savedpos = 0;
1445 crFinish(st->pktin);
1448 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1451 struct logblank_t blanks[4];
1457 if (ssh->logomitdata &&
1458 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1459 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1460 /* "Session data" packets - omit the data string. */
1461 ssh_pkt_getuint32(pkt); /* skip channel id */
1462 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1463 ssh_pkt_getuint32(pkt); /* skip extended data type */
1464 blanks[nblanks].offset = pkt->savedpos + 4;
1465 blanks[nblanks].type = PKTLOG_OMIT;
1466 ssh_pkt_getstring(pkt, &str, &slen);
1468 blanks[nblanks].len = slen;
1473 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1474 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1475 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1479 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1482 struct logblank_t blanks[4];
1487 * For outgoing packets, pkt->length represents the length of the
1488 * whole packet starting at pkt->data (including some header), and
1489 * pkt->body refers to the point within that where the log-worthy
1490 * payload begins. However, incoming packets expect pkt->length to
1491 * represent only the payload length (that is, it's measured from
1492 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1493 * packet to conform to the incoming-packet semantics, so that we
1494 * can analyse it with the ssh_pkt_get functions.
1496 pkt->length -= (pkt->body - pkt->data);
1499 if (ssh->logomitdata &&
1500 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1501 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1502 /* "Session data" packets - omit the data string. */
1503 ssh_pkt_getuint32(pkt); /* skip channel id */
1504 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1505 ssh_pkt_getuint32(pkt); /* skip extended data type */
1506 blanks[nblanks].offset = pkt->savedpos + 4;
1507 blanks[nblanks].type = PKTLOG_OMIT;
1508 ssh_pkt_getstring(pkt, &str, &slen);
1510 blanks[nblanks].len = slen;
1515 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1516 conf_get_int(ssh->conf, CONF_logomitpass)) {
1517 /* If this is a password packet, blank the password(s). */
1519 ssh_pkt_getstring(pkt, &str, &slen);
1520 ssh_pkt_getstring(pkt, &str, &slen);
1521 ssh_pkt_getstring(pkt, &str, &slen);
1522 if (slen == 8 && !memcmp(str, "password", 8)) {
1523 ssh2_pkt_getbool(pkt);
1524 /* Blank the password field. */
1525 blanks[nblanks].offset = pkt->savedpos;
1526 blanks[nblanks].type = PKTLOG_BLANK;
1527 ssh_pkt_getstring(pkt, &str, &slen);
1529 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1531 /* If there's another password field beyond it (change of
1532 * password), blank that too. */
1533 ssh_pkt_getstring(pkt, &str, &slen);
1535 blanks[nblanks-1].len =
1536 pkt->savedpos - blanks[nblanks].offset;
1539 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1540 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1541 conf_get_int(ssh->conf, CONF_logomitpass)) {
1542 /* If this is a keyboard-interactive response packet, blank
1545 ssh_pkt_getuint32(pkt);
1546 blanks[nblanks].offset = pkt->savedpos;
1547 blanks[nblanks].type = PKTLOG_BLANK;
1549 ssh_pkt_getstring(pkt, &str, &slen);
1553 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1555 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1556 conf_get_int(ssh->conf, CONF_logomitpass)) {
1558 * If this is an X forwarding request packet, blank the fake
1561 * Note that while we blank the X authentication data here, we
1562 * don't take any special action to blank the start of an X11
1563 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1564 * an X connection without having session blanking enabled is
1565 * likely to leak your cookie into the log.
1568 ssh_pkt_getuint32(pkt);
1569 ssh_pkt_getstring(pkt, &str, &slen);
1570 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1571 ssh2_pkt_getbool(pkt);
1572 ssh2_pkt_getbool(pkt);
1573 ssh_pkt_getstring(pkt, &str, &slen);
1574 blanks[nblanks].offset = pkt->savedpos;
1575 blanks[nblanks].type = PKTLOG_BLANK;
1576 ssh_pkt_getstring(pkt, &str, &slen);
1578 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1584 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1585 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1586 pkt->body, pkt->length, nblanks, blanks,
1587 &ssh->v2_outgoing_sequence,
1588 pkt->downstream_id, pkt->additional_log_text);
1591 * Undo the above adjustment of pkt->length, to put the packet
1592 * back in the state we found it.
1594 pkt->length += (pkt->body - pkt->data);
1597 static struct Packet *ssh2_rdpkt(Ssh ssh, const unsigned char **data,
1600 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1602 crBegin(ssh->ssh2_rdpkt_crstate);
1604 st->pktin = ssh_new_packet();
1606 st->pktin->type = 0;
1607 st->pktin->length = 0;
1609 st->cipherblk = ssh->sccipher->blksize;
1612 if (st->cipherblk < 8)
1614 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1616 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1617 ssh->scmac && !ssh->scmac_etm) {
1619 * When dealing with a CBC-mode cipher, we want to avoid the
1620 * possibility of an attacker's tweaking the ciphertext stream
1621 * so as to cause us to feed the same block to the block
1622 * cipher more than once and thus leak information
1623 * (VU#958563). The way we do this is not to take any
1624 * decisions on the basis of anything we've decrypted until
1625 * we've verified it with a MAC. That includes the packet
1626 * length, so we just read data and check the MAC repeatedly,
1627 * and when the MAC passes, see if the length we've got is
1630 * This defence is unnecessary in OpenSSH ETM mode, because
1631 * the whole point of ETM mode is that the attacker can't
1632 * tweak the ciphertext stream at all without the MAC
1633 * detecting it before we decrypt anything.
1636 /* May as well allocate the whole lot now. */
1637 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1640 /* Read an amount corresponding to the MAC. */
1641 for (st->i = 0; st->i < st->maclen; st->i++) {
1642 while ((*datalen) == 0)
1644 st->pktin->data[st->i] = *(*data)++;
1650 unsigned char seq[4];
1651 ssh->scmac->start(ssh->sc_mac_ctx);
1652 PUT_32BIT(seq, st->incoming_sequence);
1653 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1656 for (;;) { /* Once around this loop per cipher block. */
1657 /* Read another cipher-block's worth, and tack it onto the end. */
1658 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1659 while ((*datalen) == 0)
1661 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1664 /* Decrypt one more block (a little further back in the stream). */
1665 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1666 st->pktin->data + st->packetlen,
1668 /* Feed that block to the MAC. */
1669 ssh->scmac->bytes(ssh->sc_mac_ctx,
1670 st->pktin->data + st->packetlen, st->cipherblk);
1671 st->packetlen += st->cipherblk;
1672 /* See if that gives us a valid packet. */
1673 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1674 st->pktin->data + st->packetlen) &&
1675 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1678 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1679 bombout(("No valid incoming packet found"));
1680 ssh_free_packet(st->pktin);
1684 st->pktin->maxlen = st->packetlen + st->maclen;
1685 st->pktin->data = sresize(st->pktin->data,
1686 st->pktin->maxlen + APIEXTRA,
1688 } else if (ssh->scmac && ssh->scmac_etm) {
1689 st->pktin->data = snewn(4 + APIEXTRA, unsigned char);
1692 * OpenSSH encrypt-then-MAC mode: the packet length is
1693 * unencrypted, unless the cipher supports length encryption.
1695 for (st->i = st->len = 0; st->i < 4; st->i++) {
1696 while ((*datalen) == 0)
1698 st->pktin->data[st->i] = *(*data)++;
1701 /* Cipher supports length decryption, so do it */
1702 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
1703 /* Keep the packet the same though, so the MAC passes */
1704 unsigned char len[4];
1705 memcpy(len, st->pktin->data, 4);
1706 ssh->sccipher->decrypt_length(ssh->sc_cipher_ctx, len, 4, st->incoming_sequence);
1707 st->len = toint(GET_32BIT(len));
1709 st->len = toint(GET_32BIT(st->pktin->data));
1713 * _Completely_ silly lengths should be stomped on before they
1714 * do us any more damage.
1716 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1717 st->len % st->cipherblk != 0) {
1718 bombout(("Incoming packet length field was garbled"));
1719 ssh_free_packet(st->pktin);
1724 * So now we can work out the total packet length.
1726 st->packetlen = st->len + 4;
1729 * Allocate memory for the rest of the packet.
1731 st->pktin->maxlen = st->packetlen + st->maclen;
1732 st->pktin->data = sresize(st->pktin->data,
1733 st->pktin->maxlen + APIEXTRA,
1737 * Read the remainder of the packet.
1739 for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
1740 while ((*datalen) == 0)
1742 st->pktin->data[st->i] = *(*data)++;
1750 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1751 st->len + 4, st->incoming_sequence)) {
1752 bombout(("Incorrect MAC received on packet"));
1753 ssh_free_packet(st->pktin);
1757 /* Decrypt everything between the length field and the MAC. */
1759 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1760 st->pktin->data + 4,
1763 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1766 * Acquire and decrypt the first block of the packet. This will
1767 * contain the length and padding details.
1769 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1770 while ((*datalen) == 0)
1772 st->pktin->data[st->i] = *(*data)++;
1777 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1778 st->pktin->data, st->cipherblk);
1781 * Now get the length figure.
1783 st->len = toint(GET_32BIT(st->pktin->data));
1786 * _Completely_ silly lengths should be stomped on before they
1787 * do us any more damage.
1789 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1790 (st->len + 4) % st->cipherblk != 0) {
1791 bombout(("Incoming packet was garbled on decryption"));
1792 ssh_free_packet(st->pktin);
1797 * So now we can work out the total packet length.
1799 st->packetlen = st->len + 4;
1802 * Allocate memory for the rest of the packet.
1804 st->pktin->maxlen = st->packetlen + st->maclen;
1805 st->pktin->data = sresize(st->pktin->data,
1806 st->pktin->maxlen + APIEXTRA,
1810 * Read and decrypt the remainder of the packet.
1812 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1814 while ((*datalen) == 0)
1816 st->pktin->data[st->i] = *(*data)++;
1819 /* Decrypt everything _except_ the MAC. */
1821 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1822 st->pktin->data + st->cipherblk,
1823 st->packetlen - st->cipherblk);
1829 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1830 st->len + 4, st->incoming_sequence)) {
1831 bombout(("Incorrect MAC received on packet"));
1832 ssh_free_packet(st->pktin);
1836 /* Get and sanity-check the amount of random padding. */
1837 st->pad = st->pktin->data[4];
1838 if (st->pad < 4 || st->len - st->pad < 1) {
1839 bombout(("Invalid padding length on received packet"));
1840 ssh_free_packet(st->pktin);
1844 * This enables us to deduce the payload length.
1846 st->payload = st->len - st->pad - 1;
1848 st->pktin->length = st->payload + 5;
1849 st->pktin->encrypted_len = st->packetlen;
1851 st->pktin->sequence = st->incoming_sequence++;
1853 st->pktin->length = st->packetlen - st->pad;
1854 assert(st->pktin->length >= 0);
1857 * Decompress packet payload.
1860 unsigned char *newpayload;
1863 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1864 st->pktin->data + 5, st->pktin->length - 5,
1865 &newpayload, &newlen)) {
1866 if (st->pktin->maxlen < newlen + 5) {
1867 st->pktin->maxlen = newlen + 5;
1868 st->pktin->data = sresize(st->pktin->data,
1869 st->pktin->maxlen + APIEXTRA,
1872 st->pktin->length = 5 + newlen;
1873 memcpy(st->pktin->data + 5, newpayload, newlen);
1879 * RFC 4253 doesn't explicitly say that completely empty packets
1880 * with no type byte are forbidden, so treat them as deserving
1881 * an SSH_MSG_UNIMPLEMENTED.
1883 if (st->pktin->length <= 5) { /* == 5 we hope, but robustness */
1884 ssh2_msg_something_unimplemented(ssh, st->pktin);
1888 * pktin->body and pktin->length should identify the semantic
1889 * content of the packet, excluding the initial type byte.
1891 st->pktin->type = st->pktin->data[5];
1892 st->pktin->body = st->pktin->data + 6;
1893 st->pktin->length -= 6;
1894 assert(st->pktin->length >= 0); /* one last double-check */
1897 ssh2_log_incoming_packet(ssh, st->pktin);
1899 st->pktin->savedpos = 0;
1901 crFinish(st->pktin);
1904 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh,
1905 const unsigned char **data,
1908 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1910 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1913 * Read the packet length field.
1915 for (st->i = 0; st->i < 4; st->i++) {
1916 while ((*datalen) == 0)
1918 st->length[st->i] = *(*data)++;
1922 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1923 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1924 bombout(("Invalid packet length received"));
1928 st->pktin = ssh_new_packet();
1929 st->pktin->data = snewn(st->packetlen, unsigned char);
1931 st->pktin->encrypted_len = st->packetlen;
1933 st->pktin->sequence = st->incoming_sequence++;
1936 * Read the remainder of the packet.
1938 for (st->i = 0; st->i < st->packetlen; st->i++) {
1939 while ((*datalen) == 0)
1941 st->pktin->data[st->i] = *(*data)++;
1946 * pktin->body and pktin->length should identify the semantic
1947 * content of the packet, excluding the initial type byte.
1949 st->pktin->type = st->pktin->data[0];
1950 st->pktin->body = st->pktin->data + 1;
1951 st->pktin->length = st->packetlen - 1;
1954 * Log incoming packet, possibly omitting sensitive fields.
1957 ssh2_log_incoming_packet(ssh, st->pktin);
1959 st->pktin->savedpos = 0;
1961 crFinish(st->pktin);
1964 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1966 int pad, biglen, i, pktoffs;
1970 * XXX various versions of SC (including 8.8.4) screw up the
1971 * register allocation in this function and use the same register
1972 * (D6) for len and as a temporary, with predictable results. The
1973 * following sledgehammer prevents this.
1980 ssh1_log_outgoing_packet(ssh, pkt);
1982 if (ssh->v1_compressing) {
1983 unsigned char *compblk;
1985 zlib_compress_block(ssh->cs_comp_ctx,
1986 pkt->data + 12, pkt->length - 12,
1987 &compblk, &complen);
1988 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1989 memcpy(pkt->data + 12, compblk, complen);
1991 pkt->length = complen + 12;
1994 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1996 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1997 pad = 8 - (len % 8);
1999 biglen = len + pad; /* len(padding+type+data+CRC) */
2001 for (i = pktoffs; i < 4+8; i++)
2002 pkt->data[i] = random_byte();
2003 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
2004 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
2005 PUT_32BIT(pkt->data + pktoffs, len);
2008 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
2009 pkt->data + pktoffs + 4, biglen);
2011 if (offset_p) *offset_p = pktoffs;
2012 return biglen + 4; /* len(length+padding+type+data+CRC) */
2015 static int s_write(Ssh ssh, void *data, int len)
2018 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
2019 0, NULL, NULL, 0, NULL);
2022 return sk_write(ssh->s, (char *)data, len);
2025 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
2027 int len, backlog, offset;
2028 len = s_wrpkt_prepare(ssh, pkt, &offset);
2029 backlog = s_write(ssh, pkt->data + offset, len);
2030 if (backlog > SSH_MAX_BACKLOG)
2031 ssh_throttle_all(ssh, 1, backlog);
2032 ssh_free_packet(pkt);
2035 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
2038 len = s_wrpkt_prepare(ssh, pkt, &offset);
2039 if (ssh->deferred_len + len > ssh->deferred_size) {
2040 ssh->deferred_size = ssh->deferred_len + len + 128;
2041 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2045 memcpy(ssh->deferred_send_data + ssh->deferred_len,
2046 pkt->data + offset, len);
2047 ssh->deferred_len += len;
2048 ssh_free_packet(pkt);
2052 * Construct a SSH-1 packet with the specified contents.
2053 * (This all-at-once interface used to be the only one, but now SSH-1
2054 * packets can also be constructed incrementally.)
2056 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
2062 pkt = ssh1_pkt_init(pkttype);
2064 while ((argtype = va_arg(ap, int)) != PKT_END) {
2065 unsigned char *argp, argchar;
2067 unsigned long argint;
2070 /* Actual fields in the packet */
2072 argint = va_arg(ap, int);
2073 ssh_pkt_adduint32(pkt, argint);
2076 argchar = (unsigned char) va_arg(ap, int);
2077 ssh_pkt_addbyte(pkt, argchar);
2080 argp = va_arg(ap, unsigned char *);
2081 arglen = va_arg(ap, int);
2082 ssh_pkt_adddata(pkt, argp, arglen);
2085 sargp = va_arg(ap, char *);
2086 ssh_pkt_addstring(pkt, sargp);
2089 bn = va_arg(ap, Bignum);
2090 ssh1_pkt_addmp(pkt, bn);
2098 static void send_packet(Ssh ssh, int pkttype, ...)
2102 va_start(ap, pkttype);
2103 pkt = construct_packet(ssh, pkttype, ap);
2108 static void defer_packet(Ssh ssh, int pkttype, ...)
2112 va_start(ap, pkttype);
2113 pkt = construct_packet(ssh, pkttype, ap);
2115 s_wrpkt_defer(ssh, pkt);
2118 static int ssh_versioncmp(const char *a, const char *b)
2121 unsigned long av, bv;
2123 av = strtoul(a, &ae, 10);
2124 bv = strtoul(b, &be, 10);
2126 return (av < bv ? -1 : +1);
2131 av = strtoul(ae, &ae, 10);
2132 bv = strtoul(be, &be, 10);
2134 return (av < bv ? -1 : +1);
2139 * Utility routines for putting an SSH-protocol `string' and
2140 * `uint32' into a hash state.
2142 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2144 unsigned char lenblk[4];
2145 PUT_32BIT(lenblk, len);
2146 h->bytes(s, lenblk, 4);
2147 h->bytes(s, str, len);
2150 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2152 unsigned char intblk[4];
2153 PUT_32BIT(intblk, i);
2154 h->bytes(s, intblk, 4);
2158 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2160 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2162 if (pkt->maxlen < length) {
2163 unsigned char *body = pkt->body;
2164 int offset = body ? body - pkt->data : 0;
2165 pkt->maxlen = length + 256;
2166 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2167 if (body) pkt->body = pkt->data + offset;
2170 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2173 ssh_pkt_ensure(pkt, pkt->length);
2174 memcpy(pkt->data + pkt->length - len, data, len);
2176 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2178 ssh_pkt_adddata(pkt, &byte, 1);
2180 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2182 ssh_pkt_adddata(pkt, &value, 1);
2184 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2187 PUT_32BIT(x, value);
2188 ssh_pkt_adddata(pkt, x, 4);
2190 static void ssh_pkt_addstring_start(struct Packet *pkt)
2192 ssh_pkt_adduint32(pkt, 0);
2193 pkt->savedpos = pkt->length;
2195 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2198 ssh_pkt_adddata(pkt, data, len);
2199 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2201 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2203 ssh_pkt_addstring_data(pkt, data, strlen(data));
2205 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2207 ssh_pkt_addstring_start(pkt);
2208 ssh_pkt_addstring_str(pkt, data);
2210 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2212 int len = ssh1_bignum_length(b);
2213 unsigned char *data = snewn(len, unsigned char);
2214 (void) ssh1_write_bignum(data, b);
2215 ssh_pkt_adddata(pkt, data, len);
2218 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2221 int i, n = (bignum_bitcount(b) + 7) / 8;
2222 p = snewn(n + 1, unsigned char);
2224 for (i = 1; i <= n; i++)
2225 p[i] = bignum_byte(b, n - i);
2227 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2229 memmove(p, p + i, n + 1 - i);
2233 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2237 p = ssh2_mpint_fmt(b, &len);
2238 ssh_pkt_addstring_start(pkt);
2239 ssh_pkt_addstring_data(pkt, (char *)p, len);
2243 static struct Packet *ssh1_pkt_init(int pkt_type)
2245 struct Packet *pkt = ssh_new_packet();
2246 pkt->length = 4 + 8; /* space for length + max padding */
2247 ssh_pkt_addbyte(pkt, pkt_type);
2248 pkt->body = pkt->data + pkt->length;
2249 pkt->type = pkt_type;
2250 pkt->downstream_id = 0;
2251 pkt->additional_log_text = NULL;
2255 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2256 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2257 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2258 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2259 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2260 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2261 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2262 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2263 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2265 static struct Packet *ssh2_pkt_init(int pkt_type)
2267 struct Packet *pkt = ssh_new_packet();
2268 pkt->length = 5; /* space for packet length + padding length */
2270 pkt->type = pkt_type;
2271 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2272 pkt->body = pkt->data + pkt->length; /* after packet type */
2273 pkt->downstream_id = 0;
2274 pkt->additional_log_text = NULL;
2279 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2280 * put the MAC on it. Final packet, ready to be sent, is stored in
2281 * pkt->data. Total length is returned.
2283 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2285 int cipherblk, maclen, padding, unencrypted_prefix, i;
2288 ssh2_log_outgoing_packet(ssh, pkt);
2290 if (ssh->bare_connection) {
2292 * Trivial packet construction for the bare connection
2295 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2296 pkt->body = pkt->data + 1;
2297 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2298 return pkt->length - 1;
2302 * Compress packet payload.
2305 unsigned char *newpayload;
2308 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2310 &newpayload, &newlen)) {
2312 ssh2_pkt_adddata(pkt, newpayload, newlen);
2318 * Add padding. At least four bytes, and must also bring total
2319 * length (minus MAC) up to a multiple of the block size.
2320 * If pkt->forcepad is set, make sure the packet is at least that size
2323 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2324 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2326 unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
2327 if (pkt->length + padding < pkt->forcepad)
2328 padding = pkt->forcepad - pkt->length;
2330 (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
2332 assert(padding <= 255);
2333 maclen = ssh->csmac ? ssh->csmac->len : 0;
2334 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2335 pkt->data[4] = padding;
2336 for (i = 0; i < padding; i++)
2337 pkt->data[pkt->length + i] = random_byte();
2338 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2340 /* Encrypt length if the scheme requires it */
2341 if (ssh->cscipher && (ssh->cscipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
2342 ssh->cscipher->encrypt_length(ssh->cs_cipher_ctx, pkt->data, 4,
2343 ssh->v2_outgoing_sequence);
2346 if (ssh->csmac && ssh->csmac_etm) {
2348 * OpenSSH-defined encrypt-then-MAC protocol.
2351 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2352 pkt->data + 4, pkt->length + padding - 4);
2353 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2354 pkt->length + padding,
2355 ssh->v2_outgoing_sequence);
2358 * SSH-2 standard protocol.
2361 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2362 pkt->length + padding,
2363 ssh->v2_outgoing_sequence);
2365 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2366 pkt->data, pkt->length + padding);
2369 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2370 pkt->encrypted_len = pkt->length + padding;
2372 /* Ready-to-send packet starts at pkt->data. We return length. */
2373 pkt->body = pkt->data;
2374 return pkt->length + padding + maclen;
2378 * Routines called from the main SSH code to send packets. There
2379 * are quite a few of these, because we have two separate
2380 * mechanisms for delaying the sending of packets:
2382 * - In order to send an IGNORE message and a password message in
2383 * a single fixed-length blob, we require the ability to
2384 * concatenate the encrypted forms of those two packets _into_ a
2385 * single blob and then pass it to our <network.h> transport
2386 * layer in one go. Hence, there's a deferment mechanism which
2387 * works after packet encryption.
2389 * - In order to avoid sending any connection-layer messages
2390 * during repeat key exchange, we have to queue up any such
2391 * outgoing messages _before_ they are encrypted (and in
2392 * particular before they're allocated sequence numbers), and
2393 * then send them once we've finished.
2395 * I call these mechanisms `defer' and `queue' respectively, so as
2396 * to distinguish them reasonably easily.
2398 * The functions send_noqueue() and defer_noqueue() free the packet
2399 * structure they are passed. Every outgoing packet goes through
2400 * precisely one of these functions in its life; packets passed to
2401 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2402 * these or get queued, and then when the queue is later emptied
2403 * the packets are all passed to defer_noqueue().
2405 * When using a CBC-mode cipher, it's necessary to ensure that an
2406 * attacker can't provide data to be encrypted using an IV that they
2407 * know. We ensure this by prefixing each packet that might contain
2408 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2409 * mechanism, so in this case send_noqueue() ends up redirecting to
2410 * defer_noqueue(). If you don't like this inefficiency, don't use
2414 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2415 static void ssh_pkt_defersend(Ssh);
2418 * Send an SSH-2 packet immediately, without queuing or deferring.
2420 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2424 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2425 /* We need to send two packets, so use the deferral mechanism. */
2426 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2427 ssh_pkt_defersend(ssh);
2430 len = ssh2_pkt_construct(ssh, pkt);
2431 backlog = s_write(ssh, pkt->body, len);
2432 if (backlog > SSH_MAX_BACKLOG)
2433 ssh_throttle_all(ssh, 1, backlog);
2435 ssh->outgoing_data_size += pkt->encrypted_len;
2436 if (!ssh->kex_in_progress &&
2437 !ssh->bare_connection &&
2438 ssh->max_data_size != 0 &&
2439 ssh->outgoing_data_size > ssh->max_data_size)
2440 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2442 ssh_free_packet(pkt);
2446 * Defer an SSH-2 packet.
2448 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2451 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2452 ssh->deferred_len == 0 && !noignore &&
2453 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2455 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2456 * get encrypted with a known IV.
2458 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2459 ssh2_pkt_addstring_start(ipkt);
2460 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2462 len = ssh2_pkt_construct(ssh, pkt);
2463 if (ssh->deferred_len + len > ssh->deferred_size) {
2464 ssh->deferred_size = ssh->deferred_len + len + 128;
2465 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2469 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2470 ssh->deferred_len += len;
2471 ssh->deferred_data_size += pkt->encrypted_len;
2472 ssh_free_packet(pkt);
2476 * Queue an SSH-2 packet.
2478 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2480 assert(ssh->queueing);
2482 if (ssh->queuelen >= ssh->queuesize) {
2483 ssh->queuesize = ssh->queuelen + 32;
2484 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2487 ssh->queue[ssh->queuelen++] = pkt;
2491 * Either queue or send a packet, depending on whether queueing is
2494 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2497 ssh2_pkt_queue(ssh, pkt);
2499 ssh2_pkt_send_noqueue(ssh, pkt);
2503 * Either queue or defer a packet, depending on whether queueing is
2506 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2509 ssh2_pkt_queue(ssh, pkt);
2511 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2515 * Send the whole deferred data block constructed by
2516 * ssh2_pkt_defer() or SSH-1's defer_packet().
2518 * The expected use of the defer mechanism is that you call
2519 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2520 * not currently queueing, this simply sets up deferred_send_data
2521 * and then sends it. If we _are_ currently queueing, the calls to
2522 * ssh2_pkt_defer() put the deferred packets on to the queue
2523 * instead, and therefore ssh_pkt_defersend() has no deferred data
2524 * to send. Hence, there's no need to make it conditional on
2527 static void ssh_pkt_defersend(Ssh ssh)
2530 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2531 ssh->deferred_len = ssh->deferred_size = 0;
2532 sfree(ssh->deferred_send_data);
2533 ssh->deferred_send_data = NULL;
2534 if (backlog > SSH_MAX_BACKLOG)
2535 ssh_throttle_all(ssh, 1, backlog);
2537 if (ssh->version == 2) {
2538 ssh->outgoing_data_size += ssh->deferred_data_size;
2539 ssh->deferred_data_size = 0;
2540 if (!ssh->kex_in_progress &&
2541 !ssh->bare_connection &&
2542 ssh->max_data_size != 0 &&
2543 ssh->outgoing_data_size > ssh->max_data_size)
2544 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2549 * Send a packet whose length needs to be disguised (typically
2550 * passwords or keyboard-interactive responses).
2552 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2558 * The simplest way to do this is to adjust the
2559 * variable-length padding field in the outgoing packet.
2561 * Currently compiled out, because some Cisco SSH servers
2562 * don't like excessively padded packets (bah, why's it
2565 pkt->forcepad = padsize;
2566 ssh2_pkt_send(ssh, pkt);
2571 * If we can't do that, however, an alternative approach is
2572 * to use the pkt_defer mechanism to bundle the packet
2573 * tightly together with an SSH_MSG_IGNORE such that their
2574 * combined length is a constant. So first we construct the
2575 * final form of this packet and defer its sending.
2577 ssh2_pkt_defer(ssh, pkt);
2580 * Now construct an SSH_MSG_IGNORE which includes a string
2581 * that's an exact multiple of the cipher block size. (If
2582 * the cipher is NULL so that the block size is
2583 * unavailable, we don't do this trick at all, because we
2584 * gain nothing by it.)
2586 if (ssh->cscipher &&
2587 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2590 stringlen = (256 - ssh->deferred_len);
2591 stringlen += ssh->cscipher->blksize - 1;
2592 stringlen -= (stringlen % ssh->cscipher->blksize);
2595 * Temporarily disable actual compression, so we
2596 * can guarantee to get this string exactly the
2597 * length we want it. The compression-disabling
2598 * routine should return an integer indicating how
2599 * many bytes we should adjust our string length
2603 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2605 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2606 ssh2_pkt_addstring_start(pkt);
2607 for (i = 0; i < stringlen; i++) {
2608 char c = (char) random_byte();
2609 ssh2_pkt_addstring_data(pkt, &c, 1);
2611 ssh2_pkt_defer(ssh, pkt);
2613 ssh_pkt_defersend(ssh);
2618 * Send all queued SSH-2 packets. We send them by means of
2619 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2620 * packets that needed to be lumped together.
2622 static void ssh2_pkt_queuesend(Ssh ssh)
2626 assert(!ssh->queueing);
2628 for (i = 0; i < ssh->queuelen; i++)
2629 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2632 ssh_pkt_defersend(ssh);
2636 void bndebug(char *string, Bignum b)
2640 p = ssh2_mpint_fmt(b, &len);
2641 debug(("%s", string));
2642 for (i = 0; i < len; i++)
2643 debug((" %02x", p[i]));
2649 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2653 p = ssh2_mpint_fmt(b, &len);
2654 hash_string(h, s, p, len);
2659 * Packet decode functions for both SSH-1 and SSH-2.
2661 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2663 unsigned long value;
2664 if (pkt->length - pkt->savedpos < 4)
2665 return 0; /* arrgh, no way to decline (FIXME?) */
2666 value = GET_32BIT(pkt->body + pkt->savedpos);
2670 static int ssh2_pkt_getbool(struct Packet *pkt)
2672 unsigned long value;
2673 if (pkt->length - pkt->savedpos < 1)
2674 return 0; /* arrgh, no way to decline (FIXME?) */
2675 value = pkt->body[pkt->savedpos] != 0;
2679 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2684 if (pkt->length - pkt->savedpos < 4)
2686 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2691 if (pkt->length - pkt->savedpos < *length)
2693 *p = (char *)(pkt->body + pkt->savedpos);
2694 pkt->savedpos += *length;
2696 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2698 if (pkt->length - pkt->savedpos < length)
2700 pkt->savedpos += length;
2701 return pkt->body + (pkt->savedpos - length);
2703 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2704 const unsigned char **keystr)
2708 j = makekey(pkt->body + pkt->savedpos,
2709 pkt->length - pkt->savedpos,
2716 assert(pkt->savedpos < pkt->length);
2720 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2725 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2726 pkt->length - pkt->savedpos, &b);
2734 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2740 ssh_pkt_getstring(pkt, &p, &length);
2745 b = bignum_from_bytes((unsigned char *)p, length);
2750 * Helper function to add an SSH-2 signature blob to a packet.
2751 * Expects to be shown the public key blob as well as the signature
2752 * blob. Normally works just like ssh2_pkt_addstring, but will
2753 * fiddle with the signature packet if necessary for
2754 * BUG_SSH2_RSA_PADDING.
2756 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2757 void *pkblob_v, int pkblob_len,
2758 void *sigblob_v, int sigblob_len)
2760 unsigned char *pkblob = (unsigned char *)pkblob_v;
2761 unsigned char *sigblob = (unsigned char *)sigblob_v;
2763 /* dmemdump(pkblob, pkblob_len); */
2764 /* dmemdump(sigblob, sigblob_len); */
2767 * See if this is in fact an ssh-rsa signature and a buggy
2768 * server; otherwise we can just do this the easy way.
2770 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2771 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2772 int pos, len, siglen;
2775 * Find the byte length of the modulus.
2778 pos = 4+7; /* skip over "ssh-rsa" */
2779 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2780 if (len < 0 || len > pkblob_len - pos - 4)
2782 pos += 4 + len; /* skip over exponent */
2783 if (pkblob_len - pos < 4)
2785 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2786 if (len < 0 || len > pkblob_len - pos - 4)
2788 pos += 4; /* find modulus itself */
2789 while (len > 0 && pkblob[pos] == 0)
2791 /* debug(("modulus length is %d\n", len)); */
2794 * Now find the signature integer.
2796 pos = 4+7; /* skip over "ssh-rsa" */
2797 if (sigblob_len < pos+4)
2799 siglen = toint(GET_32BIT(sigblob+pos));
2800 if (siglen != sigblob_len - pos - 4)
2802 /* debug(("signature length is %d\n", siglen)); */
2804 if (len != siglen) {
2805 unsigned char newlen[4];
2806 ssh2_pkt_addstring_start(pkt);
2807 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2808 /* dmemdump(sigblob, pos); */
2809 pos += 4; /* point to start of actual sig */
2810 PUT_32BIT(newlen, len);
2811 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2812 /* dmemdump(newlen, 4); */
2814 while (len-- > siglen) {
2815 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2816 /* dmemdump(newlen, 1); */
2818 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2819 /* dmemdump(sigblob+pos, siglen); */
2823 /* Otherwise fall through and do it the easy way. We also come
2824 * here as a fallback if we discover above that the key blob
2825 * is misformatted in some way. */
2829 ssh2_pkt_addstring_start(pkt);
2830 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2834 * Examine the remote side's version string and compare it against
2835 * a list of known buggy implementations.
2837 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2839 char *imp; /* pointer to implementation part */
2841 imp += strcspn(imp, "-");
2843 imp += strcspn(imp, "-");
2846 ssh->remote_bugs = 0;
2849 * General notes on server version strings:
2850 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2851 * here -- in particular, we've heard of one that's perfectly happy
2852 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2853 * so we can't distinguish them.
2855 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2856 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2857 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2858 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2859 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2860 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2862 * These versions don't support SSH1_MSG_IGNORE, so we have
2863 * to use a different defence against password length
2866 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2867 logevent("We believe remote version has SSH-1 ignore bug");
2870 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2871 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2872 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2874 * These versions need a plain password sent; they can't
2875 * handle having a null and a random length of data after
2878 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2879 logevent("We believe remote version needs a plain SSH-1 password");
2882 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2883 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2884 (!strcmp(imp, "Cisco-1.25")))) {
2886 * These versions apparently have no clue whatever about
2887 * RSA authentication and will panic and die if they see
2888 * an AUTH_RSA message.
2890 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2891 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2894 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2895 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2896 !wc_match("* VShell", imp) &&
2897 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2898 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2899 wc_match("2.1 *", imp)))) {
2901 * These versions have the HMAC bug.
2903 ssh->remote_bugs |= BUG_SSH2_HMAC;
2904 logevent("We believe remote version has SSH-2 HMAC bug");
2907 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2908 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2909 !wc_match("* VShell", imp) &&
2910 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2912 * These versions have the key-derivation bug (failing to
2913 * include the literal shared secret in the hashes that
2914 * generate the keys).
2916 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2917 logevent("We believe remote version has SSH-2 key-derivation bug");
2920 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2921 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2922 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2923 wc_match("OpenSSH_3.[0-2]*", imp) ||
2924 wc_match("mod_sftp/0.[0-8]*", imp) ||
2925 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2927 * These versions have the SSH-2 RSA padding bug.
2929 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2930 logevent("We believe remote version has SSH-2 RSA padding bug");
2933 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2934 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2935 wc_match("OpenSSH_2.[0-2]*", imp))) {
2937 * These versions have the SSH-2 session-ID bug in
2938 * public-key authentication.
2940 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2941 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2944 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2945 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2946 (wc_match("DigiSSH_2.0", imp) ||
2947 wc_match("OpenSSH_2.[0-4]*", imp) ||
2948 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2949 wc_match("Sun_SSH_1.0", imp) ||
2950 wc_match("Sun_SSH_1.0.1", imp) ||
2951 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2952 wc_match("WeOnlyDo-*", imp)))) {
2954 * These versions have the SSH-2 rekey bug.
2956 ssh->remote_bugs |= BUG_SSH2_REKEY;
2957 logevent("We believe remote version has SSH-2 rekey bug");
2960 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2961 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2962 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2963 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2965 * This version ignores our makpkt and needs to be throttled.
2967 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2968 logevent("We believe remote version ignores SSH-2 maximum packet size");
2971 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2973 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2974 * none detected automatically.
2976 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2977 logevent("We believe remote version has SSH-2 ignore bug");
2980 if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
2981 (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
2982 (wc_match("OpenSSH_2.[235]*", imp)))) {
2984 * These versions only support the original (pre-RFC4419)
2985 * SSH-2 GEX request, and disconnect with a protocol error if
2986 * we use the newer version.
2988 ssh->remote_bugs |= BUG_SSH2_OLDGEX;
2989 logevent("We believe remote version has outdated SSH-2 GEX");
2992 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2994 * Servers that don't support our winadj request for one
2995 * reason or another. Currently, none detected automatically.
2997 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2998 logevent("We believe remote version has winadj bug");
3001 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
3002 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
3003 (wc_match("OpenSSH_[2-5].*", imp) ||
3004 wc_match("OpenSSH_6.[0-6]*", imp) ||
3005 wc_match("dropbear_0.[2-4][0-9]*", imp) ||
3006 wc_match("dropbear_0.5[01]*", imp)))) {
3008 * These versions have the SSH-2 channel request bug.
3009 * OpenSSH 6.7 and above do not:
3010 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
3011 * dropbear_0.52 and above do not:
3012 * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
3014 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
3015 logevent("We believe remote version has SSH-2 channel request bug");
3020 * The `software version' part of an SSH version string is required
3021 * to contain no spaces or minus signs.
3023 static void ssh_fix_verstring(char *str)
3025 /* Eat "<protoversion>-". */
3026 while (*str && *str != '-') str++;
3027 assert(*str == '-'); str++;
3029 /* Convert minus signs and spaces in the remaining string into
3032 if (*str == '-' || *str == ' ')
3039 * Send an appropriate SSH version string.
3041 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
3045 if (ssh->version == 2) {
3047 * Construct a v2 version string.
3049 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
3052 * Construct a v1 version string.
3054 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
3055 verstring = dupprintf("SSH-%s-%s\012",
3056 (ssh_versioncmp(svers, "1.5") <= 0 ?
3061 ssh_fix_verstring(verstring + strlen(protoname));
3063 /* FUZZING make PuTTY insecure, so make live use difficult. */
3067 if (ssh->version == 2) {
3070 * Record our version string.
3072 len = strcspn(verstring, "\015\012");
3073 ssh->v_c = snewn(len + 1, char);
3074 memcpy(ssh->v_c, verstring, len);
3078 logeventf(ssh, "We claim version: %.*s",
3079 strcspn(verstring, "\015\012"), verstring);
3080 s_write(ssh, verstring, strlen(verstring));
3084 static int do_ssh_init(Ssh ssh, unsigned char c)
3086 static const char protoname[] = "SSH-";
3088 struct do_ssh_init_state {
3097 crState(do_ssh_init_state);
3101 /* Search for a line beginning with the protocol name prefix in
3104 for (s->i = 0; protoname[s->i]; s->i++) {
3105 if ((char)c != protoname[s->i]) goto no;
3115 ssh->session_started = TRUE;
3117 s->vstrsize = sizeof(protoname) + 16;
3118 s->vstring = snewn(s->vstrsize, char);
3119 strcpy(s->vstring, protoname);
3120 s->vslen = strlen(protoname);
3123 if (s->vslen >= s->vstrsize - 1) {
3125 s->vstring = sresize(s->vstring, s->vstrsize, char);
3127 s->vstring[s->vslen++] = c;
3130 s->version[s->i] = '\0';
3132 } else if (s->i < sizeof(s->version) - 1)
3133 s->version[s->i++] = c;
3134 } else if (c == '\012')
3136 crReturn(1); /* get another char */
3139 ssh->agentfwd_enabled = FALSE;
3140 ssh->rdpkt2_state.incoming_sequence = 0;
3142 s->vstring[s->vslen] = 0;
3143 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3144 logeventf(ssh, "Server version: %s", s->vstring);
3145 ssh_detect_bugs(ssh, s->vstring);
3148 * Decide which SSH protocol version to support.
3151 /* Anything strictly below "2.0" means protocol 1 is supported. */
3152 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
3153 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
3154 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
3156 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3158 bombout(("SSH protocol version 1 required by our configuration "
3159 "but not provided by server"));
3162 } else if (conf_get_int(ssh->conf, CONF_sshprot) == 3) {
3164 bombout(("SSH protocol version 2 required by our configuration "
3165 "but server only provides (old, insecure) SSH-1"));
3169 /* No longer support values 1 or 2 for CONF_sshprot */
3170 assert(!"Unexpected value for CONF_sshprot");
3173 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
3178 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
3180 /* Send the version string, if we haven't already */
3181 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
3182 ssh_send_verstring(ssh, protoname, s->version);
3184 if (ssh->version == 2) {
3187 * Record their version string.
3189 len = strcspn(s->vstring, "\015\012");
3190 ssh->v_s = snewn(len + 1, char);
3191 memcpy(ssh->v_s, s->vstring, len);
3195 * Initialise SSH-2 protocol.
3197 ssh->protocol = ssh2_protocol;
3198 ssh2_protocol_setup(ssh);
3199 ssh->s_rdpkt = ssh2_rdpkt;
3202 * Initialise SSH-1 protocol.
3204 ssh->protocol = ssh1_protocol;
3205 ssh1_protocol_setup(ssh);
3206 ssh->s_rdpkt = ssh1_rdpkt;
3208 if (ssh->version == 2)
3209 do_ssh2_transport(ssh, NULL, -1, NULL);
3211 update_specials_menu(ssh->frontend);
3212 ssh->state = SSH_STATE_BEFORE_SIZE;
3213 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3220 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3223 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3224 * the ssh-connection part, extracted and given a trivial binary
3225 * packet protocol, so we replace 'SSH-' at the start with a new
3226 * name. In proper SSH style (though of course this part of the
3227 * proper SSH protocol _isn't_ subject to this kind of
3228 * DNS-domain-based extension), we define the new name in our
3231 static const char protoname[] =
3232 "SSHCONNECTION@putty.projects.tartarus.org-";
3234 struct do_ssh_connection_init_state {
3242 crState(do_ssh_connection_init_state);
3246 /* Search for a line beginning with the protocol name prefix in
3249 for (s->i = 0; protoname[s->i]; s->i++) {
3250 if ((char)c != protoname[s->i]) goto no;
3260 s->vstrsize = sizeof(protoname) + 16;
3261 s->vstring = snewn(s->vstrsize, char);
3262 strcpy(s->vstring, protoname);
3263 s->vslen = strlen(protoname);
3266 if (s->vslen >= s->vstrsize - 1) {
3268 s->vstring = sresize(s->vstring, s->vstrsize, char);
3270 s->vstring[s->vslen++] = c;
3273 s->version[s->i] = '\0';
3275 } else if (s->i < sizeof(s->version) - 1)
3276 s->version[s->i++] = c;
3277 } else if (c == '\012')
3279 crReturn(1); /* get another char */
3282 ssh->agentfwd_enabled = FALSE;
3283 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3285 s->vstring[s->vslen] = 0;
3286 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3287 logeventf(ssh, "Server version: %s", s->vstring);
3288 ssh_detect_bugs(ssh, s->vstring);
3291 * Decide which SSH protocol version to support. This is easy in
3292 * bare ssh-connection mode: only 2.0 is legal.
3294 if (ssh_versioncmp(s->version, "2.0") < 0) {
3295 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3298 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3299 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3305 logeventf(ssh, "Using bare ssh-connection protocol");
3307 /* Send the version string, if we haven't already */
3308 ssh_send_verstring(ssh, protoname, s->version);
3311 * Initialise bare connection protocol.
3313 ssh->protocol = ssh2_bare_connection_protocol;
3314 ssh2_bare_connection_protocol_setup(ssh);
3315 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3317 update_specials_menu(ssh->frontend);
3318 ssh->state = SSH_STATE_BEFORE_SIZE;
3319 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3322 * Get authconn (really just conn) under way.
3324 do_ssh2_authconn(ssh, NULL, 0, NULL);
3331 static void ssh_process_incoming_data(Ssh ssh,
3332 const unsigned char **data, int *datalen)
3334 struct Packet *pktin;
3336 pktin = ssh->s_rdpkt(ssh, data, datalen);
3338 ssh->protocol(ssh, NULL, 0, pktin);
3339 ssh_free_packet(pktin);
3343 static void ssh_queue_incoming_data(Ssh ssh,
3344 const unsigned char **data, int *datalen)
3346 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3351 static void ssh_process_queued_incoming_data(Ssh ssh)
3354 const unsigned char *data;
3357 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3358 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3362 while (!ssh->frozen && len > 0)
3363 ssh_process_incoming_data(ssh, &data, &len);
3366 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3370 static void ssh_set_frozen(Ssh ssh, int frozen)
3373 sk_set_frozen(ssh->s, frozen);
3374 ssh->frozen = frozen;
3377 static void ssh_gotdata(Ssh ssh, const unsigned char *data, int datalen)
3379 /* Log raw data, if we're in that mode. */
3381 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3382 0, NULL, NULL, 0, NULL);
3384 crBegin(ssh->ssh_gotdata_crstate);
3387 * To begin with, feed the characters one by one to the
3388 * protocol initialisation / selection function do_ssh_init().
3389 * When that returns 0, we're done with the initial greeting
3390 * exchange and can move on to packet discipline.
3393 int ret; /* need not be kept across crReturn */
3395 crReturnV; /* more data please */
3396 ret = ssh->do_ssh_init(ssh, *data);
3404 * We emerge from that loop when the initial negotiation is
3405 * over and we have selected an s_rdpkt function. Now pass
3406 * everything to s_rdpkt, and then pass the resulting packets
3407 * to the proper protocol handler.
3411 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3413 ssh_queue_incoming_data(ssh, &data, &datalen);
3414 /* This uses up all data and cannot cause anything interesting
3415 * to happen; indeed, for anything to happen at all, we must
3416 * return, so break out. */
3418 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3419 /* This uses up some or all data, and may freeze the
3421 ssh_process_queued_incoming_data(ssh);
3423 /* This uses up some or all data, and may freeze the
3425 ssh_process_incoming_data(ssh, &data, &datalen);
3427 /* FIXME this is probably EBW. */
3428 if (ssh->state == SSH_STATE_CLOSED)
3431 /* We're out of data. Go and get some more. */
3437 static int ssh_do_close(Ssh ssh, int notify_exit)
3440 struct ssh_channel *c;
3442 ssh->state = SSH_STATE_CLOSED;
3443 expire_timer_context(ssh);
3448 notify_remote_exit(ssh->frontend);
3453 * Now we must shut down any port- and X-forwarded channels going
3454 * through this connection.
3456 if (ssh->channels) {
3457 while (NULL != (c = index234(ssh->channels, 0))) {
3460 x11_close(c->u.x11.xconn);
3463 case CHAN_SOCKDATA_DORMANT:
3464 pfd_close(c->u.pfd.pf);
3467 del234(ssh->channels, c); /* moving next one to index 0 */
3468 if (ssh->version == 2)
3469 bufchain_clear(&c->v.v2.outbuffer);
3474 * Go through port-forwardings, and close any associated
3475 * listening sockets.
3477 if (ssh->portfwds) {
3478 struct ssh_portfwd *pf;
3479 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3480 /* Dispose of any listening socket. */
3482 pfl_terminate(pf->local);
3483 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3486 freetree234(ssh->portfwds);
3487 ssh->portfwds = NULL;
3491 * Also stop attempting to connection-share.
3493 if (ssh->connshare) {
3494 sharestate_free(ssh->connshare);
3495 ssh->connshare = NULL;
3501 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3502 const char *error_msg, int error_code)
3504 Ssh ssh = (Ssh) plug;
3507 * While we're attempting connection sharing, don't loudly log
3508 * everything that happens. Real TCP connections need to be logged
3509 * when we _start_ trying to connect, because it might be ages
3510 * before they respond if something goes wrong; but connection
3511 * sharing is local and quick to respond, and it's sufficient to
3512 * simply wait and see whether it worked afterwards.
3515 if (!ssh->attempting_connshare)
3516 backend_socket_log(ssh->frontend, type, addr, port,
3517 error_msg, error_code, ssh->conf,
3518 ssh->session_started);
3521 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3522 const char *ds_err, const char *us_err)
3524 if (event == SHARE_NONE) {
3525 /* In this case, 'logtext' is an error message indicating a
3526 * reason why connection sharing couldn't be set up _at all_.
3527 * Failing that, ds_err and us_err indicate why we couldn't be
3528 * a downstream and an upstream respectively. */
3530 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3533 logeventf(ssh, "Could not set up connection sharing"
3534 " as downstream: %s", ds_err);
3536 logeventf(ssh, "Could not set up connection sharing"
3537 " as upstream: %s", us_err);
3539 } else if (event == SHARE_DOWNSTREAM) {
3540 /* In this case, 'logtext' is a local endpoint address */
3541 logeventf(ssh, "Using existing shared connection at %s", logtext);
3542 /* Also we should mention this in the console window to avoid
3543 * confusing users as to why this window doesn't behave the
3545 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3546 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3548 } else if (event == SHARE_UPSTREAM) {
3549 /* In this case, 'logtext' is a local endpoint address too */
3550 logeventf(ssh, "Sharing this connection at %s", logtext);
3554 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3557 Ssh ssh = (Ssh) plug;
3558 int need_notify = ssh_do_close(ssh, FALSE);
3561 if (!ssh->close_expected)
3562 error_msg = "Server unexpectedly closed network connection";
3564 error_msg = "Server closed network connection";
3567 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3571 notify_remote_exit(ssh->frontend);
3574 logevent(error_msg);
3575 if (!ssh->close_expected || !ssh->clean_exit)
3576 connection_fatal(ssh->frontend, "%s", error_msg);
3580 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3582 Ssh ssh = (Ssh) plug;
3583 ssh_gotdata(ssh, (unsigned char *)data, len);
3584 if (ssh->state == SSH_STATE_CLOSED) {
3585 ssh_do_close(ssh, TRUE);
3591 static void ssh_sent(Plug plug, int bufsize)
3593 Ssh ssh = (Ssh) plug;
3595 * If the send backlog on the SSH socket itself clears, we
3596 * should unthrottle the whole world if it was throttled.
3598 if (bufsize < SSH_MAX_BACKLOG)
3599 ssh_throttle_all(ssh, 0, bufsize);
3602 static void ssh_hostport_setup(const char *host, int port, Conf *conf,
3603 char **savedhost, int *savedport,
3606 char *loghost = conf_get_str(conf, CONF_loghost);
3608 *loghost_ret = loghost;
3614 tmphost = dupstr(loghost);
3615 *savedport = 22; /* default ssh port */
3618 * A colon suffix on the hostname string also lets us affect
3619 * savedport. (Unless there are multiple colons, in which case
3620 * we assume this is an unbracketed IPv6 literal.)
3622 colon = host_strrchr(tmphost, ':');
3623 if (colon && colon == host_strchr(tmphost, ':')) {
3626 *savedport = atoi(colon);
3629 *savedhost = host_strduptrim(tmphost);
3632 *savedhost = host_strduptrim(host);
3634 port = 22; /* default ssh port */
3639 static int ssh_test_for_upstream(const char *host, int port, Conf *conf)
3645 random_ref(); /* platform may need this to determine share socket name */
3646 ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
3647 ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
3655 * Connect to specified host and port.
3656 * Returns an error message, or NULL on success.
3657 * Also places the canonical host name into `realhost'. It must be
3658 * freed by the caller.
3660 static const char *connect_to_host(Ssh ssh, const char *host, int port,
3661 char **realhost, int nodelay, int keepalive)
3663 static const struct plug_function_table fn_table = {
3674 int addressfamily, sshprot;
3676 ssh_hostport_setup(host, port, ssh->conf,
3677 &ssh->savedhost, &ssh->savedport, &loghost);
3679 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3682 * Try connection-sharing, in case that means we don't open a
3683 * socket after all. ssh_connection_sharing_init will connect to a
3684 * previously established upstream if it can, and failing that,
3685 * establish a listening socket for _us_ to be the upstream. In
3686 * the latter case it will return NULL just as if it had done
3687 * nothing, because here we only need to care if we're a
3688 * downstream and need to do our connection setup differently.
3690 ssh->connshare = NULL;
3691 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3692 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3693 ssh->conf, ssh, &ssh->connshare);
3694 ssh->attempting_connshare = FALSE;
3695 if (ssh->s != NULL) {
3697 * We are a downstream.
3699 ssh->bare_connection = TRUE;
3700 ssh->do_ssh_init = do_ssh_connection_init;
3701 ssh->fullhostname = NULL;
3702 *realhost = dupstr(host); /* best we can do */
3705 * We're not a downstream, so open a normal socket.
3707 ssh->do_ssh_init = do_ssh_init;
3712 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3713 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
3714 ssh->frontend, "SSH connection");
3715 if ((err = sk_addr_error(addr)) != NULL) {
3719 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3721 ssh->s = new_connection(addr, *realhost, port,
3722 0, 1, nodelay, keepalive,
3723 (Plug) ssh, ssh->conf);
3724 if ((err = sk_socket_error(ssh->s)) != NULL) {
3726 notify_remote_exit(ssh->frontend);
3732 * The SSH version number is always fixed (since we no longer support
3733 * fallback between versions), so set it now, and if it's SSH-2,
3734 * send the version string now too.
3736 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3737 assert(sshprot == 0 || sshprot == 3);
3741 if (sshprot == 3 && !ssh->bare_connection) {
3744 ssh_send_verstring(ssh, "SSH-", NULL);
3748 * loghost, if configured, overrides realhost.
3752 *realhost = dupstr(loghost);
3759 * Throttle or unthrottle the SSH connection.
3761 static void ssh_throttle_conn(Ssh ssh, int adjust)
3763 int old_count = ssh->conn_throttle_count;
3764 ssh->conn_throttle_count += adjust;
3765 assert(ssh->conn_throttle_count >= 0);
3766 if (ssh->conn_throttle_count && !old_count) {
3767 ssh_set_frozen(ssh, 1);
3768 } else if (!ssh->conn_throttle_count && old_count) {
3769 ssh_set_frozen(ssh, 0);
3774 * Throttle or unthrottle _all_ local data streams (for when sends
3775 * on the SSH connection itself back up).
3777 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3780 struct ssh_channel *c;
3782 if (enable == ssh->throttled_all)
3784 ssh->throttled_all = enable;
3785 ssh->overall_bufsize = bufsize;
3788 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3790 case CHAN_MAINSESSION:
3792 * This is treated separately, outside the switch.
3796 x11_override_throttle(c->u.x11.xconn, enable);
3799 /* Agent channels require no buffer management. */
3802 pfd_override_throttle(c->u.pfd.pf, enable);
3808 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3810 Ssh ssh = (Ssh) sshv;
3812 ssh->agent_response = reply;
3813 ssh->agent_response_len = replylen;
3815 if (ssh->version == 1)
3816 do_ssh1_login(ssh, NULL, -1, NULL);
3818 do_ssh2_authconn(ssh, NULL, -1, NULL);
3821 static void ssh_dialog_callback(void *sshv, int ret)
3823 Ssh ssh = (Ssh) sshv;
3825 ssh->user_response = ret;
3827 if (ssh->version == 1)
3828 do_ssh1_login(ssh, NULL, -1, NULL);
3830 do_ssh2_transport(ssh, NULL, -1, NULL);
3833 * This may have unfrozen the SSH connection, so do a
3836 ssh_process_queued_incoming_data(ssh);
3839 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3841 struct ssh_channel *c = (struct ssh_channel *)cv;
3842 const void *sentreply = reply;
3844 c->u.a.outstanding_requests--;
3846 /* Fake SSH_AGENT_FAILURE. */
3847 sentreply = "\0\0\0\1\5";
3850 ssh_send_channel_data(c, sentreply, replylen);
3854 * If we've already seen an incoming EOF but haven't sent an
3855 * outgoing one, this may be the moment to send it.
3857 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3858 sshfwd_write_eof(c);
3862 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3863 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3864 * => log `wire_reason'.
3866 static void ssh_disconnect(Ssh ssh, const char *client_reason,
3867 const char *wire_reason,
3868 int code, int clean_exit)
3872 client_reason = wire_reason;
3874 error = dupprintf("Disconnected: %s", client_reason);
3876 error = dupstr("Disconnected");
3878 if (ssh->version == 1) {
3879 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3881 } else if (ssh->version == 2) {
3882 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3883 ssh2_pkt_adduint32(pktout, code);
3884 ssh2_pkt_addstring(pktout, wire_reason);
3885 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3886 ssh2_pkt_send_noqueue(ssh, pktout);
3889 ssh->close_expected = TRUE;
3890 ssh->clean_exit = clean_exit;
3891 ssh_closing((Plug)ssh, error, 0, 0);
3895 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3896 const struct ssh_signkey *ssh2keytype,
3899 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3900 return -1; /* no manual keys configured */
3905 * The fingerprint string we've been given will have things
3906 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3907 * narrow down to just the colon-separated hex block at the
3908 * end of the string.
3910 const char *p = strrchr(fingerprint, ' ');
3911 fingerprint = p ? p+1 : fingerprint;
3912 /* Quick sanity checks, including making sure it's in lowercase */
3913 assert(strlen(fingerprint) == 16*3 - 1);
3914 assert(fingerprint[2] == ':');
3915 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3917 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3919 return 1; /* success */
3924 * Construct the base64-encoded public key blob and see if
3927 unsigned char *binblob;
3929 int binlen, atoms, i;
3930 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3931 atoms = (binlen + 2) / 3;
3932 base64blob = snewn(atoms * 4 + 1, char);
3933 for (i = 0; i < atoms; i++)
3934 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3935 base64blob[atoms * 4] = '\0';
3937 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3940 return 1; /* success */
3949 * Handle the key exchange and user authentication phases.
3951 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
3952 struct Packet *pktin)
3955 unsigned char cookie[8], *ptr;
3956 struct MD5Context md5c;
3957 struct do_ssh1_login_state {
3960 unsigned char *rsabuf;
3961 const unsigned char *keystr1, *keystr2;
3962 unsigned long supported_ciphers_mask, supported_auths_mask;
3963 int tried_publickey, tried_agent;
3964 int tis_auth_refused, ccard_auth_refused;
3965 unsigned char session_id[16];
3967 void *publickey_blob;
3968 int publickey_bloblen;
3969 char *publickey_comment;
3970 int privatekey_available, privatekey_encrypted;
3971 prompts_t *cur_prompt;
3974 unsigned char request[5], *response, *p;
3984 struct RSAKey servkey, hostkey;
3986 crState(do_ssh1_login_state);
3993 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3994 bombout(("Public key packet not received"));
3998 logevent("Received public keys");
4000 ptr = ssh_pkt_getdata(pktin, 8);
4002 bombout(("SSH-1 public key packet stopped before random cookie"));
4005 memcpy(cookie, ptr, 8);
4007 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
4008 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
4009 bombout(("Failed to read SSH-1 public keys from public key packet"));
4014 * Log the host key fingerprint.
4018 logevent("Host key fingerprint is:");
4019 strcpy(logmsg, " ");
4020 s->hostkey.comment = NULL;
4021 rsa_fingerprint(logmsg + strlen(logmsg),
4022 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
4026 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
4027 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
4028 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
4029 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
4030 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
4032 ssh->v1_local_protoflags =
4033 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
4034 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
4037 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
4038 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
4039 MD5Update(&md5c, cookie, 8);
4040 MD5Final(s->session_id, &md5c);
4042 for (i = 0; i < 32; i++)
4043 ssh->session_key[i] = random_byte();
4046 * Verify that the `bits' and `bytes' parameters match.
4048 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
4049 s->servkey.bits > s->servkey.bytes * 8) {
4050 bombout(("SSH-1 public keys were badly formatted"));
4054 s->len = (s->hostkey.bytes > s->servkey.bytes ?
4055 s->hostkey.bytes : s->servkey.bytes);
4057 s->rsabuf = snewn(s->len, unsigned char);
4060 * Verify the host key.
4064 * First format the key into a string.
4066 int len = rsastr_len(&s->hostkey);
4067 char fingerprint[100];
4068 char *keystr = snewn(len, char);
4069 rsastr_fmt(keystr, &s->hostkey);
4070 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
4072 /* First check against manually configured host keys. */
4073 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
4074 if (s->dlgret == 0) { /* did not match */
4075 bombout(("Host key did not appear in manually configured list"));
4078 } else if (s->dlgret < 0) { /* none configured; use standard handling */
4079 ssh_set_frozen(ssh, 1);
4080 s->dlgret = verify_ssh_host_key(ssh->frontend,
4081 ssh->savedhost, ssh->savedport,
4082 "rsa", keystr, fingerprint,
4083 ssh_dialog_callback, ssh);
4088 if (s->dlgret < 0) {
4092 bombout(("Unexpected data from server while waiting"
4093 " for user host key response"));
4096 } while (pktin || inlen > 0);
4097 s->dlgret = ssh->user_response;
4099 ssh_set_frozen(ssh, 0);
4101 if (s->dlgret == 0) {
4102 ssh_disconnect(ssh, "User aborted at host key verification",
4111 for (i = 0; i < 32; i++) {
4112 s->rsabuf[i] = ssh->session_key[i];
4114 s->rsabuf[i] ^= s->session_id[i];
4117 if (s->hostkey.bytes > s->servkey.bytes) {
4118 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4120 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4122 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4124 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4127 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4131 logevent("Encrypted session key");
4134 int cipher_chosen = 0, warn = 0;
4135 const char *cipher_string = NULL;
4137 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4138 int next_cipher = conf_get_int_int(ssh->conf,
4139 CONF_ssh_cipherlist, i);
4140 if (next_cipher == CIPHER_WARN) {
4141 /* If/when we choose a cipher, warn about it */
4143 } else if (next_cipher == CIPHER_AES) {
4144 /* XXX Probably don't need to mention this. */
4145 logevent("AES not supported in SSH-1, skipping");
4147 switch (next_cipher) {
4148 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
4149 cipher_string = "3DES"; break;
4150 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4151 cipher_string = "Blowfish"; break;
4152 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
4153 cipher_string = "single-DES"; break;
4155 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4159 if (!cipher_chosen) {
4160 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4161 bombout(("Server violates SSH-1 protocol by not "
4162 "supporting 3DES encryption"));
4164 /* shouldn't happen */
4165 bombout(("No supported ciphers found"));
4169 /* Warn about chosen cipher if necessary. */
4171 ssh_set_frozen(ssh, 1);
4172 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4173 ssh_dialog_callback, ssh);
4174 if (s->dlgret < 0) {
4178 bombout(("Unexpected data from server while waiting"
4179 " for user response"));
4182 } while (pktin || inlen > 0);
4183 s->dlgret = ssh->user_response;
4185 ssh_set_frozen(ssh, 0);
4186 if (s->dlgret == 0) {
4187 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4194 switch (s->cipher_type) {
4195 case SSH_CIPHER_3DES:
4196 logevent("Using 3DES encryption");
4198 case SSH_CIPHER_DES:
4199 logevent("Using single-DES encryption");
4201 case SSH_CIPHER_BLOWFISH:
4202 logevent("Using Blowfish encryption");
4206 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4207 PKT_CHAR, s->cipher_type,
4208 PKT_DATA, cookie, 8,
4209 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4210 PKT_DATA, s->rsabuf, s->len,
4211 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4213 logevent("Trying to enable encryption...");
4217 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4218 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4220 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4221 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4222 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4224 ssh->crcda_ctx = crcda_make_context();
4225 logevent("Installing CRC compensation attack detector");
4227 if (s->servkey.modulus) {
4228 sfree(s->servkey.modulus);
4229 s->servkey.modulus = NULL;
4231 if (s->servkey.exponent) {
4232 sfree(s->servkey.exponent);
4233 s->servkey.exponent = NULL;
4235 if (s->hostkey.modulus) {
4236 sfree(s->hostkey.modulus);
4237 s->hostkey.modulus = NULL;
4239 if (s->hostkey.exponent) {
4240 sfree(s->hostkey.exponent);
4241 s->hostkey.exponent = NULL;
4245 if (pktin->type != SSH1_SMSG_SUCCESS) {
4246 bombout(("Encryption not successfully enabled"));
4250 logevent("Successfully started encryption");
4252 fflush(stdout); /* FIXME eh? */
4254 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4255 int ret; /* need not be kept over crReturn */
4256 s->cur_prompt = new_prompts(ssh->frontend);
4257 s->cur_prompt->to_server = TRUE;
4258 s->cur_prompt->name = dupstr("SSH login name");
4259 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4260 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4263 crWaitUntil(!pktin);
4264 ret = get_userpass_input(s->cur_prompt, in, inlen);
4269 * Failed to get a username. Terminate.
4271 free_prompts(s->cur_prompt);
4272 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4275 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4276 free_prompts(s->cur_prompt);
4279 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4281 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4283 if (flags & FLAG_INTERACTIVE &&
4284 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4285 c_write_str(ssh, userlog);
4286 c_write_str(ssh, "\r\n");
4294 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4295 /* We must not attempt PK auth. Pretend we've already tried it. */
4296 s->tried_publickey = s->tried_agent = 1;
4298 s->tried_publickey = s->tried_agent = 0;
4300 s->tis_auth_refused = s->ccard_auth_refused = 0;
4302 * Load the public half of any configured keyfile for later use.
4304 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4305 if (!filename_is_null(s->keyfile)) {
4307 logeventf(ssh, "Reading key file \"%.150s\"",
4308 filename_to_str(s->keyfile));
4309 keytype = key_type(s->keyfile);
4310 if (keytype == SSH_KEYTYPE_SSH1 ||
4311 keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
4313 if (rsakey_pubblob(s->keyfile,
4314 &s->publickey_blob, &s->publickey_bloblen,
4315 &s->publickey_comment, &error)) {
4316 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
4317 if (!s->privatekey_available)
4318 logeventf(ssh, "Key file contains public key only");
4319 s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
4323 logeventf(ssh, "Unable to load key (%s)", error);
4324 msgbuf = dupprintf("Unable to load key file "
4325 "\"%.150s\" (%s)\r\n",
4326 filename_to_str(s->keyfile),
4328 c_write_str(ssh, msgbuf);
4330 s->publickey_blob = NULL;
4334 logeventf(ssh, "Unable to use this key file (%s)",
4335 key_type_to_str(keytype));
4336 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4338 filename_to_str(s->keyfile),
4339 key_type_to_str(keytype));
4340 c_write_str(ssh, msgbuf);
4342 s->publickey_blob = NULL;
4345 s->publickey_blob = NULL;
4347 while (pktin->type == SSH1_SMSG_FAILURE) {
4348 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4350 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4352 * Attempt RSA authentication using Pageant.
4358 logevent("Pageant is running. Requesting keys.");
4360 /* Request the keys held by the agent. */
4361 PUT_32BIT(s->request, 1);
4362 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4363 if (!agent_query(s->request, 5, &r, &s->responselen,
4364 ssh_agent_callback, ssh)) {
4368 bombout(("Unexpected data from server while waiting"
4369 " for agent response"));
4372 } while (pktin || inlen > 0);
4373 r = ssh->agent_response;
4374 s->responselen = ssh->agent_response_len;
4376 s->response = (unsigned char *) r;
4377 if (s->response && s->responselen >= 5 &&
4378 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4379 s->p = s->response + 5;
4380 s->nkeys = toint(GET_32BIT(s->p));
4382 logeventf(ssh, "Pageant reported negative key count %d",
4387 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4388 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4389 unsigned char *pkblob = s->p;
4393 do { /* do while (0) to make breaking easy */
4394 n = ssh1_read_bignum
4395 (s->p, toint(s->responselen-(s->p-s->response)),
4400 n = ssh1_read_bignum
4401 (s->p, toint(s->responselen-(s->p-s->response)),
4406 if (s->responselen - (s->p-s->response) < 4)
4408 s->commentlen = toint(GET_32BIT(s->p));
4410 if (s->commentlen < 0 ||
4411 toint(s->responselen - (s->p-s->response)) <
4414 s->commentp = (char *)s->p;
4415 s->p += s->commentlen;
4419 logevent("Pageant key list packet was truncated");
4423 if (s->publickey_blob) {
4424 if (!memcmp(pkblob, s->publickey_blob,
4425 s->publickey_bloblen)) {
4426 logeventf(ssh, "Pageant key #%d matches "
4427 "configured key file", s->keyi);
4428 s->tried_publickey = 1;
4430 /* Skip non-configured key */
4433 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4434 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4435 PKT_BIGNUM, s->key.modulus, PKT_END);
4437 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4438 logevent("Key refused");
4441 logevent("Received RSA challenge");
4442 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4443 bombout(("Server's RSA challenge was badly formatted"));
4448 char *agentreq, *q, *ret;
4451 len = 1 + 4; /* message type, bit count */
4452 len += ssh1_bignum_length(s->key.exponent);
4453 len += ssh1_bignum_length(s->key.modulus);
4454 len += ssh1_bignum_length(s->challenge);
4455 len += 16; /* session id */
4456 len += 4; /* response format */
4457 agentreq = snewn(4 + len, char);
4458 PUT_32BIT(agentreq, len);
4460 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4461 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4463 q += ssh1_write_bignum(q, s->key.exponent);
4464 q += ssh1_write_bignum(q, s->key.modulus);
4465 q += ssh1_write_bignum(q, s->challenge);
4466 memcpy(q, s->session_id, 16);
4468 PUT_32BIT(q, 1); /* response format */
4469 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4470 ssh_agent_callback, ssh)) {
4475 bombout(("Unexpected data from server"
4476 " while waiting for agent"
4480 } while (pktin || inlen > 0);
4481 vret = ssh->agent_response;
4482 retlen = ssh->agent_response_len;
4487 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4488 logevent("Sending Pageant's response");
4489 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4490 PKT_DATA, ret + 5, 16,
4494 if (pktin->type == SSH1_SMSG_SUCCESS) {
4496 ("Pageant's response accepted");
4497 if (flags & FLAG_VERBOSE) {
4498 c_write_str(ssh, "Authenticated using"
4500 c_write(ssh, s->commentp,
4502 c_write_str(ssh, "\" from agent\r\n");
4507 ("Pageant's response not accepted");
4510 ("Pageant failed to answer challenge");
4514 logevent("No reply received from Pageant");
4517 freebn(s->key.exponent);
4518 freebn(s->key.modulus);
4519 freebn(s->challenge);
4524 if (s->publickey_blob && !s->tried_publickey)
4525 logevent("Configured key file not in Pageant");
4527 logevent("Failed to get reply from Pageant");
4532 if (s->publickey_blob && s->privatekey_available &&
4533 !s->tried_publickey) {
4535 * Try public key authentication with the specified
4538 int got_passphrase; /* need not be kept over crReturn */
4539 if (flags & FLAG_VERBOSE)
4540 c_write_str(ssh, "Trying public key authentication.\r\n");
4541 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4542 logeventf(ssh, "Trying public key \"%s\"",
4543 filename_to_str(s->keyfile));
4544 s->tried_publickey = 1;
4545 got_passphrase = FALSE;
4546 while (!got_passphrase) {
4548 * Get a passphrase, if necessary.
4550 char *passphrase = NULL; /* only written after crReturn */
4552 if (!s->privatekey_encrypted) {
4553 if (flags & FLAG_VERBOSE)
4554 c_write_str(ssh, "No passphrase required.\r\n");
4557 int ret; /* need not be kept over crReturn */
4558 s->cur_prompt = new_prompts(ssh->frontend);
4559 s->cur_prompt->to_server = FALSE;
4560 s->cur_prompt->name = dupstr("SSH key passphrase");
4561 add_prompt(s->cur_prompt,
4562 dupprintf("Passphrase for key \"%.100s\": ",
4563 s->publickey_comment), FALSE);
4564 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4567 crWaitUntil(!pktin);
4568 ret = get_userpass_input(s->cur_prompt, in, inlen);
4572 /* Failed to get a passphrase. Terminate. */
4573 free_prompts(s->cur_prompt);
4574 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4578 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4579 free_prompts(s->cur_prompt);
4582 * Try decrypting key with passphrase.
4584 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4585 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4588 smemclr(passphrase, strlen(passphrase));
4592 /* Correct passphrase. */
4593 got_passphrase = TRUE;
4594 } else if (ret == 0) {
4595 c_write_str(ssh, "Couldn't load private key from ");
4596 c_write_str(ssh, filename_to_str(s->keyfile));
4597 c_write_str(ssh, " (");
4598 c_write_str(ssh, error);
4599 c_write_str(ssh, ").\r\n");
4600 got_passphrase = FALSE;
4601 break; /* go and try something else */
4602 } else if (ret == -1) {
4603 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4604 got_passphrase = FALSE;
4607 assert(0 && "unexpected return from loadrsakey()");
4608 got_passphrase = FALSE; /* placate optimisers */
4612 if (got_passphrase) {
4615 * Send a public key attempt.
4617 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4618 PKT_BIGNUM, s->key.modulus, PKT_END);
4621 if (pktin->type == SSH1_SMSG_FAILURE) {
4622 c_write_str(ssh, "Server refused our public key.\r\n");
4623 continue; /* go and try something else */
4625 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4626 bombout(("Bizarre response to offer of public key"));
4632 unsigned char buffer[32];
4633 Bignum challenge, response;
4635 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4636 bombout(("Server's RSA challenge was badly formatted"));
4639 response = rsadecrypt(challenge, &s->key);
4640 freebn(s->key.private_exponent);/* burn the evidence */
4642 for (i = 0; i < 32; i++) {
4643 buffer[i] = bignum_byte(response, 31 - i);
4647 MD5Update(&md5c, buffer, 32);
4648 MD5Update(&md5c, s->session_id, 16);
4649 MD5Final(buffer, &md5c);
4651 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4652 PKT_DATA, buffer, 16, PKT_END);
4659 if (pktin->type == SSH1_SMSG_FAILURE) {
4660 if (flags & FLAG_VERBOSE)
4661 c_write_str(ssh, "Failed to authenticate with"
4662 " our public key.\r\n");
4663 continue; /* go and try something else */
4664 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4665 bombout(("Bizarre response to RSA authentication response"));
4669 break; /* we're through! */
4675 * Otherwise, try various forms of password-like authentication.
4677 s->cur_prompt = new_prompts(ssh->frontend);
4679 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4680 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4681 !s->tis_auth_refused) {
4682 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4683 logevent("Requested TIS authentication");
4684 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4686 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4687 logevent("TIS authentication declined");
4688 if (flags & FLAG_INTERACTIVE)
4689 c_write_str(ssh, "TIS authentication refused.\r\n");
4690 s->tis_auth_refused = 1;
4695 char *instr_suf, *prompt;
4697 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4699 bombout(("TIS challenge packet was badly formed"));
4702 logevent("Received TIS challenge");
4703 s->cur_prompt->to_server = TRUE;
4704 s->cur_prompt->name = dupstr("SSH TIS authentication");
4705 /* Prompt heuristic comes from OpenSSH */
4706 if (memchr(challenge, '\n', challengelen)) {
4707 instr_suf = dupstr("");
4708 prompt = dupprintf("%.*s", challengelen, challenge);
4710 instr_suf = dupprintf("%.*s", challengelen, challenge);
4711 prompt = dupstr("Response: ");
4713 s->cur_prompt->instruction =
4714 dupprintf("Using TIS authentication.%s%s",
4715 (*instr_suf) ? "\n" : "",
4717 s->cur_prompt->instr_reqd = TRUE;
4718 add_prompt(s->cur_prompt, prompt, FALSE);
4722 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4723 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4724 !s->ccard_auth_refused) {
4725 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4726 logevent("Requested CryptoCard authentication");
4727 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4729 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4730 logevent("CryptoCard authentication declined");
4731 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4732 s->ccard_auth_refused = 1;
4737 char *instr_suf, *prompt;
4739 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4741 bombout(("CryptoCard challenge packet was badly formed"));
4744 logevent("Received CryptoCard challenge");
4745 s->cur_prompt->to_server = TRUE;
4746 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4747 s->cur_prompt->name_reqd = FALSE;
4748 /* Prompt heuristic comes from OpenSSH */
4749 if (memchr(challenge, '\n', challengelen)) {
4750 instr_suf = dupstr("");
4751 prompt = dupprintf("%.*s", challengelen, challenge);
4753 instr_suf = dupprintf("%.*s", challengelen, challenge);
4754 prompt = dupstr("Response: ");
4756 s->cur_prompt->instruction =
4757 dupprintf("Using CryptoCard authentication.%s%s",
4758 (*instr_suf) ? "\n" : "",
4760 s->cur_prompt->instr_reqd = TRUE;
4761 add_prompt(s->cur_prompt, prompt, FALSE);
4765 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4766 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4767 bombout(("No supported authentication methods available"));
4770 s->cur_prompt->to_server = TRUE;
4771 s->cur_prompt->name = dupstr("SSH password");
4772 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4773 ssh->username, ssh->savedhost),
4778 * Show password prompt, having first obtained it via a TIS
4779 * or CryptoCard exchange if we're doing TIS or CryptoCard
4783 int ret; /* need not be kept over crReturn */
4784 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4787 crWaitUntil(!pktin);
4788 ret = get_userpass_input(s->cur_prompt, in, inlen);
4793 * Failed to get a password (for example
4794 * because one was supplied on the command line
4795 * which has already failed to work). Terminate.
4797 free_prompts(s->cur_prompt);
4798 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4803 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4805 * Defence against traffic analysis: we send a
4806 * whole bunch of packets containing strings of
4807 * different lengths. One of these strings is the
4808 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4809 * The others are all random data in
4810 * SSH1_MSG_IGNORE packets. This way a passive
4811 * listener can't tell which is the password, and
4812 * hence can't deduce the password length.
4814 * Anybody with a password length greater than 16
4815 * bytes is going to have enough entropy in their
4816 * password that a listener won't find it _that_
4817 * much help to know how long it is. So what we'll
4820 * - if password length < 16, we send 15 packets
4821 * containing string lengths 1 through 15
4823 * - otherwise, we let N be the nearest multiple
4824 * of 8 below the password length, and send 8
4825 * packets containing string lengths N through
4826 * N+7. This won't obscure the order of
4827 * magnitude of the password length, but it will
4828 * introduce a bit of extra uncertainty.
4830 * A few servers can't deal with SSH1_MSG_IGNORE, at
4831 * least in this context. For these servers, we need
4832 * an alternative defence. We make use of the fact
4833 * that the password is interpreted as a C string:
4834 * so we can append a NUL, then some random data.
4836 * A few servers can deal with neither SSH1_MSG_IGNORE
4837 * here _nor_ a padded password string.
4838 * For these servers we are left with no defences
4839 * against password length sniffing.
4841 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4842 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4844 * The server can deal with SSH1_MSG_IGNORE, so
4845 * we can use the primary defence.
4847 int bottom, top, pwlen, i;
4850 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4852 bottom = 0; /* zero length passwords are OK! :-) */
4855 bottom = pwlen & ~7;
4859 assert(pwlen >= bottom && pwlen <= top);
4861 randomstr = snewn(top + 1, char);
4863 for (i = bottom; i <= top; i++) {
4865 defer_packet(ssh, s->pwpkt_type,
4866 PKT_STR,s->cur_prompt->prompts[0]->result,
4869 for (j = 0; j < i; j++) {
4871 randomstr[j] = random_byte();
4872 } while (randomstr[j] == '\0');
4874 randomstr[i] = '\0';
4875 defer_packet(ssh, SSH1_MSG_IGNORE,
4876 PKT_STR, randomstr, PKT_END);
4879 logevent("Sending password with camouflage packets");
4880 ssh_pkt_defersend(ssh);
4883 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4885 * The server can't deal with SSH1_MSG_IGNORE
4886 * but can deal with padded passwords, so we
4887 * can use the secondary defence.
4893 len = strlen(s->cur_prompt->prompts[0]->result);
4894 if (len < sizeof(string)) {
4896 strcpy(string, s->cur_prompt->prompts[0]->result);
4897 len++; /* cover the zero byte */
4898 while (len < sizeof(string)) {
4899 string[len++] = (char) random_byte();
4902 ss = s->cur_prompt->prompts[0]->result;
4904 logevent("Sending length-padded password");
4905 send_packet(ssh, s->pwpkt_type,
4906 PKT_INT, len, PKT_DATA, ss, len,
4910 * The server is believed unable to cope with
4911 * any of our password camouflage methods.
4914 len = strlen(s->cur_prompt->prompts[0]->result);
4915 logevent("Sending unpadded password");
4916 send_packet(ssh, s->pwpkt_type,
4918 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4922 send_packet(ssh, s->pwpkt_type,
4923 PKT_STR, s->cur_prompt->prompts[0]->result,
4926 logevent("Sent password");
4927 free_prompts(s->cur_prompt);
4929 if (pktin->type == SSH1_SMSG_FAILURE) {
4930 if (flags & FLAG_VERBOSE)
4931 c_write_str(ssh, "Access denied\r\n");
4932 logevent("Authentication refused");
4933 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4934 bombout(("Strange packet received, type %d", pktin->type));
4940 if (s->publickey_blob) {
4941 sfree(s->publickey_blob);
4942 sfree(s->publickey_comment);
4945 logevent("Authentication successful");
4950 static void ssh_channel_try_eof(struct ssh_channel *c)
4953 assert(c->pending_eof); /* precondition for calling us */
4955 return; /* can't close: not even opened yet */
4956 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4957 return; /* can't send EOF: pending outgoing data */
4959 c->pending_eof = FALSE; /* we're about to send it */
4960 if (ssh->version == 1) {
4961 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4963 c->closes |= CLOSES_SENT_EOF;
4965 struct Packet *pktout;
4966 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4967 ssh2_pkt_adduint32(pktout, c->remoteid);
4968 ssh2_pkt_send(ssh, pktout);
4969 c->closes |= CLOSES_SENT_EOF;
4970 ssh2_channel_check_close(c);
4974 Conf *sshfwd_get_conf(struct ssh_channel *c)
4980 void sshfwd_write_eof(struct ssh_channel *c)
4984 if (ssh->state == SSH_STATE_CLOSED)
4987 if (c->closes & CLOSES_SENT_EOF)
4990 c->pending_eof = TRUE;
4991 ssh_channel_try_eof(c);
4994 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4998 if (ssh->state == SSH_STATE_CLOSED)
5003 x11_close(c->u.x11.xconn);
5004 logeventf(ssh, "Forwarded X11 connection terminated due to local "
5008 case CHAN_SOCKDATA_DORMANT:
5009 pfd_close(c->u.pfd.pf);
5010 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
5013 c->type = CHAN_ZOMBIE;
5014 c->pending_eof = FALSE; /* this will confuse a zombie channel */
5016 ssh2_channel_check_close(c);
5019 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
5023 if (ssh->state == SSH_STATE_CLOSED)
5026 return ssh_send_channel_data(c, buf, len);
5029 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
5033 if (ssh->state == SSH_STATE_CLOSED)
5036 ssh_channel_unthrottle(c, bufsize);
5039 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
5041 struct queued_handler *qh = ssh->qhead;
5045 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
5048 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
5049 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
5052 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
5053 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
5057 ssh->qhead = qh->next;
5059 if (ssh->qhead->msg1 > 0) {
5060 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5061 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
5063 if (ssh->qhead->msg2 > 0) {
5064 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5065 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
5068 ssh->qhead = ssh->qtail = NULL;
5071 qh->handler(ssh, pktin, qh->ctx);
5076 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5077 chandler_fn_t handler, void *ctx)
5079 struct queued_handler *qh;
5081 qh = snew(struct queued_handler);
5084 qh->handler = handler;
5088 if (ssh->qtail == NULL) {
5092 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5093 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5096 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5097 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5100 ssh->qtail->next = qh;
5105 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5107 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5109 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5110 SSH2_MSG_REQUEST_SUCCESS)) {
5111 logeventf(ssh, "Remote port forwarding from %s enabled",
5114 logeventf(ssh, "Remote port forwarding from %s refused",
5117 rpf = del234(ssh->rportfwds, pf);
5119 pf->pfrec->remote = NULL;
5124 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5127 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5130 pf->share_ctx = share_ctx;
5131 pf->shost = dupstr(shost);
5133 pf->sportdesc = NULL;
5134 if (!ssh->rportfwds) {
5135 assert(ssh->version == 2);
5136 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5138 if (add234(ssh->rportfwds, pf) != pf) {
5146 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5149 share_got_pkt_from_server(ctx, pktin->type,
5150 pktin->body, pktin->length);
5153 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5155 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5156 ssh_sharing_global_request_response, share_ctx);
5159 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5161 struct ssh_portfwd *epf;
5165 if (!ssh->portfwds) {
5166 ssh->portfwds = newtree234(ssh_portcmp);
5169 * Go through the existing port forwardings and tag them
5170 * with status==DESTROY. Any that we want to keep will be
5171 * re-enabled (status==KEEP) as we go through the
5172 * configuration and find out which bits are the same as
5175 struct ssh_portfwd *epf;
5177 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5178 epf->status = DESTROY;
5181 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5183 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5184 char *kp, *kp2, *vp, *vp2;
5185 char address_family, type;
5186 int sport,dport,sserv,dserv;
5187 char *sports, *dports, *saddr, *host;
5191 address_family = 'A';
5193 if (*kp == 'A' || *kp == '4' || *kp == '6')
5194 address_family = *kp++;
5195 if (*kp == 'L' || *kp == 'R')
5198 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5200 * There's a colon in the middle of the source port
5201 * string, which means that the part before it is
5202 * actually a source address.
5204 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5205 saddr = host_strduptrim(saddr_tmp);
5212 sport = atoi(sports);
5216 sport = net_service_lookup(sports);
5218 logeventf(ssh, "Service lookup failed for source"
5219 " port \"%s\"", sports);
5223 if (type == 'L' && !strcmp(val, "D")) {
5224 /* dynamic forwarding */
5231 /* ordinary forwarding */
5233 vp2 = vp + host_strcspn(vp, ":");
5234 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5238 dport = atoi(dports);
5242 dport = net_service_lookup(dports);
5244 logeventf(ssh, "Service lookup failed for destination"
5245 " port \"%s\"", dports);
5250 if (sport && dport) {
5251 /* Set up a description of the source port. */
5252 struct ssh_portfwd *pfrec, *epfrec;
5254 pfrec = snew(struct ssh_portfwd);
5256 pfrec->saddr = saddr;
5257 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5258 pfrec->sport = sport;
5259 pfrec->daddr = host;
5260 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5261 pfrec->dport = dport;
5262 pfrec->local = NULL;
5263 pfrec->remote = NULL;
5264 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5265 address_family == '6' ? ADDRTYPE_IPV6 :
5268 epfrec = add234(ssh->portfwds, pfrec);
5269 if (epfrec != pfrec) {
5270 if (epfrec->status == DESTROY) {
5272 * We already have a port forwarding up and running
5273 * with precisely these parameters. Hence, no need
5274 * to do anything; simply re-tag the existing one
5277 epfrec->status = KEEP;
5280 * Anything else indicates that there was a duplicate
5281 * in our input, which we'll silently ignore.
5283 free_portfwd(pfrec);
5285 pfrec->status = CREATE;
5294 * Now go through and destroy any port forwardings which were
5297 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5298 if (epf->status == DESTROY) {
5301 message = dupprintf("%s port forwarding from %s%s%d",
5302 epf->type == 'L' ? "local" :
5303 epf->type == 'R' ? "remote" : "dynamic",
5304 epf->saddr ? epf->saddr : "",
5305 epf->saddr ? ":" : "",
5308 if (epf->type != 'D') {
5309 char *msg2 = dupprintf("%s to %s:%d", message,
5310 epf->daddr, epf->dport);
5315 logeventf(ssh, "Cancelling %s", message);
5318 /* epf->remote or epf->local may be NULL if setting up a
5319 * forwarding failed. */
5321 struct ssh_rportfwd *rpf = epf->remote;
5322 struct Packet *pktout;
5325 * Cancel the port forwarding at the server
5328 if (ssh->version == 1) {
5330 * We cannot cancel listening ports on the
5331 * server side in SSH-1! There's no message
5332 * to support it. Instead, we simply remove
5333 * the rportfwd record from the local end
5334 * so that any connections the server tries
5335 * to make on it are rejected.
5338 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5339 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5340 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5342 ssh2_pkt_addstring(pktout, epf->saddr);
5343 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5344 /* XXX: rport_acceptall may not represent
5345 * what was used to open the original connection,
5346 * since it's reconfigurable. */
5347 ssh2_pkt_addstring(pktout, "");
5349 ssh2_pkt_addstring(pktout, "localhost");
5351 ssh2_pkt_adduint32(pktout, epf->sport);
5352 ssh2_pkt_send(ssh, pktout);
5355 del234(ssh->rportfwds, rpf);
5357 } else if (epf->local) {
5358 pfl_terminate(epf->local);
5361 delpos234(ssh->portfwds, i);
5363 i--; /* so we don't skip one in the list */
5367 * And finally, set up any new port forwardings (status==CREATE).
5369 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5370 if (epf->status == CREATE) {
5371 char *sportdesc, *dportdesc;
5372 sportdesc = dupprintf("%s%s%s%s%d%s",
5373 epf->saddr ? epf->saddr : "",
5374 epf->saddr ? ":" : "",
5375 epf->sserv ? epf->sserv : "",
5376 epf->sserv ? "(" : "",
5378 epf->sserv ? ")" : "");
5379 if (epf->type == 'D') {
5382 dportdesc = dupprintf("%s:%s%s%d%s",
5384 epf->dserv ? epf->dserv : "",
5385 epf->dserv ? "(" : "",
5387 epf->dserv ? ")" : "");
5390 if (epf->type == 'L') {
5391 char *err = pfl_listen(epf->daddr, epf->dport,
5392 epf->saddr, epf->sport,
5393 ssh, conf, &epf->local,
5394 epf->addressfamily);
5396 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5397 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5398 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5399 sportdesc, dportdesc,
5400 err ? " failed: " : "", err ? err : "");
5403 } else if (epf->type == 'D') {
5404 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5405 ssh, conf, &epf->local,
5406 epf->addressfamily);
5408 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5409 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5410 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5412 err ? " failed: " : "", err ? err : "");
5417 struct ssh_rportfwd *pf;
5420 * Ensure the remote port forwardings tree exists.
5422 if (!ssh->rportfwds) {
5423 if (ssh->version == 1)
5424 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5426 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5429 pf = snew(struct ssh_rportfwd);
5430 pf->share_ctx = NULL;
5431 pf->dhost = dupstr(epf->daddr);
5432 pf->dport = epf->dport;
5434 pf->shost = dupstr(epf->saddr);
5435 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5436 pf->shost = dupstr("");
5438 pf->shost = dupstr("localhost");
5440 pf->sport = epf->sport;
5441 if (add234(ssh->rportfwds, pf) != pf) {
5442 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5443 epf->daddr, epf->dport);
5446 logeventf(ssh, "Requesting remote port %s"
5447 " forward to %s", sportdesc, dportdesc);
5449 pf->sportdesc = sportdesc;
5454 if (ssh->version == 1) {
5455 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5456 PKT_INT, epf->sport,
5457 PKT_STR, epf->daddr,
5458 PKT_INT, epf->dport,
5460 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5462 ssh_rportfwd_succfail, pf);
5464 struct Packet *pktout;
5465 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5466 ssh2_pkt_addstring(pktout, "tcpip-forward");
5467 ssh2_pkt_addbool(pktout, 1);/* want reply */
5468 ssh2_pkt_addstring(pktout, pf->shost);
5469 ssh2_pkt_adduint32(pktout, pf->sport);
5470 ssh2_pkt_send(ssh, pktout);
5472 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5473 SSH2_MSG_REQUEST_FAILURE,
5474 ssh_rportfwd_succfail, pf);
5483 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5486 int stringlen, bufsize;
5488 ssh_pkt_getstring(pktin, &string, &stringlen);
5489 if (string == NULL) {
5490 bombout(("Incoming terminal data packet was badly formed"));
5494 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5496 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5497 ssh->v1_stdout_throttling = 1;
5498 ssh_throttle_conn(ssh, +1);
5502 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5504 /* Remote side is trying to open a channel to talk to our
5505 * X-Server. Give them back a local channel number. */
5506 struct ssh_channel *c;
5507 int remoteid = ssh_pkt_getuint32(pktin);
5509 logevent("Received X11 connect request");
5510 /* Refuse if X11 forwarding is disabled. */
5511 if (!ssh->X11_fwd_enabled) {
5512 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5513 PKT_INT, remoteid, PKT_END);
5514 logevent("Rejected X11 connect request");
5516 c = snew(struct ssh_channel);
5519 ssh_channel_init(c);
5520 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5521 c->remoteid = remoteid;
5522 c->halfopen = FALSE;
5523 c->type = CHAN_X11; /* identify channel type */
5524 add234(ssh->channels, c);
5525 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5526 PKT_INT, c->remoteid, PKT_INT,
5527 c->localid, PKT_END);
5528 logevent("Opened X11 forward channel");
5532 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5534 /* Remote side is trying to open a channel to talk to our
5535 * agent. Give them back a local channel number. */
5536 struct ssh_channel *c;
5537 int remoteid = ssh_pkt_getuint32(pktin);
5539 /* Refuse if agent forwarding is disabled. */
5540 if (!ssh->agentfwd_enabled) {
5541 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5542 PKT_INT, remoteid, PKT_END);
5544 c = snew(struct ssh_channel);
5546 ssh_channel_init(c);
5547 c->remoteid = remoteid;
5548 c->halfopen = FALSE;
5549 c->type = CHAN_AGENT; /* identify channel type */
5550 c->u.a.lensofar = 0;
5551 c->u.a.message = NULL;
5552 c->u.a.outstanding_requests = 0;
5553 add234(ssh->channels, c);
5554 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5555 PKT_INT, c->remoteid, PKT_INT, c->localid,
5560 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5562 /* Remote side is trying to open a channel to talk to a
5563 * forwarded port. Give them back a local channel number. */
5564 struct ssh_rportfwd pf, *pfp;
5570 remoteid = ssh_pkt_getuint32(pktin);
5571 ssh_pkt_getstring(pktin, &host, &hostsize);
5572 port = ssh_pkt_getuint32(pktin);
5574 pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host));
5576 pfp = find234(ssh->rportfwds, &pf, NULL);
5579 logeventf(ssh, "Rejected remote port open request for %s:%d",
5581 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5582 PKT_INT, remoteid, PKT_END);
5584 struct ssh_channel *c = snew(struct ssh_channel);
5587 logeventf(ssh, "Received remote port open request for %s:%d",
5589 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5590 c, ssh->conf, pfp->pfrec->addressfamily);
5592 logeventf(ssh, "Port open failed: %s", err);
5595 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5596 PKT_INT, remoteid, PKT_END);
5598 ssh_channel_init(c);
5599 c->remoteid = remoteid;
5600 c->halfopen = FALSE;
5601 c->type = CHAN_SOCKDATA; /* identify channel type */
5602 add234(ssh->channels, c);
5603 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5604 PKT_INT, c->remoteid, PKT_INT,
5605 c->localid, PKT_END);
5606 logevent("Forwarded port opened successfully");
5613 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5615 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5616 unsigned int localid = ssh_pkt_getuint32(pktin);
5617 struct ssh_channel *c;
5619 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5620 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5621 c->remoteid = localid;
5622 c->halfopen = FALSE;
5623 c->type = CHAN_SOCKDATA;
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 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5642 struct ssh_channel *c;
5644 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5645 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5646 logevent("Forwarded connection refused by server");
5647 pfd_close(c->u.pfd.pf);
5648 del234(ssh->channels, c);
5653 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5655 /* Remote side closes a channel. */
5656 unsigned i = ssh_pkt_getuint32(pktin);
5657 struct ssh_channel *c;
5658 c = find234(ssh->channels, &i, ssh_channelfind);
5659 if (c && !c->halfopen) {
5661 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5662 !(c->closes & CLOSES_RCVD_EOF)) {
5664 * Received CHANNEL_CLOSE, which we translate into
5667 int send_close = FALSE;
5669 c->closes |= CLOSES_RCVD_EOF;
5674 x11_send_eof(c->u.x11.xconn);
5680 pfd_send_eof(c->u.pfd.pf);
5689 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5690 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5692 c->closes |= CLOSES_SENT_EOF;
5696 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5697 !(c->closes & CLOSES_RCVD_CLOSE)) {
5699 if (!(c->closes & CLOSES_SENT_EOF)) {
5700 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5701 " for which we never sent CHANNEL_CLOSE\n", i));
5704 c->closes |= CLOSES_RCVD_CLOSE;
5707 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5708 !(c->closes & CLOSES_SENT_CLOSE)) {
5709 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5710 PKT_INT, c->remoteid, PKT_END);
5711 c->closes |= CLOSES_SENT_CLOSE;
5714 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5715 ssh_channel_destroy(c);
5717 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5718 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5719 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5725 * Handle incoming data on an SSH-1 or SSH-2 agent-forwarding channel.
5727 static int ssh_agent_channel_data(struct ssh_channel *c, char *data,
5730 while (length > 0) {
5731 if (c->u.a.lensofar < 4) {
5732 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)length);
5733 memcpy(c->u.a.msglen + c->u.a.lensofar, data, l);
5736 c->u.a.lensofar += l;
5738 if (c->u.a.lensofar == 4) {
5739 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
5740 c->u.a.message = snewn(c->u.a.totallen, unsigned char);
5741 memcpy(c->u.a.message, c->u.a.msglen, 4);
5743 if (c->u.a.lensofar >= 4 && length > 0) {
5744 unsigned int l = min(c->u.a.totallen - c->u.a.lensofar,
5746 memcpy(c->u.a.message + c->u.a.lensofar, data, l);
5749 c->u.a.lensofar += l;
5751 if (c->u.a.lensofar == c->u.a.totallen) {
5754 c->u.a.outstanding_requests++;
5755 if (agent_query(c->u.a.message, c->u.a.totallen, &reply, &replylen,
5756 ssh_agentf_callback, c))
5757 ssh_agentf_callback(c, reply, replylen);
5758 sfree(c->u.a.message);
5759 c->u.a.message = NULL;
5760 c->u.a.lensofar = 0;
5763 return 0; /* agent channels never back up */
5766 static int ssh_channel_data(struct ssh_channel *c, int is_stderr,
5767 char *data, int length)
5770 case CHAN_MAINSESSION:
5771 return from_backend(c->ssh->frontend, is_stderr, data, length);
5773 return x11_send(c->u.x11.xconn, data, length);
5775 return pfd_send(c->u.pfd.pf, data, length);
5777 return ssh_agent_channel_data(c, data, length);
5782 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5784 /* Data sent down one of our channels. */
5785 int i = ssh_pkt_getuint32(pktin);
5788 struct ssh_channel *c;
5790 ssh_pkt_getstring(pktin, &p, &len);
5792 c = find234(ssh->channels, &i, ssh_channelfind);
5794 int bufsize = ssh_channel_data(c, FALSE, p, len);
5795 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5796 c->throttling_conn = 1;
5797 ssh_throttle_conn(ssh, +1);
5802 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5804 ssh->exitcode = ssh_pkt_getuint32(pktin);
5805 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5806 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5808 * In case `helpful' firewalls or proxies tack
5809 * extra human-readable text on the end of the
5810 * session which we might mistake for another
5811 * encrypted packet, we close the session once
5812 * we've sent EXIT_CONFIRMATION.
5814 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5817 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5818 static void ssh1_send_ttymode(void *data,
5819 const struct ssh_ttymode *mode, char *val)
5821 struct Packet *pktout = (struct Packet *)data;
5822 unsigned int arg = 0;
5824 switch (mode->type) {
5826 arg = ssh_tty_parse_specchar(val);
5829 arg = ssh_tty_parse_boolean(val);
5832 ssh2_pkt_addbyte(pktout, mode->opcode);
5833 ssh2_pkt_addbyte(pktout, arg);
5836 int ssh_agent_forwarding_permitted(Ssh ssh)
5838 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5841 static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
5842 struct Packet *pktin)
5844 crBegin(ssh->do_ssh1_connection_crstate);
5846 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5847 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5848 ssh1_smsg_stdout_stderr_data;
5850 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5851 ssh1_msg_channel_open_confirmation;
5852 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5853 ssh1_msg_channel_open_failure;
5854 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5855 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5856 ssh1_msg_channel_close;
5857 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5858 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5860 if (ssh_agent_forwarding_permitted(ssh)) {
5861 logevent("Requesting agent forwarding");
5862 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5866 if (pktin->type != SSH1_SMSG_SUCCESS
5867 && pktin->type != SSH1_SMSG_FAILURE) {
5868 bombout(("Protocol confusion"));
5870 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5871 logevent("Agent forwarding refused");
5873 logevent("Agent forwarding enabled");
5874 ssh->agentfwd_enabled = TRUE;
5875 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5879 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5881 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5883 if (!ssh->x11disp) {
5884 /* FIXME: return an error message from x11_setup_display */
5885 logevent("X11 forwarding not enabled: unable to"
5886 " initialise X display");
5888 ssh->x11auth = x11_invent_fake_auth
5889 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5890 ssh->x11auth->disp = ssh->x11disp;
5892 logevent("Requesting X11 forwarding");
5893 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5894 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5895 PKT_STR, ssh->x11auth->protoname,
5896 PKT_STR, ssh->x11auth->datastring,
5897 PKT_INT, ssh->x11disp->screennum,
5900 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5901 PKT_STR, ssh->x11auth->protoname,
5902 PKT_STR, ssh->x11auth->datastring,
5908 if (pktin->type != SSH1_SMSG_SUCCESS
5909 && pktin->type != SSH1_SMSG_FAILURE) {
5910 bombout(("Protocol confusion"));
5912 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5913 logevent("X11 forwarding refused");
5915 logevent("X11 forwarding enabled");
5916 ssh->X11_fwd_enabled = TRUE;
5917 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5922 ssh_setup_portfwd(ssh, ssh->conf);
5923 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5925 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5927 /* Unpick the terminal-speed string. */
5928 /* XXX perhaps we should allow no speeds to be sent. */
5929 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5930 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5931 /* Send the pty request. */
5932 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5933 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5934 ssh_pkt_adduint32(pkt, ssh->term_height);
5935 ssh_pkt_adduint32(pkt, ssh->term_width);
5936 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5937 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5938 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5939 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5940 ssh_pkt_adduint32(pkt, ssh->ispeed);
5941 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5942 ssh_pkt_adduint32(pkt, ssh->ospeed);
5943 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5945 ssh->state = SSH_STATE_INTERMED;
5949 if (pktin->type != SSH1_SMSG_SUCCESS
5950 && pktin->type != SSH1_SMSG_FAILURE) {
5951 bombout(("Protocol confusion"));
5953 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5954 c_write_str(ssh, "Server refused to allocate pty\r\n");
5955 ssh->editing = ssh->echoing = 1;
5957 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5958 ssh->ospeed, ssh->ispeed);
5959 ssh->got_pty = TRUE;
5962 ssh->editing = ssh->echoing = 1;
5965 if (conf_get_int(ssh->conf, CONF_compression)) {
5966 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5970 if (pktin->type != SSH1_SMSG_SUCCESS
5971 && pktin->type != SSH1_SMSG_FAILURE) {
5972 bombout(("Protocol confusion"));
5974 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5975 c_write_str(ssh, "Server refused to compress\r\n");
5977 logevent("Started compression");
5978 ssh->v1_compressing = TRUE;
5979 ssh->cs_comp_ctx = zlib_compress_init();
5980 logevent("Initialised zlib (RFC1950) compression");
5981 ssh->sc_comp_ctx = zlib_decompress_init();
5982 logevent("Initialised zlib (RFC1950) decompression");
5986 * Start the shell or command.
5988 * Special case: if the first-choice command is an SSH-2
5989 * subsystem (hence not usable here) and the second choice
5990 * exists, we fall straight back to that.
5993 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5995 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5996 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5997 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5998 ssh->fallback_cmd = TRUE;
6001 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
6003 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
6004 logevent("Started session");
6007 ssh->state = SSH_STATE_SESSION;
6008 if (ssh->size_needed)
6009 ssh_size(ssh, ssh->term_width, ssh->term_height);
6010 if (ssh->eof_needed)
6011 ssh_special(ssh, TS_EOF);
6014 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
6016 ssh->channels = newtree234(ssh_channelcmp);
6020 * By this point, most incoming packets are already being
6021 * handled by the dispatch table, and we need only pay
6022 * attention to the unusual ones.
6027 if (pktin->type == SSH1_SMSG_SUCCESS) {
6028 /* may be from EXEC_SHELL on some servers */
6029 } else if (pktin->type == SSH1_SMSG_FAILURE) {
6030 /* may be from EXEC_SHELL on some servers
6031 * if no pty is available or in other odd cases. Ignore */
6033 bombout(("Strange packet received: type %d", pktin->type));
6038 int len = min(inlen, 512);
6039 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
6040 PKT_INT, len, PKT_DATA, in, len,
6052 * Handle the top-level SSH-2 protocol.
6054 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
6059 ssh_pkt_getstring(pktin, &msg, &msglen);
6060 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
6063 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
6065 /* log reason code in disconnect message */
6069 ssh_pkt_getstring(pktin, &msg, &msglen);
6070 bombout(("Server sent disconnect message:\n\"%.*s\"",
6071 msglen, NULLTOEMPTY(msg)));
6074 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6076 /* Do nothing, because we're ignoring it! Duhh. */
6079 static void ssh1_protocol_setup(Ssh ssh)
6084 * Most messages are handled by the coroutines.
6086 for (i = 0; i < 256; i++)
6087 ssh->packet_dispatch[i] = NULL;
6090 * These special message types we install handlers for.
6092 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6093 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6094 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6097 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
6098 struct Packet *pktin)
6100 const unsigned char *in = (const unsigned char *)vin;
6101 if (ssh->state == SSH_STATE_CLOSED)
6104 if (pktin && ssh->packet_dispatch[pktin->type]) {
6105 ssh->packet_dispatch[pktin->type](ssh, pktin);
6109 if (!ssh->protocol_initial_phase_done) {
6110 if (do_ssh1_login(ssh, in, inlen, pktin))
6111 ssh->protocol_initial_phase_done = TRUE;
6116 do_ssh1_connection(ssh, in, inlen, pktin);
6120 * Utility routines for decoding comma-separated strings in KEXINIT.
6122 static int first_in_commasep_string(char const *needle, char const *haystack,
6126 if (!needle || !haystack) /* protect against null pointers */
6128 needlen = strlen(needle);
6130 if (haylen >= needlen && /* haystack is long enough */
6131 !memcmp(needle, haystack, needlen) && /* initial match */
6132 (haylen == needlen || haystack[needlen] == ',')
6133 /* either , or EOS follows */
6139 static int in_commasep_string(char const *needle, char const *haystack,
6144 if (!needle || !haystack) /* protect against null pointers */
6147 * Is it at the start of the string?
6149 if (first_in_commasep_string(needle, haystack, haylen))
6152 * If not, search for the next comma and resume after that.
6153 * If no comma found, terminate.
6155 p = memchr(haystack, ',', haylen);
6157 /* + 1 to skip over comma */
6158 return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
6162 * Add a value to the comma-separated string at the end of the packet.
6164 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6166 if (pkt->length - pkt->savedpos > 0)
6167 ssh_pkt_addstring_str(pkt, ",");
6168 ssh_pkt_addstring_str(pkt, data);
6173 * SSH-2 key derivation (RFC 4253 section 7.2).
6175 static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
6176 char chr, int keylen)
6178 const struct ssh_hash *h = ssh->kex->hash;
6186 /* Round up to the next multiple of hash length. */
6187 keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
6189 key = snewn(keylen_padded, unsigned char);
6191 /* First hlen bytes. */
6193 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6194 hash_mpint(h, s, K);
6195 h->bytes(s, H, h->hlen);
6196 h->bytes(s, &chr, 1);
6197 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6200 /* Subsequent blocks of hlen bytes. */
6201 if (keylen_padded > h->hlen) {
6205 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6206 hash_mpint(h, s, K);
6207 h->bytes(s, H, h->hlen);
6209 for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
6210 h->bytes(s, key + offset - h->hlen, h->hlen);
6212 h->final(s2, key + offset);
6218 /* Now clear any extra bytes of key material beyond the length
6219 * we're officially returning, because the caller won't know to
6221 if (keylen_padded > keylen)
6222 smemclr(key + keylen, keylen_padded - keylen);
6228 * Structure for constructing KEXINIT algorithm lists.
6230 #define MAXKEXLIST 16
6231 struct kexinit_algorithm {
6235 const struct ssh_kex *kex;
6239 const struct ssh_signkey *hostkey;
6243 const struct ssh2_cipher *cipher;
6247 const struct ssh_mac *mac;
6250 const struct ssh_compress *comp;
6255 * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
6256 * If the algorithm is already in the list, return a pointer to its
6257 * entry, otherwise return an entry from the end of the list.
6258 * This assumes that every time a particular name is passed in, it
6259 * comes from the same string constant. If this isn't true, this
6260 * function may need to be rewritten to use strcmp() instead.
6262 static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
6263 *list, const char *name)
6267 for (i = 0; i < MAXKEXLIST; i++)
6268 if (list[i].name == NULL || list[i].name == name) {
6269 list[i].name = name;
6272 assert(!"No space in KEXINIT list");
6277 * Handle the SSH-2 transport layer.
6279 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
6280 struct Packet *pktin)
6282 const unsigned char *in = (const unsigned char *)vin;
6284 KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
6285 KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
6288 const char * kexlist_descr[NKEXLIST] = {
6289 "key exchange algorithm", "host key algorithm",
6290 "client-to-server cipher", "server-to-client cipher",
6291 "client-to-server MAC", "server-to-client MAC",
6292 "client-to-server compression method",
6293 "server-to-client compression method" };
6294 struct do_ssh2_transport_state {
6296 int nbits, pbits, warn_kex, warn_hk, warn_cscipher, warn_sccipher;
6297 Bignum p, g, e, f, K;
6300 int kex_init_value, kex_reply_value;
6301 const struct ssh_mac *const *maclist;
6303 const struct ssh2_cipher *cscipher_tobe;
6304 const struct ssh2_cipher *sccipher_tobe;
6305 const struct ssh_mac *csmac_tobe;
6306 const struct ssh_mac *scmac_tobe;
6307 int csmac_etm_tobe, scmac_etm_tobe;
6308 const struct ssh_compress *cscomp_tobe;
6309 const struct ssh_compress *sccomp_tobe;
6310 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6311 int hostkeylen, siglen, rsakeylen;
6312 void *hkey; /* actual host key */
6313 void *rsakey; /* for RSA kex */
6314 void *eckey; /* for ECDH kex */
6315 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6316 int n_preferred_kex;
6317 const struct ssh_kexes *preferred_kex[KEX_MAX];
6319 int preferred_hk[HK_MAX];
6320 int n_preferred_ciphers;
6321 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6322 const struct ssh_compress *preferred_comp;
6323 int userauth_succeeded; /* for delayed compression */
6324 int pending_compression;
6325 int got_session_id, activated_authconn;
6326 struct Packet *pktout;
6330 struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
6332 crState(do_ssh2_transport_state);
6334 assert(!ssh->bare_connection);
6335 assert(ssh->version == 2);
6339 s->cscipher_tobe = s->sccipher_tobe = NULL;
6340 s->csmac_tobe = s->scmac_tobe = NULL;
6341 s->cscomp_tobe = s->sccomp_tobe = NULL;
6343 s->got_session_id = s->activated_authconn = FALSE;
6344 s->userauth_succeeded = FALSE;
6345 s->pending_compression = FALSE;
6348 * Be prepared to work around the buggy MAC problem.
6350 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6351 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6353 s->maclist = macs, s->nmacs = lenof(macs);
6356 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6359 struct kexinit_algorithm *alg;
6362 * Set up the preferred key exchange. (NULL => warn below here)
6364 s->n_preferred_kex = 0;
6365 for (i = 0; i < KEX_MAX; i++) {
6366 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6368 s->preferred_kex[s->n_preferred_kex++] =
6369 &ssh_diffiehellman_gex;
6372 s->preferred_kex[s->n_preferred_kex++] =
6373 &ssh_diffiehellman_group14;
6376 s->preferred_kex[s->n_preferred_kex++] =
6377 &ssh_diffiehellman_group1;
6380 s->preferred_kex[s->n_preferred_kex++] =
6384 s->preferred_kex[s->n_preferred_kex++] =
6388 /* Flag for later. Don't bother if it's the last in
6390 if (i < KEX_MAX - 1) {
6391 s->preferred_kex[s->n_preferred_kex++] = NULL;
6398 * Set up the preferred host key types. These are just the ids
6399 * in the enum in putty.h, so 'warn below here' is indicated
6402 s->n_preferred_hk = 0;
6403 for (i = 0; i < HK_MAX; i++) {
6404 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, i);
6405 /* As above, don't bother with HK_WARN if it's last in the
6407 if (id != HK_WARN || i < HK_MAX - 1)
6408 s->preferred_hk[s->n_preferred_hk++] = id;
6412 * Set up the preferred ciphers. (NULL => warn below here)
6414 s->n_preferred_ciphers = 0;
6415 for (i = 0; i < CIPHER_MAX; i++) {
6416 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6417 case CIPHER_BLOWFISH:
6418 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6421 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6422 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6426 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6429 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6431 case CIPHER_ARCFOUR:
6432 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6434 case CIPHER_CHACHA20:
6435 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
6438 /* Flag for later. Don't bother if it's the last in
6440 if (i < CIPHER_MAX - 1) {
6441 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6448 * Set up preferred compression.
6450 if (conf_get_int(ssh->conf, CONF_compression))
6451 s->preferred_comp = &ssh_zlib;
6453 s->preferred_comp = &ssh_comp_none;
6456 * Enable queueing of outgoing auth- or connection-layer
6457 * packets while we are in the middle of a key exchange.
6459 ssh->queueing = TRUE;
6462 * Flag that KEX is in progress.
6464 ssh->kex_in_progress = TRUE;
6466 for (i = 0; i < NKEXLIST; i++)
6467 for (j = 0; j < MAXKEXLIST; j++)
6468 s->kexlists[i][j].name = NULL;
6469 /* List key exchange algorithms. */
6471 for (i = 0; i < s->n_preferred_kex; i++) {
6472 const struct ssh_kexes *k = s->preferred_kex[i];
6473 if (!k) warn = TRUE;
6474 else for (j = 0; j < k->nkexes; j++) {
6475 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
6477 alg->u.kex.kex = k->list[j];
6478 alg->u.kex.warn = warn;
6481 /* List server host key algorithms. */
6482 if (!s->got_session_id) {
6484 * In the first key exchange, we list all the algorithms
6485 * we're prepared to cope with, but prefer those algorithms
6486 * for which we have a host key for this host.
6488 * If the host key algorithm is below the warning
6489 * threshold, we warn even if we did already have a key
6490 * for it, on the basis that if the user has just
6491 * reconfigured that host key type to be warned about,
6492 * they surely _do_ want to be alerted that a server
6493 * they're actually connecting to is using it.
6496 for (i = 0; i < s->n_preferred_hk; i++) {
6497 if (s->preferred_hk[i] == HK_WARN)
6499 for (j = 0; j < lenof(hostkey_algs); j++) {
6500 if (hostkey_algs[j].id != s->preferred_hk[i])
6502 if (have_ssh_host_key(ssh->savedhost, ssh->savedport,
6503 hostkey_algs[j].alg->keytype)) {
6504 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6505 hostkey_algs[j].alg->name);
6506 alg->u.hk.hostkey = hostkey_algs[j].alg;
6507 alg->u.hk.warn = warn;
6512 for (i = 0; i < s->n_preferred_hk; i++) {
6513 if (s->preferred_hk[i] == HK_WARN)
6515 for (j = 0; j < lenof(hostkey_algs); j++) {
6516 if (hostkey_algs[j].id != s->preferred_hk[i])
6518 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6519 hostkey_algs[j].alg->name);
6520 alg->u.hk.hostkey = hostkey_algs[j].alg;
6521 alg->u.hk.warn = warn;
6526 * In subsequent key exchanges, we list only the kex
6527 * algorithm that was selected in the first key exchange,
6528 * so that we keep getting the same host key and hence
6529 * don't have to interrupt the user's session to ask for
6533 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6534 ssh->hostkey->name);
6535 alg->u.hk.hostkey = ssh->hostkey;
6536 alg->u.hk.warn = FALSE;
6538 /* List encryption algorithms (client->server then server->client). */
6539 for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
6542 alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
6543 alg->u.cipher.cipher = NULL;
6544 alg->u.cipher.warn = warn;
6545 #endif /* FUZZING */
6546 for (i = 0; i < s->n_preferred_ciphers; i++) {
6547 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6548 if (!c) warn = TRUE;
6549 else for (j = 0; j < c->nciphers; j++) {
6550 alg = ssh2_kexinit_addalg(s->kexlists[k],
6552 alg->u.cipher.cipher = c->list[j];
6553 alg->u.cipher.warn = warn;
6557 /* List MAC algorithms (client->server then server->client). */
6558 for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
6560 alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
6561 alg->u.mac.mac = NULL;
6562 alg->u.mac.etm = FALSE;
6563 #endif /* FUZZING */
6564 for (i = 0; i < s->nmacs; i++) {
6565 alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
6566 alg->u.mac.mac = s->maclist[i];
6567 alg->u.mac.etm = FALSE;
6569 for (i = 0; i < s->nmacs; i++)
6570 /* For each MAC, there may also be an ETM version,
6571 * which we list second. */
6572 if (s->maclist[i]->etm_name) {
6573 alg = ssh2_kexinit_addalg(s->kexlists[j],
6574 s->maclist[i]->etm_name);
6575 alg->u.mac.mac = s->maclist[i];
6576 alg->u.mac.etm = TRUE;
6579 /* List client->server compression algorithms,
6580 * then server->client compression algorithms. (We use the
6581 * same set twice.) */
6582 for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
6583 assert(lenof(compressions) > 1);
6584 /* Prefer non-delayed versions */
6585 alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
6586 alg->u.comp = s->preferred_comp;
6587 /* We don't even list delayed versions of algorithms until
6588 * they're allowed to be used, to avoid a race. See the end of
6590 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6591 alg = ssh2_kexinit_addalg(s->kexlists[j],
6592 s->preferred_comp->delayed_name);
6593 alg->u.comp = s->preferred_comp;
6595 for (i = 0; i < lenof(compressions); i++) {
6596 const struct ssh_compress *c = compressions[i];
6597 alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
6599 if (s->userauth_succeeded && c->delayed_name) {
6600 alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
6606 * Construct and send our key exchange packet.
6608 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6609 for (i = 0; i < 16; i++)
6610 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6611 for (i = 0; i < NKEXLIST; i++) {
6612 ssh2_pkt_addstring_start(s->pktout);
6613 for (j = 0; j < MAXKEXLIST; j++) {
6614 if (s->kexlists[i][j].name == NULL) break;
6615 ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
6618 /* List client->server languages. Empty list. */
6619 ssh2_pkt_addstring_start(s->pktout);
6620 /* List server->client languages. Empty list. */
6621 ssh2_pkt_addstring_start(s->pktout);
6622 /* First KEX packet does _not_ follow, because we're not that brave. */
6623 ssh2_pkt_addbool(s->pktout, FALSE);
6625 ssh2_pkt_adduint32(s->pktout, 0);
6628 s->our_kexinitlen = s->pktout->length - 5;
6629 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6630 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6632 ssh2_pkt_send_noqueue(ssh, s->pktout);
6635 crWaitUntilV(pktin);
6638 * Now examine the other side's KEXINIT to see what we're up
6645 if (pktin->type != SSH2_MSG_KEXINIT) {
6646 bombout(("expected key exchange packet from server"));
6650 ssh->hostkey = NULL;
6651 s->cscipher_tobe = NULL;
6652 s->sccipher_tobe = NULL;
6653 s->csmac_tobe = NULL;
6654 s->scmac_tobe = NULL;
6655 s->cscomp_tobe = NULL;
6656 s->sccomp_tobe = NULL;
6657 s->warn_kex = s->warn_hk = FALSE;
6658 s->warn_cscipher = s->warn_sccipher = FALSE;
6660 pktin->savedpos += 16; /* skip garbage cookie */
6663 for (i = 0; i < NKEXLIST; i++) {
6664 ssh_pkt_getstring(pktin, &str, &len);
6666 bombout(("KEXINIT packet was incomplete"));
6670 /* If we've already selected a cipher which requires a
6671 * particular MAC, then just select that, and don't even
6672 * bother looking through the server's KEXINIT string for
6674 if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
6675 s->cscipher_tobe->required_mac) {
6676 s->csmac_tobe = s->cscipher_tobe->required_mac;
6677 s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
6680 if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
6681 s->sccipher_tobe->required_mac) {
6682 s->scmac_tobe = s->sccipher_tobe->required_mac;
6683 s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
6687 for (j = 0; j < MAXKEXLIST; j++) {
6688 struct kexinit_algorithm *alg = &s->kexlists[i][j];
6689 if (alg->name == NULL) break;
6690 if (in_commasep_string(alg->name, str, len)) {
6691 /* We've found a matching algorithm. */
6692 if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
6693 /* Check if we might need to ignore first kex pkt */
6695 !first_in_commasep_string(alg->name, str, len))
6698 if (i == KEXLIST_KEX) {
6699 ssh->kex = alg->u.kex.kex;
6700 s->warn_kex = alg->u.kex.warn;
6701 } else if (i == KEXLIST_HOSTKEY) {
6702 ssh->hostkey = alg->u.hk.hostkey;
6703 s->warn_hk = alg->u.hk.warn;
6704 } else if (i == KEXLIST_CSCIPHER) {
6705 s->cscipher_tobe = alg->u.cipher.cipher;
6706 s->warn_cscipher = alg->u.cipher.warn;
6707 } else if (i == KEXLIST_SCCIPHER) {
6708 s->sccipher_tobe = alg->u.cipher.cipher;
6709 s->warn_sccipher = alg->u.cipher.warn;
6710 } else if (i == KEXLIST_CSMAC) {
6711 s->csmac_tobe = alg->u.mac.mac;
6712 s->csmac_etm_tobe = alg->u.mac.etm;
6713 } else if (i == KEXLIST_SCMAC) {
6714 s->scmac_tobe = alg->u.mac.mac;
6715 s->scmac_etm_tobe = alg->u.mac.etm;
6716 } else if (i == KEXLIST_CSCOMP) {
6717 s->cscomp_tobe = alg->u.comp;
6718 } else if (i == KEXLIST_SCCOMP) {
6719 s->sccomp_tobe = alg->u.comp;
6723 if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
6724 in_commasep_string(alg->u.comp->delayed_name, str, len))
6725 s->pending_compression = TRUE; /* try this later */
6727 bombout(("Couldn't agree a %s (available: %.*s)",
6728 kexlist_descr[i], len, str));
6732 if (i == KEXLIST_HOSTKEY) {
6736 * In addition to deciding which host key we're
6737 * actually going to use, we should make a list of the
6738 * host keys offered by the server which we _don't_
6739 * have cached. These will be offered as cross-
6740 * certification options by ssh_get_specials.
6742 * We also count the key we're currently using for KEX
6743 * as one we've already got, because by the time this
6744 * menu becomes visible, it will be.
6746 ssh->n_uncert_hostkeys = 0;
6748 for (j = 0; j < lenof(hostkey_algs); j++) {
6749 if (hostkey_algs[j].alg != ssh->hostkey &&
6750 in_commasep_string(hostkey_algs[j].alg->name,
6752 !have_ssh_host_key(ssh->savedhost, ssh->savedport,
6753 hostkey_algs[j].alg->keytype)) {
6754 ssh->uncert_hostkeys[ssh->n_uncert_hostkeys++] = j;
6760 if (s->pending_compression) {
6761 logevent("Server supports delayed compression; "
6762 "will try this later");
6764 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6765 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6766 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6768 ssh->exhash = ssh->kex->hash->init();
6769 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6770 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6771 hash_string(ssh->kex->hash, ssh->exhash,
6772 s->our_kexinit, s->our_kexinitlen);
6773 sfree(s->our_kexinit);
6774 /* Include the type byte in the hash of server's KEXINIT */
6775 hash_string(ssh->kex->hash, ssh->exhash,
6776 pktin->body - 1, pktin->length + 1);
6779 ssh_set_frozen(ssh, 1);
6780 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6782 ssh_dialog_callback, ssh);
6783 if (s->dlgret < 0) {
6787 bombout(("Unexpected data from server while"
6788 " waiting for user response"));
6791 } while (pktin || inlen > 0);
6792 s->dlgret = ssh->user_response;
6794 ssh_set_frozen(ssh, 0);
6795 if (s->dlgret == 0) {
6796 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6806 ssh_set_frozen(ssh, 1);
6809 * Change warning box wording depending on why we chose a
6810 * warning-level host key algorithm. If it's because
6811 * that's all we have *cached*, use the askhk mechanism,
6812 * and list the host keys we could usefully cross-certify.
6813 * Otherwise, use askalg for the standard wording.
6816 for (j = 0; j < ssh->n_uncert_hostkeys; j++) {
6817 const struct ssh_signkey_with_user_pref_id *hktype =
6818 &hostkey_algs[ssh->uncert_hostkeys[j]];
6820 for (k = 0; k < HK_MAX; k++) {
6821 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, k);
6822 if (id == HK_WARN) {
6824 } else if (id == hktype->id) {
6831 char *old_ba = betteralgs;
6832 betteralgs = dupcat(betteralgs, ",",
6834 (const char *)NULL);
6837 betteralgs = dupstr(hktype->alg->name);
6842 s->dlgret = askhk(ssh->frontend, ssh->hostkey->name,
6843 betteralgs, ssh_dialog_callback, ssh);
6846 s->dlgret = askalg(ssh->frontend, "host key type",
6848 ssh_dialog_callback, ssh);
6850 if (s->dlgret < 0) {
6854 bombout(("Unexpected data from server while"
6855 " waiting for user response"));
6858 } while (pktin || inlen > 0);
6859 s->dlgret = ssh->user_response;
6861 ssh_set_frozen(ssh, 0);
6862 if (s->dlgret == 0) {
6863 ssh_disconnect(ssh, "User aborted at host key warning", NULL,
6869 if (s->warn_cscipher) {
6870 ssh_set_frozen(ssh, 1);
6871 s->dlgret = askalg(ssh->frontend,
6872 "client-to-server cipher",
6873 s->cscipher_tobe->name,
6874 ssh_dialog_callback, ssh);
6875 if (s->dlgret < 0) {
6879 bombout(("Unexpected data from server while"
6880 " waiting for user response"));
6883 } while (pktin || inlen > 0);
6884 s->dlgret = ssh->user_response;
6886 ssh_set_frozen(ssh, 0);
6887 if (s->dlgret == 0) {
6888 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6894 if (s->warn_sccipher) {
6895 ssh_set_frozen(ssh, 1);
6896 s->dlgret = askalg(ssh->frontend,
6897 "server-to-client cipher",
6898 s->sccipher_tobe->name,
6899 ssh_dialog_callback, ssh);
6900 if (s->dlgret < 0) {
6904 bombout(("Unexpected data from server while"
6905 " waiting for user response"));
6908 } while (pktin || inlen > 0);
6909 s->dlgret = ssh->user_response;
6911 ssh_set_frozen(ssh, 0);
6912 if (s->dlgret == 0) {
6913 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6919 if (s->ignorepkt) /* first_kex_packet_follows */
6920 crWaitUntilV(pktin); /* Ignore packet */
6923 if (ssh->kex->main_type == KEXTYPE_DH) {
6925 * Work out the number of bits of key we will need from the
6926 * key exchange. We start with the maximum key length of
6932 csbits = s->cscipher_tobe ? s->cscipher_tobe->real_keybits : 0;
6933 scbits = s->sccipher_tobe ? s->sccipher_tobe->real_keybits : 0;
6934 s->nbits = (csbits > scbits ? csbits : scbits);
6936 /* The keys only have hlen-bit entropy, since they're based on
6937 * a hash. So cap the key size at hlen bits. */
6938 if (s->nbits > ssh->kex->hash->hlen * 8)
6939 s->nbits = ssh->kex->hash->hlen * 8;
6942 * If we're doing Diffie-Hellman group exchange, start by
6943 * requesting a group.
6945 if (dh_is_gex(ssh->kex)) {
6946 logevent("Doing Diffie-Hellman group exchange");
6947 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6949 * Work out how big a DH group we will need to allow that
6952 s->pbits = 512 << ((s->nbits - 1) / 64);
6953 if (s->pbits < DH_MIN_SIZE)
6954 s->pbits = DH_MIN_SIZE;
6955 if (s->pbits > DH_MAX_SIZE)
6956 s->pbits = DH_MAX_SIZE;
6957 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6958 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6959 ssh2_pkt_adduint32(s->pktout, s->pbits);
6961 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6962 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6963 ssh2_pkt_adduint32(s->pktout, s->pbits);
6964 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6966 ssh2_pkt_send_noqueue(ssh, s->pktout);
6968 crWaitUntilV(pktin);
6969 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6970 bombout(("expected key exchange group packet from server"));
6973 s->p = ssh2_pkt_getmp(pktin);
6974 s->g = ssh2_pkt_getmp(pktin);
6975 if (!s->p || !s->g) {
6976 bombout(("unable to read mp-ints from incoming group packet"));
6979 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6980 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6981 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6983 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6984 ssh->kex_ctx = dh_setup_group(ssh->kex);
6985 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6986 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6987 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6988 ssh->kex->groupname);
6991 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6992 ssh->kex->hash->text_name);
6994 * Now generate and send e for Diffie-Hellman.
6996 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6997 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6998 s->pktout = ssh2_pkt_init(s->kex_init_value);
6999 ssh2_pkt_addmp(s->pktout, s->e);
7000 ssh2_pkt_send_noqueue(ssh, s->pktout);
7002 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
7003 crWaitUntilV(pktin);
7004 if (pktin->type != s->kex_reply_value) {
7005 bombout(("expected key exchange reply packet from server"));
7008 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
7009 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7010 if (!s->hostkeydata) {
7011 bombout(("unable to parse key exchange reply packet"));
7014 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7015 s->hostkeydata, s->hostkeylen);
7016 s->f = ssh2_pkt_getmp(pktin);
7018 bombout(("unable to parse key exchange reply packet"));
7021 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7023 bombout(("unable to parse key exchange reply packet"));
7028 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
7030 bombout(("key exchange reply failed validation: %s", err));
7034 s->K = dh_find_K(ssh->kex_ctx, s->f);
7036 /* We assume everything from now on will be quick, and it might
7037 * involve user interaction. */
7038 set_busy_status(ssh->frontend, BUSY_NOT);
7040 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7041 if (dh_is_gex(ssh->kex)) {
7042 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7043 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
7044 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
7045 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7046 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
7047 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
7048 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
7050 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
7051 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
7053 dh_cleanup(ssh->kex_ctx);
7055 if (dh_is_gex(ssh->kex)) {
7059 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
7061 logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
7062 ssh_ecdhkex_curve_textname(ssh->kex),
7063 ssh->kex->hash->text_name);
7064 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
7066 s->eckey = ssh_ecdhkex_newkey(ssh->kex);
7068 bombout(("Unable to generate key for ECDH"));
7074 int publicPointLength;
7075 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7077 ssh_ecdhkex_freekey(s->eckey);
7078 bombout(("Unable to encode public key for ECDH"));
7081 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
7082 ssh2_pkt_addstring_start(s->pktout);
7083 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
7087 ssh2_pkt_send_noqueue(ssh, s->pktout);
7089 crWaitUntilV(pktin);
7090 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
7091 ssh_ecdhkex_freekey(s->eckey);
7092 bombout(("expected ECDH reply packet from server"));
7096 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7097 if (!s->hostkeydata) {
7098 bombout(("unable to parse ECDH reply packet"));
7101 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7102 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7103 s->hostkeydata, s->hostkeylen);
7107 int publicPointLength;
7108 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7110 ssh_ecdhkex_freekey(s->eckey);
7111 bombout(("Unable to encode public key for ECDH hash"));
7114 hash_string(ssh->kex->hash, ssh->exhash,
7115 publicPoint, publicPointLength);
7122 ssh_pkt_getstring(pktin, &keydata, &keylen);
7124 bombout(("unable to parse ECDH reply packet"));
7127 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
7128 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
7130 ssh_ecdhkex_freekey(s->eckey);
7131 bombout(("point received in ECDH was not valid"));
7136 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7138 bombout(("unable to parse key exchange reply packet"));
7142 ssh_ecdhkex_freekey(s->eckey);
7144 logeventf(ssh, "Doing RSA key exchange with hash %s",
7145 ssh->kex->hash->text_name);
7146 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
7148 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
7151 crWaitUntilV(pktin);
7152 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
7153 bombout(("expected RSA public key packet from server"));
7157 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7158 if (!s->hostkeydata) {
7159 bombout(("unable to parse RSA public key packet"));
7162 hash_string(ssh->kex->hash, ssh->exhash,
7163 s->hostkeydata, s->hostkeylen);
7164 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7165 s->hostkeydata, s->hostkeylen);
7169 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
7171 bombout(("unable to parse RSA public key packet"));
7174 s->rsakeydata = snewn(s->rsakeylen, char);
7175 memcpy(s->rsakeydata, keydata, s->rsakeylen);
7178 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
7180 sfree(s->rsakeydata);
7181 bombout(("unable to parse RSA public key from server"));
7185 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
7188 * Next, set up a shared secret K, of precisely KLEN -
7189 * 2*HLEN - 49 bits, where KLEN is the bit length of the
7190 * RSA key modulus and HLEN is the bit length of the hash
7194 int klen = ssh_rsakex_klen(s->rsakey);
7195 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
7197 unsigned char *kstr1, *kstr2, *outstr;
7198 int kstr1len, kstr2len, outstrlen;
7200 s->K = bn_power_2(nbits - 1);
7202 for (i = 0; i < nbits; i++) {
7204 byte = random_byte();
7206 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
7210 * Encode this as an mpint.
7212 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
7213 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
7214 PUT_32BIT(kstr2, kstr1len);
7215 memcpy(kstr2 + 4, kstr1, kstr1len);
7218 * Encrypt it with the given RSA key.
7220 outstrlen = (klen + 7) / 8;
7221 outstr = snewn(outstrlen, unsigned char);
7222 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
7223 outstr, outstrlen, s->rsakey);
7226 * And send it off in a return packet.
7228 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
7229 ssh2_pkt_addstring_start(s->pktout);
7230 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
7231 ssh2_pkt_send_noqueue(ssh, s->pktout);
7233 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7240 ssh_rsakex_freekey(s->rsakey);
7242 crWaitUntilV(pktin);
7243 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7244 sfree(s->rsakeydata);
7245 bombout(("expected signature packet from server"));
7249 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7251 bombout(("unable to parse signature packet"));
7255 sfree(s->rsakeydata);
7258 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7259 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7260 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7262 ssh->kex_ctx = NULL;
7265 debug(("Exchange hash is:\n"));
7266 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7270 bombout(("Server's host key is invalid"));
7274 if (!ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7275 (char *)s->exchange_hash,
7276 ssh->kex->hash->hlen)) {
7278 bombout(("Server's host key did not match the signature supplied"));
7283 s->keystr = ssh->hostkey->fmtkey(s->hkey);
7284 if (!s->got_session_id) {
7286 * Make a note of any other host key formats that are available.
7289 int i, j, nkeys = 0;
7291 for (i = 0; i < lenof(hostkey_algs); i++) {
7292 if (hostkey_algs[i].alg == ssh->hostkey)
7295 for (j = 0; j < ssh->n_uncert_hostkeys; j++)
7296 if (ssh->uncert_hostkeys[j] == i)
7299 if (j < ssh->n_uncert_hostkeys) {
7302 newlist = dupprintf("%s/%s", list,
7303 hostkey_algs[i].alg->name);
7305 newlist = dupprintf("%s", hostkey_algs[i].alg->name);
7313 "Server also has %s host key%s, but we "
7314 "don't know %s", list,
7315 nkeys > 1 ? "s" : "",
7316 nkeys > 1 ? "any of them" : "it");
7322 * Authenticate remote host: verify host key. (We've already
7323 * checked the signature of the exchange hash.)
7325 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7326 logevent("Host key fingerprint is:");
7327 logevent(s->fingerprint);
7328 /* First check against manually configured host keys. */
7329 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7330 ssh->hostkey, s->hkey);
7331 if (s->dlgret == 0) { /* did not match */
7332 bombout(("Host key did not appear in manually configured list"));
7334 } else if (s->dlgret < 0) { /* none configured; use standard handling */
7335 ssh_set_frozen(ssh, 1);
7336 s->dlgret = verify_ssh_host_key(ssh->frontend,
7337 ssh->savedhost, ssh->savedport,
7338 ssh->hostkey->keytype, s->keystr,
7340 ssh_dialog_callback, ssh);
7344 if (s->dlgret < 0) {
7348 bombout(("Unexpected data from server while waiting"
7349 " for user host key response"));
7352 } while (pktin || inlen > 0);
7353 s->dlgret = ssh->user_response;
7355 ssh_set_frozen(ssh, 0);
7356 if (s->dlgret == 0) {
7357 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7362 sfree(s->fingerprint);
7364 * Save this host key, to check against the one presented in
7365 * subsequent rekeys.
7367 ssh->hostkey_str = s->keystr;
7368 } else if (ssh->cross_certifying) {
7369 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7370 logevent("Storing additional host key for this host:");
7371 logevent(s->fingerprint);
7372 store_host_key(ssh->savedhost, ssh->savedport,
7373 ssh->hostkey->keytype, s->keystr);
7374 ssh->cross_certifying = FALSE;
7376 * Don't forget to store the new key as the one we'll be
7377 * re-checking in future normal rekeys.
7379 ssh->hostkey_str = s->keystr;
7382 * In a rekey, we never present an interactive host key
7383 * verification request to the user. Instead, we simply
7384 * enforce that the key we're seeing this time is identical to
7385 * the one we saw before.
7387 if (strcmp(ssh->hostkey_str, s->keystr)) {
7389 bombout(("Host key was different in repeat key exchange"));
7395 ssh->hostkey->freekey(s->hkey);
7398 * The exchange hash from the very first key exchange is also
7399 * the session id, used in session key construction and
7402 if (!s->got_session_id) {
7403 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7404 memcpy(ssh->v2_session_id, s->exchange_hash,
7405 sizeof(s->exchange_hash));
7406 ssh->v2_session_id_len = ssh->kex->hash->hlen;
7407 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7408 s->got_session_id = TRUE;
7412 * Send SSH2_MSG_NEWKEYS.
7414 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7415 ssh2_pkt_send_noqueue(ssh, s->pktout);
7416 ssh->outgoing_data_size = 0; /* start counting from here */
7419 * We've sent client NEWKEYS, so create and initialise
7420 * client-to-server session keys.
7422 if (ssh->cs_cipher_ctx)
7423 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7424 ssh->cscipher = s->cscipher_tobe;
7425 if (ssh->cscipher) ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7427 if (ssh->cs_mac_ctx)
7428 ssh->csmac->free_context(ssh->cs_mac_ctx);
7429 ssh->csmac = s->csmac_tobe;
7430 ssh->csmac_etm = s->csmac_etm_tobe;
7432 ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
7434 if (ssh->cs_comp_ctx)
7435 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7436 ssh->cscomp = s->cscomp_tobe;
7437 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7440 * Set IVs on client-to-server keys. Here we use the exchange
7441 * hash from the _first_ key exchange.
7443 if (ssh->cscipher) {
7446 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
7447 ssh->cscipher->padded_keybytes);
7448 ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
7449 smemclr(key, ssh->cscipher->padded_keybytes);
7452 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
7453 ssh->cscipher->blksize);
7454 ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
7455 smemclr(key, ssh->cscipher->blksize);
7461 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
7462 ssh->csmac->keylen);
7463 ssh->csmac->setkey(ssh->cs_mac_ctx, key);
7464 smemclr(key, ssh->csmac->keylen);
7469 logeventf(ssh, "Initialised %.200s client->server encryption",
7470 ssh->cscipher->text_name);
7472 logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
7473 ssh->csmac->text_name,
7474 ssh->csmac_etm ? " (in ETM mode)" : "",
7475 ssh->cscipher->required_mac ? " (required by cipher)" : "");
7476 if (ssh->cscomp->text_name)
7477 logeventf(ssh, "Initialised %s compression",
7478 ssh->cscomp->text_name);
7481 * Now our end of the key exchange is complete, we can send all
7482 * our queued higher-layer packets.
7484 ssh->queueing = FALSE;
7485 ssh2_pkt_queuesend(ssh);
7488 * Expect SSH2_MSG_NEWKEYS from server.
7490 crWaitUntilV(pktin);
7491 if (pktin->type != SSH2_MSG_NEWKEYS) {
7492 bombout(("expected new-keys packet from server"));
7495 ssh->incoming_data_size = 0; /* start counting from here */
7498 * We've seen server NEWKEYS, so create and initialise
7499 * server-to-client session keys.
7501 if (ssh->sc_cipher_ctx)
7502 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7503 if (s->sccipher_tobe) {
7504 ssh->sccipher = s->sccipher_tobe;
7505 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7508 if (ssh->sc_mac_ctx)
7509 ssh->scmac->free_context(ssh->sc_mac_ctx);
7510 if (s->scmac_tobe) {
7511 ssh->scmac = s->scmac_tobe;
7512 ssh->scmac_etm = s->scmac_etm_tobe;
7513 ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
7516 if (ssh->sc_comp_ctx)
7517 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7518 ssh->sccomp = s->sccomp_tobe;
7519 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7522 * Set IVs on server-to-client keys. Here we use the exchange
7523 * hash from the _first_ key exchange.
7525 if (ssh->sccipher) {
7528 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
7529 ssh->sccipher->padded_keybytes);
7530 ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
7531 smemclr(key, ssh->sccipher->padded_keybytes);
7534 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
7535 ssh->sccipher->blksize);
7536 ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
7537 smemclr(key, ssh->sccipher->blksize);
7543 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
7544 ssh->scmac->keylen);
7545 ssh->scmac->setkey(ssh->sc_mac_ctx, key);
7546 smemclr(key, ssh->scmac->keylen);
7550 logeventf(ssh, "Initialised %.200s server->client encryption",
7551 ssh->sccipher->text_name);
7553 logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
7554 ssh->scmac->text_name,
7555 ssh->scmac_etm ? " (in ETM mode)" : "",
7556 ssh->sccipher->required_mac ? " (required by cipher)" : "");
7557 if (ssh->sccomp->text_name)
7558 logeventf(ssh, "Initialised %s decompression",
7559 ssh->sccomp->text_name);
7562 * Free shared secret.
7567 * Update the specials menu to list the remaining uncertified host
7570 update_specials_menu(ssh->frontend);
7573 * Key exchange is over. Loop straight back round if we have a
7574 * deferred rekey reason.
7576 if (ssh->deferred_rekey_reason) {
7577 logevent(ssh->deferred_rekey_reason);
7579 ssh->deferred_rekey_reason = NULL;
7580 goto begin_key_exchange;
7584 * Otherwise, schedule a timer for our next rekey.
7586 ssh->kex_in_progress = FALSE;
7587 ssh->last_rekey = GETTICKCOUNT();
7588 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7589 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7593 * Now we're encrypting. Begin returning 1 to the protocol main
7594 * function so that other things can run on top of the
7595 * transport. If we ever see a KEXINIT, we must go back to the
7598 * We _also_ go back to the start if we see pktin==NULL and
7599 * inlen negative, because this is a special signal meaning
7600 * `initiate client-driven rekey', and `in' contains a message
7601 * giving the reason for the rekey.
7603 * inlen==-1 means always initiate a rekey;
7604 * inlen==-2 means that userauth has completed successfully and
7605 * we should consider rekeying (for delayed compression).
7607 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7608 (!pktin && inlen < 0))) {
7610 if (!ssh->protocol_initial_phase_done) {
7611 ssh->protocol_initial_phase_done = TRUE;
7613 * Allow authconn to initialise itself.
7615 do_ssh2_authconn(ssh, NULL, 0, NULL);
7620 logevent("Server initiated key re-exchange");
7624 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7625 * delayed compression, if it's available.
7627 * draft-miller-secsh-compression-delayed-00 says that you
7628 * negotiate delayed compression in the first key exchange, and
7629 * both sides start compressing when the server has sent
7630 * USERAUTH_SUCCESS. This has a race condition -- the server
7631 * can't know when the client has seen it, and thus which incoming
7632 * packets it should treat as compressed.
7634 * Instead, we do the initial key exchange without offering the
7635 * delayed methods, but note if the server offers them; when we
7636 * get here, if a delayed method was available that was higher
7637 * on our list than what we got, we initiate a rekey in which we
7638 * _do_ list the delayed methods (and hopefully get it as a
7639 * result). Subsequent rekeys will do the same.
7641 assert(!s->userauth_succeeded); /* should only happen once */
7642 s->userauth_succeeded = TRUE;
7643 if (!s->pending_compression)
7644 /* Can't see any point rekeying. */
7645 goto wait_for_rekey; /* this is utterly horrid */
7646 /* else fall through to rekey... */
7647 s->pending_compression = FALSE;
7650 * Now we've decided to rekey.
7652 * Special case: if the server bug is set that doesn't
7653 * allow rekeying, we give a different log message and
7654 * continue waiting. (If such a server _initiates_ a rekey,
7655 * we process it anyway!)
7657 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7658 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7660 /* Reset the counters, so that at least this message doesn't
7661 * hit the event log _too_ often. */
7662 ssh->outgoing_data_size = 0;
7663 ssh->incoming_data_size = 0;
7664 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7666 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7669 goto wait_for_rekey; /* this is still utterly horrid */
7671 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7674 goto begin_key_exchange;
7680 * Send data on an SSH channel. In SSH-2, this involves buffering it
7683 static int ssh_send_channel_data(struct ssh_channel *c, const char *buf,
7686 if (c->ssh->version == 2) {
7687 bufchain_add(&c->v.v2.outbuffer, buf, len);
7688 return ssh2_try_send(c);
7690 send_packet(c->ssh, SSH1_MSG_CHANNEL_DATA,
7691 PKT_INT, c->remoteid,
7696 * In SSH-1 we can return 0 here - implying that channels are
7697 * never individually throttled - because the only
7698 * circumstance that can cause throttling will be the whole
7699 * SSH connection backing up, in which case _everything_ will
7700 * be throttled as a whole.
7707 * Attempt to send data on an SSH-2 channel.
7709 static int ssh2_try_send(struct ssh_channel *c)
7712 struct Packet *pktout;
7715 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7718 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7719 if ((unsigned)len > c->v.v2.remwindow)
7720 len = c->v.v2.remwindow;
7721 if ((unsigned)len > c->v.v2.remmaxpkt)
7722 len = c->v.v2.remmaxpkt;
7723 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7724 ssh2_pkt_adduint32(pktout, c->remoteid);
7725 ssh2_pkt_addstring_start(pktout);
7726 ssh2_pkt_addstring_data(pktout, data, len);
7727 ssh2_pkt_send(ssh, pktout);
7728 bufchain_consume(&c->v.v2.outbuffer, len);
7729 c->v.v2.remwindow -= len;
7733 * After having sent as much data as we can, return the amount
7736 ret = bufchain_size(&c->v.v2.outbuffer);
7739 * And if there's no data pending but we need to send an EOF, send
7742 if (!ret && c->pending_eof)
7743 ssh_channel_try_eof(c);
7748 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7751 if (c->closes & CLOSES_SENT_EOF)
7752 return; /* don't send on channels we've EOFed */
7753 bufsize = ssh2_try_send(c);
7756 case CHAN_MAINSESSION:
7757 /* stdin need not receive an unthrottle
7758 * notification since it will be polled */
7761 x11_unthrottle(c->u.x11.xconn);
7764 /* agent sockets are request/response and need no
7765 * buffer management */
7768 pfd_unthrottle(c->u.pfd.pf);
7774 static int ssh_is_simple(Ssh ssh)
7777 * We use the 'simple' variant of the SSH protocol if we're asked
7778 * to, except not if we're also doing connection-sharing (either
7779 * tunnelling our packets over an upstream or expecting to be
7780 * tunnelled over ourselves), since then the assumption that we
7781 * have only one channel to worry about is not true after all.
7783 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7784 !ssh->bare_connection && !ssh->connshare);
7788 * Set up most of a new ssh_channel.
7790 static void ssh_channel_init(struct ssh_channel *c)
7793 c->localid = alloc_channel_id(ssh);
7795 c->pending_eof = FALSE;
7796 c->throttling_conn = FALSE;
7797 if (ssh->version == 2) {
7798 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7799 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7800 c->v.v2.chanreq_head = NULL;
7801 c->v.v2.throttle_state = UNTHROTTLED;
7802 bufchain_init(&c->v.v2.outbuffer);
7807 * Construct the common parts of a CHANNEL_OPEN.
7809 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
7812 struct Packet *pktout;
7814 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7815 ssh2_pkt_addstring(pktout, type);
7816 ssh2_pkt_adduint32(pktout, c->localid);
7817 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7818 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7823 * CHANNEL_FAILURE doesn't come with any indication of what message
7824 * caused it, so we have to keep track of the outstanding
7825 * CHANNEL_REQUESTs ourselves.
7827 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7828 cchandler_fn_t handler, void *ctx)
7830 struct outstanding_channel_request *ocr =
7831 snew(struct outstanding_channel_request);
7833 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7834 ocr->handler = handler;
7837 if (!c->v.v2.chanreq_head)
7838 c->v.v2.chanreq_head = ocr;
7840 c->v.v2.chanreq_tail->next = ocr;
7841 c->v.v2.chanreq_tail = ocr;
7845 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7846 * NULL then a reply will be requested and the handler will be called
7847 * when it arrives. The returned packet is ready to have any
7848 * request-specific data added and be sent. Note that if a handler is
7849 * provided, it's essential that the request actually be sent.
7851 * The handler will usually be passed the response packet in pktin. If
7852 * pktin is NULL, this means that no reply will ever be forthcoming
7853 * (e.g. because the entire connection is being destroyed, or because
7854 * the server initiated channel closure before we saw the response)
7855 * and the handler should free any storage it's holding.
7857 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
7859 cchandler_fn_t handler, void *ctx)
7861 struct Packet *pktout;
7863 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7864 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7865 ssh2_pkt_adduint32(pktout, c->remoteid);
7866 ssh2_pkt_addstring(pktout, type);
7867 ssh2_pkt_addbool(pktout, handler != NULL);
7868 if (handler != NULL)
7869 ssh2_queue_chanreq_handler(c, handler, ctx);
7873 static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize)
7878 if (ssh->version == 1) {
7879 buflimit = SSH1_BUFFER_LIMIT;
7881 if (ssh_is_simple(ssh))
7884 buflimit = c->v.v2.locmaxwin;
7885 if (bufsize < buflimit)
7886 ssh2_set_window(c, buflimit - bufsize);
7888 if (c->throttling_conn && bufsize <= buflimit) {
7889 c->throttling_conn = 0;
7890 ssh_throttle_conn(ssh, -1);
7895 * Potentially enlarge the window on an SSH-2 channel.
7897 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7899 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7904 * Never send WINDOW_ADJUST for a channel that the remote side has
7905 * already sent EOF on; there's no point, since it won't be
7906 * sending any more data anyway. Ditto if _we've_ already sent
7909 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7913 * Also, never widen the window for an X11 channel when we're
7914 * still waiting to see its initial auth and may yet hand it off
7917 if (c->type == CHAN_X11 && c->u.x11.initial)
7921 * If the remote end has a habit of ignoring maxpkt, limit the
7922 * window so that it has no choice (assuming it doesn't ignore the
7925 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7926 newwin = OUR_V2_MAXPKT;
7929 * Only send a WINDOW_ADJUST if there's significantly more window
7930 * available than the other end thinks there is. This saves us
7931 * sending a WINDOW_ADJUST for every character in a shell session.
7933 * "Significant" is arbitrarily defined as half the window size.
7935 if (newwin / 2 >= c->v.v2.locwindow) {
7936 struct Packet *pktout;
7940 * In order to keep track of how much window the client
7941 * actually has available, we'd like it to acknowledge each
7942 * WINDOW_ADJUST. We can't do that directly, so we accompany
7943 * it with a CHANNEL_REQUEST that has to be acknowledged.
7945 * This is only necessary if we're opening the window wide.
7946 * If we're not, then throughput is being constrained by
7947 * something other than the maximum window size anyway.
7949 if (newwin == c->v.v2.locmaxwin &&
7950 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7951 up = snew(unsigned);
7952 *up = newwin - c->v.v2.locwindow;
7953 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7954 ssh2_handle_winadj_response, up);
7955 ssh2_pkt_send(ssh, pktout);
7957 if (c->v.v2.throttle_state != UNTHROTTLED)
7958 c->v.v2.throttle_state = UNTHROTTLING;
7960 /* Pretend the WINDOW_ADJUST was acked immediately. */
7961 c->v.v2.remlocwin = newwin;
7962 c->v.v2.throttle_state = THROTTLED;
7964 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7965 ssh2_pkt_adduint32(pktout, c->remoteid);
7966 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7967 ssh2_pkt_send(ssh, pktout);
7968 c->v.v2.locwindow = newwin;
7973 * Find the channel associated with a message. If there's no channel,
7974 * or it's not properly open, make a noise about it and return NULL.
7976 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7978 unsigned localid = ssh_pkt_getuint32(pktin);
7979 struct ssh_channel *c;
7981 c = find234(ssh->channels, &localid, ssh_channelfind);
7983 (c->type != CHAN_SHARING && c->halfopen &&
7984 pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7985 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7986 char *buf = dupprintf("Received %s for %s channel %u",
7987 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7989 c ? "half-open" : "nonexistent", localid);
7990 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7997 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7998 struct Packet *pktin, void *ctx)
8000 unsigned *sizep = ctx;
8003 * Winadj responses should always be failures. However, at least
8004 * one server ("boks_sshd") is known to return SUCCESS for channel
8005 * requests it's never heard of, such as "winadj@putty". Raised
8006 * with foxt.com as bug 090916-090424, but for the sake of a quiet
8007 * life, we don't worry about what kind of response we got.
8010 c->v.v2.remlocwin += *sizep;
8013 * winadj messages are only sent when the window is fully open, so
8014 * if we get an ack of one, we know any pending unthrottle is
8017 if (c->v.v2.throttle_state == UNTHROTTLING)
8018 c->v.v2.throttle_state = UNTHROTTLED;
8021 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
8023 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
8024 struct outstanding_channel_request *ocr;
8027 if (c->type == CHAN_SHARING) {
8028 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8029 pktin->body, pktin->length);
8032 ocr = c->v.v2.chanreq_head;
8034 ssh2_msg_unexpected(ssh, pktin);
8037 ocr->handler(c, pktin, ocr->ctx);
8038 c->v.v2.chanreq_head = ocr->next;
8041 * We may now initiate channel-closing procedures, if that
8042 * CHANNEL_REQUEST was the last thing outstanding before we send
8045 ssh2_channel_check_close(c);
8048 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
8050 struct ssh_channel *c;
8051 c = ssh2_channel_msg(ssh, pktin);
8054 if (c->type == CHAN_SHARING) {
8055 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8056 pktin->body, pktin->length);
8059 if (!(c->closes & CLOSES_SENT_EOF)) {
8060 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
8061 ssh2_try_send_and_unthrottle(ssh, c);
8065 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
8069 struct ssh_channel *c;
8070 c = ssh2_channel_msg(ssh, pktin);
8073 if (c->type == CHAN_SHARING) {
8074 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8075 pktin->body, pktin->length);
8078 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
8079 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
8080 return; /* extended but not stderr */
8081 ssh_pkt_getstring(pktin, &data, &length);
8084 c->v.v2.locwindow -= length;
8085 c->v.v2.remlocwin -= length;
8086 bufsize = ssh_channel_data(c, pktin->type ==
8087 SSH2_MSG_CHANNEL_EXTENDED_DATA,
8090 * If it looks like the remote end hit the end of its window,
8091 * and we didn't want it to do that, think about using a
8094 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
8095 c->v.v2.locmaxwin < 0x40000000)
8096 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
8098 * If we are not buffering too much data,
8099 * enlarge the window again at the remote side.
8100 * If we are buffering too much, we may still
8101 * need to adjust the window if the server's
8104 if (bufsize < c->v.v2.locmaxwin)
8105 ssh2_set_window(c, c->v.v2.locmaxwin - bufsize);
8107 * If we're either buffering way too much data, or if we're
8108 * buffering anything at all and we're in "simple" mode,
8109 * throttle the whole channel.
8111 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
8112 && !c->throttling_conn) {
8113 c->throttling_conn = 1;
8114 ssh_throttle_conn(ssh, +1);
8119 static void ssh_check_termination(Ssh ssh)
8121 if (ssh->version == 2 &&
8122 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
8123 (ssh->channels && count234(ssh->channels) == 0) &&
8124 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
8126 * We used to send SSH_MSG_DISCONNECT here, because I'd
8127 * believed that _every_ conforming SSH-2 connection had to
8128 * end with a disconnect being sent by at least one side;
8129 * apparently I was wrong and it's perfectly OK to
8130 * unceremoniously slam the connection shut when you're done,
8131 * and indeed OpenSSH feels this is more polite than sending a
8132 * DISCONNECT. So now we don't.
8134 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
8138 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
8139 const char *peerinfo)
8142 logeventf(ssh, "Connection sharing downstream #%u connected from %s",
8145 logeventf(ssh, "Connection sharing downstream #%u connected", id);
8148 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
8150 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
8151 ssh_check_termination(ssh);
8154 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
8159 va_start(ap, logfmt);
8160 buf = dupvprintf(logfmt, ap);
8163 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
8165 logeventf(ssh, "Connection sharing: %s", buf);
8169 static void ssh_channel_destroy(struct ssh_channel *c)
8174 case CHAN_MAINSESSION:
8175 ssh->mainchan = NULL;
8176 update_specials_menu(ssh->frontend);
8179 if (c->u.x11.xconn != NULL)
8180 x11_close(c->u.x11.xconn);
8181 logevent("Forwarded X11 connection terminated");
8184 sfree(c->u.a.message);
8187 if (c->u.pfd.pf != NULL)
8188 pfd_close(c->u.pfd.pf);
8189 logevent("Forwarded port closed");
8193 del234(ssh->channels, c);
8194 if (ssh->version == 2) {
8195 bufchain_clear(&c->v.v2.outbuffer);
8196 assert(c->v.v2.chanreq_head == NULL);
8201 * If that was the last channel left open, we might need to
8204 ssh_check_termination(ssh);
8207 static void ssh2_channel_check_close(struct ssh_channel *c)
8210 struct Packet *pktout;
8214 * If we've sent out our own CHANNEL_OPEN but not yet seen
8215 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
8216 * it's too early to be sending close messages of any kind.
8221 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
8222 c->type == CHAN_ZOMBIE) &&
8223 !c->v.v2.chanreq_head &&
8224 !(c->closes & CLOSES_SENT_CLOSE)) {
8226 * We have both sent and received EOF (or the channel is a
8227 * zombie), and we have no outstanding channel requests, which
8228 * means the channel is in final wind-up. But we haven't sent
8229 * CLOSE, so let's do so now.
8231 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
8232 ssh2_pkt_adduint32(pktout, c->remoteid);
8233 ssh2_pkt_send(ssh, pktout);
8234 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
8237 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
8238 assert(c->v.v2.chanreq_head == NULL);
8240 * We have both sent and received CLOSE, which means we're
8241 * completely done with the channel.
8243 ssh_channel_destroy(c);
8247 static void ssh2_channel_got_eof(struct ssh_channel *c)
8249 if (c->closes & CLOSES_RCVD_EOF)
8250 return; /* already seen EOF */
8251 c->closes |= CLOSES_RCVD_EOF;
8253 if (c->type == CHAN_X11) {
8254 x11_send_eof(c->u.x11.xconn);
8255 } else if (c->type == CHAN_AGENT) {
8256 if (c->u.a.outstanding_requests == 0) {
8257 /* Manufacture an outgoing EOF in response to the incoming one. */
8258 sshfwd_write_eof(c);
8260 } else if (c->type == CHAN_SOCKDATA) {
8261 pfd_send_eof(c->u.pfd.pf);
8262 } else if (c->type == CHAN_MAINSESSION) {
8265 if (!ssh->sent_console_eof &&
8266 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
8268 * Either from_backend_eof told us that the front end
8269 * wants us to close the outgoing side of the connection
8270 * as soon as we see EOF from the far end, or else we've
8271 * unilaterally decided to do that because we've allocated
8272 * a remote pty and hence EOF isn't a particularly
8273 * meaningful concept.
8275 sshfwd_write_eof(c);
8277 ssh->sent_console_eof = TRUE;
8280 ssh2_channel_check_close(c);
8283 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
8285 struct ssh_channel *c;
8287 c = ssh2_channel_msg(ssh, pktin);
8290 if (c->type == CHAN_SHARING) {
8291 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8292 pktin->body, pktin->length);
8295 ssh2_channel_got_eof(c);
8298 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
8300 struct ssh_channel *c;
8302 c = ssh2_channel_msg(ssh, pktin);
8305 if (c->type == CHAN_SHARING) {
8306 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8307 pktin->body, pktin->length);
8312 * When we receive CLOSE on a channel, we assume it comes with an
8313 * implied EOF if we haven't seen EOF yet.
8315 ssh2_channel_got_eof(c);
8317 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
8319 * It also means we stop expecting to see replies to any
8320 * outstanding channel requests, so clean those up too.
8321 * (ssh_chanreq_init will enforce by assertion that we don't
8322 * subsequently put anything back on this list.)
8324 while (c->v.v2.chanreq_head) {
8325 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8326 ocr->handler(c, NULL, ocr->ctx);
8327 c->v.v2.chanreq_head = ocr->next;
8333 * And we also send an outgoing EOF, if we haven't already, on the
8334 * assumption that CLOSE is a pretty forceful announcement that
8335 * the remote side is doing away with the entire channel. (If it
8336 * had wanted to send us EOF and continue receiving data from us,
8337 * it would have just sent CHANNEL_EOF.)
8339 if (!(c->closes & CLOSES_SENT_EOF)) {
8341 * Make sure we don't read any more from whatever our local
8342 * data source is for this channel.
8345 case CHAN_MAINSESSION:
8346 ssh->send_ok = 0; /* stop trying to read from stdin */
8349 x11_override_throttle(c->u.x11.xconn, 1);
8352 pfd_override_throttle(c->u.pfd.pf, 1);
8357 * Abandon any buffered data we still wanted to send to this
8358 * channel. Receiving a CHANNEL_CLOSE is an indication that
8359 * the server really wants to get on and _destroy_ this
8360 * channel, and it isn't going to send us any further
8361 * WINDOW_ADJUSTs to permit us to send pending stuff.
8363 bufchain_clear(&c->v.v2.outbuffer);
8366 * Send outgoing EOF.
8368 sshfwd_write_eof(c);
8372 * Now process the actual close.
8374 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8375 c->closes |= CLOSES_RCVD_CLOSE;
8376 ssh2_channel_check_close(c);
8380 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8382 struct ssh_channel *c;
8384 c = ssh2_channel_msg(ssh, pktin);
8387 if (c->type == CHAN_SHARING) {
8388 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8389 pktin->body, pktin->length);
8392 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8393 c->remoteid = ssh_pkt_getuint32(pktin);
8394 c->halfopen = FALSE;
8395 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8396 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8398 if (c->type == CHAN_SOCKDATA_DORMANT) {
8399 c->type = CHAN_SOCKDATA;
8401 pfd_confirm(c->u.pfd.pf);
8402 } else if (c->type == CHAN_ZOMBIE) {
8404 * This case can occur if a local socket error occurred
8405 * between us sending out CHANNEL_OPEN and receiving
8406 * OPEN_CONFIRMATION. In this case, all we can do is
8407 * immediately initiate close proceedings now that we know the
8408 * server's id to put in the close message.
8410 ssh2_channel_check_close(c);
8413 * We never expect to receive OPEN_CONFIRMATION for any
8414 * *other* channel type (since only local-to-remote port
8415 * forwardings cause us to send CHANNEL_OPEN after the main
8416 * channel is live - all other auxiliary channel types are
8417 * initiated from the server end). It's safe to enforce this
8418 * by assertion rather than by ssh_disconnect, because the
8419 * real point is that we never constructed a half-open channel
8420 * structure in the first place with any type other than the
8423 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8427 ssh_channel_try_eof(c); /* in case we had a pending EOF */
8430 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8432 static const char *const reasons[] = {
8433 "<unknown reason code>",
8434 "Administratively prohibited",
8436 "Unknown channel type",
8437 "Resource shortage",
8439 unsigned reason_code;
8440 char *reason_string;
8442 struct ssh_channel *c;
8444 c = ssh2_channel_msg(ssh, pktin);
8447 if (c->type == CHAN_SHARING) {
8448 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8449 pktin->body, pktin->length);
8452 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8454 if (c->type == CHAN_SOCKDATA_DORMANT) {
8455 reason_code = ssh_pkt_getuint32(pktin);
8456 if (reason_code >= lenof(reasons))
8457 reason_code = 0; /* ensure reasons[reason_code] in range */
8458 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8459 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8460 reasons[reason_code], reason_length,
8461 NULLTOEMPTY(reason_string));
8463 pfd_close(c->u.pfd.pf);
8464 } else if (c->type == CHAN_ZOMBIE) {
8466 * This case can occur if a local socket error occurred
8467 * between us sending out CHANNEL_OPEN and receiving
8468 * OPEN_FAILURE. In this case, we need do nothing except allow
8469 * the code below to throw the half-open channel away.
8473 * We never expect to receive OPEN_FAILURE for any *other*
8474 * channel type (since only local-to-remote port forwardings
8475 * cause us to send CHANNEL_OPEN after the main channel is
8476 * live - all other auxiliary channel types are initiated from
8477 * the server end). It's safe to enforce this by assertion
8478 * rather than by ssh_disconnect, because the real point is
8479 * that we never constructed a half-open channel structure in
8480 * the first place with any type other than the above.
8482 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8485 del234(ssh->channels, c);
8489 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8492 int typelen, want_reply;
8493 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8494 struct ssh_channel *c;
8495 struct Packet *pktout;
8497 c = ssh2_channel_msg(ssh, pktin);
8500 if (c->type == CHAN_SHARING) {
8501 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8502 pktin->body, pktin->length);
8505 ssh_pkt_getstring(pktin, &type, &typelen);
8506 want_reply = ssh2_pkt_getbool(pktin);
8508 if (c->closes & CLOSES_SENT_CLOSE) {
8510 * We don't reply to channel requests after we've sent
8511 * CHANNEL_CLOSE for the channel, because our reply might
8512 * cross in the network with the other side's CHANNEL_CLOSE
8513 * and arrive after they have wound the channel up completely.
8519 * Having got the channel number, we now look at
8520 * the request type string to see if it's something
8523 if (c == ssh->mainchan) {
8525 * We recognise "exit-status" and "exit-signal" on
8526 * the primary channel.
8528 if (typelen == 11 &&
8529 !memcmp(type, "exit-status", 11)) {
8531 ssh->exitcode = ssh_pkt_getuint32(pktin);
8532 logeventf(ssh, "Server sent command exit status %d",
8534 reply = SSH2_MSG_CHANNEL_SUCCESS;
8536 } else if (typelen == 11 &&
8537 !memcmp(type, "exit-signal", 11)) {
8539 int is_plausible = TRUE, is_int = FALSE;
8540 char *fmt_sig = NULL, *fmt_msg = NULL;
8542 int msglen = 0, core = FALSE;
8543 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8544 * provide an `int' for the signal, despite its
8545 * having been a `string' in the drafts of RFC 4254 since at
8546 * least 2001. (Fixed in session.c 1.147.) Try to
8547 * infer which we can safely parse it as. */
8549 unsigned char *p = pktin->body +
8551 long len = pktin->length - pktin->savedpos;
8552 unsigned long num = GET_32BIT(p); /* what is it? */
8553 /* If it's 0, it hardly matters; assume string */
8557 int maybe_int = FALSE, maybe_str = FALSE;
8558 #define CHECK_HYPOTHESIS(offset, result) \
8561 int q = toint(offset); \
8562 if (q >= 0 && q+4 <= len) { \
8563 q = toint(q + 4 + GET_32BIT(p+q)); \
8564 if (q >= 0 && q+4 <= len && \
8565 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8570 CHECK_HYPOTHESIS(4+1, maybe_int);
8571 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8572 #undef CHECK_HYPOTHESIS
8573 if (maybe_int && !maybe_str)
8575 else if (!maybe_int && maybe_str)
8578 /* Crikey. Either or neither. Panic. */
8579 is_plausible = FALSE;
8582 ssh->exitcode = 128; /* means `unknown signal' */
8585 /* Old non-standard OpenSSH. */
8586 int signum = ssh_pkt_getuint32(pktin);
8587 fmt_sig = dupprintf(" %d", signum);
8588 ssh->exitcode = 128 + signum;
8590 /* As per RFC 4254. */
8593 ssh_pkt_getstring(pktin, &sig, &siglen);
8594 /* Signal name isn't supposed to be blank, but
8595 * let's cope gracefully if it is. */
8597 fmt_sig = dupprintf(" \"%.*s\"",
8602 * Really hideous method of translating the
8603 * signal description back into a locally
8604 * meaningful number.
8609 #define TRANSLATE_SIGNAL(s) \
8610 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8611 ssh->exitcode = 128 + SIG ## s
8613 TRANSLATE_SIGNAL(ABRT);
8616 TRANSLATE_SIGNAL(ALRM);
8619 TRANSLATE_SIGNAL(FPE);
8622 TRANSLATE_SIGNAL(HUP);
8625 TRANSLATE_SIGNAL(ILL);
8628 TRANSLATE_SIGNAL(INT);
8631 TRANSLATE_SIGNAL(KILL);
8634 TRANSLATE_SIGNAL(PIPE);
8637 TRANSLATE_SIGNAL(QUIT);
8640 TRANSLATE_SIGNAL(SEGV);
8643 TRANSLATE_SIGNAL(TERM);
8646 TRANSLATE_SIGNAL(USR1);
8649 TRANSLATE_SIGNAL(USR2);
8651 #undef TRANSLATE_SIGNAL
8653 ssh->exitcode = 128;
8655 core = ssh2_pkt_getbool(pktin);
8656 ssh_pkt_getstring(pktin, &msg, &msglen);
8658 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8660 /* ignore lang tag */
8661 } /* else don't attempt to parse */
8662 logeventf(ssh, "Server exited on signal%s%s%s",
8663 fmt_sig ? fmt_sig : "",
8664 core ? " (core dumped)" : "",
8665 fmt_msg ? fmt_msg : "");
8668 reply = SSH2_MSG_CHANNEL_SUCCESS;
8673 * This is a channel request we don't know
8674 * about, so we now either ignore the request
8675 * or respond with CHANNEL_FAILURE, depending
8678 reply = SSH2_MSG_CHANNEL_FAILURE;
8681 pktout = ssh2_pkt_init(reply);
8682 ssh2_pkt_adduint32(pktout, c->remoteid);
8683 ssh2_pkt_send(ssh, pktout);
8687 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8690 int typelen, want_reply;
8691 struct Packet *pktout;
8693 ssh_pkt_getstring(pktin, &type, &typelen);
8694 want_reply = ssh2_pkt_getbool(pktin);
8697 * We currently don't support any global requests
8698 * at all, so we either ignore the request or
8699 * respond with REQUEST_FAILURE, depending on
8703 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8704 ssh2_pkt_send(ssh, pktout);
8708 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8712 struct X11FakeAuth *auth;
8715 * Make up a new set of fake X11 auth data, and add it to the tree
8716 * of currently valid ones with an indication of the sharing
8717 * context that it's relevant to.
8719 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8720 auth->share_cs = share_cs;
8721 auth->share_chan = share_chan;
8726 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8728 del234(ssh->x11authtree, auth);
8729 x11_free_fake_auth(auth);
8732 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8739 const char *error = NULL;
8740 struct ssh_channel *c;
8741 unsigned remid, winsize, pktsize;
8742 unsigned our_winsize_override = 0;
8743 struct Packet *pktout;
8745 ssh_pkt_getstring(pktin, &type, &typelen);
8746 c = snew(struct ssh_channel);
8749 remid = ssh_pkt_getuint32(pktin);
8750 winsize = ssh_pkt_getuint32(pktin);
8751 pktsize = ssh_pkt_getuint32(pktin);
8753 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8756 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8757 addrstr = dupprintf("%.*s", peeraddrlen, NULLTOEMPTY(peeraddr));
8758 peerport = ssh_pkt_getuint32(pktin);
8760 logeventf(ssh, "Received X11 connect request from %s:%d",
8763 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8764 error = "X11 forwarding is not enabled";
8766 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8769 c->u.x11.initial = TRUE;
8772 * If we are a connection-sharing upstream, then we should
8773 * initially present a very small window, adequate to take
8774 * the X11 initial authorisation packet but not much more.
8775 * Downstream will then present us a larger window (by
8776 * fiat of the connection-sharing protocol) and we can
8777 * guarantee to send a positive-valued WINDOW_ADJUST.
8780 our_winsize_override = 128;
8782 logevent("Opened X11 forward channel");
8786 } else if (typelen == 15 &&
8787 !memcmp(type, "forwarded-tcpip", 15)) {
8788 struct ssh_rportfwd pf, *realpf;
8791 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8792 pf.shost = dupprintf("%.*s", shostlen, NULLTOEMPTY(shost));
8793 pf.sport = ssh_pkt_getuint32(pktin);
8794 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8795 peerport = ssh_pkt_getuint32(pktin);
8796 realpf = find234(ssh->rportfwds, &pf, NULL);
8797 logeventf(ssh, "Received remote port %s:%d open request "
8798 "from %.*s:%d", pf.shost, pf.sport,
8799 peeraddrlen, NULLTOEMPTY(peeraddr), peerport);
8802 if (realpf == NULL) {
8803 error = "Remote port is not recognised";
8807 if (realpf->share_ctx) {
8809 * This port forwarding is on behalf of a
8810 * connection-sharing downstream, so abandon our own
8811 * channel-open procedure and just pass the message on
8814 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8815 pktin->body, pktin->length);
8820 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8821 c, ssh->conf, realpf->pfrec->addressfamily);
8822 logeventf(ssh, "Attempting to forward remote port to "
8823 "%s:%d", realpf->dhost, realpf->dport);
8825 logeventf(ssh, "Port open failed: %s", err);
8827 error = "Port open failed";
8829 logevent("Forwarded port opened successfully");
8830 c->type = CHAN_SOCKDATA;
8833 } else if (typelen == 22 &&
8834 !memcmp(type, "auth-agent@openssh.com", 22)) {
8835 if (!ssh->agentfwd_enabled)
8836 error = "Agent forwarding is not enabled";
8838 c->type = CHAN_AGENT; /* identify channel type */
8839 c->u.a.lensofar = 0;
8840 c->u.a.message = NULL;
8841 c->u.a.outstanding_requests = 0;
8844 error = "Unsupported channel type requested";
8847 c->remoteid = remid;
8848 c->halfopen = FALSE;
8850 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8851 ssh2_pkt_adduint32(pktout, c->remoteid);
8852 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8853 ssh2_pkt_addstring(pktout, error);
8854 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8855 ssh2_pkt_send(ssh, pktout);
8856 logeventf(ssh, "Rejected channel open: %s", error);
8859 ssh_channel_init(c);
8860 c->v.v2.remwindow = winsize;
8861 c->v.v2.remmaxpkt = pktsize;
8862 if (our_winsize_override) {
8863 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8864 our_winsize_override;
8866 add234(ssh->channels, c);
8867 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8868 ssh2_pkt_adduint32(pktout, c->remoteid);
8869 ssh2_pkt_adduint32(pktout, c->localid);
8870 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8871 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8872 ssh2_pkt_send(ssh, pktout);
8876 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8877 void *share_cs, void *share_chan,
8878 const char *peer_addr, int peer_port,
8879 int endian, int protomajor, int protominor,
8880 const void *initial_data, int initial_len)
8883 * This function is called when we've just discovered that an X
8884 * forwarding channel on which we'd been handling the initial auth
8885 * ourselves turns out to be destined for a connection-sharing
8886 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8887 * that we completely stop tracking windows and buffering data and
8888 * just pass more or less unmodified SSH messages back and forth.
8890 c->type = CHAN_SHARING;
8891 c->u.sharing.ctx = share_cs;
8892 share_setup_x11_channel(share_cs, share_chan,
8893 c->localid, c->remoteid, c->v.v2.remwindow,
8894 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8895 peer_addr, peer_port, endian,
8896 protomajor, protominor,
8897 initial_data, initial_len);
8900 void sshfwd_x11_is_local(struct ssh_channel *c)
8903 * This function is called when we've just discovered that an X
8904 * forwarding channel is _not_ destined for a connection-sharing
8905 * downstream but we're going to handle it ourselves. We stop
8906 * presenting a cautiously small window and go into ordinary data
8909 c->u.x11.initial = FALSE;
8910 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8914 * Buffer banner messages for later display at some convenient point,
8915 * if we're going to display them.
8917 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8919 /* Arbitrary limit to prevent unbounded inflation of buffer */
8920 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8921 bufchain_size(&ssh->banner) <= 131072) {
8922 char *banner = NULL;
8924 ssh_pkt_getstring(pktin, &banner, &size);
8926 bufchain_add(&ssh->banner, banner, size);
8930 /* Helper function to deal with sending tty modes for "pty-req" */
8931 static void ssh2_send_ttymode(void *data,
8932 const struct ssh_ttymode *mode, char *val)
8934 struct Packet *pktout = (struct Packet *)data;
8935 unsigned int arg = 0;
8937 switch (mode->type) {
8939 arg = ssh_tty_parse_specchar(val);
8942 arg = ssh_tty_parse_boolean(val);
8945 ssh2_pkt_addbyte(pktout, mode->opcode);
8946 ssh2_pkt_adduint32(pktout, arg);
8949 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8952 struct ssh2_setup_x11_state {
8956 struct Packet *pktout;
8957 crStateP(ssh2_setup_x11_state, ctx);
8961 logevent("Requesting X11 forwarding");
8962 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8964 ssh2_pkt_addbool(pktout, 0); /* many connections */
8965 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8966 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8967 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8968 ssh2_pkt_send(ssh, pktout);
8970 /* Wait to be called back with either a response packet, or NULL
8971 * meaning clean up and free our data */
8975 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8976 logevent("X11 forwarding enabled");
8977 ssh->X11_fwd_enabled = TRUE;
8979 logevent("X11 forwarding refused");
8985 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8988 struct ssh2_setup_agent_state {
8992 struct Packet *pktout;
8993 crStateP(ssh2_setup_agent_state, ctx);
8997 logevent("Requesting OpenSSH-style agent forwarding");
8998 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
8999 ssh2_setup_agent, s);
9000 ssh2_pkt_send(ssh, pktout);
9002 /* Wait to be called back with either a response packet, or NULL
9003 * meaning clean up and free our data */
9007 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9008 logevent("Agent forwarding enabled");
9009 ssh->agentfwd_enabled = TRUE;
9011 logevent("Agent forwarding refused");
9017 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
9020 struct ssh2_setup_pty_state {
9024 struct Packet *pktout;
9025 crStateP(ssh2_setup_pty_state, ctx);
9029 /* Unpick the terminal-speed string. */
9030 /* XXX perhaps we should allow no speeds to be sent. */
9031 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
9032 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
9033 /* Build the pty request. */
9034 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
9036 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
9037 ssh2_pkt_adduint32(pktout, ssh->term_width);
9038 ssh2_pkt_adduint32(pktout, ssh->term_height);
9039 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
9040 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
9041 ssh2_pkt_addstring_start(pktout);
9042 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
9043 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
9044 ssh2_pkt_adduint32(pktout, ssh->ispeed);
9045 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
9046 ssh2_pkt_adduint32(pktout, ssh->ospeed);
9047 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
9048 ssh2_pkt_send(ssh, pktout);
9049 ssh->state = SSH_STATE_INTERMED;
9051 /* Wait to be called back with either a response packet, or NULL
9052 * meaning clean up and free our data */
9056 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9057 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9058 ssh->ospeed, ssh->ispeed);
9059 ssh->got_pty = TRUE;
9061 c_write_str(ssh, "Server refused to allocate pty\r\n");
9062 ssh->editing = ssh->echoing = 1;
9069 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
9072 struct ssh2_setup_env_state {
9074 int num_env, env_left, env_ok;
9077 struct Packet *pktout;
9078 crStateP(ssh2_setup_env_state, ctx);
9083 * Send environment variables.
9085 * Simplest thing here is to send all the requests at once, and
9086 * then wait for a whole bunch of successes or failures.
9092 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9094 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9095 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
9096 ssh2_pkt_addstring(pktout, key);
9097 ssh2_pkt_addstring(pktout, val);
9098 ssh2_pkt_send(ssh, pktout);
9103 logeventf(ssh, "Sent %d environment variables", s->num_env);
9108 s->env_left = s->num_env;
9110 while (s->env_left > 0) {
9111 /* Wait to be called back with either a response packet,
9112 * or NULL meaning clean up and free our data */
9114 if (!pktin) goto out;
9115 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
9120 if (s->env_ok == s->num_env) {
9121 logevent("All environment variables successfully set");
9122 } else if (s->env_ok == 0) {
9123 logevent("All environment variables refused");
9124 c_write_str(ssh, "Server refused to set environment variables\r\n");
9126 logeventf(ssh, "%d environment variables refused",
9127 s->num_env - s->env_ok);
9128 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9136 * Handle the SSH-2 userauth and connection layers.
9138 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
9140 do_ssh2_authconn(ssh, NULL, 0, pktin);
9143 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
9147 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
9150 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
9151 struct Packet *pktin)
9153 struct do_ssh2_authconn_state {
9157 AUTH_TYPE_PUBLICKEY,
9158 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
9159 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
9161 AUTH_TYPE_GSSAPI, /* always QUIET */
9162 AUTH_TYPE_KEYBOARD_INTERACTIVE,
9163 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
9165 int done_service_req;
9166 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
9167 int tried_pubkey_config, done_agent;
9172 int kbd_inter_refused;
9173 int we_are_in, userauth_success;
9174 prompts_t *cur_prompt;
9179 void *publickey_blob;
9180 int publickey_bloblen;
9181 int privatekey_available, privatekey_encrypted;
9182 char *publickey_algorithm;
9183 char *publickey_comment;
9184 unsigned char agent_request[5], *agent_response, *agentp;
9185 int agent_responselen;
9186 unsigned char *pkblob_in_agent;
9188 char *pkblob, *alg, *commentp;
9189 int pklen, alglen, commentlen;
9190 int siglen, retlen, len;
9191 char *q, *agentreq, *ret;
9192 struct Packet *pktout;
9195 struct ssh_gss_library *gsslib;
9196 Ssh_gss_ctx gss_ctx;
9197 Ssh_gss_buf gss_buf;
9198 Ssh_gss_buf gss_rcvtok, gss_sndtok;
9199 Ssh_gss_name gss_srv_name;
9200 Ssh_gss_stat gss_stat;
9203 crState(do_ssh2_authconn_state);
9207 /* Register as a handler for all the messages this coroutine handles. */
9208 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
9209 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
9210 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
9211 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
9212 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
9213 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
9214 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
9215 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
9216 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
9217 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
9218 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
9219 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
9220 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
9221 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
9222 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
9223 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
9224 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
9225 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
9226 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
9227 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
9229 s->done_service_req = FALSE;
9230 s->we_are_in = s->userauth_success = FALSE;
9231 s->agent_response = NULL;
9233 s->tried_gssapi = FALSE;
9236 if (!ssh->bare_connection) {
9237 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
9239 * Request userauth protocol, and await a response to it.
9241 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9242 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
9243 ssh2_pkt_send(ssh, s->pktout);
9244 crWaitUntilV(pktin);
9245 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
9246 s->done_service_req = TRUE;
9248 if (!s->done_service_req) {
9250 * Request connection protocol directly, without authentication.
9252 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9253 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9254 ssh2_pkt_send(ssh, s->pktout);
9255 crWaitUntilV(pktin);
9256 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
9257 s->we_are_in = TRUE; /* no auth required */
9259 bombout(("Server refused service request"));
9264 s->we_are_in = TRUE;
9267 /* Arrange to be able to deal with any BANNERs that come in.
9268 * (We do this now as packets may come in during the next bit.) */
9269 bufchain_init(&ssh->banner);
9270 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
9271 ssh2_msg_userauth_banner;
9274 * Misc one-time setup for authentication.
9276 s->publickey_blob = NULL;
9277 if (!s->we_are_in) {
9280 * Load the public half of any configured public key file
9283 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9284 if (!filename_is_null(s->keyfile)) {
9286 logeventf(ssh, "Reading key file \"%.150s\"",
9287 filename_to_str(s->keyfile));
9288 keytype = key_type(s->keyfile);
9289 if (keytype == SSH_KEYTYPE_SSH2 ||
9290 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
9291 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
9294 ssh2_userkey_loadpub(s->keyfile,
9295 &s->publickey_algorithm,
9296 &s->publickey_bloblen,
9297 &s->publickey_comment, &error);
9298 if (s->publickey_blob) {
9299 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
9300 if (!s->privatekey_available)
9301 logeventf(ssh, "Key file contains public key only");
9302 s->privatekey_encrypted =
9303 ssh2_userkey_encrypted(s->keyfile, NULL);
9306 logeventf(ssh, "Unable to load key (%s)",
9308 msgbuf = dupprintf("Unable to load key file "
9309 "\"%.150s\" (%s)\r\n",
9310 filename_to_str(s->keyfile),
9312 c_write_str(ssh, msgbuf);
9317 logeventf(ssh, "Unable to use this key file (%s)",
9318 key_type_to_str(keytype));
9319 msgbuf = dupprintf("Unable to use key file \"%.150s\""
9321 filename_to_str(s->keyfile),
9322 key_type_to_str(keytype));
9323 c_write_str(ssh, msgbuf);
9325 s->publickey_blob = NULL;
9330 * Find out about any keys Pageant has (but if there's a
9331 * public key configured, filter out all others).
9334 s->agent_response = NULL;
9335 s->pkblob_in_agent = NULL;
9336 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9340 logevent("Pageant is running. Requesting keys.");
9342 /* Request the keys held by the agent. */
9343 PUT_32BIT(s->agent_request, 1);
9344 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9345 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
9346 ssh_agent_callback, ssh)) {
9350 bombout(("Unexpected data from server while"
9351 " waiting for agent response"));
9354 } while (pktin || inlen > 0);
9355 r = ssh->agent_response;
9356 s->agent_responselen = ssh->agent_response_len;
9358 s->agent_response = (unsigned char *) r;
9359 if (s->agent_response && s->agent_responselen >= 5 &&
9360 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9363 p = s->agent_response + 5;
9364 s->nkeys = toint(GET_32BIT(p));
9367 * Vet the Pageant response to ensure that the key
9368 * count and blob lengths make sense.
9371 logeventf(ssh, "Pageant response contained a negative"
9372 " key count %d", s->nkeys);
9374 goto done_agent_query;
9376 unsigned char *q = p + 4;
9377 int lenleft = s->agent_responselen - 5 - 4;
9379 for (keyi = 0; keyi < s->nkeys; keyi++) {
9380 int bloblen, commentlen;
9382 logeventf(ssh, "Pageant response was truncated");
9384 goto done_agent_query;
9386 bloblen = toint(GET_32BIT(q));
9387 if (bloblen < 0 || bloblen > lenleft) {
9388 logeventf(ssh, "Pageant response was truncated");
9390 goto done_agent_query;
9392 lenleft -= 4 + bloblen;
9394 commentlen = toint(GET_32BIT(q));
9395 if (commentlen < 0 || commentlen > lenleft) {
9396 logeventf(ssh, "Pageant response was truncated");
9398 goto done_agent_query;
9400 lenleft -= 4 + commentlen;
9401 q += 4 + commentlen;
9406 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9407 if (s->publickey_blob) {
9408 /* See if configured key is in agent. */
9409 for (keyi = 0; keyi < s->nkeys; keyi++) {
9410 s->pklen = toint(GET_32BIT(p));
9411 if (s->pklen == s->publickey_bloblen &&
9412 !memcmp(p+4, s->publickey_blob,
9413 s->publickey_bloblen)) {
9414 logeventf(ssh, "Pageant key #%d matches "
9415 "configured key file", keyi);
9417 s->pkblob_in_agent = p;
9421 p += toint(GET_32BIT(p)) + 4; /* comment */
9423 if (!s->pkblob_in_agent) {
9424 logevent("Configured key file not in Pageant");
9429 logevent("Failed to get reply from Pageant");
9437 * We repeat this whole loop, including the username prompt,
9438 * until we manage a successful authentication. If the user
9439 * types the wrong _password_, they can be sent back to the
9440 * beginning to try another username, if this is configured on.
9441 * (If they specify a username in the config, they are never
9442 * asked, even if they do give a wrong password.)
9444 * I think this best serves the needs of
9446 * - the people who have no configuration, no keys, and just
9447 * want to try repeated (username,password) pairs until they
9448 * type both correctly
9450 * - people who have keys and configuration but occasionally
9451 * need to fall back to passwords
9453 * - people with a key held in Pageant, who might not have
9454 * logged in to a particular machine before; so they want to
9455 * type a username, and then _either_ their key will be
9456 * accepted, _or_ they will type a password. If they mistype
9457 * the username they will want to be able to get back and
9460 s->got_username = FALSE;
9461 while (!s->we_are_in) {
9465 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9467 * We got a username last time round this loop, and
9468 * with change_username turned off we don't try to get
9471 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9472 int ret; /* need not be kept over crReturn */
9473 s->cur_prompt = new_prompts(ssh->frontend);
9474 s->cur_prompt->to_server = TRUE;
9475 s->cur_prompt->name = dupstr("SSH login name");
9476 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9477 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9480 crWaitUntilV(!pktin);
9481 ret = get_userpass_input(s->cur_prompt, in, inlen);
9486 * get_userpass_input() failed to get a username.
9489 free_prompts(s->cur_prompt);
9490 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9493 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9494 free_prompts(s->cur_prompt);
9497 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9498 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9499 c_write_str(ssh, stuff);
9503 s->got_username = TRUE;
9506 * Send an authentication request using method "none": (a)
9507 * just in case it succeeds, and (b) so that we know what
9508 * authentication methods we can usefully try next.
9510 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9512 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9513 ssh2_pkt_addstring(s->pktout, ssh->username);
9514 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9515 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9516 ssh2_pkt_send(ssh, s->pktout);
9517 s->type = AUTH_TYPE_NONE;
9519 s->we_are_in = FALSE;
9521 s->tried_pubkey_config = FALSE;
9522 s->kbd_inter_refused = FALSE;
9524 /* Reset agent request state. */
9525 s->done_agent = FALSE;
9526 if (s->agent_response) {
9527 if (s->pkblob_in_agent) {
9528 s->agentp = s->pkblob_in_agent;
9530 s->agentp = s->agent_response + 5 + 4;
9536 char *methods = NULL;
9540 * Wait for the result of the last authentication request.
9543 crWaitUntilV(pktin);
9545 * Now is a convenient point to spew any banner material
9546 * that we've accumulated. (This should ensure that when
9547 * we exit the auth loop, we haven't any left to deal
9551 int size = bufchain_size(&ssh->banner);
9553 * Don't show the banner if we're operating in
9554 * non-verbose non-interactive mode. (It's probably
9555 * a script, which means nobody will read the
9556 * banner _anyway_, and moreover the printing of
9557 * the banner will screw up processing on the
9558 * output of (say) plink.)
9560 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9561 char *banner = snewn(size, char);
9562 bufchain_fetch(&ssh->banner, banner, size);
9563 c_write_untrusted(ssh, banner, size);
9566 bufchain_clear(&ssh->banner);
9568 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9569 logevent("Access granted");
9570 s->we_are_in = s->userauth_success = TRUE;
9574 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9575 bombout(("Strange packet received during authentication: "
9576 "type %d", pktin->type));
9583 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9584 * we can look at the string in it and know what we can
9585 * helpfully try next.
9587 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9588 ssh_pkt_getstring(pktin, &methods, &methlen);
9589 if (!ssh2_pkt_getbool(pktin)) {
9591 * We have received an unequivocal Access
9592 * Denied. This can translate to a variety of
9593 * messages, or no message at all.
9595 * For forms of authentication which are attempted
9596 * implicitly, by which I mean without printing
9597 * anything in the window indicating that we're
9598 * trying them, we should never print 'Access
9601 * If we do print a message saying that we're
9602 * attempting some kind of authentication, it's OK
9603 * to print a followup message saying it failed -
9604 * but the message may sometimes be more specific
9605 * than simply 'Access denied'.
9607 * Additionally, if we'd just tried password
9608 * authentication, we should break out of this
9609 * whole loop so as to go back to the username
9610 * prompt (iff we're configured to allow
9611 * username change attempts).
9613 if (s->type == AUTH_TYPE_NONE) {
9615 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9616 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9617 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9618 c_write_str(ssh, "Server refused our key\r\n");
9619 logevent("Server refused our key");
9620 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9621 /* This _shouldn't_ happen except by a
9622 * protocol bug causing client and server to
9623 * disagree on what is a correct signature. */
9624 c_write_str(ssh, "Server refused public-key signature"
9625 " despite accepting key!\r\n");
9626 logevent("Server refused public-key signature"
9627 " despite accepting key!");
9628 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9629 /* quiet, so no c_write */
9630 logevent("Server refused keyboard-interactive authentication");
9631 } else if (s->type==AUTH_TYPE_GSSAPI) {
9632 /* always quiet, so no c_write */
9633 /* also, the code down in the GSSAPI block has
9634 * already logged this in the Event Log */
9635 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9636 logevent("Keyboard-interactive authentication failed");
9637 c_write_str(ssh, "Access denied\r\n");
9639 assert(s->type == AUTH_TYPE_PASSWORD);
9640 logevent("Password authentication failed");
9641 c_write_str(ssh, "Access denied\r\n");
9643 if (conf_get_int(ssh->conf, CONF_change_username)) {
9644 /* XXX perhaps we should allow
9645 * keyboard-interactive to do this too? */
9646 s->we_are_in = FALSE;
9651 c_write_str(ssh, "Further authentication required\r\n");
9652 logevent("Further authentication required");
9656 in_commasep_string("publickey", methods, methlen);
9658 in_commasep_string("password", methods, methlen);
9659 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9660 in_commasep_string("keyboard-interactive", methods, methlen);
9662 if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9663 in_commasep_string("gssapi-with-mic", methods, methlen)) {
9664 /* Try loading the GSS libraries and see if we
9667 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9668 s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
9670 /* No point in even bothering to try to load the
9671 * GSS libraries, if the user configuration and
9672 * server aren't both prepared to attempt GSSAPI
9673 * auth in the first place. */
9674 s->can_gssapi = FALSE;
9679 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9681 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9684 * Attempt public-key authentication using a key from Pageant.
9687 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9689 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9691 /* Unpack key from agent response */
9692 s->pklen = toint(GET_32BIT(s->agentp));
9694 s->pkblob = (char *)s->agentp;
9695 s->agentp += s->pklen;
9696 s->alglen = toint(GET_32BIT(s->pkblob));
9697 s->alg = s->pkblob + 4;
9698 s->commentlen = toint(GET_32BIT(s->agentp));
9700 s->commentp = (char *)s->agentp;
9701 s->agentp += s->commentlen;
9702 /* s->agentp now points at next key, if any */
9704 /* See if server will accept it */
9705 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9706 ssh2_pkt_addstring(s->pktout, ssh->username);
9707 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9708 /* service requested */
9709 ssh2_pkt_addstring(s->pktout, "publickey");
9711 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9712 ssh2_pkt_addstring_start(s->pktout);
9713 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9714 ssh2_pkt_addstring_start(s->pktout);
9715 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9716 ssh2_pkt_send(ssh, s->pktout);
9717 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9719 crWaitUntilV(pktin);
9720 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9722 /* Offer of key refused. */
9729 if (flags & FLAG_VERBOSE) {
9730 c_write_str(ssh, "Authenticating with "
9732 c_write(ssh, s->commentp, s->commentlen);
9733 c_write_str(ssh, "\" from agent\r\n");
9737 * Server is willing to accept the key.
9738 * Construct a SIGN_REQUEST.
9740 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9741 ssh2_pkt_addstring(s->pktout, ssh->username);
9742 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9743 /* service requested */
9744 ssh2_pkt_addstring(s->pktout, "publickey");
9746 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9747 ssh2_pkt_addstring_start(s->pktout);
9748 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9749 ssh2_pkt_addstring_start(s->pktout);
9750 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9752 /* Ask agent for signature. */
9753 s->siglen = s->pktout->length - 5 + 4 +
9754 ssh->v2_session_id_len;
9755 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9757 s->len = 1; /* message type */
9758 s->len += 4 + s->pklen; /* key blob */
9759 s->len += 4 + s->siglen; /* data to sign */
9760 s->len += 4; /* flags */
9761 s->agentreq = snewn(4 + s->len, char);
9762 PUT_32BIT(s->agentreq, s->len);
9763 s->q = s->agentreq + 4;
9764 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9765 PUT_32BIT(s->q, s->pklen);
9767 memcpy(s->q, s->pkblob, s->pklen);
9769 PUT_32BIT(s->q, s->siglen);
9771 /* Now the data to be signed... */
9772 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9773 PUT_32BIT(s->q, ssh->v2_session_id_len);
9776 memcpy(s->q, ssh->v2_session_id,
9777 ssh->v2_session_id_len);
9778 s->q += ssh->v2_session_id_len;
9779 memcpy(s->q, s->pktout->data + 5,
9780 s->pktout->length - 5);
9781 s->q += s->pktout->length - 5;
9782 /* And finally the (zero) flags word. */
9784 if (!agent_query(s->agentreq, s->len + 4,
9786 ssh_agent_callback, ssh)) {
9790 bombout(("Unexpected data from server"
9791 " while waiting for agent"
9795 } while (pktin || inlen > 0);
9796 vret = ssh->agent_response;
9797 s->retlen = ssh->agent_response_len;
9802 if (s->retlen >= 9 &&
9803 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9804 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9805 logevent("Sending Pageant's response");
9806 ssh2_add_sigblob(ssh, s->pktout,
9807 s->pkblob, s->pklen,
9809 GET_32BIT(s->ret + 5));
9810 ssh2_pkt_send(ssh, s->pktout);
9811 s->type = AUTH_TYPE_PUBLICKEY;
9813 /* FIXME: less drastic response */
9814 bombout(("Pageant failed to answer challenge"));
9820 /* Do we have any keys left to try? */
9821 if (s->pkblob_in_agent) {
9822 s->done_agent = TRUE;
9823 s->tried_pubkey_config = TRUE;
9826 if (s->keyi >= s->nkeys)
9827 s->done_agent = TRUE;
9830 } else if (s->can_pubkey && s->publickey_blob &&
9831 s->privatekey_available && !s->tried_pubkey_config) {
9833 struct ssh2_userkey *key; /* not live over crReturn */
9834 char *passphrase; /* not live over crReturn */
9836 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9838 s->tried_pubkey_config = TRUE;
9841 * Try the public key supplied in the configuration.
9843 * First, offer the public blob to see if the server is
9844 * willing to accept it.
9846 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9847 ssh2_pkt_addstring(s->pktout, ssh->username);
9848 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9849 /* service requested */
9850 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9851 ssh2_pkt_addbool(s->pktout, FALSE);
9852 /* no signature included */
9853 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9854 ssh2_pkt_addstring_start(s->pktout);
9855 ssh2_pkt_addstring_data(s->pktout,
9856 (char *)s->publickey_blob,
9857 s->publickey_bloblen);
9858 ssh2_pkt_send(ssh, s->pktout);
9859 logevent("Offered public key");
9861 crWaitUntilV(pktin);
9862 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9863 /* Key refused. Give up. */
9864 s->gotit = TRUE; /* reconsider message next loop */
9865 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9866 continue; /* process this new message */
9868 logevent("Offer of public key accepted");
9871 * Actually attempt a serious authentication using
9874 if (flags & FLAG_VERBOSE) {
9875 c_write_str(ssh, "Authenticating with public key \"");
9876 c_write_str(ssh, s->publickey_comment);
9877 c_write_str(ssh, "\"\r\n");
9881 const char *error; /* not live over crReturn */
9882 if (s->privatekey_encrypted) {
9884 * Get a passphrase from the user.
9886 int ret; /* need not be kept over crReturn */
9887 s->cur_prompt = new_prompts(ssh->frontend);
9888 s->cur_prompt->to_server = FALSE;
9889 s->cur_prompt->name = dupstr("SSH key passphrase");
9890 add_prompt(s->cur_prompt,
9891 dupprintf("Passphrase for key \"%.100s\": ",
9892 s->publickey_comment),
9894 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9897 crWaitUntilV(!pktin);
9898 ret = get_userpass_input(s->cur_prompt,
9903 /* Failed to get a passphrase. Terminate. */
9904 free_prompts(s->cur_prompt);
9905 ssh_disconnect(ssh, NULL,
9906 "Unable to authenticate",
9907 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9912 dupstr(s->cur_prompt->prompts[0]->result);
9913 free_prompts(s->cur_prompt);
9915 passphrase = NULL; /* no passphrase needed */
9919 * Try decrypting the key.
9921 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9922 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9924 /* burn the evidence */
9925 smemclr(passphrase, strlen(passphrase));
9928 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9930 (key == SSH2_WRONG_PASSPHRASE)) {
9931 c_write_str(ssh, "Wrong passphrase\r\n");
9933 /* and loop again */
9935 c_write_str(ssh, "Unable to load private key (");
9936 c_write_str(ssh, error);
9937 c_write_str(ssh, ")\r\n");
9939 break; /* try something else */
9945 unsigned char *pkblob, *sigblob, *sigdata;
9946 int pkblob_len, sigblob_len, sigdata_len;
9950 * We have loaded the private key and the server
9951 * has announced that it's willing to accept it.
9952 * Hallelujah. Generate a signature and send it.
9954 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9955 ssh2_pkt_addstring(s->pktout, ssh->username);
9956 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9957 /* service requested */
9958 ssh2_pkt_addstring(s->pktout, "publickey");
9960 ssh2_pkt_addbool(s->pktout, TRUE);
9961 /* signature follows */
9962 ssh2_pkt_addstring(s->pktout, key->alg->name);
9963 pkblob = key->alg->public_blob(key->data,
9965 ssh2_pkt_addstring_start(s->pktout);
9966 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9970 * The data to be signed is:
9974 * followed by everything so far placed in the
9977 sigdata_len = s->pktout->length - 5 + 4 +
9978 ssh->v2_session_id_len;
9979 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9981 sigdata = snewn(sigdata_len, unsigned char);
9983 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9984 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9987 memcpy(sigdata+p, ssh->v2_session_id,
9988 ssh->v2_session_id_len);
9989 p += ssh->v2_session_id_len;
9990 memcpy(sigdata+p, s->pktout->data + 5,
9991 s->pktout->length - 5);
9992 p += s->pktout->length - 5;
9993 assert(p == sigdata_len);
9994 sigblob = key->alg->sign(key->data, (char *)sigdata,
9995 sigdata_len, &sigblob_len);
9996 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
9997 sigblob, sigblob_len);
10002 ssh2_pkt_send(ssh, s->pktout);
10003 logevent("Sent public key signature");
10004 s->type = AUTH_TYPE_PUBLICKEY;
10005 key->alg->freekey(key->data);
10006 sfree(key->comment);
10011 } else if (s->can_gssapi && !s->tried_gssapi) {
10013 /* GSSAPI Authentication */
10015 int micoffset, len;
10018 s->type = AUTH_TYPE_GSSAPI;
10019 s->tried_gssapi = TRUE;
10021 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
10024 * Pick the highest GSS library on the preference
10030 for (i = 0; i < ngsslibs; i++) {
10031 int want_id = conf_get_int_int(ssh->conf,
10032 CONF_ssh_gsslist, i);
10033 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
10034 if (ssh->gsslibs->libraries[j].id == want_id) {
10035 s->gsslib = &ssh->gsslibs->libraries[j];
10036 goto got_gsslib; /* double break */
10041 * We always expect to have found something in
10042 * the above loop: we only came here if there
10043 * was at least one viable GSS library, and the
10044 * preference list should always mention
10045 * everything and only change the order.
10050 if (s->gsslib->gsslogmsg)
10051 logevent(s->gsslib->gsslogmsg);
10053 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
10054 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10055 ssh2_pkt_addstring(s->pktout, ssh->username);
10056 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10057 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
10058 logevent("Attempting GSSAPI authentication");
10060 /* add mechanism info */
10061 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
10063 /* number of GSSAPI mechanisms */
10064 ssh2_pkt_adduint32(s->pktout,1);
10066 /* length of OID + 2 */
10067 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
10068 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
10070 /* length of OID */
10071 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
10073 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
10074 s->gss_buf.length);
10075 ssh2_pkt_send(ssh, s->pktout);
10076 crWaitUntilV(pktin);
10077 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
10078 logevent("GSSAPI authentication request refused");
10082 /* check returned packet ... */
10084 ssh_pkt_getstring(pktin, &data, &len);
10085 s->gss_rcvtok.value = data;
10086 s->gss_rcvtok.length = len;
10087 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
10088 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
10089 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
10090 memcmp((char *)s->gss_rcvtok.value + 2,
10091 s->gss_buf.value,s->gss_buf.length) ) {
10092 logevent("GSSAPI authentication - wrong response from server");
10096 /* now start running */
10097 s->gss_stat = s->gsslib->import_name(s->gsslib,
10100 if (s->gss_stat != SSH_GSS_OK) {
10101 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
10102 logevent("GSSAPI import name failed - Bad service name");
10104 logevent("GSSAPI import name failed");
10108 /* fetch TGT into GSS engine */
10109 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
10111 if (s->gss_stat != SSH_GSS_OK) {
10112 logevent("GSSAPI authentication failed to get credentials");
10113 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10117 /* initial tokens are empty */
10118 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
10119 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
10121 /* now enter the loop */
10123 s->gss_stat = s->gsslib->init_sec_context
10127 conf_get_int(ssh->conf, CONF_gssapifwd),
10131 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
10132 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
10133 logevent("GSSAPI authentication initialisation failed");
10135 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
10136 &s->gss_buf) == SSH_GSS_OK) {
10137 logevent(s->gss_buf.value);
10138 sfree(s->gss_buf.value);
10143 logevent("GSSAPI authentication initialised");
10145 /* Client and server now exchange tokens until GSSAPI
10146 * no longer says CONTINUE_NEEDED */
10148 if (s->gss_sndtok.length != 0) {
10149 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
10150 ssh_pkt_addstring_start(s->pktout);
10151 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
10152 ssh2_pkt_send(ssh, s->pktout);
10153 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
10156 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
10157 crWaitUntilV(pktin);
10158 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
10159 logevent("GSSAPI authentication - bad server response");
10160 s->gss_stat = SSH_GSS_FAILURE;
10163 ssh_pkt_getstring(pktin, &data, &len);
10164 s->gss_rcvtok.value = data;
10165 s->gss_rcvtok.length = len;
10167 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
10169 if (s->gss_stat != SSH_GSS_OK) {
10170 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10171 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10174 logevent("GSSAPI authentication loop finished OK");
10176 /* Now send the MIC */
10178 s->pktout = ssh2_pkt_init(0);
10179 micoffset = s->pktout->length;
10180 ssh_pkt_addstring_start(s->pktout);
10181 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
10182 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
10183 ssh_pkt_addstring(s->pktout, ssh->username);
10184 ssh_pkt_addstring(s->pktout, "ssh-connection");
10185 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
10187 s->gss_buf.value = (char *)s->pktout->data + micoffset;
10188 s->gss_buf.length = s->pktout->length - micoffset;
10190 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
10191 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
10192 ssh_pkt_addstring_start(s->pktout);
10193 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
10194 ssh2_pkt_send(ssh, s->pktout);
10195 s->gsslib->free_mic(s->gsslib, &mic);
10199 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10200 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10203 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
10206 * Keyboard-interactive authentication.
10209 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
10211 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
10213 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10214 ssh2_pkt_addstring(s->pktout, ssh->username);
10215 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10216 /* service requested */
10217 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
10219 ssh2_pkt_addstring(s->pktout, ""); /* lang */
10220 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
10221 ssh2_pkt_send(ssh, s->pktout);
10223 logevent("Attempting keyboard-interactive authentication");
10225 crWaitUntilV(pktin);
10226 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
10227 /* Server is not willing to do keyboard-interactive
10228 * at all (or, bizarrely but legally, accepts the
10229 * user without actually issuing any prompts).
10230 * Give up on it entirely. */
10232 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
10233 s->kbd_inter_refused = TRUE; /* don't try it again */
10238 * Loop while the server continues to send INFO_REQUESTs.
10240 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
10242 char *name, *inst, *lang;
10243 int name_len, inst_len, lang_len;
10247 * We've got a fresh USERAUTH_INFO_REQUEST.
10248 * Get the preamble and start building a prompt.
10250 ssh_pkt_getstring(pktin, &name, &name_len);
10251 ssh_pkt_getstring(pktin, &inst, &inst_len);
10252 ssh_pkt_getstring(pktin, &lang, &lang_len);
10253 s->cur_prompt = new_prompts(ssh->frontend);
10254 s->cur_prompt->to_server = TRUE;
10257 * Get any prompt(s) from the packet.
10259 s->num_prompts = ssh_pkt_getuint32(pktin);
10260 for (i = 0; i < s->num_prompts; i++) {
10264 static char noprompt[] =
10265 "<server failed to send prompt>: ";
10267 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10268 echo = ssh2_pkt_getbool(pktin);
10271 prompt_len = lenof(noprompt)-1;
10273 add_prompt(s->cur_prompt,
10274 dupprintf("%.*s", prompt_len, prompt),
10279 /* FIXME: better prefix to distinguish from
10280 * local prompts? */
10281 s->cur_prompt->name =
10282 dupprintf("SSH server: %.*s", name_len, name);
10283 s->cur_prompt->name_reqd = TRUE;
10285 s->cur_prompt->name =
10286 dupstr("SSH server authentication");
10287 s->cur_prompt->name_reqd = FALSE;
10289 /* We add a prefix to try to make it clear that a prompt
10290 * has come from the server.
10291 * FIXME: ugly to print "Using..." in prompt _every_
10292 * time round. Can this be done more subtly? */
10293 /* Special case: for reasons best known to themselves,
10294 * some servers send k-i requests with no prompts and
10295 * nothing to display. Keep quiet in this case. */
10296 if (s->num_prompts || name_len || inst_len) {
10297 s->cur_prompt->instruction =
10298 dupprintf("Using keyboard-interactive authentication.%s%.*s",
10299 inst_len ? "\n" : "", inst_len, inst);
10300 s->cur_prompt->instr_reqd = TRUE;
10302 s->cur_prompt->instr_reqd = FALSE;
10306 * Display any instructions, and get the user's
10310 int ret; /* not live over crReturn */
10311 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10314 crWaitUntilV(!pktin);
10315 ret = get_userpass_input(s->cur_prompt, in, inlen);
10320 * Failed to get responses. Terminate.
10322 free_prompts(s->cur_prompt);
10323 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10324 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10331 * Send the response(s) to the server.
10333 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
10334 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
10335 for (i=0; i < s->num_prompts; i++) {
10336 ssh2_pkt_addstring(s->pktout,
10337 s->cur_prompt->prompts[i]->result);
10339 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10342 * Free the prompts structure from this iteration.
10343 * If there's another, a new one will be allocated
10344 * when we return to the top of this while loop.
10346 free_prompts(s->cur_prompt);
10349 * Get the next packet in case it's another
10352 crWaitUntilV(pktin);
10357 * We should have SUCCESS or FAILURE now.
10361 } else if (s->can_passwd) {
10364 * Plain old password authentication.
10366 int ret; /* not live over crReturn */
10367 int changereq_first_time; /* not live over crReturn */
10369 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10371 s->cur_prompt = new_prompts(ssh->frontend);
10372 s->cur_prompt->to_server = TRUE;
10373 s->cur_prompt->name = dupstr("SSH password");
10374 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10379 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10382 crWaitUntilV(!pktin);
10383 ret = get_userpass_input(s->cur_prompt, in, inlen);
10388 * Failed to get responses. Terminate.
10390 free_prompts(s->cur_prompt);
10391 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10392 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10397 * Squirrel away the password. (We may need it later if
10398 * asked to change it.)
10400 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10401 free_prompts(s->cur_prompt);
10404 * Send the password packet.
10406 * We pad out the password packet to 256 bytes to make
10407 * it harder for an attacker to find the length of the
10410 * Anyone using a password longer than 256 bytes
10411 * probably doesn't have much to worry about from
10412 * people who find out how long their password is!
10414 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10415 ssh2_pkt_addstring(s->pktout, ssh->username);
10416 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10417 /* service requested */
10418 ssh2_pkt_addstring(s->pktout, "password");
10419 ssh2_pkt_addbool(s->pktout, FALSE);
10420 ssh2_pkt_addstring(s->pktout, s->password);
10421 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10422 logevent("Sent password");
10423 s->type = AUTH_TYPE_PASSWORD;
10426 * Wait for next packet, in case it's a password change
10429 crWaitUntilV(pktin);
10430 changereq_first_time = TRUE;
10432 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10435 * We're being asked for a new password
10436 * (perhaps not for the first time).
10437 * Loop until the server accepts it.
10440 int got_new = FALSE; /* not live over crReturn */
10441 char *prompt; /* not live over crReturn */
10442 int prompt_len; /* not live over crReturn */
10446 if (changereq_first_time)
10447 msg = "Server requested password change";
10449 msg = "Server rejected new password";
10451 c_write_str(ssh, msg);
10452 c_write_str(ssh, "\r\n");
10455 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10457 s->cur_prompt = new_prompts(ssh->frontend);
10458 s->cur_prompt->to_server = TRUE;
10459 s->cur_prompt->name = dupstr("New SSH password");
10460 s->cur_prompt->instruction =
10461 dupprintf("%.*s", prompt_len, NULLTOEMPTY(prompt));
10462 s->cur_prompt->instr_reqd = TRUE;
10464 * There's no explicit requirement in the protocol
10465 * for the "old" passwords in the original and
10466 * password-change messages to be the same, and
10467 * apparently some Cisco kit supports password change
10468 * by the user entering a blank password originally
10469 * and the real password subsequently, so,
10470 * reluctantly, we prompt for the old password again.
10472 * (On the other hand, some servers don't even bother
10473 * to check this field.)
10475 add_prompt(s->cur_prompt,
10476 dupstr("Current password (blank for previously entered password): "),
10478 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10480 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10484 * Loop until the user manages to enter the same
10489 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10492 crWaitUntilV(!pktin);
10493 ret = get_userpass_input(s->cur_prompt, in, inlen);
10498 * Failed to get responses. Terminate.
10500 /* burn the evidence */
10501 free_prompts(s->cur_prompt);
10502 smemclr(s->password, strlen(s->password));
10503 sfree(s->password);
10504 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10505 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10511 * If the user specified a new original password
10512 * (IYSWIM), overwrite any previously specified
10514 * (A side effect is that the user doesn't have to
10515 * re-enter it if they louse up the new password.)
10517 if (s->cur_prompt->prompts[0]->result[0]) {
10518 smemclr(s->password, strlen(s->password));
10519 /* burn the evidence */
10520 sfree(s->password);
10522 dupstr(s->cur_prompt->prompts[0]->result);
10526 * Check the two new passwords match.
10528 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10529 s->cur_prompt->prompts[2]->result)
10532 /* They don't. Silly user. */
10533 c_write_str(ssh, "Passwords do not match\r\n");
10538 * Send the new password (along with the old one).
10539 * (see above for padding rationale)
10541 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10542 ssh2_pkt_addstring(s->pktout, ssh->username);
10543 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10544 /* service requested */
10545 ssh2_pkt_addstring(s->pktout, "password");
10546 ssh2_pkt_addbool(s->pktout, TRUE);
10547 ssh2_pkt_addstring(s->pktout, s->password);
10548 ssh2_pkt_addstring(s->pktout,
10549 s->cur_prompt->prompts[1]->result);
10550 free_prompts(s->cur_prompt);
10551 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10552 logevent("Sent new password");
10555 * Now see what the server has to say about it.
10556 * (If it's CHANGEREQ again, it's not happy with the
10559 crWaitUntilV(pktin);
10560 changereq_first_time = FALSE;
10565 * We need to reexamine the current pktin at the top
10566 * of the loop. Either:
10567 * - we weren't asked to change password at all, in
10568 * which case it's a SUCCESS or FAILURE with the
10570 * - we sent a new password, and the server was
10571 * either OK with it (SUCCESS or FAILURE w/partial
10572 * success) or unhappy with the _old_ password
10573 * (FAILURE w/o partial success)
10574 * In any of these cases, we go back to the top of
10575 * the loop and start again.
10580 * We don't need the old password any more, in any
10581 * case. Burn the evidence.
10583 smemclr(s->password, strlen(s->password));
10584 sfree(s->password);
10587 char *str = dupprintf("No supported authentication methods available"
10588 " (server sent: %.*s)",
10591 ssh_disconnect(ssh, str,
10592 "No supported authentication methods available",
10593 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10603 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10605 /* Clear up various bits and pieces from authentication. */
10606 if (s->publickey_blob) {
10607 sfree(s->publickey_algorithm);
10608 sfree(s->publickey_blob);
10609 sfree(s->publickey_comment);
10611 if (s->agent_response)
10612 sfree(s->agent_response);
10614 if (s->userauth_success && !ssh->bare_connection) {
10616 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10617 * packets since. Signal the transport layer to consider enacting
10618 * delayed compression.
10620 * (Relying on we_are_in is not sufficient, as
10621 * draft-miller-secsh-compression-delayed is quite clear that it
10622 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10623 * become set for other reasons.)
10625 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10628 ssh->channels = newtree234(ssh_channelcmp);
10631 * Set up handlers for some connection protocol messages, so we
10632 * don't have to handle them repeatedly in this coroutine.
10634 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10635 ssh2_msg_channel_window_adjust;
10636 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10637 ssh2_msg_global_request;
10640 * Create the main session channel.
10642 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10643 ssh->mainchan = NULL;
10645 ssh->mainchan = snew(struct ssh_channel);
10646 ssh->mainchan->ssh = ssh;
10647 ssh_channel_init(ssh->mainchan);
10649 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10651 * Just start a direct-tcpip channel and use it as the main
10654 ssh_send_port_open(ssh->mainchan,
10655 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10656 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10658 ssh->ncmode = TRUE;
10660 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10661 logevent("Opening session as main channel");
10662 ssh2_pkt_send(ssh, s->pktout);
10663 ssh->ncmode = FALSE;
10665 crWaitUntilV(pktin);
10666 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10667 bombout(("Server refused to open channel"));
10669 /* FIXME: error data comes back in FAILURE packet */
10671 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10672 bombout(("Server's channel confirmation cited wrong channel"));
10675 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10676 ssh->mainchan->halfopen = FALSE;
10677 ssh->mainchan->type = CHAN_MAINSESSION;
10678 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10679 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10680 add234(ssh->channels, ssh->mainchan);
10681 update_specials_menu(ssh->frontend);
10682 logevent("Opened main channel");
10686 * Now we have a channel, make dispatch table entries for
10687 * general channel-based messages.
10689 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10690 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10691 ssh2_msg_channel_data;
10692 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10693 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10694 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10695 ssh2_msg_channel_open_confirmation;
10696 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10697 ssh2_msg_channel_open_failure;
10698 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10699 ssh2_msg_channel_request;
10700 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10701 ssh2_msg_channel_open;
10702 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10703 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10706 * Now the connection protocol is properly up and running, with
10707 * all those dispatch table entries, so it's safe to let
10708 * downstreams start trying to open extra channels through us.
10710 if (ssh->connshare)
10711 share_activate(ssh->connshare, ssh->v_s);
10713 if (ssh->mainchan && ssh_is_simple(ssh)) {
10715 * This message indicates to the server that we promise
10716 * not to try to run any other channel in parallel with
10717 * this one, so it's safe for it to advertise a very large
10718 * window and leave the flow control to TCP.
10720 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10721 "simple@putty.projects.tartarus.org",
10723 ssh2_pkt_send(ssh, s->pktout);
10727 * Enable port forwardings.
10729 ssh_setup_portfwd(ssh, ssh->conf);
10731 if (ssh->mainchan && !ssh->ncmode) {
10733 * Send the CHANNEL_REQUESTS for the main session channel.
10734 * Each one is handled by its own little asynchronous
10738 /* Potentially enable X11 forwarding. */
10739 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10741 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10743 if (!ssh->x11disp) {
10744 /* FIXME: return an error message from x11_setup_display */
10745 logevent("X11 forwarding not enabled: unable to"
10746 " initialise X display");
10748 ssh->x11auth = x11_invent_fake_auth
10749 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10750 ssh->x11auth->disp = ssh->x11disp;
10752 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10756 /* Potentially enable agent forwarding. */
10757 if (ssh_agent_forwarding_permitted(ssh))
10758 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10760 /* Now allocate a pty for the session. */
10761 if (!conf_get_int(ssh->conf, CONF_nopty))
10762 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10764 /* Send environment variables. */
10765 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10768 * Start a shell or a remote command. We may have to attempt
10769 * this twice if the config data has provided a second choice
10776 if (ssh->fallback_cmd) {
10777 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10778 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10780 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10781 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10785 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10786 ssh2_response_authconn, NULL);
10787 ssh2_pkt_addstring(s->pktout, cmd);
10789 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10790 ssh2_response_authconn, NULL);
10791 ssh2_pkt_addstring(s->pktout, cmd);
10793 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10794 ssh2_response_authconn, NULL);
10796 ssh2_pkt_send(ssh, s->pktout);
10798 crWaitUntilV(pktin);
10800 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10801 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10802 bombout(("Unexpected response to shell/command request:"
10803 " packet type %d", pktin->type));
10807 * We failed to start the command. If this is the
10808 * fallback command, we really are finished; if it's
10809 * not, and if the fallback command exists, try falling
10810 * back to it before complaining.
10812 if (!ssh->fallback_cmd &&
10813 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10814 logevent("Primary command failed; attempting fallback");
10815 ssh->fallback_cmd = TRUE;
10818 bombout(("Server refused to start a shell/command"));
10821 logevent("Started a shell/command");
10826 ssh->editing = ssh->echoing = TRUE;
10829 ssh->state = SSH_STATE_SESSION;
10830 if (ssh->size_needed)
10831 ssh_size(ssh, ssh->term_width, ssh->term_height);
10832 if (ssh->eof_needed)
10833 ssh_special(ssh, TS_EOF);
10839 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10847 * _All_ the connection-layer packets we expect to
10848 * receive are now handled by the dispatch table.
10849 * Anything that reaches here must be bogus.
10852 bombout(("Strange packet received: type %d", pktin->type));
10854 } else if (ssh->mainchan) {
10856 * We have spare data. Add it to the channel buffer.
10858 ssh_send_channel_data(ssh->mainchan, (char *)in, inlen);
10866 * Handlers for SSH-2 messages that might arrive at any moment.
10868 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10870 /* log reason code in disconnect message */
10872 int reason, msglen;
10874 reason = ssh_pkt_getuint32(pktin);
10875 ssh_pkt_getstring(pktin, &msg, &msglen);
10877 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10878 buf = dupprintf("Received disconnect message (%s)",
10879 ssh2_disconnect_reasons[reason]);
10881 buf = dupprintf("Received disconnect message (unknown"
10882 " type %d)", reason);
10886 buf = dupprintf("Disconnection message text: %.*s",
10887 msglen, NULLTOEMPTY(msg));
10889 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10891 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10892 ssh2_disconnect_reasons[reason] : "unknown",
10893 msglen, NULLTOEMPTY(msg)));
10897 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10899 /* log the debug message */
10903 /* XXX maybe we should actually take notice of the return value */
10904 ssh2_pkt_getbool(pktin);
10905 ssh_pkt_getstring(pktin, &msg, &msglen);
10907 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
10910 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10912 do_ssh2_transport(ssh, NULL, 0, pktin);
10916 * Called if we receive a packet that isn't allowed by the protocol.
10917 * This only applies to packets whose meaning PuTTY understands.
10918 * Entirely unknown packets are handled below.
10920 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10922 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10923 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10925 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10929 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10931 struct Packet *pktout;
10932 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10933 ssh2_pkt_adduint32(pktout, pktin->sequence);
10935 * UNIMPLEMENTED messages MUST appear in the same order as the
10936 * messages they respond to. Hence, never queue them.
10938 ssh2_pkt_send_noqueue(ssh, pktout);
10942 * Handle the top-level SSH-2 protocol.
10944 static void ssh2_protocol_setup(Ssh ssh)
10949 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10951 for (i = 0; i < 256; i++)
10952 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10955 * Initially, we only accept transport messages (and a few generic
10956 * ones). do_ssh2_authconn will add more when it starts.
10957 * Messages that are understood but not currently acceptable go to
10958 * ssh2_msg_unexpected.
10960 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10961 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10962 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10963 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10964 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10965 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10966 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10967 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10968 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10969 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10970 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10971 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10972 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10973 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10974 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10975 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10976 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10977 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10978 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10979 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10980 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10981 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10982 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10983 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10984 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10985 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10986 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10987 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10988 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10989 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10990 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10991 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10992 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10995 * These messages have a special handler from the start.
10997 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10998 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
10999 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11002 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
11007 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
11009 for (i = 0; i < 256; i++)
11010 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
11013 * Initially, we set all ssh-connection messages to 'unexpected';
11014 * do_ssh2_authconn will fill things in properly. We also handle a
11015 * couple of messages from the transport protocol which aren't
11016 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
11019 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
11020 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
11021 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
11022 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
11023 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
11024 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
11025 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
11026 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
11027 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
11028 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
11029 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
11030 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
11031 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
11032 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
11034 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
11037 * These messages have a special handler from the start.
11039 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11040 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
11041 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11044 static void ssh2_timer(void *ctx, unsigned long now)
11046 Ssh ssh = (Ssh)ctx;
11048 if (ssh->state == SSH_STATE_CLOSED)
11051 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11052 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
11053 now == ssh->next_rekey) {
11054 do_ssh2_transport(ssh, "timeout", -1, NULL);
11058 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
11059 struct Packet *pktin)
11061 const unsigned char *in = (const unsigned char *)vin;
11062 if (ssh->state == SSH_STATE_CLOSED)
11066 ssh->incoming_data_size += pktin->encrypted_len;
11067 if (!ssh->kex_in_progress &&
11068 ssh->max_data_size != 0 &&
11069 ssh->incoming_data_size > ssh->max_data_size)
11070 do_ssh2_transport(ssh, "too much data received", -1, NULL);
11074 ssh->packet_dispatch[pktin->type](ssh, pktin);
11075 else if (!ssh->protocol_initial_phase_done)
11076 do_ssh2_transport(ssh, in, inlen, pktin);
11078 do_ssh2_authconn(ssh, in, inlen, pktin);
11081 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
11082 struct Packet *pktin)
11084 const unsigned char *in = (const unsigned char *)vin;
11085 if (ssh->state == SSH_STATE_CLOSED)
11089 ssh->packet_dispatch[pktin->type](ssh, pktin);
11091 do_ssh2_authconn(ssh, in, inlen, pktin);
11094 static void ssh_cache_conf_values(Ssh ssh)
11096 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
11100 * Called to set up the connection.
11102 * Returns an error message, or NULL on success.
11104 static const char *ssh_init(void *frontend_handle, void **backend_handle,
11106 const char *host, int port, char **realhost,
11107 int nodelay, int keepalive)
11112 ssh = snew(struct ssh_tag);
11113 ssh->conf = conf_copy(conf);
11114 ssh_cache_conf_values(ssh);
11115 ssh->version = 0; /* when not ready yet */
11117 ssh->cipher = NULL;
11118 ssh->v1_cipher_ctx = NULL;
11119 ssh->crcda_ctx = NULL;
11120 ssh->cscipher = NULL;
11121 ssh->cs_cipher_ctx = NULL;
11122 ssh->sccipher = NULL;
11123 ssh->sc_cipher_ctx = NULL;
11125 ssh->cs_mac_ctx = NULL;
11127 ssh->sc_mac_ctx = NULL;
11128 ssh->cscomp = NULL;
11129 ssh->cs_comp_ctx = NULL;
11130 ssh->sccomp = NULL;
11131 ssh->sc_comp_ctx = NULL;
11133 ssh->kex_ctx = NULL;
11134 ssh->hostkey = NULL;
11135 ssh->hostkey_str = NULL;
11136 ssh->exitcode = -1;
11137 ssh->close_expected = FALSE;
11138 ssh->clean_exit = FALSE;
11139 ssh->state = SSH_STATE_PREPACKET;
11140 ssh->size_needed = FALSE;
11141 ssh->eof_needed = FALSE;
11143 ssh->logctx = NULL;
11144 ssh->deferred_send_data = NULL;
11145 ssh->deferred_len = 0;
11146 ssh->deferred_size = 0;
11147 ssh->fallback_cmd = 0;
11148 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
11149 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
11150 ssh->x11disp = NULL;
11151 ssh->x11auth = NULL;
11152 ssh->x11authtree = newtree234(x11_authcmp);
11153 ssh->v1_compressing = FALSE;
11154 ssh->v2_outgoing_sequence = 0;
11155 ssh->ssh1_rdpkt_crstate = 0;
11156 ssh->ssh2_rdpkt_crstate = 0;
11157 ssh->ssh2_bare_rdpkt_crstate = 0;
11158 ssh->ssh_gotdata_crstate = 0;
11159 ssh->do_ssh1_connection_crstate = 0;
11160 ssh->do_ssh_init_state = NULL;
11161 ssh->do_ssh_connection_init_state = NULL;
11162 ssh->do_ssh1_login_state = NULL;
11163 ssh->do_ssh2_transport_state = NULL;
11164 ssh->do_ssh2_authconn_state = NULL;
11167 ssh->mainchan = NULL;
11168 ssh->throttled_all = 0;
11169 ssh->v1_stdout_throttling = 0;
11171 ssh->queuelen = ssh->queuesize = 0;
11172 ssh->queueing = FALSE;
11173 ssh->qhead = ssh->qtail = NULL;
11174 ssh->deferred_rekey_reason = NULL;
11175 bufchain_init(&ssh->queued_incoming_data);
11176 ssh->frozen = FALSE;
11177 ssh->username = NULL;
11178 ssh->sent_console_eof = FALSE;
11179 ssh->got_pty = FALSE;
11180 ssh->bare_connection = FALSE;
11181 ssh->X11_fwd_enabled = FALSE;
11182 ssh->connshare = NULL;
11183 ssh->attempting_connshare = FALSE;
11184 ssh->session_started = FALSE;
11185 ssh->specials = NULL;
11186 ssh->n_uncert_hostkeys = 0;
11187 ssh->cross_certifying = FALSE;
11189 *backend_handle = ssh;
11192 if (crypto_startup() == 0)
11193 return "Microsoft high encryption pack not installed!";
11196 ssh->frontend = frontend_handle;
11197 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
11198 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
11200 ssh->channels = NULL;
11201 ssh->rportfwds = NULL;
11202 ssh->portfwds = NULL;
11207 ssh->conn_throttle_count = 0;
11208 ssh->overall_bufsize = 0;
11209 ssh->fallback_cmd = 0;
11211 ssh->protocol = NULL;
11213 ssh->protocol_initial_phase_done = FALSE;
11215 ssh->pinger = NULL;
11217 ssh->incoming_data_size = ssh->outgoing_data_size =
11218 ssh->deferred_data_size = 0L;
11219 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11220 CONF_ssh_rekey_data));
11221 ssh->kex_in_progress = FALSE;
11224 ssh->gsslibs = NULL;
11227 random_ref(); /* do this now - may be needed by sharing setup code */
11229 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
11238 static void ssh_free(void *handle)
11240 Ssh ssh = (Ssh) handle;
11241 struct ssh_channel *c;
11242 struct ssh_rportfwd *pf;
11243 struct X11FakeAuth *auth;
11245 if (ssh->v1_cipher_ctx)
11246 ssh->cipher->free_context(ssh->v1_cipher_ctx);
11247 if (ssh->cs_cipher_ctx)
11248 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
11249 if (ssh->sc_cipher_ctx)
11250 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
11251 if (ssh->cs_mac_ctx)
11252 ssh->csmac->free_context(ssh->cs_mac_ctx);
11253 if (ssh->sc_mac_ctx)
11254 ssh->scmac->free_context(ssh->sc_mac_ctx);
11255 if (ssh->cs_comp_ctx) {
11257 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
11259 zlib_compress_cleanup(ssh->cs_comp_ctx);
11261 if (ssh->sc_comp_ctx) {
11263 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
11265 zlib_decompress_cleanup(ssh->sc_comp_ctx);
11268 dh_cleanup(ssh->kex_ctx);
11269 sfree(ssh->savedhost);
11271 while (ssh->queuelen-- > 0)
11272 ssh_free_packet(ssh->queue[ssh->queuelen]);
11275 while (ssh->qhead) {
11276 struct queued_handler *qh = ssh->qhead;
11277 ssh->qhead = qh->next;
11280 ssh->qhead = ssh->qtail = NULL;
11282 if (ssh->channels) {
11283 while ((c = delpos234(ssh->channels, 0)) != NULL) {
11286 if (c->u.x11.xconn != NULL)
11287 x11_close(c->u.x11.xconn);
11289 case CHAN_SOCKDATA:
11290 case CHAN_SOCKDATA_DORMANT:
11291 if (c->u.pfd.pf != NULL)
11292 pfd_close(c->u.pfd.pf);
11295 if (ssh->version == 2) {
11296 struct outstanding_channel_request *ocr, *nocr;
11297 ocr = c->v.v2.chanreq_head;
11299 ocr->handler(c, NULL, ocr->ctx);
11304 bufchain_clear(&c->v.v2.outbuffer);
11308 freetree234(ssh->channels);
11309 ssh->channels = NULL;
11312 if (ssh->connshare)
11313 sharestate_free(ssh->connshare);
11315 if (ssh->rportfwds) {
11316 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
11318 freetree234(ssh->rportfwds);
11319 ssh->rportfwds = NULL;
11321 sfree(ssh->deferred_send_data);
11323 x11_free_display(ssh->x11disp);
11324 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
11325 x11_free_fake_auth(auth);
11326 freetree234(ssh->x11authtree);
11327 sfree(ssh->do_ssh_init_state);
11328 sfree(ssh->do_ssh1_login_state);
11329 sfree(ssh->do_ssh2_transport_state);
11330 sfree(ssh->do_ssh2_authconn_state);
11333 sfree(ssh->fullhostname);
11334 sfree(ssh->hostkey_str);
11335 sfree(ssh->specials);
11336 if (ssh->crcda_ctx) {
11337 crcda_free_context(ssh->crcda_ctx);
11338 ssh->crcda_ctx = NULL;
11341 ssh_do_close(ssh, TRUE);
11342 expire_timer_context(ssh);
11344 pinger_free(ssh->pinger);
11345 bufchain_clear(&ssh->queued_incoming_data);
11346 sfree(ssh->username);
11347 conf_free(ssh->conf);
11350 ssh_gss_cleanup(ssh->gsslibs);
11358 * Reconfigure the SSH backend.
11360 static void ssh_reconfig(void *handle, Conf *conf)
11362 Ssh ssh = (Ssh) handle;
11363 const char *rekeying = NULL;
11364 int rekey_mandatory = FALSE;
11365 unsigned long old_max_data_size;
11368 pinger_reconfig(ssh->pinger, ssh->conf, conf);
11370 ssh_setup_portfwd(ssh, conf);
11372 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11373 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11375 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11376 unsigned long now = GETTICKCOUNT();
11378 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11379 rekeying = "timeout shortened";
11381 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11385 old_max_data_size = ssh->max_data_size;
11386 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11387 CONF_ssh_rekey_data));
11388 if (old_max_data_size != ssh->max_data_size &&
11389 ssh->max_data_size != 0) {
11390 if (ssh->outgoing_data_size > ssh->max_data_size ||
11391 ssh->incoming_data_size > ssh->max_data_size)
11392 rekeying = "data limit lowered";
11395 if (conf_get_int(ssh->conf, CONF_compression) !=
11396 conf_get_int(conf, CONF_compression)) {
11397 rekeying = "compression setting changed";
11398 rekey_mandatory = TRUE;
11401 for (i = 0; i < CIPHER_MAX; i++)
11402 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11403 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11404 rekeying = "cipher settings changed";
11405 rekey_mandatory = TRUE;
11407 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11408 conf_get_int(conf, CONF_ssh2_des_cbc)) {
11409 rekeying = "cipher settings changed";
11410 rekey_mandatory = TRUE;
11413 conf_free(ssh->conf);
11414 ssh->conf = conf_copy(conf);
11415 ssh_cache_conf_values(ssh);
11417 if (!ssh->bare_connection && rekeying) {
11418 if (!ssh->kex_in_progress) {
11419 do_ssh2_transport(ssh, rekeying, -1, NULL);
11420 } else if (rekey_mandatory) {
11421 ssh->deferred_rekey_reason = rekeying;
11427 * Called to send data down the SSH connection.
11429 static int ssh_send(void *handle, const char *buf, int len)
11431 Ssh ssh = (Ssh) handle;
11433 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11436 ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
11438 return ssh_sendbuffer(ssh);
11442 * Called to query the current amount of buffered stdin data.
11444 static int ssh_sendbuffer(void *handle)
11446 Ssh ssh = (Ssh) handle;
11447 int override_value;
11449 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11453 * If the SSH socket itself has backed up, add the total backup
11454 * size on that to any individual buffer on the stdin channel.
11456 override_value = 0;
11457 if (ssh->throttled_all)
11458 override_value = ssh->overall_bufsize;
11460 if (ssh->version == 1) {
11461 return override_value;
11462 } else if (ssh->version == 2) {
11463 if (!ssh->mainchan)
11464 return override_value;
11466 return (override_value +
11467 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11474 * Called to set the size of the window from SSH's POV.
11476 static void ssh_size(void *handle, int width, int height)
11478 Ssh ssh = (Ssh) handle;
11479 struct Packet *pktout;
11481 ssh->term_width = width;
11482 ssh->term_height = height;
11484 switch (ssh->state) {
11485 case SSH_STATE_BEFORE_SIZE:
11486 case SSH_STATE_PREPACKET:
11487 case SSH_STATE_CLOSED:
11488 break; /* do nothing */
11489 case SSH_STATE_INTERMED:
11490 ssh->size_needed = TRUE; /* buffer for later */
11492 case SSH_STATE_SESSION:
11493 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11494 if (ssh->version == 1) {
11495 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11496 PKT_INT, ssh->term_height,
11497 PKT_INT, ssh->term_width,
11498 PKT_INT, 0, PKT_INT, 0, PKT_END);
11499 } else if (ssh->mainchan) {
11500 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11502 ssh2_pkt_adduint32(pktout, ssh->term_width);
11503 ssh2_pkt_adduint32(pktout, ssh->term_height);
11504 ssh2_pkt_adduint32(pktout, 0);
11505 ssh2_pkt_adduint32(pktout, 0);
11506 ssh2_pkt_send(ssh, pktout);
11514 * Return a list of the special codes that make sense in this
11517 static const struct telnet_special *ssh_get_specials(void *handle)
11519 static const struct telnet_special ssh1_ignore_special[] = {
11520 {"IGNORE message", TS_NOP}
11522 static const struct telnet_special ssh2_ignore_special[] = {
11523 {"IGNORE message", TS_NOP},
11525 static const struct telnet_special ssh2_rekey_special[] = {
11526 {"Repeat key exchange", TS_REKEY},
11528 static const struct telnet_special ssh2_session_specials[] = {
11531 /* These are the signal names defined by RFC 4254.
11532 * They include all the ISO C signals, but are a subset of the POSIX
11533 * required signals. */
11534 {"SIGINT (Interrupt)", TS_SIGINT},
11535 {"SIGTERM (Terminate)", TS_SIGTERM},
11536 {"SIGKILL (Kill)", TS_SIGKILL},
11537 {"SIGQUIT (Quit)", TS_SIGQUIT},
11538 {"SIGHUP (Hangup)", TS_SIGHUP},
11539 {"More signals", TS_SUBMENU},
11540 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11541 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11542 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11543 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11544 {NULL, TS_EXITMENU}
11546 static const struct telnet_special specials_end[] = {
11547 {NULL, TS_EXITMENU}
11550 struct telnet_special *specials = NULL;
11551 int nspecials = 0, specialsize = 0;
11553 Ssh ssh = (Ssh) handle;
11555 sfree(ssh->specials);
11557 #define ADD_SPECIALS(name) do \
11559 int len = lenof(name); \
11560 if (nspecials + len > specialsize) { \
11561 specialsize = (nspecials + len) * 5 / 4 + 32; \
11562 specials = sresize(specials, specialsize, struct telnet_special); \
11564 memcpy(specials+nspecials, name, len*sizeof(struct telnet_special)); \
11565 nspecials += len; \
11568 if (ssh->version == 1) {
11569 /* Don't bother offering IGNORE if we've decided the remote
11570 * won't cope with it, since we wouldn't bother sending it if
11572 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11573 ADD_SPECIALS(ssh1_ignore_special);
11574 } else if (ssh->version == 2) {
11575 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11576 ADD_SPECIALS(ssh2_ignore_special);
11577 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11578 ADD_SPECIALS(ssh2_rekey_special);
11580 ADD_SPECIALS(ssh2_session_specials);
11582 if (ssh->n_uncert_hostkeys) {
11583 static const struct telnet_special uncert_start[] = {
11585 {"Cache new host key type", TS_SUBMENU},
11587 static const struct telnet_special uncert_end[] = {
11588 {NULL, TS_EXITMENU},
11592 ADD_SPECIALS(uncert_start);
11593 for (i = 0; i < ssh->n_uncert_hostkeys; i++) {
11594 struct telnet_special uncert[1];
11595 const struct ssh_signkey *alg =
11596 hostkey_algs[ssh->uncert_hostkeys[i]].alg;
11597 uncert[0].name = alg->name;
11598 uncert[0].code = TS_LOCALSTART + ssh->uncert_hostkeys[i];
11599 ADD_SPECIALS(uncert);
11601 ADD_SPECIALS(uncert_end);
11603 } /* else we're not ready yet */
11606 ADD_SPECIALS(specials_end);
11608 ssh->specials = specials;
11615 #undef ADD_SPECIALS
11619 * Send special codes. TS_EOF is useful for `plink', so you
11620 * can send an EOF and collect resulting output (e.g. `plink
11623 static void ssh_special(void *handle, Telnet_Special code)
11625 Ssh ssh = (Ssh) handle;
11626 struct Packet *pktout;
11628 if (code == TS_EOF) {
11629 if (ssh->state != SSH_STATE_SESSION) {
11631 * Buffer the EOF in case we are pre-SESSION, so we can
11632 * send it as soon as we reach SESSION.
11634 if (code == TS_EOF)
11635 ssh->eof_needed = TRUE;
11638 if (ssh->version == 1) {
11639 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11640 } else if (ssh->mainchan) {
11641 sshfwd_write_eof(ssh->mainchan);
11642 ssh->send_ok = 0; /* now stop trying to read from stdin */
11644 logevent("Sent EOF message");
11645 } else if (code == TS_PING || code == TS_NOP) {
11646 if (ssh->state == SSH_STATE_CLOSED
11647 || ssh->state == SSH_STATE_PREPACKET) return;
11648 if (ssh->version == 1) {
11649 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11650 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11652 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11653 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11654 ssh2_pkt_addstring_start(pktout);
11655 ssh2_pkt_send_noqueue(ssh, pktout);
11658 } else if (code == TS_REKEY) {
11659 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11660 ssh->version == 2) {
11661 do_ssh2_transport(ssh, "at user request", -1, NULL);
11663 } else if (code >= TS_LOCALSTART) {
11664 ssh->hostkey = hostkey_algs[code - TS_LOCALSTART].alg;
11665 ssh->cross_certifying = TRUE;
11666 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11667 ssh->version == 2) {
11668 do_ssh2_transport(ssh, "cross-certifying new host key", -1, NULL);
11670 } else if (code == TS_BRK) {
11671 if (ssh->state == SSH_STATE_CLOSED
11672 || ssh->state == SSH_STATE_PREPACKET) return;
11673 if (ssh->version == 1) {
11674 logevent("Unable to send BREAK signal in SSH-1");
11675 } else if (ssh->mainchan) {
11676 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11677 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11678 ssh2_pkt_send(ssh, pktout);
11681 /* Is is a POSIX signal? */
11682 const char *signame = NULL;
11683 if (code == TS_SIGABRT) signame = "ABRT";
11684 if (code == TS_SIGALRM) signame = "ALRM";
11685 if (code == TS_SIGFPE) signame = "FPE";
11686 if (code == TS_SIGHUP) signame = "HUP";
11687 if (code == TS_SIGILL) signame = "ILL";
11688 if (code == TS_SIGINT) signame = "INT";
11689 if (code == TS_SIGKILL) signame = "KILL";
11690 if (code == TS_SIGPIPE) signame = "PIPE";
11691 if (code == TS_SIGQUIT) signame = "QUIT";
11692 if (code == TS_SIGSEGV) signame = "SEGV";
11693 if (code == TS_SIGTERM) signame = "TERM";
11694 if (code == TS_SIGUSR1) signame = "USR1";
11695 if (code == TS_SIGUSR2) signame = "USR2";
11696 /* The SSH-2 protocol does in principle support arbitrary named
11697 * signals, including signame@domain, but we don't support those. */
11699 /* It's a signal. */
11700 if (ssh->version == 2 && ssh->mainchan) {
11701 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11702 ssh2_pkt_addstring(pktout, signame);
11703 ssh2_pkt_send(ssh, pktout);
11704 logeventf(ssh, "Sent signal SIG%s", signame);
11707 /* Never heard of it. Do nothing */
11712 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11714 Ssh ssh = (Ssh) handle;
11715 struct ssh_channel *c;
11716 c = snew(struct ssh_channel);
11719 ssh_channel_init(c);
11720 c->halfopen = TRUE;
11721 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11723 add234(ssh->channels, c);
11727 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11729 struct ssh_channel *c;
11730 c = snew(struct ssh_channel);
11733 ssh_channel_init(c);
11734 c->type = CHAN_SHARING;
11735 c->u.sharing.ctx = sharing_ctx;
11736 add234(ssh->channels, c);
11740 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11742 struct ssh_channel *c;
11744 c = find234(ssh->channels, &localid, ssh_channelfind);
11746 ssh_channel_destroy(c);
11749 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11750 const void *data, int datalen,
11751 const char *additional_log_text)
11753 struct Packet *pkt;
11755 pkt = ssh2_pkt_init(type);
11756 pkt->downstream_id = id;
11757 pkt->additional_log_text = additional_log_text;
11758 ssh2_pkt_adddata(pkt, data, datalen);
11759 ssh2_pkt_send(ssh, pkt);
11763 * This is called when stdout/stderr (the entity to which
11764 * from_backend sends data) manages to clear some backlog.
11766 static void ssh_unthrottle(void *handle, int bufsize)
11768 Ssh ssh = (Ssh) handle;
11770 if (ssh->version == 1) {
11771 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11772 ssh->v1_stdout_throttling = 0;
11773 ssh_throttle_conn(ssh, -1);
11777 ssh_channel_unthrottle(ssh->mainchan, bufsize);
11781 * Now process any SSH connection data that was stashed in our
11782 * queue while we were frozen.
11784 ssh_process_queued_incoming_data(ssh);
11787 void ssh_send_port_open(void *channel, const char *hostname, int port,
11790 struct ssh_channel *c = (struct ssh_channel *)channel;
11792 struct Packet *pktout;
11794 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11796 if (ssh->version == 1) {
11797 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11798 PKT_INT, c->localid,
11801 /* PKT_STR, <org:orgport>, */
11804 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11806 char *trimmed_host = host_strduptrim(hostname);
11807 ssh2_pkt_addstring(pktout, trimmed_host);
11808 sfree(trimmed_host);
11810 ssh2_pkt_adduint32(pktout, port);
11812 * We make up values for the originator data; partly it's
11813 * too much hassle to keep track, and partly I'm not
11814 * convinced the server should be told details like that
11815 * about my local network configuration.
11816 * The "originator IP address" is syntactically a numeric
11817 * IP address, and some servers (e.g., Tectia) get upset
11818 * if it doesn't match this syntax.
11820 ssh2_pkt_addstring(pktout, "0.0.0.0");
11821 ssh2_pkt_adduint32(pktout, 0);
11822 ssh2_pkt_send(ssh, pktout);
11826 static int ssh_connected(void *handle)
11828 Ssh ssh = (Ssh) handle;
11829 return ssh->s != NULL;
11832 static int ssh_sendok(void *handle)
11834 Ssh ssh = (Ssh) handle;
11835 return ssh->send_ok;
11838 static int ssh_ldisc(void *handle, int option)
11840 Ssh ssh = (Ssh) handle;
11841 if (option == LD_ECHO)
11842 return ssh->echoing;
11843 if (option == LD_EDIT)
11844 return ssh->editing;
11848 static void ssh_provide_ldisc(void *handle, void *ldisc)
11850 Ssh ssh = (Ssh) handle;
11851 ssh->ldisc = ldisc;
11854 static void ssh_provide_logctx(void *handle, void *logctx)
11856 Ssh ssh = (Ssh) handle;
11857 ssh->logctx = logctx;
11860 static int ssh_return_exitcode(void *handle)
11862 Ssh ssh = (Ssh) handle;
11863 if (ssh->s != NULL)
11866 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11870 * cfg_info for SSH is the protocol running in this session.
11871 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11872 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11874 static int ssh_cfg_info(void *handle)
11876 Ssh ssh = (Ssh) handle;
11877 if (ssh->version == 0)
11878 return 0; /* don't know yet */
11879 else if (ssh->bare_connection)
11882 return ssh->version;
11886 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11887 * that fails. This variable is the means by which scp.c can reach
11888 * into the SSH code and find out which one it got.
11890 extern int ssh_fallback_cmd(void *handle)
11892 Ssh ssh = (Ssh) handle;
11893 return ssh->fallback_cmd;
11896 Backend ssh_backend = {
11906 ssh_return_exitcode,
11910 ssh_provide_logctx,
11913 ssh_test_for_upstream,