18 #define logevent(s) { logevent(s); \
19 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
20 { fprintf(stderr, "%s\n", s); fflush(stderr); } }
22 /* logevent, only printf-formatted. */
23 void logeventf(char *fmt, ...)
29 vsprintf(stuff, fmt, ap);
34 #define bombout(msg) ( ssh_state = SSH_STATE_CLOSED, \
35 (s ? sk_close(s), s = NULL : 0), \
36 logeventf msg, connection_fatal msg )
38 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
39 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
40 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
41 #define SSH1_CMSG_USER 4 /* 0x4 */
42 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
43 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
44 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
45 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
46 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
47 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
48 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
49 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
50 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
51 #define SSH1_SMSG_FAILURE 15 /* 0xf */
52 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
53 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
54 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
55 #define SSH1_CMSG_EOF 19 /* 0x13 */
56 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
57 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
58 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
59 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
60 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
61 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
62 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
63 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
64 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
65 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
66 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
67 #define SSH1_MSG_IGNORE 32 /* 0x20 */
68 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
69 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
70 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
71 #define SSH1_MSG_DEBUG 36 /* 0x24 */
72 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
73 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
74 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
75 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
76 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
77 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
78 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
80 #define SSH1_AUTH_TIS 5 /* 0x5 */
81 #define SSH1_AUTH_CCARD 16 /* 0x10 */
83 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
84 /* Mask for protoflags we will echo back to server if seen */
85 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
87 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
88 #define SSH2_MSG_IGNORE 2 /* 0x2 */
89 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
90 #define SSH2_MSG_DEBUG 4 /* 0x4 */
91 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
92 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
93 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
94 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
95 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
96 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
97 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
98 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
99 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
100 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
101 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
102 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
103 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
104 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
105 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
106 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
107 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
108 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
109 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
110 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
111 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
112 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
113 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
114 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
115 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
116 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
117 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
118 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
119 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
120 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
121 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
122 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
125 * Packet type contexts, so that ssh2_pkt_type can correctly decode
126 * the ambiguous type numbers back into the correct type strings.
128 #define SSH2_PKTCTX_DHGROUP1 0x0001
129 #define SSH2_PKTCTX_DHGEX 0x0002
130 #define SSH2_PKTCTX_PUBLICKEY 0x0010
131 #define SSH2_PKTCTX_PASSWORD 0x0020
132 #define SSH2_PKTCTX_KBDINTER 0x0040
133 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
135 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
136 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
137 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
138 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
139 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
140 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
141 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
142 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
143 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
144 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
145 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
146 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
147 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
148 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
149 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
151 static const char *const ssh2_disconnect_reasons[] = {
153 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
154 "SSH_DISCONNECT_PROTOCOL_ERROR",
155 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
156 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
157 "SSH_DISCONNECT_MAC_ERROR",
158 "SSH_DISCONNECT_COMPRESSION_ERROR",
159 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
160 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
161 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
162 "SSH_DISCONNECT_CONNECTION_LOST",
163 "SSH_DISCONNECT_BY_APPLICATION",
164 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
165 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
166 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
167 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
170 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
171 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
172 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
173 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
175 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
178 * Various remote-bug flags.
180 #define BUG_CHOKES_ON_SSH1_IGNORE 1
181 #define BUG_SSH2_HMAC 2
182 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
183 #define BUG_CHOKES_ON_RSA 8
184 #define BUG_SSH2_RSA_PADDING 16
185 #define BUG_SSH2_DERIVEKEY 32
186 #define BUG_SSH2_DH_GEX 64
188 static int ssh_pkt_ctx = 0;
190 #define translate(x) if (type == x) return #x
191 #define translatec(x,ctx) if (type == x && (ssh_pkt_ctx & ctx)) return #x
192 char *ssh1_pkt_type(int type)
194 translate(SSH1_MSG_DISCONNECT);
195 translate(SSH1_SMSG_PUBLIC_KEY);
196 translate(SSH1_CMSG_SESSION_KEY);
197 translate(SSH1_CMSG_USER);
198 translate(SSH1_CMSG_AUTH_RSA);
199 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
200 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
201 translate(SSH1_CMSG_AUTH_PASSWORD);
202 translate(SSH1_CMSG_REQUEST_PTY);
203 translate(SSH1_CMSG_WINDOW_SIZE);
204 translate(SSH1_CMSG_EXEC_SHELL);
205 translate(SSH1_CMSG_EXEC_CMD);
206 translate(SSH1_SMSG_SUCCESS);
207 translate(SSH1_SMSG_FAILURE);
208 translate(SSH1_CMSG_STDIN_DATA);
209 translate(SSH1_SMSG_STDOUT_DATA);
210 translate(SSH1_SMSG_STDERR_DATA);
211 translate(SSH1_CMSG_EOF);
212 translate(SSH1_SMSG_EXIT_STATUS);
213 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
214 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
215 translate(SSH1_MSG_CHANNEL_DATA);
216 translate(SSH1_MSG_CHANNEL_CLOSE);
217 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
218 translate(SSH1_SMSG_X11_OPEN);
219 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
220 translate(SSH1_MSG_PORT_OPEN);
221 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
222 translate(SSH1_SMSG_AGENT_OPEN);
223 translate(SSH1_MSG_IGNORE);
224 translate(SSH1_CMSG_EXIT_CONFIRMATION);
225 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
226 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
227 translate(SSH1_MSG_DEBUG);
228 translate(SSH1_CMSG_REQUEST_COMPRESSION);
229 translate(SSH1_CMSG_AUTH_TIS);
230 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
231 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
232 translate(SSH1_CMSG_AUTH_CCARD);
233 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
234 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
237 char *ssh2_pkt_type(int type)
239 translate(SSH2_MSG_DISCONNECT);
240 translate(SSH2_MSG_IGNORE);
241 translate(SSH2_MSG_UNIMPLEMENTED);
242 translate(SSH2_MSG_DEBUG);
243 translate(SSH2_MSG_SERVICE_REQUEST);
244 translate(SSH2_MSG_SERVICE_ACCEPT);
245 translate(SSH2_MSG_KEXINIT);
246 translate(SSH2_MSG_NEWKEYS);
247 translatec(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP1);
248 translatec(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP1);
249 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
250 translatec(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
251 translatec(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
252 translatec(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
253 translate(SSH2_MSG_USERAUTH_REQUEST);
254 translate(SSH2_MSG_USERAUTH_FAILURE);
255 translate(SSH2_MSG_USERAUTH_SUCCESS);
256 translate(SSH2_MSG_USERAUTH_BANNER);
257 translatec(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
258 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
259 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
260 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
261 translate(SSH2_MSG_GLOBAL_REQUEST);
262 translate(SSH2_MSG_REQUEST_SUCCESS);
263 translate(SSH2_MSG_REQUEST_FAILURE);
264 translate(SSH2_MSG_CHANNEL_OPEN);
265 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
266 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
267 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
268 translate(SSH2_MSG_CHANNEL_DATA);
269 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
270 translate(SSH2_MSG_CHANNEL_EOF);
271 translate(SSH2_MSG_CHANNEL_CLOSE);
272 translate(SSH2_MSG_CHANNEL_REQUEST);
273 translate(SSH2_MSG_CHANNEL_SUCCESS);
274 translate(SSH2_MSG_CHANNEL_FAILURE);
280 #define GET_32BIT(cp) \
281 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
282 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
283 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
284 ((unsigned long)(unsigned char)(cp)[3]))
286 #define PUT_32BIT(cp, value) { \
287 (cp)[0] = (unsigned char)((value) >> 24); \
288 (cp)[1] = (unsigned char)((value) >> 16); \
289 (cp)[2] = (unsigned char)((value) >> 8); \
290 (cp)[3] = (unsigned char)(value); }
292 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
294 /* Coroutine mechanics for the sillier bits of the code */
295 #define crBegin1 static int crLine = 0;
296 #define crBegin2 switch(crLine) { case 0:;
297 #define crBegin crBegin1; crBegin2;
298 #define crFinish(z) } crLine = 0; return (z)
299 #define crFinishV } crLine = 0; return
300 #define crReturn(z) \
302 crLine=__LINE__; return (z); case __LINE__:;\
306 crLine=__LINE__; return; case __LINE__:;\
308 #define crStop(z) do{ crLine = 0; return (z); }while(0)
309 #define crStopV do{ crLine = 0; return; }while(0)
310 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
311 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
313 extern char *x11_init(Socket *, char *, void *);
314 extern void x11_close(Socket);
315 extern int x11_send(Socket, char *, int);
316 extern void x11_invent_auth(char *, int, char *, int);
317 extern void x11_unthrottle(Socket s);
318 extern void x11_override_throttle(Socket s, int enable);
320 extern char *pfd_newconnect(Socket * s, char *hostname, int port, void *c);
321 extern char *pfd_addforward(char *desthost, int destport, int port);
322 extern void pfd_close(Socket s);
323 extern int pfd_send(Socket s, char *data, int len);
324 extern void pfd_confirm(Socket s);
325 extern void pfd_unthrottle(Socket s);
326 extern void pfd_override_throttle(Socket s, int enable);
328 static void ssh2_pkt_init(int pkt_type);
329 static void ssh2_pkt_addbool(unsigned char value);
330 static void ssh2_pkt_adduint32(unsigned long value);
331 static void ssh2_pkt_addstring_start(void);
332 static void ssh2_pkt_addstring_str(char *data);
333 static void ssh2_pkt_addstring_data(char *data, int len);
334 static void ssh2_pkt_addstring(char *data);
335 static char *ssh2_mpint_fmt(Bignum b, int *len);
336 static void ssh2_pkt_addmp(Bignum b);
337 static int ssh2_pkt_construct(void);
338 static void ssh2_pkt_send(void);
341 * Buffer management constants. There are several of these for
342 * various different purposes:
344 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
345 * on a local data stream before we throttle the whole SSH
346 * connection (in SSH1 only). Throttling the whole connection is
347 * pretty drastic so we set this high in the hope it won't
350 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
351 * on the SSH connection itself before we defensively throttle
352 * _all_ local data streams. This is pretty drastic too (though
353 * thankfully unlikely in SSH2 since the window mechanism should
354 * ensure that the server never has any need to throttle its end
355 * of the connection), so we set this high as well.
357 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
361 #define SSH1_BUFFER_LIMIT 32768
362 #define SSH_MAX_BACKLOG 32768
363 #define OUR_V2_WINSIZE 16384
365 const static struct ssh_kex *kex_algs[] = {
366 &ssh_diffiehellman_gex,
370 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
372 static void nullmac_key(unsigned char *key)
375 static void nullmac_generate(unsigned char *blk, int len,
379 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq)
383 const static struct ssh_mac ssh_mac_none = {
384 nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
386 const static struct ssh_mac *macs[] = {
387 &ssh_sha1, &ssh_md5, &ssh_mac_none
389 const static struct ssh_mac *buggymacs[] = {
390 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
393 static void ssh_comp_none_init(void)
396 static int ssh_comp_none_block(unsigned char *block, int len,
397 unsigned char **outblock, int *outlen)
401 static int ssh_comp_none_disable(void)
405 const static struct ssh_compress ssh_comp_none = {
407 ssh_comp_none_init, ssh_comp_none_block,
408 ssh_comp_none_init, ssh_comp_none_block,
409 ssh_comp_none_disable
411 extern const struct ssh_compress ssh_zlib;
412 const static struct ssh_compress *compressions[] = {
413 &ssh_zlib, &ssh_comp_none
416 enum { /* channel types */
421 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
425 * 2-3-4 tree storing channels.
428 unsigned remoteid, localid;
431 * In SSH1, this value contains four bits:
433 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
434 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
435 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
436 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
438 * A channel is completely finished with when all four bits are set.
442 struct ssh1_data_channel {
445 struct ssh2_data_channel {
447 unsigned remwindow, remmaxpkt;
452 struct ssh_agent_channel {
453 unsigned char *message;
454 unsigned char msglen[4];
455 int lensofar, totallen;
457 struct ssh_x11_channel {
460 struct ssh_pfd_channel {
467 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
468 * 2 use this structure in different ways, reflecting SSH 2's
469 * altogether saner approach to port forwarding.
471 * In SSH 1, you arrange a remote forwarding by sending the server
472 * the remote port number, and the local destination host:port.
473 * When a connection comes in, the server sends you back that
474 * host:port pair, and you connect to it. This is a ready-made
475 * security hole if you're not on the ball: a malicious server
476 * could send you back _any_ host:port pair, so if you trustingly
477 * connect to the address it gives you then you've just opened the
478 * entire inside of your corporate network just by connecting
479 * through it to a dodgy SSH server. Hence, we must store a list of
480 * host:port pairs we _are_ trying to forward to, and reject a
481 * connection request from the server if it's not in the list.
483 * In SSH 2, each side of the connection minds its own business and
484 * doesn't send unnecessary information to the other. You arrange a
485 * remote forwarding by sending the server just the remote port
486 * number. When a connection comes in, the server tells you which
487 * of its ports was connected to; and _you_ have to remember what
488 * local host:port pair went with that port number.
490 * Hence: in SSH 1 this structure stores host:port pairs we intend
491 * to allow connections to, and is indexed by those host:port
492 * pairs. In SSH 2 it stores a mapping from source port to
493 * destination host:port pair, and is indexed by source port.
495 struct ssh_rportfwd {
496 unsigned sport, dport;
509 static SHA_State exhash, exhashbase;
511 static Socket s = NULL;
513 static unsigned char session_key[32];
514 static int ssh1_compressing;
515 static int ssh1_remote_protoflags;
516 static int ssh1_local_protoflags;
517 static int ssh_agentfwd_enabled;
518 static int ssh_X11_fwd_enabled;
519 static int ssh_remote_bugs;
520 static const struct ssh_cipher *cipher = NULL;
521 static const struct ssh2_cipher *cscipher = NULL;
522 static const struct ssh2_cipher *sccipher = NULL;
523 static const struct ssh_mac *csmac = NULL;
524 static const struct ssh_mac *scmac = NULL;
525 static const struct ssh_compress *cscomp = NULL;
526 static const struct ssh_compress *sccomp = NULL;
527 static const struct ssh_kex *kex = NULL;
528 static const struct ssh_signkey *hostkey = NULL;
529 static unsigned char ssh2_session_id[20];
531 static char *savedhost;
532 static int savedport;
533 static int ssh_send_ok;
534 static int ssh_echoing, ssh_editing;
536 static tree234 *ssh_channels; /* indexed by local id */
537 static struct ssh_channel *mainchan; /* primary session channel */
538 static int ssh_exitcode = -1;
540 static tree234 *ssh_rportfwds;
544 SSH_STATE_BEFORE_SIZE,
548 } ssh_state = SSH_STATE_PREPACKET;
550 static int size_needed = FALSE, eof_needed = FALSE;
552 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
553 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
554 static unsigned char *deferred_send_data = NULL;
555 static int deferred_len = 0, deferred_size = 0;
558 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
559 * that fails. This variable is the means by which scp.c can reach
560 * into the SSH code and find out which one it got.
562 int ssh_fallback_cmd = 0;
564 static int ssh_version;
565 static int ssh1_throttle_count;
566 static int ssh_overall_bufsize;
567 static int ssh_throttled_all;
568 static int ssh1_stdout_throttling;
569 static void (*ssh_protocol) (unsigned char *in, int inlen, int ispkt);
570 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
571 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
572 static void ssh_size(void);
573 static void ssh_special(Telnet_Special);
574 static int ssh2_try_send(struct ssh_channel *c);
575 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
577 static void ssh_throttle_all(int enable, int bufsize);
578 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
579 static int (*s_rdpkt) (unsigned char **data, int *datalen);
580 static int ssh_sendbuffer(void);
582 static struct rdpkt1_state_tag {
583 long len, pad, biglen, to_read;
584 unsigned long realcrc, gotcrc;
590 static struct rdpkt2_state_tag {
591 long len, pad, payload, packetlen, maclen;
594 unsigned long incoming_sequence;
597 static int ssh_channelcmp(void *av, void *bv)
599 struct ssh_channel *a = (struct ssh_channel *) av;
600 struct ssh_channel *b = (struct ssh_channel *) bv;
601 if (a->localid < b->localid)
603 if (a->localid > b->localid)
607 static int ssh_channelfind(void *av, void *bv)
609 unsigned *a = (unsigned *) av;
610 struct ssh_channel *b = (struct ssh_channel *) bv;
618 static int ssh_rportcmp_ssh1(void *av, void *bv)
620 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
621 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
623 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
624 return i < 0 ? -1 : +1;
625 if (a->dport > b->dport)
627 if (a->dport < b->dport)
632 static int ssh_rportcmp_ssh2(void *av, void *bv)
634 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
635 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
637 if (a->sport > b->sport)
639 if (a->sport < b->sport)
644 static int alloc_channel_id(void)
646 const unsigned CHANNEL_NUMBER_OFFSET = 256;
647 unsigned low, high, mid;
649 struct ssh_channel *c;
652 * First-fit allocation of channel numbers: always pick the
653 * lowest unused one. To do this, binary-search using the
654 * counted B-tree to find the largest channel ID which is in a
655 * contiguous sequence from the beginning. (Precisely
656 * everything in that sequence must have ID equal to its tree
657 * index plus CHANNEL_NUMBER_OFFSET.)
659 tsize = count234(ssh_channels);
663 while (high - low > 1) {
664 mid = (high + low) / 2;
665 c = index234(ssh_channels, mid);
666 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
667 low = mid; /* this one is fine */
669 high = mid; /* this one is past it */
672 * Now low points to either -1, or the tree index of the
673 * largest ID in the initial sequence.
676 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
677 assert(NULL == find234(ssh_channels, &i, ssh_channelfind));
679 return low + 1 + CHANNEL_NUMBER_OFFSET;
682 static void c_write(char *buf, int len)
684 if ((flags & FLAG_STDERR)) {
686 for (i = 0; i < len; i++)
688 fputc(buf[i], stderr);
691 from_backend(1, buf, len);
694 static void c_write_untrusted(char *buf, int len)
697 for (i = 0; i < len; i++) {
700 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
705 static void c_write_str(char *buf)
707 c_write(buf, strlen(buf));
711 * Collect incoming data in the incoming packet buffer.
712 * Decipher and verify the packet when it is completely read.
713 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
714 * Update the *data and *datalen variables.
715 * Return the additional nr of bytes needed, or 0 when
716 * a complete packet is available.
718 static int ssh1_rdpkt(unsigned char **data, int *datalen)
720 struct rdpkt1_state_tag *st = &rdpkt1_state;
729 for (st->i = st->len = 0; st->i < 4; st->i++) {
730 while ((*datalen) == 0)
732 st->len = (st->len << 8) + **data;
733 (*data)++, (*datalen)--;
736 st->pad = 8 - (st->len % 8);
737 st->biglen = st->len + st->pad;
738 pktin.length = st->len - 5;
740 if (pktin.maxlen < st->biglen) {
741 pktin.maxlen = st->biglen;
742 pktin.data = (pktin.data == NULL ? smalloc(st->biglen + APIEXTRA) :
743 srealloc(pktin.data, st->biglen + APIEXTRA));
745 fatalbox("Out of memory");
748 st->to_read = st->biglen;
750 while (st->to_read > 0) {
751 st->chunk = st->to_read;
752 while ((*datalen) == 0)
753 crReturn(st->to_read);
754 if (st->chunk > (*datalen))
755 st->chunk = (*datalen);
756 memcpy(st->p, *data, st->chunk);
758 *datalen -= st->chunk;
760 st->to_read -= st->chunk;
763 if (cipher && detect_attack(pktin.data, st->biglen, NULL)) {
764 bombout(("Network attack (CRC compensation) detected!"));
769 cipher->decrypt(pktin.data, st->biglen);
771 st->realcrc = crc32(pktin.data, st->biglen - 4);
772 st->gotcrc = GET_32BIT(pktin.data + st->biglen - 4);
773 if (st->gotcrc != st->realcrc) {
774 bombout(("Incorrect CRC received on packet"));
778 pktin.body = pktin.data + st->pad + 1;
780 if (ssh1_compressing) {
781 unsigned char *decompblk;
783 zlib_decompress_block(pktin.body - 1, pktin.length + 1,
784 &decompblk, &decomplen);
786 if (pktin.maxlen < st->pad + decomplen) {
787 pktin.maxlen = st->pad + decomplen;
788 pktin.data = srealloc(pktin.data, pktin.maxlen + APIEXTRA);
789 pktin.body = pktin.data + st->pad + 1;
791 fatalbox("Out of memory");
794 memcpy(pktin.body - 1, decompblk, decomplen);
796 pktin.length = decomplen - 1;
799 pktin.type = pktin.body[-1];
801 log_packet(PKT_INCOMING, pktin.type, ssh1_pkt_type(pktin.type),
802 pktin.body, pktin.length);
804 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
805 pktin.type == SSH1_SMSG_STDERR_DATA ||
806 pktin.type == SSH1_MSG_DEBUG ||
807 pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
808 pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
809 long stringlen = GET_32BIT(pktin.body);
810 if (stringlen + 4 != pktin.length) {
811 bombout(("Received data packet with bogus string length"));
816 if (pktin.type == SSH1_MSG_DEBUG) {
817 /* log debug message */
819 int stringlen = GET_32BIT(pktin.body);
820 strcpy(buf, "Remote debug message: ");
823 memcpy(buf + 8, pktin.body + 4, stringlen);
824 buf[8 + stringlen] = '\0';
827 } else if (pktin.type == SSH1_MSG_IGNORE) {
832 if (pktin.type == SSH1_MSG_DISCONNECT) {
833 /* log reason code in disconnect message */
835 unsigned msglen = GET_32BIT(pktin.body);
837 strcpy(buf, "Remote sent disconnect: ");
838 nowlen = strlen(buf);
839 if (msglen > sizeof(buf) - nowlen - 1)
840 msglen = sizeof(buf) - nowlen - 1;
841 memcpy(buf + nowlen, pktin.body + 4, msglen);
842 buf[nowlen + msglen] = '\0';
843 /* logevent(buf); (this is now done within the bombout macro) */
844 bombout(("Server sent disconnect message:\n\"%s\"", buf+nowlen));
851 static int ssh2_rdpkt(unsigned char **data, int *datalen)
853 struct rdpkt2_state_tag *st = &rdpkt2_state;
861 st->cipherblk = sccipher->blksize;
864 if (st->cipherblk < 8)
867 if (pktin.maxlen < st->cipherblk) {
868 pktin.maxlen = st->cipherblk;
871 NULL ? smalloc(st->cipherblk +
872 APIEXTRA) : srealloc(pktin.data,
876 fatalbox("Out of memory");
880 * Acquire and decrypt the first block of the packet. This will
881 * contain the length and padding details.
883 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
884 while ((*datalen) == 0)
885 crReturn(st->cipherblk - st->i);
886 pktin.data[st->i] = *(*data)++;
891 sccipher->decrypt(pktin.data, st->cipherblk);
894 * Now get the length and padding figures.
896 st->len = GET_32BIT(pktin.data);
897 st->pad = pktin.data[4];
900 * _Completely_ silly lengths should be stomped on before they
901 * do us any more damage.
903 if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
904 bombout(("Incoming packet was garbled on decryption"));
909 * This enables us to deduce the payload length.
911 st->payload = st->len - st->pad - 1;
913 pktin.length = st->payload + 5;
916 * So now we can work out the total packet length.
918 st->packetlen = st->len + 4;
919 st->maclen = scmac ? scmac->len : 0;
922 * Adjust memory allocation if packet is too big.
924 if (pktin.maxlen < st->packetlen + st->maclen) {
925 pktin.maxlen = st->packetlen + st->maclen;
928 NULL ? smalloc(pktin.maxlen + APIEXTRA) : srealloc(pktin.data,
933 fatalbox("Out of memory");
937 * Read and decrypt the remainder of the packet.
939 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
941 while ((*datalen) == 0)
942 crReturn(st->packetlen + st->maclen - st->i);
943 pktin.data[st->i] = *(*data)++;
946 /* Decrypt everything _except_ the MAC. */
948 sccipher->decrypt(pktin.data + st->cipherblk,
949 st->packetlen - st->cipherblk);
955 && !scmac->verify(pktin.data, st->len + 4,
956 st->incoming_sequence)) {
957 bombout(("Incorrect MAC received on packet"));
960 st->incoming_sequence++; /* whether or not we MACed */
963 * Decompress packet payload.
966 unsigned char *newpayload;
968 if (sccomp && sccomp->decompress(pktin.data + 5, pktin.length - 5,
969 &newpayload, &newlen)) {
970 if (pktin.maxlen < newlen + 5) {
971 pktin.maxlen = newlen + 5;
974 NULL ? smalloc(pktin.maxlen +
975 APIEXTRA) : srealloc(pktin.data,
979 fatalbox("Out of memory");
981 pktin.length = 5 + newlen;
982 memcpy(pktin.data + 5, newpayload, newlen);
988 pktin.type = pktin.data[5];
990 log_packet(PKT_INCOMING, pktin.type, ssh2_pkt_type(pktin.type),
991 pktin.data+6, pktin.length-6);
993 switch (pktin.type) {
995 * These packets we must handle instantly.
997 case SSH2_MSG_DISCONNECT:
999 /* log reason code in disconnect message */
1001 int reason = GET_32BIT(pktin.data + 6);
1002 unsigned msglen = GET_32BIT(pktin.data + 10);
1004 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
1005 sprintf(buf, "Received disconnect message (%s)",
1006 ssh2_disconnect_reasons[reason]);
1008 sprintf(buf, "Received disconnect message (unknown type %d)",
1012 strcpy(buf, "Disconnection message text: ");
1013 nowlen = strlen(buf);
1014 if (msglen > sizeof(buf) - nowlen - 1)
1015 msglen = sizeof(buf) - nowlen - 1;
1016 memcpy(buf + nowlen, pktin.data + 14, msglen);
1017 buf[nowlen + msglen] = '\0';
1019 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
1021 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
1022 ssh2_disconnect_reasons[reason] : "unknown",
1027 case SSH2_MSG_IGNORE:
1029 case SSH2_MSG_DEBUG:
1031 /* log the debug message */
1033 /* int display = pktin.body[6]; */
1034 int stringlen = GET_32BIT(pktin.data+7);
1036 strcpy(buf, "Remote debug message: ");
1037 prefix = strlen(buf);
1038 if (stringlen > sizeof(buf)-prefix-1)
1039 stringlen = sizeof(buf)-prefix-1;
1040 memcpy(buf + prefix, pktin.data + 11, stringlen);
1041 buf[prefix + stringlen] = '\0';
1044 goto next_packet; /* FIXME: print the debug message */
1047 * These packets we need do nothing about here.
1049 case SSH2_MSG_UNIMPLEMENTED:
1050 case SSH2_MSG_SERVICE_REQUEST:
1051 case SSH2_MSG_SERVICE_ACCEPT:
1052 case SSH2_MSG_KEXINIT:
1053 case SSH2_MSG_NEWKEYS:
1054 case SSH2_MSG_KEXDH_INIT:
1055 case SSH2_MSG_KEXDH_REPLY:
1056 /* case SSH2_MSG_KEX_DH_GEX_REQUEST: duplicate case value */
1057 /* case SSH2_MSG_KEX_DH_GEX_GROUP: duplicate case value */
1058 case SSH2_MSG_KEX_DH_GEX_INIT:
1059 case SSH2_MSG_KEX_DH_GEX_REPLY:
1060 case SSH2_MSG_USERAUTH_REQUEST:
1061 case SSH2_MSG_USERAUTH_FAILURE:
1062 case SSH2_MSG_USERAUTH_SUCCESS:
1063 case SSH2_MSG_USERAUTH_BANNER:
1064 case SSH2_MSG_USERAUTH_PK_OK:
1065 /* case SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: duplicate case value */
1066 /* case SSH2_MSG_USERAUTH_INFO_REQUEST: duplicate case value */
1067 case SSH2_MSG_USERAUTH_INFO_RESPONSE:
1068 case SSH2_MSG_GLOBAL_REQUEST:
1069 case SSH2_MSG_REQUEST_SUCCESS:
1070 case SSH2_MSG_REQUEST_FAILURE:
1071 case SSH2_MSG_CHANNEL_OPEN:
1072 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
1073 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
1074 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1075 case SSH2_MSG_CHANNEL_DATA:
1076 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1077 case SSH2_MSG_CHANNEL_EOF:
1078 case SSH2_MSG_CHANNEL_CLOSE:
1079 case SSH2_MSG_CHANNEL_REQUEST:
1080 case SSH2_MSG_CHANNEL_SUCCESS:
1081 case SSH2_MSG_CHANNEL_FAILURE:
1085 * For anything else we send SSH2_MSG_UNIMPLEMENTED.
1088 ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
1089 ssh2_pkt_adduint32(st->incoming_sequence - 1);
1097 static void ssh1_pktout_size(int len)
1101 len += 5; /* type and CRC */
1102 pad = 8 - (len % 8);
1105 pktout.length = len - 5;
1106 if (pktout.maxlen < biglen) {
1107 pktout.maxlen = biglen;
1109 /* Allocate enough buffer space for extra block
1110 * for MS CryptEncrypt() */
1111 pktout.data = (pktout.data == NULL ? smalloc(biglen + 12) :
1112 srealloc(pktout.data, biglen + 12));
1114 pktout.data = (pktout.data == NULL ? smalloc(biglen + 4) :
1115 srealloc(pktout.data, biglen + 4));
1118 fatalbox("Out of memory");
1120 pktout.body = pktout.data + 4 + pad + 1;
1123 static void s_wrpkt_start(int type, int len)
1125 ssh1_pktout_size(len);
1129 static int s_wrpkt_prepare(void)
1131 int pad, len, biglen, i;
1134 pktout.body[-1] = pktout.type;
1136 log_packet(PKT_OUTGOING, pktout.type, ssh1_pkt_type(pktout.type),
1137 pktout.body, pktout.length);
1139 if (ssh1_compressing) {
1140 unsigned char *compblk;
1142 zlib_compress_block(pktout.body - 1, pktout.length + 1,
1143 &compblk, &complen);
1144 ssh1_pktout_size(complen - 1);
1145 memcpy(pktout.body - 1, compblk, complen);
1149 len = pktout.length + 5; /* type and CRC */
1150 pad = 8 - (len % 8);
1153 for (i = 0; i < pad; i++)
1154 pktout.data[i + 4] = random_byte();
1155 crc = crc32(pktout.data + 4, biglen - 4);
1156 PUT_32BIT(pktout.data + biglen, crc);
1157 PUT_32BIT(pktout.data, len);
1160 cipher->encrypt(pktout.data + 4, biglen);
1165 static void s_wrpkt(void)
1168 len = s_wrpkt_prepare();
1169 backlog = sk_write(s, pktout.data, len);
1170 if (backlog > SSH_MAX_BACKLOG)
1171 ssh_throttle_all(1, backlog);
1174 static void s_wrpkt_defer(void)
1177 len = s_wrpkt_prepare();
1178 if (deferred_len + len > deferred_size) {
1179 deferred_size = deferred_len + len + 128;
1180 deferred_send_data = srealloc(deferred_send_data, deferred_size);
1182 memcpy(deferred_send_data + deferred_len, pktout.data, len);
1183 deferred_len += len;
1187 * Construct a packet with the specified contents.
1189 static void construct_packet(int pkttype, va_list ap1, va_list ap2)
1191 unsigned char *p, *argp, argchar;
1192 unsigned long argint;
1193 int pktlen, argtype, arglen;
1197 while ((argtype = va_arg(ap1, int)) != PKT_END) {
1200 (void) va_arg(ap1, int);
1204 (void) va_arg(ap1, char);
1208 (void) va_arg(ap1, unsigned char *);
1209 arglen = va_arg(ap1, int);
1213 argp = va_arg(ap1, unsigned char *);
1214 arglen = strlen(argp);
1215 pktlen += 4 + arglen;
1218 bn = va_arg(ap1, Bignum);
1219 pktlen += ssh1_bignum_length(bn);
1226 s_wrpkt_start(pkttype, pktlen);
1229 while ((argtype = va_arg(ap2, int)) != PKT_END) {
1232 argint = va_arg(ap2, int);
1233 PUT_32BIT(p, argint);
1237 argchar = va_arg(ap2, unsigned char);
1242 argp = va_arg(ap2, unsigned char *);
1243 arglen = va_arg(ap2, int);
1244 memcpy(p, argp, arglen);
1248 argp = va_arg(ap2, unsigned char *);
1249 arglen = strlen(argp);
1250 PUT_32BIT(p, arglen);
1251 memcpy(p + 4, argp, arglen);
1255 bn = va_arg(ap2, Bignum);
1256 p += ssh1_write_bignum(p, bn);
1262 static void send_packet(int pkttype, ...)
1265 va_start(ap1, pkttype);
1266 va_start(ap2, pkttype);
1267 construct_packet(pkttype, ap1, ap2);
1271 static void defer_packet(int pkttype, ...)
1274 va_start(ap1, pkttype);
1275 va_start(ap2, pkttype);
1276 construct_packet(pkttype, ap1, ap2);
1280 static int ssh_versioncmp(char *a, char *b)
1283 unsigned long av, bv;
1285 av = strtoul(a, &ae, 10);
1286 bv = strtoul(b, &be, 10);
1288 return (av < bv ? -1 : +1);
1293 av = strtoul(ae, &ae, 10);
1294 bv = strtoul(be, &be, 10);
1296 return (av < bv ? -1 : +1);
1302 * Utility routines for putting an SSH-protocol `string' and
1303 * `uint32' into a SHA state.
1306 static void sha_string(SHA_State * s, void *str, int len)
1308 unsigned char lenblk[4];
1309 PUT_32BIT(lenblk, len);
1310 SHA_Bytes(s, lenblk, 4);
1311 SHA_Bytes(s, str, len);
1314 static void sha_uint32(SHA_State * s, unsigned i)
1316 unsigned char intblk[4];
1317 PUT_32BIT(intblk, i);
1318 SHA_Bytes(s, intblk, 4);
1322 * SSH2 packet construction functions.
1324 static void ssh2_pkt_ensure(int length)
1326 if (pktout.maxlen < length) {
1327 pktout.maxlen = length + 256;
1330 NULL ? smalloc(pktout.maxlen +
1331 APIEXTRA) : srealloc(pktout.data,
1335 fatalbox("Out of memory");
1338 static void ssh2_pkt_adddata(void *data, int len)
1340 pktout.length += len;
1341 ssh2_pkt_ensure(pktout.length);
1342 memcpy(pktout.data + pktout.length - len, data, len);
1344 static void ssh2_pkt_addbyte(unsigned char byte)
1346 ssh2_pkt_adddata(&byte, 1);
1348 static void ssh2_pkt_init(int pkt_type)
1351 ssh2_pkt_addbyte((unsigned char) pkt_type);
1353 static void ssh2_pkt_addbool(unsigned char value)
1355 ssh2_pkt_adddata(&value, 1);
1357 static void ssh2_pkt_adduint32(unsigned long value)
1360 PUT_32BIT(x, value);
1361 ssh2_pkt_adddata(x, 4);
1363 static void ssh2_pkt_addstring_start(void)
1365 ssh2_pkt_adduint32(0);
1366 pktout.savedpos = pktout.length;
1368 static void ssh2_pkt_addstring_str(char *data)
1370 ssh2_pkt_adddata(data, strlen(data));
1371 PUT_32BIT(pktout.data + pktout.savedpos - 4,
1372 pktout.length - pktout.savedpos);
1374 static void ssh2_pkt_addstring_data(char *data, int len)
1376 ssh2_pkt_adddata(data, len);
1377 PUT_32BIT(pktout.data + pktout.savedpos - 4,
1378 pktout.length - pktout.savedpos);
1380 static void ssh2_pkt_addstring(char *data)
1382 ssh2_pkt_addstring_start();
1383 ssh2_pkt_addstring_str(data);
1385 static char *ssh2_mpint_fmt(Bignum b, int *len)
1388 int i, n = (bignum_bitcount(b) + 7) / 8;
1391 fatalbox("out of memory");
1393 for (i = 1; i <= n; i++)
1394 p[i] = bignum_byte(b, n - i);
1396 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1398 memmove(p, p + i, n + 1 - i);
1402 static void ssh2_pkt_addmp(Bignum b)
1406 p = ssh2_mpint_fmt(b, &len);
1407 ssh2_pkt_addstring_start();
1408 ssh2_pkt_addstring_data(p, len);
1413 * Construct an SSH2 final-form packet: compress it, encrypt it,
1414 * put the MAC on it. Final packet, ready to be sent, is stored in
1415 * pktout.data. Total length is returned.
1417 static int ssh2_pkt_construct(void)
1419 int cipherblk, maclen, padding, i;
1420 static unsigned long outgoing_sequence = 0;
1422 log_packet(PKT_OUTGOING, pktout.data[5], ssh2_pkt_type(pktout.data[5]),
1423 pktout.data + 6, pktout.length - 6);
1426 * Compress packet payload.
1429 unsigned char *newpayload;
1431 if (cscomp && cscomp->compress(pktout.data + 5, pktout.length - 5,
1432 &newpayload, &newlen)) {
1434 ssh2_pkt_adddata(newpayload, newlen);
1440 * Add padding. At least four bytes, and must also bring total
1441 * length (minus MAC) up to a multiple of the block size.
1443 cipherblk = cscipher ? cscipher->blksize : 8; /* block size */
1444 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1447 (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
1448 maclen = csmac ? csmac->len : 0;
1449 ssh2_pkt_ensure(pktout.length + padding + maclen);
1450 pktout.data[4] = padding;
1451 for (i = 0; i < padding; i++)
1452 pktout.data[pktout.length + i] = random_byte();
1453 PUT_32BIT(pktout.data, pktout.length + padding - 4);
1455 csmac->generate(pktout.data, pktout.length + padding,
1457 outgoing_sequence++; /* whether or not we MACed */
1460 cscipher->encrypt(pktout.data, pktout.length + padding);
1462 /* Ready-to-send packet starts at pktout.data. We return length. */
1463 return pktout.length + padding + maclen;
1467 * Construct and send an SSH2 packet immediately.
1469 static void ssh2_pkt_send(void)
1473 len = ssh2_pkt_construct();
1474 backlog = sk_write(s, pktout.data, len);
1475 if (backlog > SSH_MAX_BACKLOG)
1476 ssh_throttle_all(1, backlog);
1480 * Construct an SSH2 packet and add it to a deferred data block.
1481 * Useful for sending multiple packets in a single sk_write() call,
1482 * to prevent a traffic-analysing listener from being able to work
1483 * out the length of any particular packet (such as the password
1486 * Note that because SSH2 sequence-numbers its packets, this can
1487 * NOT be used as an m4-style `defer' allowing packets to be
1488 * constructed in one order and sent in another.
1490 static void ssh2_pkt_defer(void)
1492 int len = ssh2_pkt_construct();
1493 if (deferred_len + len > deferred_size) {
1494 deferred_size = deferred_len + len + 128;
1495 deferred_send_data = srealloc(deferred_send_data, deferred_size);
1497 memcpy(deferred_send_data + deferred_len, pktout.data, len);
1498 deferred_len += len;
1502 * Send the whole deferred data block constructed by
1503 * ssh2_pkt_defer() or SSH1's defer_packet().
1505 static void ssh_pkt_defersend(void)
1508 backlog = sk_write(s, deferred_send_data, deferred_len);
1509 deferred_len = deferred_size = 0;
1510 sfree(deferred_send_data);
1511 deferred_send_data = NULL;
1512 if (backlog > SSH_MAX_BACKLOG)
1513 ssh_throttle_all(1, backlog);
1517 void bndebug(char *string, Bignum b)
1521 p = ssh2_mpint_fmt(b, &len);
1522 debug(("%s", string));
1523 for (i = 0; i < len; i++)
1524 debug((" %02x", p[i]));
1530 static void sha_mpint(SHA_State * s, Bignum b)
1534 p = ssh2_mpint_fmt(b, &len);
1535 sha_string(s, p, len);
1540 * SSH2 packet decode functions.
1542 static unsigned long ssh2_pkt_getuint32(void)
1544 unsigned long value;
1545 if (pktin.length - pktin.savedpos < 4)
1546 return 0; /* arrgh, no way to decline (FIXME?) */
1547 value = GET_32BIT(pktin.data + pktin.savedpos);
1548 pktin.savedpos += 4;
1551 static int ssh2_pkt_getbool(void)
1553 unsigned long value;
1554 if (pktin.length - pktin.savedpos < 1)
1555 return 0; /* arrgh, no way to decline (FIXME?) */
1556 value = pktin.data[pktin.savedpos] != 0;
1560 static void ssh2_pkt_getstring(char **p, int *length)
1565 if (pktin.length - pktin.savedpos < 4)
1567 len = GET_32BIT(pktin.data + pktin.savedpos);
1571 pktin.savedpos += 4;
1572 if (pktin.length - pktin.savedpos < *length)
1574 *p = pktin.data + pktin.savedpos;
1575 pktin.savedpos += *length;
1577 static Bignum ssh2_pkt_getmp(void)
1583 ssh2_pkt_getstring(&p, &length);
1587 bombout(("internal error: Can't handle negative mpints"));
1590 b = bignum_from_bytes(p, length);
1595 * Helper function to add an SSH2 signature blob to a packet.
1596 * Expects to be shown the public key blob as well as the signature
1597 * blob. Normally works just like ssh2_pkt_addstring, but will
1598 * fiddle with the signature packet if necessary for
1599 * BUG_SSH2_RSA_PADDING.
1601 static void ssh2_add_sigblob(void *pkblob_v, int pkblob_len,
1602 void *sigblob_v, int sigblob_len)
1604 unsigned char *pkblob = (unsigned char *)pkblob_v;
1605 unsigned char *sigblob = (unsigned char *)sigblob_v;
1607 /* dmemdump(pkblob, pkblob_len); */
1608 /* dmemdump(sigblob, sigblob_len); */
1611 * See if this is in fact an ssh-rsa signature and a buggy
1612 * server; otherwise we can just do this the easy way.
1614 if ((ssh_remote_bugs & BUG_SSH2_RSA_PADDING) &&
1615 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
1616 int pos, len, siglen;
1619 * Find the byte length of the modulus.
1622 pos = 4+7; /* skip over "ssh-rsa" */
1623 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
1624 len = GET_32BIT(pkblob+pos); /* find length of modulus */
1625 pos += 4; /* find modulus itself */
1626 while (len > 0 && pkblob[pos] == 0)
1628 /* debug(("modulus length is %d\n", len)); */
1631 * Now find the signature integer.
1633 pos = 4+7; /* skip over "ssh-rsa" */
1634 siglen = GET_32BIT(sigblob+pos);
1635 /* debug(("signature length is %d\n", siglen)); */
1637 if (len != siglen) {
1638 unsigned char newlen[4];
1639 ssh2_pkt_addstring_start();
1640 ssh2_pkt_addstring_data(sigblob, pos);
1641 /* dmemdump(sigblob, pos); */
1642 pos += 4; /* point to start of actual sig */
1643 PUT_32BIT(newlen, len);
1644 ssh2_pkt_addstring_data(newlen, 4);
1645 /* dmemdump(newlen, 4); */
1647 while (len-- > siglen) {
1648 ssh2_pkt_addstring_data(newlen, 1);
1649 /* dmemdump(newlen, 1); */
1651 ssh2_pkt_addstring_data(sigblob+pos, siglen);
1652 /* dmemdump(sigblob+pos, siglen); */
1656 /* Otherwise fall through and do it the easy way. */
1659 ssh2_pkt_addstring_start();
1660 ssh2_pkt_addstring_data(sigblob, sigblob_len);
1664 * Examine the remote side's version string and compare it against
1665 * a list of known buggy implementations.
1667 static void ssh_detect_bugs(char *vstring)
1669 char *imp; /* pointer to implementation part */
1671 imp += strcspn(imp, "-");
1673 imp += strcspn(imp, "-");
1676 ssh_remote_bugs = 0;
1678 if (cfg.sshbug_ignore1 == BUG_ON ||
1679 (cfg.sshbug_ignore1 == BUG_AUTO &&
1680 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1681 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1682 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25")))) {
1684 * These versions don't support SSH1_MSG_IGNORE, so we have
1685 * to use a different defence against password length
1688 ssh_remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1689 logevent("We believe remote version has SSH1 ignore bug");
1692 if (cfg.sshbug_plainpw1 == BUG_ON ||
1693 (cfg.sshbug_plainpw1 == BUG_AUTO &&
1694 (!strcmp(imp, "Cisco-1.25")))) {
1696 * These versions need a plain password sent; they can't
1697 * handle having a null and a random length of data after
1700 ssh_remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
1701 logevent("We believe remote version needs a plain SSH1 password");
1704 if (cfg.sshbug_rsa1 == BUG_ON ||
1705 (cfg.sshbug_rsa1 == BUG_AUTO &&
1706 (!strcmp(imp, "Cisco-1.25")))) {
1708 * These versions apparently have no clue whatever about
1709 * RSA authentication and will panic and die if they see
1710 * an AUTH_RSA message.
1712 ssh_remote_bugs |= BUG_CHOKES_ON_RSA;
1713 logevent("We believe remote version can't handle RSA authentication");
1716 if (cfg.sshbug_hmac2 == BUG_ON ||
1717 (cfg.sshbug_hmac2 == BUG_AUTO &&
1718 (!strncmp(imp, "2.1.0", 5) || !strncmp(imp, "2.0.", 4) ||
1719 !strncmp(imp, "2.2.0", 5) || !strncmp(imp, "2.3.0", 5) ||
1720 !strncmp(imp, "2.1 ", 4)))) {
1722 * These versions have the HMAC bug.
1724 ssh_remote_bugs |= BUG_SSH2_HMAC;
1725 logevent("We believe remote version has SSH2 HMAC bug");
1728 if (cfg.sshbug_derivekey2 == BUG_ON ||
1729 (cfg.sshbug_derivekey2 == BUG_AUTO &&
1730 (!strncmp(imp, "2.0.", 4)))) {
1732 * These versions have the key-derivation bug (failing to
1733 * include the literal shared secret in the hashes that
1734 * generate the keys).
1736 ssh_remote_bugs |= BUG_SSH2_DERIVEKEY;
1737 logevent("We believe remote version has SSH2 key-derivation bug");
1740 if (cfg.sshbug_rsapad2 == BUG_ON ||
1741 (cfg.sshbug_rsapad2 == BUG_AUTO &&
1742 ((!strncmp(imp, "OpenSSH_2.", 10) && imp[10]>='5' && imp[10]<='9') ||
1743 (!strncmp(imp, "OpenSSH_3.", 10) && imp[10]>='0' && imp[10]<='2')))){
1745 * These versions have the SSH2 RSA padding bug.
1747 ssh_remote_bugs |= BUG_SSH2_RSA_PADDING;
1748 logevent("We believe remote version has SSH2 RSA padding bug");
1751 if (cfg.sshbug_dhgex2 == BUG_ON) {
1753 * These versions have the SSH2 DH GEX bug.
1755 ssh_remote_bugs |= BUG_SSH2_DH_GEX;
1756 logevent("We believe remote version has SSH2 DH group exchange bug");
1760 static int do_ssh_init(unsigned char c)
1763 static char version[10];
1764 static char *vstring;
1765 static int vstrsize;
1768 static int proto1, proto2;
1772 /* Search for the string "SSH-" in the input. */
1775 static const int transS[] = { 1, 2, 2, 1 };
1776 static const int transH[] = { 0, 0, 3, 0 };
1777 static const int transminus[] = { 0, 0, 0, -1 };
1788 crReturn(1); /* get another character */
1792 vstring = smalloc(vstrsize);
1793 strcpy(vstring, "SSH-");
1797 crReturn(1); /* get another char */
1798 if (vslen >= vstrsize - 1) {
1800 vstring = srealloc(vstring, vstrsize);
1802 vstring[vslen++] = c;
1807 } else if (i < sizeof(version) - 1)
1809 } else if (c == '\n')
1813 ssh_agentfwd_enabled = FALSE;
1814 rdpkt2_state.incoming_sequence = 0;
1817 vlog = smalloc(20 + vslen);
1818 vstring[strcspn (vstring, "\r\n")] = '\0'; /* remove end-of-line chars */
1819 sprintf(vlog, "Server version: %s", vstring);
1821 ssh_detect_bugs(vstring);
1825 * Decide which SSH protocol version to support.
1828 /* Anything strictly below "2.0" means protocol 1 is supported. */
1829 proto1 = ssh_versioncmp(version, "2.0") < 0;
1830 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
1831 proto2 = ssh_versioncmp(version, "1.99") >= 0;
1833 if (cfg.sshprot == 0 && !proto1) {
1834 bombout(("SSH protocol version 1 required by user but not provided by server"));
1837 if (cfg.sshprot == 3 && !proto2) {
1838 bombout(("SSH protocol version 2 required by user but not provided by server"));
1842 if (proto2 && (cfg.sshprot >= 2 || !proto1)) {
1846 char verstring[80], vlog[100];
1847 sprintf(verstring, "SSH-2.0-%s", sshver);
1848 SHA_Init(&exhashbase);
1850 * Hash our version string and their version string.
1852 sha_string(&exhashbase, verstring, strlen(verstring));
1853 sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
1854 sprintf(vlog, "We claim version: %s", verstring);
1856 strcat(verstring, "\n");
1857 logevent("Using SSH protocol version 2");
1858 sk_write(s, verstring, strlen(verstring));
1859 ssh_protocol = ssh2_protocol;
1861 s_rdpkt = ssh2_rdpkt;
1866 char verstring[80], vlog[100];
1867 sprintf(verstring, "SSH-%s-%s",
1868 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"),
1870 sprintf(vlog, "We claim version: %s", verstring);
1872 strcat(verstring, "\n");
1874 logevent("Using SSH protocol version 1");
1875 sk_write(s, verstring, strlen(verstring));
1876 ssh_protocol = ssh1_protocol;
1878 s_rdpkt = ssh1_rdpkt;
1880 ssh_state = SSH_STATE_BEFORE_SIZE;
1887 static void ssh_gotdata(unsigned char *data, int datalen)
1892 * To begin with, feed the characters one by one to the
1893 * protocol initialisation / selection function do_ssh_init().
1894 * When that returns 0, we're done with the initial greeting
1895 * exchange and can move on to packet discipline.
1900 crReturnV; /* more data please */
1901 ret = do_ssh_init(*data);
1909 * We emerge from that loop when the initial negotiation is
1910 * over and we have selected an s_rdpkt function. Now pass
1911 * everything to s_rdpkt, and then pass the resulting packets
1912 * to the proper protocol handler.
1917 while (datalen > 0) {
1918 if (s_rdpkt(&data, &datalen) == 0) {
1919 if (ssh_state == SSH_STATE_CLOSED) {
1922 ssh_protocol(NULL, 0, 1);
1923 if (ssh_state == SSH_STATE_CLOSED) {
1933 static int ssh_closing(Plug plug, char *error_msg, int error_code,
1936 ssh_state = SSH_STATE_CLOSED;
1942 /* A socket error has occurred. */
1943 logevent(error_msg);
1944 connection_fatal(error_msg);
1946 /* Otherwise, the remote side closed the connection normally. */
1951 static int ssh_receive(Plug plug, int urgent, char *data, int len)
1953 ssh_gotdata(data, len);
1954 if (ssh_state == SSH_STATE_CLOSED) {
1964 static void ssh_sent(Plug plug, int bufsize)
1967 * If the send backlog on the SSH socket itself clears, we
1968 * should unthrottle the whole world if it was throttled.
1970 if (bufsize < SSH_MAX_BACKLOG)
1971 ssh_throttle_all(0, bufsize);
1975 * Connect to specified host and port.
1976 * Returns an error message, or NULL on success.
1977 * Also places the canonical host name into `realhost'. It must be
1978 * freed by the caller.
1980 static char *connect_to_host(char *host, int port, char **realhost, int nodelay)
1982 static struct plug_function_table fn_table = {
1987 }, *fn_table_ptr = &fn_table;
1996 savedhost = smalloc(1 + strlen(host));
1998 fatalbox("Out of memory");
1999 strcpy(savedhost, host);
2002 port = 22; /* default ssh port */
2017 sprintf(buf, "Looking up host \"%.170s\"", host);
2020 addr = sk_namelookup(host, realhost);
2021 if ((err = sk_addr_error(addr)))
2025 *realhost = strdup(FWhost);
2032 char buf[200], addrbuf[100];
2033 sk_getaddr(addr, addrbuf, 100);
2034 sprintf(buf, "Connecting to %.100s port %d", addrbuf, port);
2037 s = new_connection(addr, *realhost, port, 0, 1, nodelay, &fn_table_ptr);
2038 if ((err = sk_socket_error(s))) {
2044 sk_write(s, "connect ", 8);
2045 sk_write(s, FWhost, strlen(FWhost));
2048 sprintf(buf, " %d\n", FWport);
2049 sk_write(s, buf, strlen(buf));
2057 * Throttle or unthrottle the SSH connection.
2059 static void ssh1_throttle(int adjust)
2061 int old_count = ssh1_throttle_count;
2062 ssh1_throttle_count += adjust;
2063 assert(ssh1_throttle_count >= 0);
2064 if (ssh1_throttle_count && !old_count) {
2065 sk_set_frozen(s, 1);
2066 } else if (!ssh1_throttle_count && old_count) {
2067 sk_set_frozen(s, 0);
2072 * Throttle or unthrottle _all_ local data streams (for when sends
2073 * on the SSH connection itself back up).
2075 static void ssh_throttle_all(int enable, int bufsize)
2078 struct ssh_channel *c;
2080 if (enable == ssh_throttled_all)
2082 ssh_throttled_all = enable;
2083 ssh_overall_bufsize = bufsize;
2086 for (i = 0; NULL != (c = index234(ssh_channels, i)); i++) {
2088 case CHAN_MAINSESSION:
2090 * This is treated separately, outside the switch.
2094 x11_override_throttle(c->u.x11.s, enable);
2097 /* Agent channels require no buffer management. */
2100 pfd_override_throttle(c->u.x11.s, enable);
2107 * Username and password input, abstracted off into reusable
2108 * routines (hopefully even reusable between SSH1 and SSH2!).
2110 static char *ssh_userpass_input_buffer;
2111 static int ssh_userpass_input_buflen;
2112 static int ssh_userpass_input_bufpos;
2113 static int ssh_userpass_input_echo;
2115 /* Set up a username or password input loop on a given buffer. */
2116 void setup_userpass_input(char *buffer, int buflen, int echo)
2118 ssh_userpass_input_buffer = buffer;
2119 ssh_userpass_input_buflen = buflen;
2120 ssh_userpass_input_bufpos = 0;
2121 ssh_userpass_input_echo = echo;
2125 * Process some terminal data in the course of username/password
2126 * input. Returns >0 for success (line of input returned in
2127 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2128 * for inconclusive (keep waiting for more input please).
2130 int process_userpass_input(unsigned char *in, int inlen)
2135 switch (c = *in++) {
2138 ssh_userpass_input_buffer[ssh_userpass_input_bufpos] = 0;
2139 ssh_userpass_input_buffer[ssh_userpass_input_buflen-1] = 0;
2144 if (ssh_userpass_input_bufpos > 0) {
2145 if (ssh_userpass_input_echo)
2146 c_write_str("\b \b");
2147 ssh_userpass_input_bufpos--;
2152 while (ssh_userpass_input_bufpos > 0) {
2153 if (ssh_userpass_input_echo)
2154 c_write_str("\b \b");
2155 ssh_userpass_input_bufpos--;
2163 if (((c >= ' ' && c <= '~') ||
2164 ((unsigned char) c >= 160))
2165 && ssh_userpass_input_bufpos < ssh_userpass_input_buflen-1) {
2166 ssh_userpass_input_buffer[ssh_userpass_input_bufpos++] = c;
2167 if (ssh_userpass_input_echo)
2177 * Handle the key exchange and user authentication phases.
2179 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
2183 static unsigned char *rsabuf, *keystr1, *keystr2;
2184 unsigned char cookie[8];
2185 struct RSAKey servkey, hostkey;
2186 struct MD5Context md5c;
2187 static unsigned long supported_ciphers_mask, supported_auths_mask;
2188 static int tried_publickey, tried_agent;
2189 static int tis_auth_refused, ccard_auth_refused;
2190 static unsigned char session_id[16];
2191 static int cipher_type;
2192 static char username[100];
2193 static void *publickey_blob;
2194 int publickey_bloblen;
2201 if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
2202 bombout(("Public key packet not received"));
2206 logevent("Received public keys");
2208 memcpy(cookie, pktin.body, 8);
2210 i = makekey(pktin.body + 8, &servkey, &keystr1, 0);
2211 j = makekey(pktin.body + 8 + i, &hostkey, &keystr2, 0);
2214 * Log the host key fingerprint.
2218 logevent("Host key fingerprint is:");
2219 strcpy(logmsg, " ");
2220 hostkey.comment = NULL;
2221 rsa_fingerprint(logmsg + strlen(logmsg),
2222 sizeof(logmsg) - strlen(logmsg), &hostkey);
2226 ssh1_remote_protoflags = GET_32BIT(pktin.body + 8 + i + j);
2227 supported_ciphers_mask = GET_32BIT(pktin.body + 12 + i + j);
2228 supported_auths_mask = GET_32BIT(pktin.body + 16 + i + j);
2230 ssh1_local_protoflags =
2231 ssh1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
2232 ssh1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
2235 MD5Update(&md5c, keystr2, hostkey.bytes);
2236 MD5Update(&md5c, keystr1, servkey.bytes);
2237 MD5Update(&md5c, pktin.body, 8);
2238 MD5Final(session_id, &md5c);
2240 for (i = 0; i < 32; i++)
2241 session_key[i] = random_byte();
2243 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
2245 rsabuf = smalloc(len);
2247 fatalbox("Out of memory");
2250 * Verify the host key.
2254 * First format the key into a string.
2256 int len = rsastr_len(&hostkey);
2257 char fingerprint[100];
2258 char *keystr = smalloc(len);
2260 fatalbox("Out of memory");
2261 rsastr_fmt(keystr, &hostkey);
2262 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
2263 verify_ssh_host_key(savedhost, savedport, "rsa", keystr,
2268 for (i = 0; i < 32; i++) {
2269 rsabuf[i] = session_key[i];
2271 rsabuf[i] ^= session_id[i];
2274 if (hostkey.bytes > servkey.bytes) {
2275 rsaencrypt(rsabuf, 32, &servkey);
2276 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
2278 rsaencrypt(rsabuf, 32, &hostkey);
2279 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
2282 logevent("Encrypted session key");
2285 int cipher_chosen = 0, warn = 0;
2286 char *cipher_string = NULL;
2287 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
2288 int next_cipher = cfg.ssh_cipherlist[i];
2289 if (next_cipher == CIPHER_WARN) {
2290 /* If/when we choose a cipher, warn about it */
2292 } else if (next_cipher == CIPHER_AES) {
2293 /* XXX Probably don't need to mention this. */
2294 logevent("AES not supported in SSH1, skipping");
2296 switch (next_cipher) {
2297 case CIPHER_3DES: cipher_type = SSH_CIPHER_3DES;
2298 cipher_string = "3DES"; break;
2299 case CIPHER_BLOWFISH: cipher_type = SSH_CIPHER_BLOWFISH;
2300 cipher_string = "Blowfish"; break;
2301 case CIPHER_DES: cipher_type = SSH_CIPHER_DES;
2302 cipher_string = "single-DES"; break;
2304 if (supported_ciphers_mask & (1 << cipher_type))
2308 if (!cipher_chosen) {
2309 if ((supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
2310 bombout(("Server violates SSH 1 protocol by not "
2311 "supporting 3DES encryption"));
2313 /* shouldn't happen */
2314 bombout(("No supported ciphers found"));
2318 /* Warn about chosen cipher if necessary. */
2320 askcipher(cipher_string, 0);
2323 switch (cipher_type) {
2324 case SSH_CIPHER_3DES:
2325 logevent("Using 3DES encryption");
2327 case SSH_CIPHER_DES:
2328 logevent("Using single-DES encryption");
2330 case SSH_CIPHER_BLOWFISH:
2331 logevent("Using Blowfish encryption");
2335 send_packet(SSH1_CMSG_SESSION_KEY,
2336 PKT_CHAR, cipher_type,
2337 PKT_DATA, cookie, 8,
2338 PKT_CHAR, (len * 8) >> 8, PKT_CHAR, (len * 8) & 0xFF,
2339 PKT_DATA, rsabuf, len,
2340 PKT_INT, ssh1_local_protoflags, PKT_END);
2342 logevent("Trying to enable encryption...");
2346 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
2347 cipher_type == SSH_CIPHER_DES ? &ssh_des : &ssh_3des;
2348 cipher->sesskey(session_key);
2352 if (pktin.type != SSH1_SMSG_SUCCESS) {
2353 bombout(("Encryption not successfully enabled"));
2357 logevent("Successfully started encryption");
2361 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2362 if (ssh_get_line && !ssh_getline_pw_only) {
2363 if (!ssh_get_line("login as: ",
2364 username, sizeof(username), FALSE)) {
2366 * get_line failed to get a username.
2369 logevent("No username provided. Abandoning session.");
2370 ssh_state = SSH_STATE_CLOSED;
2375 c_write_str("login as: ");
2378 setup_userpass_input(username, sizeof(username), 1);
2380 crWaitUntil(!ispkt);
2381 ret = process_userpass_input(in, inlen);
2385 c_write_str("\r\n");
2388 strncpy(username, cfg.username, sizeof(username));
2389 username[sizeof(username)-1] = '\0';
2392 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
2394 char userlog[22 + sizeof(username)];
2395 sprintf(userlog, "Sent username \"%s\"", username);
2397 if (flags & FLAG_INTERACTIVE &&
2398 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
2399 strcat(userlog, "\r\n");
2400 c_write_str(userlog);
2407 if ((ssh_remote_bugs & BUG_CHOKES_ON_RSA)) {
2408 /* We must not attempt PK auth. Pretend we've already tried it. */
2409 tried_publickey = tried_agent = 1;
2411 tried_publickey = tried_agent = 0;
2413 tis_auth_refused = ccard_auth_refused = 0;
2414 /* Load the public half of cfg.keyfile so we notice if it's in Pageant */
2416 if (!rsakey_pubblob(cfg.keyfile, &publickey_blob, &publickey_bloblen))
2417 publickey_blob = NULL;
2419 publickey_blob = NULL;
2421 while (pktin.type == SSH1_SMSG_FAILURE) {
2422 static char password[100];
2423 static char prompt[200];
2426 static int pwpkt_type;
2427 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2429 if (agent_exists() && !tried_agent) {
2431 * Attempt RSA authentication using Pageant.
2433 static unsigned char request[5], *response, *p;
2434 static int responselen;
2435 static int i, nkeys;
2436 static int authed = FALSE;
2440 logevent("Pageant is running. Requesting keys.");
2442 /* Request the keys held by the agent. */
2443 PUT_32BIT(request, 1);
2444 request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2445 agent_query(request, 5, &r, &responselen);
2446 response = (unsigned char *) r;
2447 if (response && responselen >= 5 &&
2448 response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2450 nkeys = GET_32BIT(p);
2454 sprintf(buf, "Pageant has %d SSH1 keys", nkeys);
2457 for (i = 0; i < nkeys; i++) {
2458 static struct RSAKey key;
2459 static Bignum challenge;
2460 static char *commentp;
2461 static int commentlen;
2465 sprintf(buf, "Trying Pageant key #%d", i);
2468 if (publickey_blob &&
2469 !memcmp(p, publickey_blob, publickey_bloblen)) {
2470 logevent("This key matches configured key file");
2471 tried_publickey = 1;
2474 p += ssh1_read_bignum(p, &key.exponent);
2475 p += ssh1_read_bignum(p, &key.modulus);
2476 commentlen = GET_32BIT(p);
2480 send_packet(SSH1_CMSG_AUTH_RSA,
2481 PKT_BIGNUM, key.modulus, PKT_END);
2483 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2484 logevent("Key refused");
2487 logevent("Received RSA challenge");
2488 ssh1_read_bignum(pktin.body, &challenge);
2490 char *agentreq, *q, *ret;
2493 len = 1 + 4; /* message type, bit count */
2494 len += ssh1_bignum_length(key.exponent);
2495 len += ssh1_bignum_length(key.modulus);
2496 len += ssh1_bignum_length(challenge);
2497 len += 16; /* session id */
2498 len += 4; /* response format */
2499 agentreq = smalloc(4 + len);
2500 PUT_32BIT(agentreq, len);
2502 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
2503 PUT_32BIT(q, bignum_bitcount(key.modulus));
2505 q += ssh1_write_bignum(q, key.exponent);
2506 q += ssh1_write_bignum(q, key.modulus);
2507 q += ssh1_write_bignum(q, challenge);
2508 memcpy(q, session_id, 16);
2510 PUT_32BIT(q, 1); /* response format */
2511 agent_query(agentreq, len + 4, &vret, &retlen);
2515 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
2516 logevent("Sending Pageant's response");
2517 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
2518 PKT_DATA, ret + 5, 16,
2522 if (pktin.type == SSH1_SMSG_SUCCESS) {
2524 ("Pageant's response accepted");
2525 if (flags & FLAG_VERBOSE) {
2527 ("Authenticated using RSA key \"");
2528 c_write(commentp, commentlen);
2529 c_write_str("\" from agent\r\n");
2534 ("Pageant's response not accepted");
2537 ("Pageant failed to answer challenge");
2541 logevent("No reply received from Pageant");
2544 freebn(key.exponent);
2545 freebn(key.modulus);
2554 if (*cfg.keyfile && !tried_publickey)
2555 pwpkt_type = SSH1_CMSG_AUTH_RSA;
2557 if (cfg.try_tis_auth &&
2558 (supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
2559 !tis_auth_refused) {
2560 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
2561 logevent("Requested TIS authentication");
2562 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
2564 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
2565 logevent("TIS authentication declined");
2566 if (flags & FLAG_INTERACTIVE)
2567 c_write_str("TIS authentication refused.\r\n");
2568 tis_auth_refused = 1;
2571 int challengelen = ((pktin.body[0] << 24) |
2572 (pktin.body[1] << 16) |
2573 (pktin.body[2] << 8) |
2575 logevent("Received TIS challenge");
2576 if (challengelen > sizeof(prompt) - 1)
2577 challengelen = sizeof(prompt) - 1; /* prevent overrun */
2578 memcpy(prompt, pktin.body + 4, challengelen);
2579 /* Prompt heuristic comes from OpenSSH */
2580 strncpy(prompt + challengelen,
2581 memchr(prompt, '\n', challengelen) ?
2582 "": "\r\nResponse: ",
2583 (sizeof prompt) - challengelen);
2584 prompt[(sizeof prompt) - 1] = '\0';
2587 if (cfg.try_tis_auth &&
2588 (supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
2589 !ccard_auth_refused) {
2590 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
2591 logevent("Requested CryptoCard authentication");
2592 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
2594 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
2595 logevent("CryptoCard authentication declined");
2596 c_write_str("CryptoCard authentication refused.\r\n");
2597 ccard_auth_refused = 1;
2600 int challengelen = ((pktin.body[0] << 24) |
2601 (pktin.body[1] << 16) |
2602 (pktin.body[2] << 8) |
2604 logevent("Received CryptoCard challenge");
2605 if (challengelen > sizeof(prompt) - 1)
2606 challengelen = sizeof(prompt) - 1; /* prevent overrun */
2607 memcpy(prompt, pktin.body + 4, challengelen);
2608 strncpy(prompt + challengelen,
2609 memchr(prompt, '\n', challengelen) ?
2610 "" : "\r\nResponse: ",
2611 sizeof(prompt) - challengelen);
2612 prompt[sizeof(prompt) - 1] = '\0';
2615 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2616 sprintf(prompt, "%.90s@%.90s's password: ",
2617 username, savedhost);
2619 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2620 char *comment = NULL;
2623 if (flags & FLAG_VERBOSE)
2624 c_write_str("Trying public key authentication.\r\n");
2625 sprintf(msgbuf, "Trying public key \"%.200s\"", cfg.keyfile);
2627 type = key_type(cfg.keyfile);
2628 if (type != SSH_KEYTYPE_SSH1) {
2629 sprintf(msgbuf, "Key is of wrong type (%s)",
2630 key_type_to_str(type));
2632 c_write_str(msgbuf);
2633 c_write_str("\r\n");
2634 tried_publickey = 1;
2637 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
2638 if (flags & FLAG_VERBOSE)
2639 c_write_str("No passphrase required.\r\n");
2642 sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
2647 * Show password prompt, having first obtained it via a TIS
2648 * or CryptoCard exchange if we're doing TIS or CryptoCard
2652 if (!ssh_get_line(prompt, password, sizeof(password), TRUE)) {
2654 * get_line failed to get a password (for example
2655 * because one was supplied on the command line
2656 * which has already failed to work). Terminate.
2658 send_packet(SSH1_MSG_DISCONNECT,
2659 PKT_STR, "No more passwords available to try",
2661 logevent("Unable to authenticate");
2662 connection_fatal("Unable to authenticate");
2663 ssh_state = SSH_STATE_CLOSED;
2667 /* Prompt may have come from server. We've munged it a bit, so
2668 * we know it to be zero-terminated at least once. */
2670 c_write_untrusted(prompt, strlen(prompt));
2673 setup_userpass_input(password, sizeof(password), 0);
2675 crWaitUntil(!ispkt);
2676 ret = process_userpass_input(in, inlen);
2680 c_write_str("\r\n");
2684 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2686 * Try public key authentication with the specified
2689 static struct RSAKey pubkey;
2690 static Bignum challenge, response;
2692 static unsigned char buffer[32];
2694 tried_publickey = 1;
2695 i = loadrsakey(cfg.keyfile, &pubkey, password);
2697 c_write_str("Couldn't load private key from ");
2698 c_write_str(cfg.keyfile);
2699 c_write_str(".\r\n");
2700 continue; /* go and try password */
2703 c_write_str("Wrong passphrase.\r\n");
2704 tried_publickey = 0;
2705 continue; /* try again */
2709 * Send a public key attempt.
2711 send_packet(SSH1_CMSG_AUTH_RSA,
2712 PKT_BIGNUM, pubkey.modulus, PKT_END);
2715 if (pktin.type == SSH1_SMSG_FAILURE) {
2716 c_write_str("Server refused our public key.\r\n");
2717 continue; /* go and try password */
2719 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2720 bombout(("Bizarre response to offer of public key"));
2723 ssh1_read_bignum(pktin.body, &challenge);
2724 response = rsadecrypt(challenge, &pubkey);
2725 freebn(pubkey.private_exponent); /* burn the evidence */
2727 for (i = 0; i < 32; i++) {
2728 buffer[i] = bignum_byte(response, 31 - i);
2732 MD5Update(&md5c, buffer, 32);
2733 MD5Update(&md5c, session_id, 16);
2734 MD5Final(buffer, &md5c);
2736 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
2737 PKT_DATA, buffer, 16, PKT_END);
2740 if (pktin.type == SSH1_SMSG_FAILURE) {
2741 if (flags & FLAG_VERBOSE)
2743 ("Failed to authenticate with our public key.\r\n");
2744 continue; /* go and try password */
2745 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
2747 ("Bizarre response to RSA authentication response"));
2751 break; /* we're through! */
2753 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2755 * Defence against traffic analysis: we send a
2756 * whole bunch of packets containing strings of
2757 * different lengths. One of these strings is the
2758 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2759 * The others are all random data in
2760 * SSH1_MSG_IGNORE packets. This way a passive
2761 * listener can't tell which is the password, and
2762 * hence can't deduce the password length.
2764 * Anybody with a password length greater than 16
2765 * bytes is going to have enough entropy in their
2766 * password that a listener won't find it _that_
2767 * much help to know how long it is. So what we'll
2770 * - if password length < 16, we send 15 packets
2771 * containing string lengths 1 through 15
2773 * - otherwise, we let N be the nearest multiple
2774 * of 8 below the password length, and send 8
2775 * packets containing string lengths N through
2776 * N+7. This won't obscure the order of
2777 * magnitude of the password length, but it will
2778 * introduce a bit of extra uncertainty.
2780 * A few servers (the old 1.2.18 through 1.2.22)
2781 * can't deal with SSH1_MSG_IGNORE. For these
2782 * servers, we need an alternative defence. We make
2783 * use of the fact that the password is interpreted
2784 * as a C string: so we can append a NUL, then some
2787 * One server (a Cisco one) can deal with neither
2788 * SSH1_MSG_IGNORE _nor_ a padded password string.
2789 * For this server we are left with no defences
2790 * against password length sniffing.
2792 if (!(ssh_remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
2794 * The server can deal with SSH1_MSG_IGNORE, so
2795 * we can use the primary defence.
2797 int bottom, top, pwlen, i;
2800 pwlen = strlen(password);
2802 bottom = 0; /* zero length passwords are OK! :-) */
2805 bottom = pwlen & ~7;
2809 assert(pwlen >= bottom && pwlen <= top);
2811 randomstr = smalloc(top + 1);
2813 for (i = bottom; i <= top; i++) {
2815 defer_packet(pwpkt_type, PKT_STR, password,
2818 for (j = 0; j < i; j++) {
2820 randomstr[j] = random_byte();
2821 } while (randomstr[j] == '\0');
2823 randomstr[i] = '\0';
2824 defer_packet(SSH1_MSG_IGNORE,
2825 PKT_STR, randomstr, PKT_END);
2828 logevent("Sending password with camouflage packets");
2829 ssh_pkt_defersend();
2831 else if (!(ssh_remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
2833 * The server can't deal with SSH1_MSG_IGNORE
2834 * but can deal with padded passwords, so we
2835 * can use the secondary defence.
2841 len = strlen(password);
2842 if (len < sizeof(string)) {
2844 strcpy(string, password);
2845 len++; /* cover the zero byte */
2846 while (len < sizeof(string)) {
2847 string[len++] = (char) random_byte();
2852 logevent("Sending length-padded password");
2853 send_packet(pwpkt_type, PKT_INT, len,
2854 PKT_DATA, s, len, PKT_END);
2857 * The server has _both_
2858 * BUG_CHOKES_ON_SSH1_IGNORE and
2859 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2860 * therefore nothing we can do.
2863 len = strlen(password);
2864 logevent("Sending unpadded password");
2865 send_packet(pwpkt_type, PKT_INT, len,
2866 PKT_DATA, password, len, PKT_END);
2869 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
2872 logevent("Sent password");
2873 memset(password, 0, strlen(password));
2875 if (pktin.type == SSH1_SMSG_FAILURE) {
2876 if (flags & FLAG_VERBOSE)
2877 c_write_str("Access denied\r\n");
2878 logevent("Authentication refused");
2879 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2880 logevent("Received disconnect request");
2881 ssh_state = SSH_STATE_CLOSED;
2883 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
2884 bombout(("Strange packet received, type %d", pktin.type));
2889 logevent("Authentication successful");
2894 void sshfwd_close(struct ssh_channel *c)
2896 if (c && !c->closes) {
2898 * If the channel's remoteid is -1, we have sent
2899 * CHANNEL_OPEN for this channel, but it hasn't even been
2900 * acknowledged by the server. So we must set a close flag
2901 * on it now, and then when the server acks the channel
2902 * open, we can close it then.
2904 if (((int)c->remoteid) != -1) {
2905 if (ssh_version == 1) {
2906 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
2909 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2910 ssh2_pkt_adduint32(c->remoteid);
2914 c->closes = 1; /* sent MSG_CLOSE */
2915 if (c->type == CHAN_X11) {
2917 logevent("Forwarded X11 connection terminated");
2918 } else if (c->type == CHAN_SOCKDATA ||
2919 c->type == CHAN_SOCKDATA_DORMANT) {
2921 logevent("Forwarded port closed");
2926 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
2928 if (ssh_version == 1) {
2929 send_packet(SSH1_MSG_CHANNEL_DATA,
2930 PKT_INT, c->remoteid,
2931 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2933 * In SSH1 we can return 0 here - implying that forwarded
2934 * connections are never individually throttled - because
2935 * the only circumstance that can cause throttling will be
2936 * the whole SSH connection backing up, in which case
2937 * _everything_ will be throttled as a whole.
2941 ssh2_add_channel_data(c, buf, len);
2942 return ssh2_try_send(c);
2946 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
2948 if (ssh_version == 1) {
2949 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
2950 c->v.v1.throttling = 0;
2954 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
2958 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt)
2964 while (!do_ssh1_login(in, inlen, ispkt)) {
2967 if (ssh_state == SSH_STATE_CLOSED)
2970 if (cfg.agentfwd && agent_exists()) {
2971 logevent("Requesting agent forwarding");
2972 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
2976 if (pktin.type != SSH1_SMSG_SUCCESS
2977 && pktin.type != SSH1_SMSG_FAILURE) {
2978 bombout(("Protocol confusion"));
2980 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2981 logevent("Agent forwarding refused");
2983 logevent("Agent forwarding enabled");
2984 ssh_agentfwd_enabled = TRUE;
2988 if (cfg.x11_forward) {
2989 char proto[20], data[64];
2990 logevent("Requesting X11 forwarding");
2991 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
2992 if (ssh1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
2993 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2994 PKT_STR, proto, PKT_STR, data,
2995 PKT_INT, 0, PKT_END);
2997 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2998 PKT_STR, proto, PKT_STR, data, PKT_END);
3003 if (pktin.type != SSH1_SMSG_SUCCESS
3004 && pktin.type != SSH1_SMSG_FAILURE) {
3005 bombout(("Protocol confusion"));
3007 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3008 logevent("X11 forwarding refused");
3010 logevent("X11 forwarding enabled");
3011 ssh_X11_fwd_enabled = TRUE;
3019 int sport,dport,sserv,dserv;
3020 char sports[256], dports[256], host[256];
3024 ssh_rportfwds = newtree234(ssh_rportcmp_ssh1);
3025 /* Add port forwardings. */
3030 while (*e && *e != '\t')
3036 while (*e && *e != ':')
3046 dport = atoi(dports);
3050 se = getservbyname(dports, NULL);
3052 dport = ntohs(se->s_port);
3055 "Service lookup failed for destination port \"%s\"",
3060 sport = atoi(sports);
3064 se = getservbyname(sports, NULL);
3066 sport = ntohs(se->s_port);
3069 "Service lookup failed for source port \"%s\"",
3074 if (sport && dport) {
3076 pfd_addforward(host, dport, sport);
3077 sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
3078 " %s:%.*s%.*s%d%.*s",
3079 sserv ? strlen(sports) : 0, sports,
3080 sserv, "(", sport, sserv, ")",
3082 dserv ? strlen(dports) : 0, dports,
3083 dserv, "(", dport, dserv, ")");
3086 struct ssh_rportfwd *pf;
3087 pf = smalloc(sizeof(*pf));
3088 strcpy(pf->dhost, host);
3090 if (add234(ssh_rportfwds, pf) != pf) {
3092 "Duplicate remote port forwarding to %s:%d",
3097 sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
3098 " forward to %s:%.*s%.*s%d%.*s",
3099 sserv ? strlen(sports) : 0, sports,
3100 sserv, "(", sport, sserv, ")",
3102 dserv ? strlen(dports) : 0, dports,
3103 dserv, "(", dport, dserv, ")");
3105 send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST,
3113 if (pktin.type != SSH1_SMSG_SUCCESS
3114 && pktin.type != SSH1_SMSG_FAILURE) {
3115 bombout(("Protocol confusion"));
3117 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3118 c_write_str("Server refused port forwarding\r\n");
3119 ssh_editing = ssh_echoing = 1;
3121 logevent("Remote port forwarding enabled");
3129 send_packet(SSH1_CMSG_REQUEST_PTY,
3130 PKT_STR, cfg.termtype,
3131 PKT_INT, rows, PKT_INT, cols,
3132 PKT_INT, 0, PKT_INT, 0, PKT_CHAR, 0, PKT_END);
3133 ssh_state = SSH_STATE_INTERMED;
3137 if (pktin.type != SSH1_SMSG_SUCCESS
3138 && pktin.type != SSH1_SMSG_FAILURE) {
3139 bombout(("Protocol confusion"));
3141 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3142 c_write_str("Server refused to allocate pty\r\n");
3143 ssh_editing = ssh_echoing = 1;
3145 logevent("Allocated pty");
3147 ssh_editing = ssh_echoing = 1;
3150 if (cfg.compression) {
3151 send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
3155 if (pktin.type != SSH1_SMSG_SUCCESS
3156 && pktin.type != SSH1_SMSG_FAILURE) {
3157 bombout(("Protocol confusion"));
3159 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3160 c_write_str("Server refused to compress\r\n");
3162 logevent("Started compression");
3163 ssh1_compressing = TRUE;
3164 zlib_compress_init();
3165 zlib_decompress_init();
3169 * Start the shell or command.
3171 * Special case: if the first-choice command is an SSH2
3172 * subsystem (hence not usable here) and the second choice
3173 * exists, we fall straight back to that.
3176 char *cmd = cfg.remote_cmd_ptr;
3178 if (cfg.ssh_subsys && cfg.remote_cmd_ptr2) {
3179 cmd = cfg.remote_cmd_ptr2;
3180 ssh_fallback_cmd = TRUE;
3183 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
3185 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
3186 logevent("Started session");
3189 ssh_state = SSH_STATE_SESSION;
3193 ssh_special(TS_EOF);
3195 ldisc_send(NULL, 0, 0); /* cause ldisc to notice changes */
3197 ssh_channels = newtree234(ssh_channelcmp);
3201 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
3202 pktin.type == SSH1_SMSG_STDERR_DATA) {
3203 long len = GET_32BIT(pktin.body);
3205 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
3206 pktin.body + 4, len);
3207 if (!ssh1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
3208 ssh1_stdout_throttling = 1;
3211 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
3212 ssh_state = SSH_STATE_CLOSED;
3213 logevent("Received disconnect request");
3215 } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
3216 /* Remote side is trying to open a channel to talk to our
3217 * X-Server. Give them back a local channel number. */
3218 struct ssh_channel *c;
3220 logevent("Received X11 connect request");
3221 /* Refuse if X11 forwarding is disabled. */
3222 if (!ssh_X11_fwd_enabled) {
3223 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3224 PKT_INT, GET_32BIT(pktin.body), PKT_END);
3225 logevent("Rejected X11 connect request");
3227 c = smalloc(sizeof(struct ssh_channel));
3229 if (x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL) {
3230 logevent("opening X11 forward connection failed");
3232 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3233 PKT_INT, GET_32BIT(pktin.body),
3237 ("opening X11 forward connection succeeded");
3238 c->remoteid = GET_32BIT(pktin.body);
3239 c->localid = alloc_channel_id();
3241 c->v.v1.throttling = 0;
3242 c->type = CHAN_X11; /* identify channel type */
3243 add234(ssh_channels, c);
3244 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3245 PKT_INT, c->remoteid, PKT_INT,
3246 c->localid, PKT_END);
3247 logevent("Opened X11 forward channel");
3250 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
3251 /* Remote side is trying to open a channel to talk to our
3252 * agent. Give them back a local channel number. */
3253 struct ssh_channel *c;
3255 /* Refuse if agent forwarding is disabled. */
3256 if (!ssh_agentfwd_enabled) {
3257 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3258 PKT_INT, GET_32BIT(pktin.body), PKT_END);
3260 c = smalloc(sizeof(struct ssh_channel));
3261 c->remoteid = GET_32BIT(pktin.body);
3262 c->localid = alloc_channel_id();
3264 c->v.v1.throttling = 0;
3265 c->type = CHAN_AGENT; /* identify channel type */
3266 c->u.a.lensofar = 0;
3267 add234(ssh_channels, c);
3268 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3269 PKT_INT, c->remoteid, PKT_INT, c->localid,
3272 } else if (pktin.type == SSH1_MSG_PORT_OPEN) {
3273 /* Remote side is trying to open a channel to talk to a
3274 * forwarded port. Give them back a local channel number. */
3275 struct ssh_channel *c;
3276 struct ssh_rportfwd pf;
3278 char host[256], buf[1024];
3280 c = smalloc(sizeof(struct ssh_channel));
3282 hostsize = GET_32BIT(pktin.body+4);
3283 for(h = host, p = pktin.body+8; hostsize != 0; hostsize--) {
3284 if (h+1 < host+sizeof(host))
3289 port = GET_32BIT(p);
3291 strcpy(pf.dhost, host);
3294 if (find234(ssh_rportfwds, &pf, NULL) == NULL) {
3295 sprintf(buf, "Rejected remote port open request for %s:%d",
3298 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3299 PKT_INT, GET_32BIT(pktin.body), PKT_END);
3301 sprintf(buf, "Received remote port open request for %s:%d",
3304 e = pfd_newconnect(&c->u.pfd.s, host, port, c);
3307 sprintf(buf, "Port open failed: %s", e);
3310 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3311 PKT_INT, GET_32BIT(pktin.body),
3314 c->remoteid = GET_32BIT(pktin.body);
3315 c->localid = alloc_channel_id();
3317 c->v.v1.throttling = 0;
3318 c->type = CHAN_SOCKDATA; /* identify channel type */
3319 add234(ssh_channels, c);
3320 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3321 PKT_INT, c->remoteid, PKT_INT,
3322 c->localid, PKT_END);
3323 logevent("Forwarded port opened successfully");
3327 } else if (pktin.type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
3328 unsigned int remoteid = GET_32BIT(pktin.body);
3329 unsigned int localid = GET_32BIT(pktin.body+4);
3330 struct ssh_channel *c;
3332 c = find234(ssh_channels, &remoteid, ssh_channelfind);
3333 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3334 c->remoteid = localid;
3335 c->type = CHAN_SOCKDATA;
3336 c->v.v1.throttling = 0;
3337 pfd_confirm(c->u.pfd.s);
3340 if (c && c->closes) {
3342 * We have a pending close on this channel,
3343 * which we decided on before the server acked
3344 * the channel open. So now we know the
3345 * remoteid, we can close it again.
3347 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
3351 } else if (pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
3352 unsigned int remoteid = GET_32BIT(pktin.body);
3353 unsigned int localid = GET_32BIT(pktin.body+4);
3354 struct ssh_channel *c;
3356 c = find234(ssh_channels, &remoteid, ssh_channelfind);
3357 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3358 logevent("Forwarded connection refused by server");
3359 pfd_close(c->u.pfd.s);
3360 del234(ssh_channels, c);
3364 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
3365 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
3366 /* Remote side closes a channel. */
3367 unsigned i = GET_32BIT(pktin.body);
3368 struct ssh_channel *c;
3369 c = find234(ssh_channels, &i, ssh_channelfind);
3370 if (c && ((int)c->remoteid) != -1) {
3373 (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
3375 if ((c->closes == 0) && (c->type == CHAN_X11)) {
3376 logevent("Forwarded X11 connection terminated");
3377 assert(c->u.x11.s != NULL);
3378 x11_close(c->u.x11.s);
3381 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
3382 logevent("Forwarded port closed");
3383 assert(c->u.pfd.s != NULL);
3384 pfd_close(c->u.pfd.s);
3388 c->closes |= (closetype << 2); /* seen this message */
3389 if (!(c->closes & closetype)) {
3390 send_packet(pktin.type, PKT_INT, c->remoteid,
3392 c->closes |= closetype; /* sent it too */
3395 if (c->closes == 15) {
3396 del234(ssh_channels, c);
3400 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
3401 pktin.type == SSH1_MSG_CHANNEL_CLOSE ? "" :
3402 "_CONFIRMATION", c ? "half-open" : "nonexistent",
3405 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
3406 /* Data sent down one of our channels. */
3407 int i = GET_32BIT(pktin.body);
3408 int len = GET_32BIT(pktin.body + 4);
3409 unsigned char *p = pktin.body + 8;
3410 struct ssh_channel *c;
3411 c = find234(ssh_channels, &i, ssh_channelfind);
3416 bufsize = x11_send(c->u.x11.s, p, len);
3419 bufsize = pfd_send(c->u.pfd.s, p, len);
3422 /* Data for an agent message. Buffer it. */
3424 if (c->u.a.lensofar < 4) {
3425 int l = min(4 - c->u.a.lensofar, len);
3426 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
3430 c->u.a.lensofar += l;
3432 if (c->u.a.lensofar == 4) {
3434 4 + GET_32BIT(c->u.a.msglen);
3435 c->u.a.message = smalloc(c->u.a.totallen);
3436 memcpy(c->u.a.message, c->u.a.msglen, 4);
3438 if (c->u.a.lensofar >= 4 && len > 0) {
3440 min(c->u.a.totallen - c->u.a.lensofar,
3442 memcpy(c->u.a.message + c->u.a.lensofar, p,
3446 c->u.a.lensofar += l;
3448 if (c->u.a.lensofar == c->u.a.totallen) {
3449 void *reply, *sentreply;
3451 agent_query(c->u.a.message,
3452 c->u.a.totallen, &reply,
3457 /* Fake SSH_AGENT_FAILURE. */
3458 sentreply = "\0\0\0\1\5";
3461 send_packet(SSH1_MSG_CHANNEL_DATA,
3462 PKT_INT, c->remoteid,
3464 PKT_DATA, sentreply, replylen,
3468 sfree(c->u.a.message);
3469 c->u.a.lensofar = 0;
3472 bufsize = 0; /* agent channels never back up */
3475 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
3476 c->v.v1.throttling = 1;
3480 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
3481 /* may be from EXEC_SHELL on some servers */
3482 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3483 /* may be from EXEC_SHELL on some servers
3484 * if no pty is available or in other odd cases. Ignore */
3485 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
3487 ssh_exitcode = GET_32BIT(pktin.body);
3488 sprintf(buf, "Server sent command exit status %d",
3491 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
3493 * In case `helpful' firewalls or proxies tack
3494 * extra human-readable text on the end of the
3495 * session which we might mistake for another
3496 * encrypted packet, we close the session once
3497 * we've sent EXIT_CONFIRMATION.
3499 ssh_state = SSH_STATE_CLOSED;
3502 bombout(("Strange packet received: type %d", pktin.type));
3507 int len = min(inlen, 512);
3508 send_packet(SSH1_CMSG_STDIN_DATA,
3509 PKT_INT, len, PKT_DATA, in, len, PKT_END);
3520 * Utility routine for decoding comma-separated strings in KEXINIT.
3522 static int in_commasep_string(char *needle, char *haystack, int haylen)
3525 if (!needle || !haystack)
3526 return 0; /* protect against null pointers */
3527 needlen = strlen(needle);
3530 * Is it at the start of the string?
3532 if (haylen >= needlen && /* haystack is long enough */
3533 !memcmp(needle, haystack, needlen) && /* initial match */
3534 (haylen == needlen || haystack[needlen] == ',')
3535 /* either , or EOS follows */
3539 * If not, search for the next comma and resume after that.
3540 * If no comma found, terminate.
3542 while (haylen > 0 && *haystack != ',')
3543 haylen--, haystack++;
3546 haylen--, haystack++; /* skip over comma itself */
3551 * SSH2 key creation method.
3553 static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr,
3557 /* First 20 bytes. */
3559 if (!(ssh_remote_bugs & BUG_SSH2_DERIVEKEY))
3561 SHA_Bytes(&s, H, 20);
3562 SHA_Bytes(&s, &chr, 1);
3563 SHA_Bytes(&s, sessid, 20);
3564 SHA_Final(&s, keyspace);
3565 /* Next 20 bytes. */
3567 if (!(ssh_remote_bugs & BUG_SSH2_DERIVEKEY))
3569 SHA_Bytes(&s, H, 20);
3570 SHA_Bytes(&s, keyspace, 20);
3571 SHA_Final(&s, keyspace + 20);
3575 * Handle the SSH2 transport layer.
3577 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
3579 static int i, j, len, nbits, pbits, warn;
3581 static Bignum p, g, e, f, K;
3582 static int kex_init_value, kex_reply_value;
3583 static const struct ssh_mac **maclist;
3585 static const struct ssh2_cipher *cscipher_tobe = NULL;
3586 static const struct ssh2_cipher *sccipher_tobe = NULL;
3587 static const struct ssh_mac *csmac_tobe = NULL;
3588 static const struct ssh_mac *scmac_tobe = NULL;
3589 static const struct ssh_compress *cscomp_tobe = NULL;
3590 static const struct ssh_compress *sccomp_tobe = NULL;
3591 static char *hostkeydata, *sigdata, *keystr, *fingerprint;
3592 static int hostkeylen, siglen;
3593 static void *hkey; /* actual host key */
3594 static unsigned char exchange_hash[20];
3595 static unsigned char keyspace[40];
3596 static int n_preferred_ciphers;
3597 static const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
3598 static const struct ssh_compress *preferred_comp;
3599 static int cipherstr_started;
3600 static int first_kex;
3607 * Set up the preferred ciphers. (NULL => warn below here)
3609 n_preferred_ciphers = 0;
3610 for (i = 0; i < CIPHER_MAX; i++) {
3611 switch (cfg.ssh_cipherlist[i]) {
3612 case CIPHER_BLOWFISH:
3613 preferred_ciphers[n_preferred_ciphers] = &ssh2_blowfish;
3614 n_preferred_ciphers++;
3617 if (cfg.ssh2_des_cbc) {
3618 preferred_ciphers[n_preferred_ciphers] = &ssh2_des;
3619 n_preferred_ciphers++;
3623 preferred_ciphers[n_preferred_ciphers] = &ssh2_3des;
3624 n_preferred_ciphers++;
3627 preferred_ciphers[n_preferred_ciphers] = &ssh2_aes;
3628 n_preferred_ciphers++;
3631 /* Flag for later. Don't bother if it's the last in
3633 if (i < CIPHER_MAX - 1) {
3634 preferred_ciphers[n_preferred_ciphers] = NULL;
3635 n_preferred_ciphers++;
3642 * Set up preferred compression.
3644 if (cfg.compression)
3645 preferred_comp = &ssh_zlib;
3647 preferred_comp = &ssh_comp_none;
3650 * Be prepared to work around the buggy MAC problem.
3652 if (ssh_remote_bugs & BUG_SSH2_HMAC)
3653 maclist = buggymacs, nmacs = lenof(buggymacs);
3655 maclist = macs, nmacs = lenof(macs);
3659 * Construct and send our key exchange packet.
3661 ssh2_pkt_init(SSH2_MSG_KEXINIT);
3662 for (i = 0; i < 16; i++)
3663 ssh2_pkt_addbyte((unsigned char) random_byte());
3664 /* List key exchange algorithms. */
3665 ssh2_pkt_addstring_start();
3666 for (i = 0; i < lenof(kex_algs); i++) {
3667 if (kex_algs[i] == &ssh_diffiehellman_gex &&
3668 (ssh_remote_bugs & BUG_SSH2_DH_GEX))
3670 ssh2_pkt_addstring_str(kex_algs[i]->name);
3671 if (i < lenof(kex_algs) - 1)
3672 ssh2_pkt_addstring_str(",");
3674 /* List server host key algorithms. */
3675 ssh2_pkt_addstring_start();
3676 for (i = 0; i < lenof(hostkey_algs); i++) {
3677 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
3678 if (i < lenof(hostkey_algs) - 1)
3679 ssh2_pkt_addstring_str(",");
3681 /* List client->server encryption algorithms. */
3682 ssh2_pkt_addstring_start();
3683 cipherstr_started = 0;
3684 for (i = 0; i < n_preferred_ciphers; i++) {
3685 const struct ssh2_ciphers *c = preferred_ciphers[i];
3686 if (!c) continue; /* warning flag */
3687 for (j = 0; j < c->nciphers; j++) {
3688 if (cipherstr_started)
3689 ssh2_pkt_addstring_str(",");
3690 ssh2_pkt_addstring_str(c->list[j]->name);
3691 cipherstr_started = 1;
3694 /* List server->client encryption algorithms. */
3695 ssh2_pkt_addstring_start();
3696 cipherstr_started = 0;
3697 for (i = 0; i < n_preferred_ciphers; i++) {
3698 const struct ssh2_ciphers *c = preferred_ciphers[i];
3699 if (!c) continue; /* warning flag */
3700 for (j = 0; j < c->nciphers; j++) {
3701 if (cipherstr_started)
3702 ssh2_pkt_addstring_str(",");
3703 ssh2_pkt_addstring_str(c->list[j]->name);
3704 cipherstr_started = 1;
3707 /* List client->server MAC algorithms. */
3708 ssh2_pkt_addstring_start();
3709 for (i = 0; i < nmacs; i++) {
3710 ssh2_pkt_addstring_str(maclist[i]->name);
3712 ssh2_pkt_addstring_str(",");
3714 /* List server->client MAC algorithms. */
3715 ssh2_pkt_addstring_start();
3716 for (i = 0; i < nmacs; i++) {
3717 ssh2_pkt_addstring_str(maclist[i]->name);
3719 ssh2_pkt_addstring_str(",");
3721 /* List client->server compression algorithms. */
3722 ssh2_pkt_addstring_start();
3723 for (i = 0; i < lenof(compressions) + 1; i++) {
3724 const struct ssh_compress *c =
3725 i == 0 ? preferred_comp : compressions[i - 1];
3726 ssh2_pkt_addstring_str(c->name);
3727 if (i < lenof(compressions))
3728 ssh2_pkt_addstring_str(",");
3730 /* List server->client compression algorithms. */
3731 ssh2_pkt_addstring_start();
3732 for (i = 0; i < lenof(compressions) + 1; i++) {
3733 const struct ssh_compress *c =
3734 i == 0 ? preferred_comp : compressions[i - 1];
3735 ssh2_pkt_addstring_str(c->name);
3736 if (i < lenof(compressions))
3737 ssh2_pkt_addstring_str(",");
3739 /* List client->server languages. Empty list. */
3740 ssh2_pkt_addstring_start();
3741 /* List server->client languages. Empty list. */
3742 ssh2_pkt_addstring_start();
3743 /* First KEX packet does _not_ follow, because we're not that brave. */
3744 ssh2_pkt_addbool(FALSE);
3746 ssh2_pkt_adduint32(0);
3748 exhash = exhashbase;
3749 sha_string(&exhash, pktout.data + 5, pktout.length - 5);
3755 if (pktin.length > 5)
3756 sha_string(&exhash, pktin.data + 5, pktin.length - 5);
3759 * Now examine the other side's KEXINIT to see what we're up
3762 if (pktin.type != SSH2_MSG_KEXINIT) {
3763 bombout(("expected key exchange packet from server"));
3768 cscipher_tobe = NULL;
3769 sccipher_tobe = NULL;
3774 pktin.savedpos += 16; /* skip garbage cookie */
3775 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
3776 for (i = 0; i < lenof(kex_algs); i++) {
3777 if (kex_algs[i] == &ssh_diffiehellman_gex &&
3778 (ssh_remote_bugs & BUG_SSH2_DH_GEX))
3780 if (in_commasep_string(kex_algs[i]->name, str, len)) {
3785 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
3786 for (i = 0; i < lenof(hostkey_algs); i++) {
3787 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
3788 hostkey = hostkey_algs[i];
3792 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
3794 for (i = 0; i < n_preferred_ciphers; i++) {
3795 const struct ssh2_ciphers *c = preferred_ciphers[i];
3799 for (j = 0; j < c->nciphers; j++) {
3800 if (in_commasep_string(c->list[j]->name, str, len)) {
3801 cscipher_tobe = c->list[j];
3806 if (cscipher_tobe) {
3808 askcipher(cscipher_tobe->name, 1);
3812 if (!cscipher_tobe) {
3813 bombout(("Couldn't agree a client-to-server cipher (available: %.450s)",
3818 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
3820 for (i = 0; i < n_preferred_ciphers; i++) {
3821 const struct ssh2_ciphers *c = preferred_ciphers[i];
3825 for (j = 0; j < c->nciphers; j++) {
3826 if (in_commasep_string(c->list[j]->name, str, len)) {
3827 sccipher_tobe = c->list[j];
3832 if (sccipher_tobe) {
3834 askcipher(sccipher_tobe->name, 2);
3838 if (!sccipher_tobe) {
3839 bombout(("Couldn't agree a server-to-client cipher (available: %.450s)",
3844 ssh2_pkt_getstring(&str, &len); /* client->server mac */
3845 for (i = 0; i < nmacs; i++) {
3846 if (in_commasep_string(maclist[i]->name, str, len)) {
3847 csmac_tobe = maclist[i];
3851 ssh2_pkt_getstring(&str, &len); /* server->client mac */
3852 for (i = 0; i < nmacs; i++) {
3853 if (in_commasep_string(maclist[i]->name, str, len)) {
3854 scmac_tobe = maclist[i];
3858 ssh2_pkt_getstring(&str, &len); /* client->server compression */
3859 for (i = 0; i < lenof(compressions) + 1; i++) {
3860 const struct ssh_compress *c =
3861 i == 0 ? preferred_comp : compressions[i - 1];
3862 if (in_commasep_string(c->name, str, len)) {
3867 ssh2_pkt_getstring(&str, &len); /* server->client compression */
3868 for (i = 0; i < lenof(compressions) + 1; i++) {
3869 const struct ssh_compress *c =
3870 i == 0 ? preferred_comp : compressions[i - 1];
3871 if (in_commasep_string(c->name, str, len)) {
3878 * Work out the number of bits of key we will need from the key
3879 * exchange. We start with the maximum key length of either
3885 csbits = cscipher_tobe->keylen;
3886 scbits = sccipher_tobe->keylen;
3887 nbits = (csbits > scbits ? csbits : scbits);
3889 /* The keys only have 160-bit entropy, since they're based on
3890 * a SHA-1 hash. So cap the key size at 160 bits. */
3895 * If we're doing Diffie-Hellman group exchange, start by
3896 * requesting a group.
3898 if (kex == &ssh_diffiehellman_gex) {
3899 logevent("Doing Diffie-Hellman group exchange");
3900 ssh_pkt_ctx |= SSH2_PKTCTX_DHGEX;
3902 * Work out how big a DH group we will need to allow that
3905 pbits = 512 << ((nbits - 1) / 64);
3906 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
3907 ssh2_pkt_adduint32(pbits);
3911 if (pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
3912 bombout(("expected key exchange group packet from server"));
3915 p = ssh2_pkt_getmp();
3916 g = ssh2_pkt_getmp();
3917 dh_setup_group(p, g);
3918 kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
3919 kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
3921 ssh_pkt_ctx |= SSH2_PKTCTX_DHGROUP1;
3923 kex_init_value = SSH2_MSG_KEXDH_INIT;
3924 kex_reply_value = SSH2_MSG_KEXDH_REPLY;
3927 logevent("Doing Diffie-Hellman key exchange");
3929 * Now generate and send e for Diffie-Hellman.
3931 e = dh_create_e(nbits * 2);
3932 ssh2_pkt_init(kex_init_value);
3937 if (pktin.type != kex_reply_value) {
3938 bombout(("expected key exchange reply packet from server"));
3941 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
3942 f = ssh2_pkt_getmp();
3943 ssh2_pkt_getstring(&sigdata, &siglen);
3947 sha_string(&exhash, hostkeydata, hostkeylen);
3948 if (kex == &ssh_diffiehellman_gex) {
3949 sha_uint32(&exhash, pbits);
3950 sha_mpint(&exhash, p);
3951 sha_mpint(&exhash, g);
3953 sha_mpint(&exhash, e);
3954 sha_mpint(&exhash, f);
3955 sha_mpint(&exhash, K);
3956 SHA_Final(&exhash, exchange_hash);
3961 debug(("Exchange hash is:\n"));
3962 dmemdump(exchange_hash, 20);
3965 hkey = hostkey->newkey(hostkeydata, hostkeylen);
3967 !hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
3968 bombout(("Server's host key did not match the signature supplied"));
3973 * Authenticate remote host: verify host key. (We've already
3974 * checked the signature of the exchange hash.)
3976 keystr = hostkey->fmtkey(hkey);
3977 fingerprint = hostkey->fingerprint(hkey);
3978 verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
3979 keystr, fingerprint);
3980 if (first_kex) { /* don't bother logging this in rekeys */
3981 logevent("Host key fingerprint is:");
3982 logevent(fingerprint);
3986 hostkey->freekey(hkey);
3989 * Send SSH2_MSG_NEWKEYS.
3991 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
3995 * Expect SSH2_MSG_NEWKEYS from server.
3998 if (pktin.type != SSH2_MSG_NEWKEYS) {
3999 bombout(("expected new-keys packet from server"));
4004 * Create and initialise session keys.
4006 cscipher = cscipher_tobe;
4007 sccipher = sccipher_tobe;
4010 cscomp = cscomp_tobe;
4011 sccomp = sccomp_tobe;
4012 cscomp->compress_init();
4013 sccomp->decompress_init();
4015 * Set IVs after keys. Here we use the exchange hash from the
4016 * _first_ key exchange.
4019 memcpy(ssh2_session_id, exchange_hash, sizeof(exchange_hash));
4020 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'C', keyspace);
4021 cscipher->setcskey(keyspace);
4022 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'D', keyspace);
4023 sccipher->setsckey(keyspace);
4024 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'A', keyspace);
4025 cscipher->setcsiv(keyspace);
4026 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'B', keyspace);
4027 sccipher->setsciv(keyspace);
4028 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'E', keyspace);
4029 csmac->setcskey(keyspace);
4030 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'F', keyspace);
4031 scmac->setsckey(keyspace);
4034 * If this is the first key exchange phase, we must pass the
4035 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
4036 * wants to see it but because it will need time to initialise
4037 * itself before it sees an actual packet. In subsequent key
4038 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
4039 * it would only confuse the layer above.
4047 * Now we're encrypting. Begin returning 1 to the protocol main
4048 * function so that other things can run on top of the
4049 * transport. If we ever see a KEXINIT, we must go back to the
4052 while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
4055 logevent("Server initiated key re-exchange");
4056 goto begin_key_exchange;
4062 * Add data to an SSH2 channel output buffer.
4064 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
4067 bufchain_add(&c->v.v2.outbuffer, buf, len);
4071 * Attempt to send data on an SSH2 channel.
4073 static int ssh2_try_send(struct ssh_channel *c)
4075 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
4078 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
4079 if ((unsigned)len > c->v.v2.remwindow)
4080 len = c->v.v2.remwindow;
4081 if ((unsigned)len > c->v.v2.remmaxpkt)
4082 len = c->v.v2.remmaxpkt;
4083 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
4084 ssh2_pkt_adduint32(c->remoteid);
4085 ssh2_pkt_addstring_start();
4086 ssh2_pkt_addstring_data(data, len);
4088 bufchain_consume(&c->v.v2.outbuffer, len);
4089 c->v.v2.remwindow -= len;
4093 * After having sent as much data as we can, return the amount
4096 return bufchain_size(&c->v.v2.outbuffer);
4100 * Potentially enlarge the window on an SSH2 channel.
4102 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
4105 * Never send WINDOW_ADJUST for a channel that the remote side
4106 * already thinks it's closed; there's no point, since it won't
4107 * be sending any more data anyway.
4112 if (newwin > c->v.v2.locwindow) {
4113 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4114 ssh2_pkt_adduint32(c->remoteid);
4115 ssh2_pkt_adduint32(newwin - c->v.v2.locwindow);
4117 c->v.v2.locwindow = newwin;
4122 * Handle the SSH2 userauth and connection layers.
4124 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
4127 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
4129 AUTH_KEYBOARD_INTERACTIVE
4133 AUTH_TYPE_PUBLICKEY,
4134 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
4135 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
4137 AUTH_TYPE_KEYBOARD_INTERACTIVE,
4138 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
4140 static int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
4141 static int tried_pubkey_config, tried_agent, tried_keyb_inter;
4142 static int kbd_inter_running;
4143 static int we_are_in;
4144 static int num_prompts, curr_prompt, echo;
4145 static char username[100];
4146 static int got_username;
4147 static char pwprompt[200];
4148 static char password[100];
4149 static void *publickey_blob;
4150 static int publickey_bloblen;
4155 * Request userauth protocol, and await a response to it.
4157 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
4158 ssh2_pkt_addstring("ssh-userauth");
4160 crWaitUntilV(ispkt);
4161 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
4162 bombout(("Server refused user authentication protocol"));
4167 * We repeat this whole loop, including the username prompt,
4168 * until we manage a successful authentication. If the user
4169 * types the wrong _password_, they are sent back to the
4170 * beginning to try another username. (If they specify a
4171 * username in the config, they are never asked, even if they
4172 * do give a wrong password.)
4174 * I think this best serves the needs of
4176 * - the people who have no configuration, no keys, and just
4177 * want to try repeated (username,password) pairs until they
4178 * type both correctly
4180 * - people who have keys and configuration but occasionally
4181 * need to fall back to passwords
4183 * - people with a key held in Pageant, who might not have
4184 * logged in to a particular machine before; so they want to
4185 * type a username, and then _either_ their key will be
4186 * accepted, _or_ they will type a password. If they mistype
4187 * the username they will want to be able to get back and
4191 got_username = FALSE;
4196 if (got_username && !cfg.change_username) {
4198 * We got a username last time round this loop, and
4199 * with change_username turned off we don't try to get
4202 } else if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
4203 if (ssh_get_line && !ssh_getline_pw_only) {
4204 if (!ssh_get_line("login as: ",
4205 username, sizeof(username), FALSE)) {
4207 * get_line failed to get a username.
4210 logevent("No username provided. Abandoning session.");
4211 ssh_state = SSH_STATE_CLOSED;
4216 c_write_str("login as: ");
4218 setup_userpass_input(username, sizeof(username), 1);
4220 crWaitUntilV(!ispkt);
4221 ret = process_userpass_input(in, inlen);
4226 c_write_str("\r\n");
4227 username[strcspn(username, "\n\r")] = '\0';
4230 strncpy(username, cfg.username, sizeof(username));
4231 username[sizeof(username)-1] = '\0';
4232 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
4233 sprintf(stuff, "Using username \"%s\".\r\n", username);
4237 got_username = TRUE;
4240 * Send an authentication request using method "none": (a)
4241 * just in case it succeeds, and (b) so that we know what
4242 * authentication methods we can usefully try next.
4244 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4246 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4247 ssh2_pkt_addstring(username);
4248 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4249 ssh2_pkt_addstring("none"); /* method */
4251 type = AUTH_TYPE_NONE;
4255 tried_pubkey_config = FALSE;
4256 tried_agent = FALSE;
4257 tried_keyb_inter = FALSE;
4258 kbd_inter_running = FALSE;
4259 /* Load the pub half of cfg.keyfile so we notice if it's in Pageant */
4262 logeventf("Reading private key file \"%.150s\"", cfg.keyfile);
4263 keytype = key_type(cfg.keyfile);
4264 if (keytype == SSH_KEYTYPE_SSH2)
4265 publickey_blob = ssh2_userkey_loadpub(cfg.keyfile, NULL,
4266 &publickey_bloblen);
4269 logeventf("Unable to use this key file (%s)",
4270 key_type_to_str(keytype));
4271 sprintf(msgbuf, "Unable to use key file \"%.150s\" (%s)\r\n",
4272 cfg.keyfile, key_type_to_str(keytype));
4273 c_write_str(msgbuf);
4274 publickey_blob = NULL;
4277 publickey_blob = NULL;
4281 * Wait for the result of the last authentication request.
4284 crWaitUntilV(ispkt);
4285 while (pktin.type == SSH2_MSG_USERAUTH_BANNER) {
4289 * Don't show the banner if we're operating in
4290 * non-verbose non-interactive mode. (It's probably
4291 * a script, which means nobody will read the
4292 * banner _anyway_, and moreover the printing of
4293 * the banner will screw up processing on the
4294 * output of (say) plink.)
4296 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
4297 ssh2_pkt_getstring(&banner, &size);
4299 c_write_untrusted(banner, size);
4301 crWaitUntilV(ispkt);
4303 if (pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
4304 logevent("Access granted");
4309 if (kbd_inter_running &&
4310 pktin.type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
4312 * This is either a further set-of-prompts packet
4313 * in keyboard-interactive authentication, or it's
4314 * the same one and we came back here with `gotit'
4315 * set. In the former case, we must reset the
4316 * curr_prompt variable.
4320 } else if (pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
4321 bombout(("Strange packet received during authentication: type %d",
4329 * OK, we're now sitting on a USERAUTH_FAILURE message, so
4330 * we can look at the string in it and know what we can
4331 * helpfully try next.
4333 if (pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
4336 ssh2_pkt_getstring(&methods, &methlen);
4337 kbd_inter_running = FALSE;
4338 if (!ssh2_pkt_getbool()) {
4340 * We have received an unequivocal Access
4341 * Denied. This can translate to a variety of
4344 * - if we'd just tried "none" authentication,
4345 * it's not worth printing anything at all
4347 * - if we'd just tried a public key _offer_,
4348 * the message should be "Server refused our
4349 * key" (or no message at all if the key
4350 * came from Pageant)
4352 * - if we'd just tried anything else, the
4353 * message really should be "Access denied".
4355 * Additionally, if we'd just tried password
4356 * authentication, we should break out of this
4357 * whole loop so as to go back to the username
4360 if (type == AUTH_TYPE_NONE) {
4362 } else if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
4363 type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
4364 if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
4365 c_write_str("Server refused our key\r\n");
4366 logevent("Server refused public key");
4367 } else if (type == AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
4368 /* server declined keyboard-interactive; ignore */
4370 c_write_str("Access denied\r\n");
4371 logevent("Access denied");
4372 if (type == AUTH_TYPE_PASSWORD) {
4378 c_write_str("Further authentication required\r\n");
4379 logevent("Further authentication required");
4383 in_commasep_string("publickey", methods, methlen);
4385 in_commasep_string("password", methods, methlen);
4386 can_keyb_inter = cfg.try_ki_auth &&
4387 in_commasep_string("keyboard-interactive", methods, methlen);
4391 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4394 * Most password/passphrase prompts will be
4395 * non-echoing, so we set this to 0 by default.
4396 * Exception is that some keyboard-interactive prompts
4397 * can be echoing, in which case we'll set this to 1.
4401 if (!method && can_pubkey && agent_exists() && !tried_agent) {
4403 * Attempt public-key authentication using Pageant.
4405 static unsigned char request[5], *response, *p;
4406 static int responselen;
4407 static int i, nkeys;
4408 static int authed = FALSE;
4411 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4412 ssh_pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4416 logevent("Pageant is running. Requesting keys.");
4418 /* Request the keys held by the agent. */
4419 PUT_32BIT(request, 1);
4420 request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
4421 agent_query(request, 5, &r, &responselen);
4422 response = (unsigned char *) r;
4423 if (response && responselen >= 5 &&
4424 response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
4426 nkeys = GET_32BIT(p);
4430 sprintf(buf, "Pageant has %d SSH2 keys", nkeys);
4433 for (i = 0; i < nkeys; i++) {
4434 static char *pkblob, *alg, *commentp;
4435 static int pklen, alglen, commentlen;
4436 static int siglen, retlen, len;
4437 static char *q, *agentreq, *ret;
4442 sprintf(buf, "Trying Pageant key #%d", i);
4445 pklen = GET_32BIT(p);
4447 if (publickey_blob &&
4448 pklen == publickey_bloblen &&
4449 !memcmp(p, publickey_blob, publickey_bloblen)) {
4450 logevent("This key matches configured key file");
4451 tried_pubkey_config = 1;
4455 alglen = GET_32BIT(pkblob);
4457 commentlen = GET_32BIT(p);
4461 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4462 ssh2_pkt_addstring(username);
4463 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4464 ssh2_pkt_addstring("publickey"); /* method */
4465 ssh2_pkt_addbool(FALSE); /* no signature included */
4466 ssh2_pkt_addstring_start();
4467 ssh2_pkt_addstring_data(alg, alglen);
4468 ssh2_pkt_addstring_start();
4469 ssh2_pkt_addstring_data(pkblob, pklen);
4472 crWaitUntilV(ispkt);
4473 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4474 logevent("Key refused");
4478 if (flags & FLAG_VERBOSE) {
4480 ("Authenticating with public key \"");
4481 c_write(commentp, commentlen);
4482 c_write_str("\" from agent\r\n");
4486 * Server is willing to accept the key.
4487 * Construct a SIGN_REQUEST.
4489 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4490 ssh2_pkt_addstring(username);
4491 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4492 ssh2_pkt_addstring("publickey"); /* method */
4493 ssh2_pkt_addbool(TRUE);
4494 ssh2_pkt_addstring_start();
4495 ssh2_pkt_addstring_data(alg, alglen);
4496 ssh2_pkt_addstring_start();
4497 ssh2_pkt_addstring_data(pkblob, pklen);
4499 siglen = pktout.length - 5 + 4 + 20;
4500 len = 1; /* message type */
4501 len += 4 + pklen; /* key blob */
4502 len += 4 + siglen; /* data to sign */
4503 len += 4; /* flags */
4504 agentreq = smalloc(4 + len);
4505 PUT_32BIT(agentreq, len);
4507 *q++ = SSH2_AGENTC_SIGN_REQUEST;
4508 PUT_32BIT(q, pklen);
4510 memcpy(q, pkblob, pklen);
4512 PUT_32BIT(q, siglen);
4514 /* Now the data to be signed... */
4517 memcpy(q, ssh2_session_id, 20);
4519 memcpy(q, pktout.data + 5, pktout.length - 5);
4520 q += pktout.length - 5;
4521 /* And finally the (zero) flags word. */
4523 agent_query(agentreq, len + 4, &vret, &retlen);
4527 if (ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
4528 logevent("Sending Pageant's response");
4529 ssh2_add_sigblob(pkblob, pklen,
4530 ret + 9, GET_32BIT(ret + 5));
4536 ("Pageant failed to answer challenge");
4546 if (!method && can_pubkey && publickey_blob
4547 && !tried_pubkey_config) {
4548 unsigned char *pub_blob;
4549 char *algorithm, *comment;
4552 tried_pubkey_config = TRUE;
4554 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4555 ssh_pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4558 * Try the public key supplied in the configuration.
4560 * First, offer the public blob to see if the server is
4561 * willing to accept it.
4563 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
4566 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4567 ssh2_pkt_addstring(username);
4568 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4569 ssh2_pkt_addstring("publickey"); /* method */
4570 ssh2_pkt_addbool(FALSE); /* no signature included */
4571 ssh2_pkt_addstring(algorithm);
4572 ssh2_pkt_addstring_start();
4573 ssh2_pkt_addstring_data(pub_blob, pub_blob_len);
4575 logevent("Offered public key"); /* FIXME */
4577 crWaitUntilV(ispkt);
4578 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4580 type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
4581 continue; /* key refused; give up on it */
4584 logevent("Offer of public key accepted");
4586 * Actually attempt a serious authentication using
4589 if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
4591 "Passphrase for key \"%.100s\": ",
4597 c_write_str("Authenticating with public key \"");
4598 c_write_str(comment);
4599 c_write_str("\"\r\n");
4600 method = AUTH_PUBLICKEY_FILE;
4604 if (!method && can_keyb_inter && !tried_keyb_inter) {
4605 method = AUTH_KEYBOARD_INTERACTIVE;
4606 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4607 tried_keyb_inter = TRUE;
4609 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4610 ssh_pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4612 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4613 ssh2_pkt_addstring(username);
4614 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4615 ssh2_pkt_addstring("keyboard-interactive"); /* method */
4616 ssh2_pkt_addstring(""); /* lang */
4617 ssh2_pkt_addstring("");
4620 crWaitUntilV(ispkt);
4621 if (pktin.type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
4622 if (pktin.type == SSH2_MSG_USERAUTH_FAILURE)
4624 logevent("Keyboard-interactive authentication refused");
4625 type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
4629 kbd_inter_running = TRUE;
4633 if (kbd_inter_running) {
4634 method = AUTH_KEYBOARD_INTERACTIVE;
4635 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4636 tried_keyb_inter = TRUE;
4638 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4639 ssh_pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4641 if (curr_prompt == 0) {
4643 * We've got a fresh USERAUTH_INFO_REQUEST.
4644 * Display header data, and start going through
4647 char *name, *inst, *lang;
4648 int name_len, inst_len, lang_len;
4650 ssh2_pkt_getstring(&name, &name_len);
4651 ssh2_pkt_getstring(&inst, &inst_len);
4652 ssh2_pkt_getstring(&lang, &lang_len);
4654 c_write_untrusted(name, name_len);
4655 c_write_str("\r\n");
4658 c_write_untrusted(inst, inst_len);
4659 c_write_str("\r\n");
4661 num_prompts = ssh2_pkt_getuint32();
4665 * If there are prompts remaining in the packet,
4666 * display one and get a response.
4668 if (curr_prompt < num_prompts) {
4672 ssh2_pkt_getstring(&prompt, &prompt_len);
4673 if (prompt_len > 0) {
4674 strncpy(pwprompt, prompt, sizeof(pwprompt));
4675 pwprompt[prompt_len < sizeof(pwprompt) ?
4676 prompt_len : sizeof(pwprompt)-1] = '\0';
4679 "<server failed to send prompt>: ");
4681 echo = ssh2_pkt_getbool();
4687 if (!method && can_passwd) {
4688 method = AUTH_PASSWORD;
4689 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4690 ssh_pkt_ctx |= SSH2_PKTCTX_PASSWORD;
4691 sprintf(pwprompt, "%.90s@%.90s's password: ", username,
4698 if (!ssh_get_line(pwprompt, password,
4699 sizeof(password), TRUE)) {
4701 * get_line failed to get a password (for
4702 * example because one was supplied on the
4703 * command line which has already failed to
4706 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4707 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4709 ("No more passwords available to try");
4710 ssh2_pkt_addstring("en"); /* language tag */
4712 logevent("Unable to authenticate");
4713 connection_fatal("Unable to authenticate");
4714 ssh_state = SSH_STATE_CLOSED;
4719 c_write_untrusted(pwprompt, strlen(pwprompt));
4722 setup_userpass_input(password, sizeof(password), echo);
4724 crWaitUntilV(!ispkt);
4725 ret = process_userpass_input(in, inlen);
4729 c_write_str("\r\n");
4733 if (method == AUTH_PUBLICKEY_FILE) {
4735 * We have our passphrase. Now try the actual authentication.
4737 struct ssh2_userkey *key;
4739 key = ssh2_load_userkey(cfg.keyfile, password);
4740 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
4741 if (key == SSH2_WRONG_PASSPHRASE) {
4742 c_write_str("Wrong passphrase\r\n");
4743 tried_pubkey_config = FALSE;
4745 c_write_str("Unable to load private key\r\n");
4746 tried_pubkey_config = TRUE;
4748 /* Send a spurious AUTH_NONE to return to the top. */
4749 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4750 ssh2_pkt_addstring(username);
4751 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4752 ssh2_pkt_addstring("none"); /* method */
4754 type = AUTH_TYPE_NONE;
4756 unsigned char *pkblob, *sigblob, *sigdata;
4757 int pkblob_len, sigblob_len, sigdata_len;
4760 * We have loaded the private key and the server
4761 * has announced that it's willing to accept it.
4762 * Hallelujah. Generate a signature and send it.
4764 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4765 ssh2_pkt_addstring(username);
4766 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4767 ssh2_pkt_addstring("publickey"); /* method */
4768 ssh2_pkt_addbool(TRUE);
4769 ssh2_pkt_addstring(key->alg->name);
4770 pkblob = key->alg->public_blob(key->data, &pkblob_len);
4771 ssh2_pkt_addstring_start();
4772 ssh2_pkt_addstring_data(pkblob, pkblob_len);
4775 * The data to be signed is:
4779 * followed by everything so far placed in the
4782 sigdata_len = pktout.length - 5 + 4 + 20;
4783 sigdata = smalloc(sigdata_len);
4784 PUT_32BIT(sigdata, 20);
4785 memcpy(sigdata + 4, ssh2_session_id, 20);
4786 memcpy(sigdata + 24, pktout.data + 5,
4788 sigblob = key->alg->sign(key->data, sigdata,
4789 sigdata_len, &sigblob_len);
4790 ssh2_add_sigblob(pkblob, pkblob_len,
4791 sigblob, sigblob_len);
4797 type = AUTH_TYPE_PUBLICKEY;
4799 } else if (method == AUTH_PASSWORD) {
4801 * We send the password packet lumped tightly together with
4802 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4803 * string long enough to make the total length of the two
4804 * packets constant. This should ensure that a passive
4805 * listener doing traffic analyis can't work out the length
4808 * For this to work, we need an assumption about the
4809 * maximum length of the password packet. I think 256 is
4810 * pretty conservative. Anyone using a password longer than
4811 * that probably doesn't have much to worry about from
4812 * people who find out how long their password is!
4814 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4815 ssh2_pkt_addstring(username);
4816 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4817 ssh2_pkt_addstring("password");
4818 ssh2_pkt_addbool(FALSE);
4819 ssh2_pkt_addstring(password);
4822 * We'll include a string that's an exact multiple of the
4823 * cipher block size. If the cipher is NULL for some
4824 * reason, we don't do this trick at all because we gain
4830 stringlen = (256 - deferred_len);
4831 stringlen += cscipher->blksize - 1;
4832 stringlen -= (stringlen % cscipher->blksize);
4835 * Temporarily disable actual compression,
4836 * so we can guarantee to get this string
4837 * exactly the length we want it. The
4838 * compression-disabling routine should
4839 * return an integer indicating how many
4840 * bytes we should adjust our string length
4843 stringlen -= cscomp->disable_compression();
4845 ssh2_pkt_init(SSH2_MSG_IGNORE);
4846 ssh2_pkt_addstring_start();
4847 for (i = 0; i < stringlen; i++) {
4848 char c = (char) random_byte();
4849 ssh2_pkt_addstring_data(&c, 1);
4853 ssh_pkt_defersend();
4854 logevent("Sent password");
4855 type = AUTH_TYPE_PASSWORD;
4856 } else if (method == AUTH_KEYBOARD_INTERACTIVE) {
4857 if (curr_prompt == 0) {
4858 ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
4859 ssh2_pkt_adduint32(num_prompts);
4861 if (need_pw) { /* only add pw if we just got one! */
4862 ssh2_pkt_addstring(password);
4863 memset(password, 0, sizeof(password));
4866 if (curr_prompt >= num_prompts) {
4870 * If there are prompts remaining, we set
4871 * `gotit' so that we won't attempt to get
4872 * another packet. Then we go back round the
4873 * loop and will end up retrieving another
4874 * prompt out of the existing packet. Funky or
4879 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4882 ("No supported authentication methods left to try!\r\n");
4884 ("No supported authentications offered. Disconnecting");
4885 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4886 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4888 ("No supported authentication methods available");
4889 ssh2_pkt_addstring("en"); /* language tag */
4891 ssh_state = SSH_STATE_CLOSED;
4895 } while (!we_are_in);
4898 * Now we're authenticated for the connection protocol. The
4899 * connection protocol will automatically have started at this
4900 * point; there's no need to send SERVICE_REQUEST.
4904 * So now create a channel with a session in it.
4906 ssh_channels = newtree234(ssh_channelcmp);
4907 mainchan = smalloc(sizeof(struct ssh_channel));
4908 mainchan->localid = alloc_channel_id();
4909 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
4910 ssh2_pkt_addstring("session");
4911 ssh2_pkt_adduint32(mainchan->localid);
4912 mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
4913 ssh2_pkt_adduint32(mainchan->v.v2.locwindow); /* our window size */
4914 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
4916 crWaitUntilV(ispkt);
4917 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
4918 bombout(("Server refused to open a session"));
4920 /* FIXME: error data comes back in FAILURE packet */
4922 if (ssh2_pkt_getuint32() != mainchan->localid) {
4923 bombout(("Server's channel confirmation cited wrong channel"));
4926 mainchan->remoteid = ssh2_pkt_getuint32();
4927 mainchan->type = CHAN_MAINSESSION;
4928 mainchan->closes = 0;
4929 mainchan->v.v2.remwindow = ssh2_pkt_getuint32();
4930 mainchan->v.v2.remmaxpkt = ssh2_pkt_getuint32();
4931 bufchain_init(&mainchan->v.v2.outbuffer);
4932 add234(ssh_channels, mainchan);
4933 logevent("Opened channel for session");
4936 * Potentially enable X11 forwarding.
4938 if (cfg.x11_forward) {
4939 char proto[20], data[64];
4940 logevent("Requesting X11 forwarding");
4941 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
4942 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4943 ssh2_pkt_adduint32(mainchan->remoteid);
4944 ssh2_pkt_addstring("x11-req");
4945 ssh2_pkt_addbool(1); /* want reply */
4946 ssh2_pkt_addbool(0); /* many connections */
4947 ssh2_pkt_addstring(proto);
4948 ssh2_pkt_addstring(data);
4949 ssh2_pkt_adduint32(0); /* screen number */
4953 crWaitUntilV(ispkt);
4954 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4955 unsigned i = ssh2_pkt_getuint32();
4956 struct ssh_channel *c;
4957 c = find234(ssh_channels, &i, ssh_channelfind);
4959 continue; /* nonexistent channel */
4960 c->v.v2.remwindow += ssh2_pkt_getuint32();
4962 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4964 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4965 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4966 bombout(("Unexpected response to X11 forwarding request:"
4967 " packet type %d", pktin.type));
4970 logevent("X11 forwarding refused");
4972 logevent("X11 forwarding enabled");
4973 ssh_X11_fwd_enabled = TRUE;
4978 * Enable port forwardings.
4981 static char *e; /* preserve across crReturn */
4984 int sport,dport,sserv,dserv;
4985 char sports[256], dports[256], host[256];
4989 ssh_rportfwds = newtree234(ssh_rportcmp_ssh2);
4990 /* Add port forwardings. */
4995 while (*e && *e != '\t')
5001 while (*e && *e != ':')
5011 dport = atoi(dports);
5015 se = getservbyname(dports, NULL);
5017 dport = ntohs(se->s_port);
5020 "Service lookup failed for destination port \"%s\"",
5025 sport = atoi(sports);
5029 se = getservbyname(sports, NULL);
5031 sport = ntohs(se->s_port);
5034 "Service lookup failed for source port \"%s\"",
5039 if (sport && dport) {
5041 pfd_addforward(host, dport, sport);
5042 sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
5043 " %s:%.*s%.*s%d%.*s",
5044 sserv ? strlen(sports) : 0, sports,
5045 sserv, "(", sport, sserv, ")",
5047 dserv ? strlen(dports) : 0, dports,
5048 dserv, "(", dport, dserv, ")");
5051 struct ssh_rportfwd *pf;
5052 pf = smalloc(sizeof(*pf));
5053 strcpy(pf->dhost, host);
5056 if (add234(ssh_rportfwds, pf) != pf) {
5058 "Duplicate remote port forwarding to %s:%d",
5063 sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
5064 " forward to %s:%.*s%.*s%d%.*s",
5065 sserv ? strlen(sports) : 0, sports,
5066 sserv, "(", sport, sserv, ")",
5068 dserv ? strlen(dports) : 0, dports,
5069 dserv, "(", dport, dserv, ")");
5071 ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5072 ssh2_pkt_addstring("tcpip-forward");
5073 ssh2_pkt_addbool(1);/* want reply */
5074 if (cfg.rport_acceptall)
5075 ssh2_pkt_addstring("0.0.0.0");
5077 ssh2_pkt_addstring("127.0.0.1");
5078 ssh2_pkt_adduint32(sport);
5082 crWaitUntilV(ispkt);
5083 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5084 unsigned i = ssh2_pkt_getuint32();
5085 struct ssh_channel *c;
5086 c = find234(ssh_channels, &i, ssh_channelfind);
5088 continue;/* nonexistent channel */
5089 c->v.v2.remwindow += ssh2_pkt_getuint32();
5091 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5093 if (pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
5094 if (pktin.type != SSH2_MSG_REQUEST_FAILURE) {
5095 bombout(("Unexpected response to port "
5096 "forwarding request: packet type %d",
5100 logevent("Server refused this port forwarding");
5102 logevent("Remote port forwarding enabled");
5111 * Potentially enable agent forwarding.
5113 if (cfg.agentfwd && agent_exists()) {
5114 logevent("Requesting OpenSSH-style agent forwarding");
5115 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5116 ssh2_pkt_adduint32(mainchan->remoteid);
5117 ssh2_pkt_addstring("auth-agent-req@openssh.com");
5118 ssh2_pkt_addbool(1); /* want reply */
5122 crWaitUntilV(ispkt);
5123 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5124 unsigned i = ssh2_pkt_getuint32();
5125 struct ssh_channel *c;
5126 c = find234(ssh_channels, &i, ssh_channelfind);
5128 continue; /* nonexistent channel */
5129 c->v.v2.remwindow += ssh2_pkt_getuint32();
5131 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5133 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5134 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5135 bombout(("Unexpected response to agent forwarding request:"
5136 " packet type %d", pktin.type));
5139 logevent("Agent forwarding refused");
5141 logevent("Agent forwarding enabled");
5142 ssh_agentfwd_enabled = TRUE;
5147 * Now allocate a pty for the session.
5150 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5151 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
5152 ssh2_pkt_addstring("pty-req");
5153 ssh2_pkt_addbool(1); /* want reply */
5154 ssh2_pkt_addstring(cfg.termtype);
5155 ssh2_pkt_adduint32(cols);
5156 ssh2_pkt_adduint32(rows);
5157 ssh2_pkt_adduint32(0); /* pixel width */
5158 ssh2_pkt_adduint32(0); /* pixel height */
5159 ssh2_pkt_addstring_start();
5160 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
5162 ssh_state = SSH_STATE_INTERMED;
5165 crWaitUntilV(ispkt);
5166 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5167 unsigned i = ssh2_pkt_getuint32();
5168 struct ssh_channel *c;
5169 c = find234(ssh_channels, &i, ssh_channelfind);
5171 continue; /* nonexistent channel */
5172 c->v.v2.remwindow += ssh2_pkt_getuint32();
5174 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5176 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5177 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5178 bombout(("Unexpected response to pty request:"
5179 " packet type %d", pktin.type));
5182 c_write_str("Server refused to allocate pty\r\n");
5183 ssh_editing = ssh_echoing = 1;
5185 logevent("Allocated pty");
5188 ssh_editing = ssh_echoing = 1;
5192 * Start a shell or a remote command. We may have to attempt
5193 * this twice if the config data has provided a second choice
5200 if (ssh_fallback_cmd) {
5201 subsys = cfg.ssh_subsys2;
5202 cmd = cfg.remote_cmd_ptr2;
5204 subsys = cfg.ssh_subsys;
5205 cmd = cfg.remote_cmd_ptr;
5208 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5209 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
5211 ssh2_pkt_addstring("subsystem");
5212 ssh2_pkt_addbool(1); /* want reply */
5213 ssh2_pkt_addstring(cmd);
5215 ssh2_pkt_addstring("exec");
5216 ssh2_pkt_addbool(1); /* want reply */
5217 ssh2_pkt_addstring(cmd);
5219 ssh2_pkt_addstring("shell");
5220 ssh2_pkt_addbool(1); /* want reply */
5224 crWaitUntilV(ispkt);
5225 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5226 unsigned i = ssh2_pkt_getuint32();
5227 struct ssh_channel *c;
5228 c = find234(ssh_channels, &i, ssh_channelfind);
5230 continue; /* nonexistent channel */
5231 c->v.v2.remwindow += ssh2_pkt_getuint32();
5233 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5234 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5235 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5236 bombout(("Unexpected response to shell/command request:"
5237 " packet type %d", pktin.type));
5241 * We failed to start the command. If this is the
5242 * fallback command, we really are finished; if it's
5243 * not, and if the fallback command exists, try falling
5244 * back to it before complaining.
5246 if (!ssh_fallback_cmd && cfg.remote_cmd_ptr2 != NULL) {
5247 logevent("Primary command failed; attempting fallback");
5248 ssh_fallback_cmd = TRUE;
5251 bombout(("Server refused to start a shell/command"));
5254 logevent("Started a shell/command");
5259 ssh_state = SSH_STATE_SESSION;
5263 ssh_special(TS_EOF);
5268 ldisc_send(NULL, 0, 0); /* cause ldisc to notice changes */
5271 static int try_send;
5275 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
5276 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
5279 unsigned i = ssh2_pkt_getuint32();
5280 struct ssh_channel *c;
5281 c = find234(ssh_channels, &i, ssh_channelfind);
5283 continue; /* nonexistent channel */
5284 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
5285 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
5286 continue; /* extended but not stderr */
5287 ssh2_pkt_getstring(&data, &length);
5290 c->v.v2.locwindow -= length;
5292 case CHAN_MAINSESSION:
5294 from_backend(pktin.type ==
5295 SSH2_MSG_CHANNEL_EXTENDED_DATA,
5299 bufsize = x11_send(c->u.x11.s, data, length);
5302 bufsize = pfd_send(c->u.pfd.s, data, length);
5305 while (length > 0) {
5306 if (c->u.a.lensofar < 4) {
5307 int l = min(4 - c->u.a.lensofar, length);
5308 memcpy(c->u.a.msglen + c->u.a.lensofar,
5312 c->u.a.lensofar += l;
5314 if (c->u.a.lensofar == 4) {
5316 4 + GET_32BIT(c->u.a.msglen);
5317 c->u.a.message = smalloc(c->u.a.totallen);
5318 memcpy(c->u.a.message, c->u.a.msglen, 4);
5320 if (c->u.a.lensofar >= 4 && length > 0) {
5322 min(c->u.a.totallen - c->u.a.lensofar,
5324 memcpy(c->u.a.message + c->u.a.lensofar,
5328 c->u.a.lensofar += l;
5330 if (c->u.a.lensofar == c->u.a.totallen) {
5331 void *reply, *sentreply;
5333 agent_query(c->u.a.message,
5334 c->u.a.totallen, &reply,
5339 /* Fake SSH_AGENT_FAILURE. */
5340 sentreply = "\0\0\0\1\5";
5343 ssh2_add_channel_data(c, sentreply,
5348 sfree(c->u.a.message);
5349 c->u.a.lensofar = 0;
5356 * If we are not buffering too much data,
5357 * enlarge the window again at the remote side.
5359 if (bufsize < OUR_V2_WINSIZE)
5360 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
5362 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
5363 ssh_state = SSH_STATE_CLOSED;
5364 logevent("Received disconnect message");
5366 } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
5367 unsigned i = ssh2_pkt_getuint32();
5368 struct ssh_channel *c;
5370 c = find234(ssh_channels, &i, ssh_channelfind);
5372 continue; /* nonexistent channel */
5374 if (c->type == CHAN_X11) {
5376 * Remote EOF on an X11 channel means we should
5377 * wrap up and close the channel ourselves.
5379 x11_close(c->u.x11.s);
5381 } else if (c->type == CHAN_AGENT) {
5383 } else if (c->type == CHAN_SOCKDATA) {
5384 pfd_close(c->u.pfd.s);
5387 } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
5388 unsigned i = ssh2_pkt_getuint32();
5389 struct ssh_channel *c;
5391 c = find234(ssh_channels, &i, ssh_channelfind);
5392 if (!c || ((int)c->remoteid) == -1) {
5393 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
5394 c ? "half-open" : "nonexistent", i));
5396 /* Do pre-close processing on the channel. */
5398 case CHAN_MAINSESSION:
5399 break; /* nothing to see here, move along */
5401 if (c->u.x11.s != NULL)
5402 x11_close(c->u.x11.s);
5409 if (c->u.pfd.s != NULL)
5410 pfd_close(c->u.pfd.s);
5414 if (c->closes == 0) {
5415 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5416 ssh2_pkt_adduint32(c->remoteid);
5419 del234(ssh_channels, c);
5420 bufchain_clear(&c->v.v2.outbuffer);
5424 * See if that was the last channel left open.
5426 if (count234(ssh_channels) == 0) {
5429 * We used to send SSH_MSG_DISCONNECT here,
5430 * because I'd believed that _every_ conforming
5431 * SSH2 connection had to end with a disconnect
5432 * being sent by at least one side; apparently
5433 * I was wrong and it's perfectly OK to
5434 * unceremoniously slam the connection shut
5435 * when you're done, and indeed OpenSSH feels
5436 * this is more polite than sending a
5437 * DISCONNECT. So now we don't.
5439 logevent("All channels closed. Disconnecting");
5440 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5441 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
5442 ssh2_pkt_addstring("All open channels closed");
5443 ssh2_pkt_addstring("en"); /* language tag */
5446 ssh_state = SSH_STATE_CLOSED;
5449 continue; /* remote sends close; ignore (FIXME) */
5450 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5451 unsigned i = ssh2_pkt_getuint32();
5452 struct ssh_channel *c;
5453 c = find234(ssh_channels, &i, ssh_channelfind);
5455 continue; /* nonexistent channel */
5456 c->v.v2.remwindow += ssh2_pkt_getuint32();
5458 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
5459 unsigned i = ssh2_pkt_getuint32();
5460 struct ssh_channel *c;
5461 c = find234(ssh_channels, &i, ssh_channelfind);
5463 continue; /* nonexistent channel */
5464 if (c->type != CHAN_SOCKDATA_DORMANT)
5465 continue; /* dunno why they're confirming this */
5466 c->remoteid = ssh2_pkt_getuint32();
5467 c->type = CHAN_SOCKDATA;
5468 c->v.v2.remwindow = ssh2_pkt_getuint32();
5469 c->v.v2.remmaxpkt = ssh2_pkt_getuint32();
5471 pfd_confirm(c->u.pfd.s);
5474 * We have a pending close on this channel,
5475 * which we decided on before the server acked
5476 * the channel open. So now we know the
5477 * remoteid, we can close it again.
5479 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5480 ssh2_pkt_adduint32(c->remoteid);
5483 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
5484 unsigned i = ssh2_pkt_getuint32();
5485 struct ssh_channel *c;
5486 c = find234(ssh_channels, &i, ssh_channelfind);
5488 continue; /* nonexistent channel */
5489 if (c->type != CHAN_SOCKDATA_DORMANT)
5490 continue; /* dunno why they're failing this */
5492 logevent("Forwarded connection refused by server");
5494 pfd_close(c->u.pfd.s);
5496 del234(ssh_channels, c);
5498 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
5501 int typelen, want_reply;
5502 struct ssh_channel *c;
5504 localid = ssh2_pkt_getuint32();
5505 ssh2_pkt_getstring(&type, &typelen);
5506 want_reply = ssh2_pkt_getbool();
5509 * First, check that the channel exists. Otherwise,
5510 * we can instantly disconnect with a rude message.
5512 c = find234(ssh_channels, &localid, ssh_channelfind);
5515 sprintf(buf, "Received channel request for nonexistent"
5516 " channel %d", localid);
5518 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5519 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
5520 ssh2_pkt_addstring(buf);
5521 ssh2_pkt_addstring("en"); /* language tag */
5523 connection_fatal("%s", buf);
5524 ssh_state = SSH_STATE_CLOSED;
5529 * Having got the channel number, we now look at
5530 * the request type string to see if it's something
5533 if (typelen == 11 && !memcmp(type, "exit-status", 11) &&
5535 /* We recognise "exit-status" on the primary channel. */
5537 ssh_exitcode = ssh2_pkt_getuint32();
5538 sprintf(buf, "Server sent command exit status %d",
5542 ssh2_pkt_init(SSH2_MSG_CHANNEL_SUCCESS);
5543 ssh2_pkt_adduint32(c->remoteid);
5548 * This is a channel request we don't know
5549 * about, so we now either ignore the request
5550 * or respond with CHANNEL_FAILURE, depending
5554 ssh2_pkt_init(SSH2_MSG_CHANNEL_FAILURE);
5555 ssh2_pkt_adduint32(c->remoteid);
5559 } else if (pktin.type == SSH2_MSG_GLOBAL_REQUEST) {
5561 int typelen, want_reply;
5563 ssh2_pkt_getstring(&type, &typelen);
5564 want_reply = ssh2_pkt_getbool();
5567 * We currently don't support any global requests
5568 * at all, so we either ignore the request or
5569 * respond with REQUEST_FAILURE, depending on
5573 ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
5576 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
5580 struct ssh_channel *c;
5581 unsigned remid, winsize, pktsize;
5582 ssh2_pkt_getstring(&type, &typelen);
5583 c = smalloc(sizeof(struct ssh_channel));
5585 remid = ssh2_pkt_getuint32();
5586 winsize = ssh2_pkt_getuint32();
5587 pktsize = ssh2_pkt_getuint32();
5589 if (typelen == 3 && !memcmp(type, "x11", 3)) {
5590 if (!ssh_X11_fwd_enabled)
5591 error = "X11 forwarding is not enabled";
5592 else if (x11_init(&c->u.x11.s, cfg.x11_display, c) !=
5594 error = "Unable to open an X11 connection";
5598 } else if (typelen == 15 &&
5599 !memcmp(type, "forwarded-tcpip", 15)) {
5600 struct ssh_rportfwd pf, *realpf;
5603 ssh2_pkt_getstring(&dummy, &dummylen);/* skip address */
5604 pf.sport = ssh2_pkt_getuint32();
5605 realpf = find234(ssh_rportfwds, &pf, NULL);
5606 if (realpf == NULL) {
5607 error = "Remote port is not recognised";
5609 char *e = pfd_newconnect(&c->u.pfd.s, realpf->dhost,
5612 sprintf(buf, "Received remote port open request for %s:%d",
5613 realpf->dhost, realpf->dport);
5616 sprintf(buf, "Port open failed: %s", e);
5618 error = "Port open failed";
5620 logevent("Forwarded port opened successfully");
5621 c->type = CHAN_SOCKDATA;
5624 } else if (typelen == 22 &&
5625 !memcmp(type, "auth-agent@openssh.com", 3)) {
5626 if (!ssh_agentfwd_enabled)
5627 error = "Agent forwarding is not enabled";
5629 c->type = CHAN_AGENT; /* identify channel type */
5630 c->u.a.lensofar = 0;
5633 error = "Unsupported channel type requested";
5636 c->remoteid = remid;
5638 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
5639 ssh2_pkt_adduint32(c->remoteid);
5640 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
5641 ssh2_pkt_addstring(error);
5642 ssh2_pkt_addstring("en"); /* language tag */
5646 c->localid = alloc_channel_id();
5648 c->v.v2.locwindow = OUR_V2_WINSIZE;
5649 c->v.v2.remwindow = winsize;
5650 c->v.v2.remmaxpkt = pktsize;
5651 bufchain_init(&c->v.v2.outbuffer);
5652 add234(ssh_channels, c);
5653 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
5654 ssh2_pkt_adduint32(c->remoteid);
5655 ssh2_pkt_adduint32(c->localid);
5656 ssh2_pkt_adduint32(c->v.v2.locwindow);
5657 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
5661 bombout(("Strange packet received: type %d", pktin.type));
5666 * We have spare data. Add it to the channel buffer.
5668 ssh2_add_channel_data(mainchan, in, inlen);
5673 struct ssh_channel *c;
5675 * Try to send data on all channels if we can.
5677 for (i = 0; NULL != (c = index234(ssh_channels, i)); i++) {
5678 int bufsize = ssh2_try_send(c);
5681 case CHAN_MAINSESSION:
5682 /* stdin need not receive an unthrottle
5683 * notification since it will be polled */
5686 x11_unthrottle(c->u.x11.s);
5689 /* agent sockets are request/response and need no
5690 * buffer management */
5693 pfd_unthrottle(c->u.pfd.s);
5705 * Handle the top-level SSH2 protocol.
5707 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
5709 if (do_ssh2_transport(in, inlen, ispkt) == 0)
5711 do_ssh2_authconn(in, inlen, ispkt);
5715 * Called to set up the connection.
5717 * Returns an error message, or NULL on success.
5719 static char *ssh_init(char *host, int port, char **realhost, int nodelay)
5724 if (crypto_startup() == 0)
5725 return "Microsoft high encryption pack not installed!";
5731 ssh1_throttle_count = 0;
5732 ssh_overall_bufsize = 0;
5733 ssh_fallback_cmd = 0;
5735 p = connect_to_host(host, port, realhost, nodelay);
5743 * Called to send data down the Telnet connection.
5745 static int ssh_send(char *buf, int len)
5747 if (s == NULL || ssh_protocol == NULL)
5750 ssh_protocol(buf, len, 0);
5752 return ssh_sendbuffer();
5756 * Called to query the current amount of buffered stdin data.
5758 static int ssh_sendbuffer(void)
5762 if (s == NULL || ssh_protocol == NULL)
5766 * If the SSH socket itself has backed up, add the total backup
5767 * size on that to any individual buffer on the stdin channel.
5770 if (ssh_throttled_all)
5771 override_value = ssh_overall_bufsize;
5773 if (ssh_version == 1) {
5774 return override_value;
5775 } else if (ssh_version == 2) {
5776 if (!mainchan || mainchan->closes > 0)
5777 return override_value;
5779 return override_value + bufchain_size(&mainchan->v.v2.outbuffer);
5786 * Called to set the size of the window from SSH's POV.
5788 static void ssh_size(void)
5790 switch (ssh_state) {
5791 case SSH_STATE_BEFORE_SIZE:
5792 case SSH_STATE_PREPACKET:
5793 case SSH_STATE_CLOSED:
5794 break; /* do nothing */
5795 case SSH_STATE_INTERMED:
5796 size_needed = TRUE; /* buffer for later */
5798 case SSH_STATE_SESSION:
5800 if (ssh_version == 1) {
5801 send_packet(SSH1_CMSG_WINDOW_SIZE,
5802 PKT_INT, rows, PKT_INT, cols,
5803 PKT_INT, 0, PKT_INT, 0, PKT_END);
5805 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5806 ssh2_pkt_adduint32(mainchan->remoteid);
5807 ssh2_pkt_addstring("window-change");
5808 ssh2_pkt_addbool(0);
5809 ssh2_pkt_adduint32(cols);
5810 ssh2_pkt_adduint32(rows);
5811 ssh2_pkt_adduint32(0);
5812 ssh2_pkt_adduint32(0);
5821 * Send Telnet special codes. TS_EOF is useful for `plink', so you
5822 * can send an EOF and collect resulting output (e.g. `plink
5825 static void ssh_special(Telnet_Special code)
5827 if (code == TS_EOF) {
5828 if (ssh_state != SSH_STATE_SESSION) {
5830 * Buffer the EOF in case we are pre-SESSION, so we can
5831 * send it as soon as we reach SESSION.
5837 if (ssh_version == 1) {
5838 send_packet(SSH1_CMSG_EOF, PKT_END);
5840 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
5841 ssh2_pkt_adduint32(mainchan->remoteid);
5844 logevent("Sent EOF message");
5845 } else if (code == TS_PING) {
5846 if (ssh_state == SSH_STATE_CLOSED
5847 || ssh_state == SSH_STATE_PREPACKET) return;
5848 if (ssh_version == 1) {
5849 if (!(ssh_remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
5850 send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
5852 ssh2_pkt_init(SSH2_MSG_IGNORE);
5853 ssh2_pkt_addstring_start();
5861 void *new_sock_channel(Socket s)
5863 struct ssh_channel *c;
5864 c = smalloc(sizeof(struct ssh_channel));
5867 c->remoteid = -1; /* to be set when open confirmed */
5868 c->localid = alloc_channel_id();
5870 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
5872 bufchain_init(&c->v.v2.outbuffer);
5873 add234(ssh_channels, c);
5879 * This is called when stdout/stderr (the entity to which
5880 * from_backend sends data) manages to clear some backlog.
5882 void ssh_unthrottle(int bufsize)
5884 if (ssh_version == 1) {
5885 if (ssh1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
5886 ssh1_stdout_throttling = 0;
5890 if (mainchan && mainchan->closes == 0)
5891 ssh2_set_window(mainchan, OUR_V2_WINSIZE - bufsize);
5895 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
5897 struct ssh_channel *c = (struct ssh_channel *)channel;
5900 sprintf(buf, "Opening forwarded connection to %.512s:%d", hostname, port);
5903 if (ssh_version == 1) {
5904 send_packet(SSH1_MSG_PORT_OPEN,
5905 PKT_INT, c->localid,
5908 //PKT_STR, <org:orgport>,
5911 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
5912 ssh2_pkt_addstring("direct-tcpip");
5913 ssh2_pkt_adduint32(c->localid);
5914 c->v.v2.locwindow = OUR_V2_WINSIZE;
5915 ssh2_pkt_adduint32(c->v.v2.locwindow);/* our window size */
5916 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
5917 ssh2_pkt_addstring(hostname);
5918 ssh2_pkt_adduint32(port);
5920 * We make up values for the originator data; partly it's
5921 * too much hassle to keep track, and partly I'm not
5922 * convinced the server should be told details like that
5923 * about my local network configuration.
5925 ssh2_pkt_addstring("client-side-connection");
5926 ssh2_pkt_adduint32(0);
5932 static Socket ssh_socket(void)
5937 static int ssh_sendok(void)
5942 static int ssh_ldisc(int option)
5944 if (option == LD_ECHO)
5946 if (option == LD_EDIT)
5951 static int ssh_return_exitcode(void)
5953 return ssh_exitcode;
5956 Backend ssh_backend = {
5963 ssh_return_exitcode,