18 #define logevent(s) { logevent(s); \
19 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
20 { fprintf(stderr, "%s\n", s); fflush(stderr); } }
22 #define bombout(msg) ( ssh_state = SSH_STATE_CLOSED, \
23 (s ? sk_close(s), s = NULL : 0), \
24 connection_fatal msg )
26 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
27 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
28 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
29 #define SSH1_CMSG_USER 4 /* 0x4 */
30 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
31 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
32 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
33 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
34 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
35 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
36 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
37 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
38 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
39 #define SSH1_SMSG_FAILURE 15 /* 0xf */
40 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
41 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
42 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
43 #define SSH1_CMSG_EOF 19 /* 0x13 */
44 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
45 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
46 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
47 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
48 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
49 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
50 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
51 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
52 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
53 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
54 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
55 #define SSH1_MSG_IGNORE 32 /* 0x20 */
56 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
57 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
58 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
59 #define SSH1_MSG_DEBUG 36 /* 0x24 */
60 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
61 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
62 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
63 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
64 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
65 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
66 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
68 #define SSH1_AUTH_TIS 5 /* 0x5 */
69 #define SSH1_AUTH_CCARD 16 /* 0x10 */
71 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
72 /* Mask for protoflags we will echo back to server if seen */
73 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
75 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
76 #define SSH2_MSG_IGNORE 2 /* 0x2 */
77 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
78 #define SSH2_MSG_DEBUG 4 /* 0x4 */
79 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
80 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
81 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
82 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
83 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
84 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
85 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
86 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
87 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
88 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
89 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
90 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
91 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
92 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
93 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
94 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
95 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
96 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
97 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
98 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
99 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
100 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
101 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
102 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
103 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
104 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
105 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
106 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
107 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
108 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
109 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
110 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
113 * Packet type contexts, so that ssh2_pkt_type can correctly decode
114 * the ambiguous type numbers back into the correct type strings.
116 #define SSH2_PKTCTX_DHGROUP1 0x0001
117 #define SSH2_PKTCTX_DHGEX 0x0002
118 #define SSH2_PKTCTX_PUBLICKEY 0x0010
119 #define SSH2_PKTCTX_PASSWORD 0x0020
120 #define SSH2_PKTCTX_KBDINTER 0x0040
121 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
123 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
124 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
125 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
126 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
127 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
128 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
129 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
130 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
131 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
132 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
133 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
134 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
135 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
136 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
137 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
139 static const char *const ssh2_disconnect_reasons[] = {
141 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
142 "SSH_DISCONNECT_PROTOCOL_ERROR",
143 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
144 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
145 "SSH_DISCONNECT_MAC_ERROR",
146 "SSH_DISCONNECT_COMPRESSION_ERROR",
147 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
148 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
149 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
150 "SSH_DISCONNECT_CONNECTION_LOST",
151 "SSH_DISCONNECT_BY_APPLICATION",
152 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
153 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
154 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
155 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
158 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
159 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
160 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
161 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
163 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
166 * Various remote-bug flags.
168 #define BUG_CHOKES_ON_SSH1_IGNORE 1
169 #define BUG_SSH2_HMAC 2
170 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
172 static int ssh_pkt_ctx = 0;
174 #define translate(x) if (type == x) return #x
175 #define translatec(x,ctx) if (type == x && (ssh_pkt_ctx & ctx)) return #x
176 char *ssh1_pkt_type(int type)
178 translate(SSH1_MSG_DISCONNECT);
179 translate(SSH1_SMSG_PUBLIC_KEY);
180 translate(SSH1_CMSG_SESSION_KEY);
181 translate(SSH1_CMSG_USER);
182 translate(SSH1_CMSG_AUTH_RSA);
183 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
184 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
185 translate(SSH1_CMSG_AUTH_PASSWORD);
186 translate(SSH1_CMSG_REQUEST_PTY);
187 translate(SSH1_CMSG_WINDOW_SIZE);
188 translate(SSH1_CMSG_EXEC_SHELL);
189 translate(SSH1_CMSG_EXEC_CMD);
190 translate(SSH1_SMSG_SUCCESS);
191 translate(SSH1_SMSG_FAILURE);
192 translate(SSH1_CMSG_STDIN_DATA);
193 translate(SSH1_SMSG_STDOUT_DATA);
194 translate(SSH1_SMSG_STDERR_DATA);
195 translate(SSH1_CMSG_EOF);
196 translate(SSH1_SMSG_EXIT_STATUS);
197 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
198 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
199 translate(SSH1_MSG_CHANNEL_DATA);
200 translate(SSH1_MSG_CHANNEL_CLOSE);
201 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
202 translate(SSH1_SMSG_X11_OPEN);
203 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
204 translate(SSH1_MSG_PORT_OPEN);
205 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
206 translate(SSH1_SMSG_AGENT_OPEN);
207 translate(SSH1_MSG_IGNORE);
208 translate(SSH1_CMSG_EXIT_CONFIRMATION);
209 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
210 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
211 translate(SSH1_MSG_DEBUG);
212 translate(SSH1_CMSG_REQUEST_COMPRESSION);
213 translate(SSH1_CMSG_AUTH_TIS);
214 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
215 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
216 translate(SSH1_CMSG_AUTH_CCARD);
217 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
218 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
221 char *ssh2_pkt_type(int type)
223 translate(SSH2_MSG_DISCONNECT);
224 translate(SSH2_MSG_IGNORE);
225 translate(SSH2_MSG_UNIMPLEMENTED);
226 translate(SSH2_MSG_DEBUG);
227 translate(SSH2_MSG_SERVICE_REQUEST);
228 translate(SSH2_MSG_SERVICE_ACCEPT);
229 translate(SSH2_MSG_KEXINIT);
230 translate(SSH2_MSG_NEWKEYS);
231 translatec(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP1);
232 translatec(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP1);
233 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
234 translatec(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
235 translatec(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
236 translatec(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
237 translate(SSH2_MSG_USERAUTH_REQUEST);
238 translate(SSH2_MSG_USERAUTH_FAILURE);
239 translate(SSH2_MSG_USERAUTH_SUCCESS);
240 translate(SSH2_MSG_USERAUTH_BANNER);
241 translatec(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
242 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
243 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
244 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
245 translate(SSH2_MSG_GLOBAL_REQUEST);
246 translate(SSH2_MSG_REQUEST_SUCCESS);
247 translate(SSH2_MSG_REQUEST_FAILURE);
248 translate(SSH2_MSG_CHANNEL_OPEN);
249 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
250 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
251 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
252 translate(SSH2_MSG_CHANNEL_DATA);
253 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
254 translate(SSH2_MSG_CHANNEL_EOF);
255 translate(SSH2_MSG_CHANNEL_CLOSE);
256 translate(SSH2_MSG_CHANNEL_REQUEST);
257 translate(SSH2_MSG_CHANNEL_SUCCESS);
258 translate(SSH2_MSG_CHANNEL_FAILURE);
264 #define GET_32BIT(cp) \
265 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
266 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
267 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
268 ((unsigned long)(unsigned char)(cp)[3]))
270 #define PUT_32BIT(cp, value) { \
271 (cp)[0] = (unsigned char)((value) >> 24); \
272 (cp)[1] = (unsigned char)((value) >> 16); \
273 (cp)[2] = (unsigned char)((value) >> 8); \
274 (cp)[3] = (unsigned char)(value); }
276 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
278 /* Coroutine mechanics for the sillier bits of the code */
279 #define crBegin1 static int crLine = 0;
280 #define crBegin2 switch(crLine) { case 0:;
281 #define crBegin crBegin1; crBegin2;
282 #define crFinish(z) } crLine = 0; return (z)
283 #define crFinishV } crLine = 0; return
284 #define crReturn(z) \
286 crLine=__LINE__; return (z); case __LINE__:;\
290 crLine=__LINE__; return; case __LINE__:;\
292 #define crStop(z) do{ crLine = 0; return (z); }while(0)
293 #define crStopV do{ crLine = 0; return; }while(0)
294 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
295 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
297 extern char *x11_init(Socket *, char *, void *);
298 extern void x11_close(Socket);
299 extern int x11_send(Socket, char *, int);
300 extern void x11_invent_auth(char *, int, char *, int);
301 extern void x11_unthrottle(Socket s);
302 extern void x11_override_throttle(Socket s, int enable);
304 extern char *pfd_newconnect(Socket * s, char *hostname, int port, void *c);
305 extern char *pfd_addforward(char *desthost, int destport, int port);
306 extern void pfd_close(Socket s);
307 extern int pfd_send(Socket s, char *data, int len);
308 extern void pfd_confirm(Socket s);
309 extern void pfd_unthrottle(Socket s);
310 extern void pfd_override_throttle(Socket s, int enable);
312 static void ssh2_pkt_init(int pkt_type);
313 static void ssh2_pkt_addbool(unsigned char value);
314 static void ssh2_pkt_adduint32(unsigned long value);
315 static void ssh2_pkt_addstring_start(void);
316 static void ssh2_pkt_addstring_str(char *data);
317 static void ssh2_pkt_addstring_data(char *data, int len);
318 static void ssh2_pkt_addstring(char *data);
319 static char *ssh2_mpint_fmt(Bignum b, int *len);
320 static void ssh2_pkt_addmp(Bignum b);
321 static int ssh2_pkt_construct(void);
322 static void ssh2_pkt_send(void);
325 * Buffer management constants. There are several of these for
326 * various different purposes:
328 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
329 * on a local data stream before we throttle the whole SSH
330 * connection (in SSH1 only). Throttling the whole connection is
331 * pretty drastic so we set this high in the hope it won't
334 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
335 * on the SSH connection itself before we defensively throttle
336 * _all_ local data streams. This is pretty drastic too (though
337 * thankfully unlikely in SSH2 since the window mechanism should
338 * ensure that the server never has any need to throttle its end
339 * of the connection), so we set this high as well.
341 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
345 #define SSH1_BUFFER_LIMIT 32768
346 #define SSH_MAX_BACKLOG 32768
347 #define OUR_V2_WINSIZE 16384
349 const static struct ssh_kex *kex_algs[] = {
350 &ssh_diffiehellman_gex,
354 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
356 static void nullmac_key(unsigned char *key)
359 static void nullmac_generate(unsigned char *blk, int len,
363 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq)
367 const static struct ssh_mac ssh_mac_none = {
368 nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
370 const static struct ssh_mac *macs[] = {
371 &ssh_sha1, &ssh_md5, &ssh_mac_none
373 const static struct ssh_mac *buggymacs[] = {
374 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
377 static void ssh_comp_none_init(void)
380 static int ssh_comp_none_block(unsigned char *block, int len,
381 unsigned char **outblock, int *outlen)
385 static int ssh_comp_none_disable(void)
389 const static struct ssh_compress ssh_comp_none = {
391 ssh_comp_none_init, ssh_comp_none_block,
392 ssh_comp_none_init, ssh_comp_none_block,
393 ssh_comp_none_disable
395 extern const struct ssh_compress ssh_zlib;
396 const static struct ssh_compress *compressions[] = {
397 &ssh_zlib, &ssh_comp_none
400 enum { /* channel types */
405 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
409 * 2-3-4 tree storing channels.
412 unsigned remoteid, localid;
416 struct ssh1_data_channel {
419 struct ssh2_data_channel {
421 unsigned remwindow, remmaxpkt;
426 struct ssh_agent_channel {
427 unsigned char *message;
428 unsigned char msglen[4];
429 int lensofar, totallen;
431 struct ssh_x11_channel {
434 struct ssh_pfd_channel {
441 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
442 * 2 use this structure in different ways, reflecting SSH 2's
443 * altogether saner approach to port forwarding.
445 * In SSH 1, you arrange a remote forwarding by sending the server
446 * the remote port number, and the local destination host:port.
447 * When a connection comes in, the server sends you back that
448 * host:port pair, and you connect to it. This is a ready-made
449 * security hole if you're not on the ball: a malicious server
450 * could send you back _any_ host:port pair, so if you trustingly
451 * connect to the address it gives you then you've just opened the
452 * entire inside of your corporate network just by connecting
453 * through it to a dodgy SSH server. Hence, we must store a list of
454 * host:port pairs we _are_ trying to forward to, and reject a
455 * connection request from the server if it's not in the list.
457 * In SSH 2, each side of the connection minds its own business and
458 * doesn't send unnecessary information to the other. You arrange a
459 * remote forwarding by sending the server just the remote port
460 * number. When a connection comes in, the server tells you which
461 * of its ports was connected to; and _you_ have to remember what
462 * local host:port pair went with that port number.
464 * Hence: in SSH 1 this structure stores host:port pairs we intend
465 * to allow connections to, and is indexed by those host:port
466 * pairs. In SSH 2 it stores a mapping from source port to
467 * destination host:port pair, and is indexed by source port.
469 struct ssh_rportfwd {
470 unsigned sport, dport;
483 static SHA_State exhash, exhashbase;
485 static Socket s = NULL;
487 static unsigned char session_key[32];
488 static int ssh1_compressing;
489 static int ssh1_remote_protoflags;
490 static int ssh1_local_protoflags;
491 static int ssh_agentfwd_enabled;
492 static int ssh_X11_fwd_enabled;
493 static int ssh_remote_bugs;
494 static const struct ssh_cipher *cipher = NULL;
495 static const struct ssh2_cipher *cscipher = NULL;
496 static const struct ssh2_cipher *sccipher = NULL;
497 static const struct ssh_mac *csmac = NULL;
498 static const struct ssh_mac *scmac = NULL;
499 static const struct ssh_compress *cscomp = NULL;
500 static const struct ssh_compress *sccomp = NULL;
501 static const struct ssh_kex *kex = NULL;
502 static const struct ssh_signkey *hostkey = NULL;
503 static unsigned char ssh2_session_id[20];
504 int (*ssh_get_line) (const char *prompt, char *str, int maxlen,
507 static char *savedhost;
508 static int savedport;
509 static int ssh_send_ok;
510 static int ssh_echoing, ssh_editing;
512 static tree234 *ssh_channels; /* indexed by local id */
513 static struct ssh_channel *mainchan; /* primary session channel */
514 static int ssh_exitcode = -1;
516 static tree234 *ssh_rportfwds;
520 SSH_STATE_BEFORE_SIZE,
524 } ssh_state = SSH_STATE_PREPACKET;
526 static int size_needed = FALSE, eof_needed = FALSE;
528 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
529 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
530 static unsigned char *deferred_send_data = NULL;
531 static int deferred_len = 0, deferred_size = 0;
534 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
535 * that fails. This variable is the means by which scp.c can reach
536 * into the SSH code and find out which one it got.
538 int ssh_fallback_cmd = 0;
540 static int ssh_version;
541 static int ssh1_throttle_count;
542 static int ssh_overall_bufsize;
543 static int ssh_throttled_all;
544 static int ssh1_stdout_throttling;
545 static void (*ssh_protocol) (unsigned char *in, int inlen, int ispkt);
546 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
547 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
548 static void ssh_size(void);
549 static void ssh_special(Telnet_Special);
550 static int ssh2_try_send(struct ssh_channel *c);
551 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
553 static void ssh_throttle_all(int enable, int bufsize);
554 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
555 static int (*s_rdpkt) (unsigned char **data, int *datalen);
556 static int ssh_sendbuffer(void);
558 static struct rdpkt1_state_tag {
559 long len, pad, biglen, to_read;
560 unsigned long realcrc, gotcrc;
566 static struct rdpkt2_state_tag {
567 long len, pad, payload, packetlen, maclen;
570 unsigned long incoming_sequence;
573 static int ssh_channelcmp(void *av, void *bv)
575 struct ssh_channel *a = (struct ssh_channel *) av;
576 struct ssh_channel *b = (struct ssh_channel *) bv;
577 if (a->localid < b->localid)
579 if (a->localid > b->localid)
583 static int ssh_channelfind(void *av, void *bv)
585 unsigned *a = (unsigned *) av;
586 struct ssh_channel *b = (struct ssh_channel *) bv;
594 static int ssh_rportcmp_ssh1(void *av, void *bv)
596 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
597 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
599 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
600 return i < 0 ? -1 : +1;
601 if (a->dport > b->dport)
603 if (a->dport < b->dport)
608 static int ssh_rportcmp_ssh2(void *av, void *bv)
610 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
611 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
613 if (a->sport > b->sport)
615 if (a->sport < b->sport)
620 static int alloc_channel_id(void)
622 const unsigned CHANNEL_NUMBER_OFFSET = 256;
623 unsigned low, high, mid;
625 struct ssh_channel *c;
628 * First-fit allocation of channel numbers: always pick the
629 * lowest unused one. To do this, binary-search using the
630 * counted B-tree to find the largest channel ID which is in a
631 * contiguous sequence from the beginning. (Precisely
632 * everything in that sequence must have ID equal to its tree
633 * index plus CHANNEL_NUMBER_OFFSET.)
635 tsize = count234(ssh_channels);
639 while (high - low > 1) {
640 mid = (high + low) / 2;
641 c = index234(ssh_channels, mid);
642 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
643 low = mid; /* this one is fine */
645 high = mid; /* this one is past it */
648 * Now low points to either -1, or the tree index of the
649 * largest ID in the initial sequence.
652 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
653 assert(NULL == find234(ssh_channels, &i, ssh_channelfind));
655 return low + 1 + CHANNEL_NUMBER_OFFSET;
658 static void c_write(char *buf, int len)
660 if ((flags & FLAG_STDERR)) {
662 for (i = 0; i < len; i++)
664 fputc(buf[i], stderr);
667 from_backend(1, buf, len);
670 static void c_write_untrusted(char *buf, int len)
673 for (i = 0; i < len; i++) {
676 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
681 static void c_write_str(char *buf)
683 c_write(buf, strlen(buf));
687 * Collect incoming data in the incoming packet buffer.
688 * Decipher and verify the packet when it is completely read.
689 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
690 * Update the *data and *datalen variables.
691 * Return the additional nr of bytes needed, or 0 when
692 * a complete packet is available.
694 static int ssh1_rdpkt(unsigned char **data, int *datalen)
696 struct rdpkt1_state_tag *st = &rdpkt1_state;
705 for (st->i = st->len = 0; st->i < 4; st->i++) {
706 while ((*datalen) == 0)
708 st->len = (st->len << 8) + **data;
709 (*data)++, (*datalen)--;
712 st->pad = 8 - (st->len % 8);
713 st->biglen = st->len + st->pad;
714 pktin.length = st->len - 5;
716 if (pktin.maxlen < st->biglen) {
717 pktin.maxlen = st->biglen;
718 pktin.data = (pktin.data == NULL ? smalloc(st->biglen + APIEXTRA) :
719 srealloc(pktin.data, st->biglen + APIEXTRA));
721 fatalbox("Out of memory");
724 st->to_read = st->biglen;
726 while (st->to_read > 0) {
727 st->chunk = st->to_read;
728 while ((*datalen) == 0)
729 crReturn(st->to_read);
730 if (st->chunk > (*datalen))
731 st->chunk = (*datalen);
732 memcpy(st->p, *data, st->chunk);
734 *datalen -= st->chunk;
736 st->to_read -= st->chunk;
739 if (cipher && detect_attack(pktin.data, st->biglen, NULL)) {
740 bombout(("Network attack (CRC compensation) detected!"));
745 cipher->decrypt(pktin.data, st->biglen);
747 st->realcrc = crc32(pktin.data, st->biglen - 4);
748 st->gotcrc = GET_32BIT(pktin.data + st->biglen - 4);
749 if (st->gotcrc != st->realcrc) {
750 bombout(("Incorrect CRC received on packet"));
754 pktin.body = pktin.data + st->pad + 1;
756 if (ssh1_compressing) {
757 unsigned char *decompblk;
759 zlib_decompress_block(pktin.body - 1, pktin.length + 1,
760 &decompblk, &decomplen);
762 if (pktin.maxlen < st->pad + decomplen) {
763 pktin.maxlen = st->pad + decomplen;
764 pktin.data = srealloc(pktin.data, pktin.maxlen + APIEXTRA);
765 pktin.body = pktin.data + st->pad + 1;
767 fatalbox("Out of memory");
770 memcpy(pktin.body - 1, decompblk, decomplen);
772 pktin.length = decomplen - 1;
775 pktin.type = pktin.body[-1];
777 log_packet(PKT_INCOMING, pktin.type, ssh1_pkt_type(pktin.type),
778 pktin.body, pktin.length);
780 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
781 pktin.type == SSH1_SMSG_STDERR_DATA ||
782 pktin.type == SSH1_MSG_DEBUG ||
783 pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
784 pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
785 long stringlen = GET_32BIT(pktin.body);
786 if (stringlen + 4 != pktin.length) {
787 bombout(("Received data packet with bogus string length"));
792 if (pktin.type == SSH1_MSG_DEBUG) {
793 /* log debug message */
795 int stringlen = GET_32BIT(pktin.body);
796 strcpy(buf, "Remote: ");
799 memcpy(buf + 8, pktin.body + 4, stringlen);
800 buf[8 + stringlen] = '\0';
803 } else if (pktin.type == SSH1_MSG_IGNORE) {
808 if (pktin.type == SSH1_MSG_DISCONNECT) {
809 /* log reason code in disconnect message */
811 unsigned msglen = GET_32BIT(pktin.body);
813 strcpy(buf, "Remote sent disconnect: ");
814 nowlen = strlen(buf);
815 if (msglen > sizeof(buf) - nowlen - 1)
816 msglen = sizeof(buf) - nowlen - 1;
817 memcpy(buf + nowlen, pktin.body + 4, msglen);
818 buf[nowlen + msglen] = '\0';
820 bombout(("Server sent disconnect message:\n\"%s\"", buf+nowlen));
827 static int ssh2_rdpkt(unsigned char **data, int *datalen)
829 struct rdpkt2_state_tag *st = &rdpkt2_state;
837 st->cipherblk = sccipher->blksize;
840 if (st->cipherblk < 8)
843 if (pktin.maxlen < st->cipherblk) {
844 pktin.maxlen = st->cipherblk;
847 NULL ? smalloc(st->cipherblk +
848 APIEXTRA) : srealloc(pktin.data,
852 fatalbox("Out of memory");
856 * Acquire and decrypt the first block of the packet. This will
857 * contain the length and padding details.
859 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
860 while ((*datalen) == 0)
861 crReturn(st->cipherblk - st->i);
862 pktin.data[st->i] = *(*data)++;
867 sccipher->decrypt(pktin.data, st->cipherblk);
870 * Now get the length and padding figures.
872 st->len = GET_32BIT(pktin.data);
873 st->pad = pktin.data[4];
876 * This enables us to deduce the payload length.
878 st->payload = st->len - st->pad - 1;
880 pktin.length = st->payload + 5;
883 * So now we can work out the total packet length.
885 st->packetlen = st->len + 4;
886 st->maclen = scmac ? scmac->len : 0;
889 * Adjust memory allocation if packet is too big.
891 if (pktin.maxlen < st->packetlen + st->maclen) {
892 pktin.maxlen = st->packetlen + st->maclen;
895 NULL ? smalloc(pktin.maxlen + APIEXTRA) : srealloc(pktin.data,
900 fatalbox("Out of memory");
904 * Read and decrypt the remainder of the packet.
906 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
908 while ((*datalen) == 0)
909 crReturn(st->packetlen + st->maclen - st->i);
910 pktin.data[st->i] = *(*data)++;
913 /* Decrypt everything _except_ the MAC. */
915 sccipher->decrypt(pktin.data + st->cipherblk,
916 st->packetlen - st->cipherblk);
922 && !scmac->verify(pktin.data, st->len + 4,
923 st->incoming_sequence)) {
924 bombout(("Incorrect MAC received on packet"));
927 st->incoming_sequence++; /* whether or not we MACed */
930 * Decompress packet payload.
933 unsigned char *newpayload;
935 if (sccomp && sccomp->decompress(pktin.data + 5, pktin.length - 5,
936 &newpayload, &newlen)) {
937 if (pktin.maxlen < newlen + 5) {
938 pktin.maxlen = newlen + 5;
941 NULL ? smalloc(pktin.maxlen +
942 APIEXTRA) : srealloc(pktin.data,
946 fatalbox("Out of memory");
948 pktin.length = 5 + newlen;
949 memcpy(pktin.data + 5, newpayload, newlen);
955 pktin.type = pktin.data[5];
957 log_packet(PKT_INCOMING, pktin.type, ssh2_pkt_type(pktin.type),
958 pktin.data+6, pktin.length-6);
960 switch (pktin.type) {
962 * These packets we must handle instantly.
964 case SSH2_MSG_DISCONNECT:
966 /* log reason code in disconnect message */
968 int reason = GET_32BIT(pktin.data + 6);
969 unsigned msglen = GET_32BIT(pktin.data + 10);
971 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
972 sprintf(buf, "Received disconnect message (%s)",
973 ssh2_disconnect_reasons[reason]);
975 sprintf(buf, "Received disconnect message (unknown type %d)",
979 strcpy(buf, "Disconnection message text: ");
980 nowlen = strlen(buf);
981 if (msglen > sizeof(buf) - nowlen - 1)
982 msglen = sizeof(buf) - nowlen - 1;
983 memcpy(buf + nowlen, pktin.data + 14, msglen);
984 buf[nowlen + msglen] = '\0';
986 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
988 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
989 ssh2_disconnect_reasons[reason] : "unknown",
994 case SSH2_MSG_IGNORE:
998 /* log the debug message */
1000 /* int display = pktin.body[6]; */
1001 int stringlen = GET_32BIT(pktin.data+7);
1003 strcpy(buf, "Remote debug message: ");
1004 prefix = strlen(buf);
1005 if (stringlen > sizeof(buf)-prefix-1)
1006 stringlen = sizeof(buf)-prefix-1;
1007 memcpy(buf + prefix, pktin.data + 11, stringlen);
1008 buf[prefix + stringlen] = '\0';
1011 goto next_packet; /* FIXME: print the debug message */
1014 * These packets we need do nothing about here.
1016 case SSH2_MSG_UNIMPLEMENTED:
1017 case SSH2_MSG_SERVICE_REQUEST:
1018 case SSH2_MSG_SERVICE_ACCEPT:
1019 case SSH2_MSG_KEXINIT:
1020 case SSH2_MSG_NEWKEYS:
1021 case SSH2_MSG_KEXDH_INIT:
1022 case SSH2_MSG_KEXDH_REPLY:
1023 /* case SSH2_MSG_KEX_DH_GEX_REQUEST: duplicate case value */
1024 /* case SSH2_MSG_KEX_DH_GEX_GROUP: duplicate case value */
1025 case SSH2_MSG_KEX_DH_GEX_INIT:
1026 case SSH2_MSG_KEX_DH_GEX_REPLY:
1027 case SSH2_MSG_USERAUTH_REQUEST:
1028 case SSH2_MSG_USERAUTH_FAILURE:
1029 case SSH2_MSG_USERAUTH_SUCCESS:
1030 case SSH2_MSG_USERAUTH_BANNER:
1031 case SSH2_MSG_USERAUTH_PK_OK:
1032 /* case SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: duplicate case value */
1033 /* case SSH2_MSG_USERAUTH_INFO_REQUEST: duplicate case value */
1034 case SSH2_MSG_USERAUTH_INFO_RESPONSE:
1035 case SSH2_MSG_GLOBAL_REQUEST:
1036 case SSH2_MSG_REQUEST_SUCCESS:
1037 case SSH2_MSG_REQUEST_FAILURE:
1038 case SSH2_MSG_CHANNEL_OPEN:
1039 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
1040 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
1041 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1042 case SSH2_MSG_CHANNEL_DATA:
1043 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1044 case SSH2_MSG_CHANNEL_EOF:
1045 case SSH2_MSG_CHANNEL_CLOSE:
1046 case SSH2_MSG_CHANNEL_REQUEST:
1047 case SSH2_MSG_CHANNEL_SUCCESS:
1048 case SSH2_MSG_CHANNEL_FAILURE:
1052 * For anything else we send SSH2_MSG_UNIMPLEMENTED.
1055 ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
1056 ssh2_pkt_adduint32(st->incoming_sequence - 1);
1064 static void ssh1_pktout_size(int len)
1068 len += 5; /* type and CRC */
1069 pad = 8 - (len % 8);
1072 pktout.length = len - 5;
1073 if (pktout.maxlen < biglen) {
1074 pktout.maxlen = biglen;
1076 /* Allocate enough buffer space for extra block
1077 * for MS CryptEncrypt() */
1078 pktout.data = (pktout.data == NULL ? smalloc(biglen + 12) :
1079 srealloc(pktout.data, biglen + 12));
1081 pktout.data = (pktout.data == NULL ? smalloc(biglen + 4) :
1082 srealloc(pktout.data, biglen + 4));
1085 fatalbox("Out of memory");
1087 pktout.body = pktout.data + 4 + pad + 1;
1090 static void s_wrpkt_start(int type, int len)
1092 ssh1_pktout_size(len);
1096 static int s_wrpkt_prepare(void)
1098 int pad, len, biglen, i;
1101 pktout.body[-1] = pktout.type;
1103 log_packet(PKT_OUTGOING, pktout.type, ssh1_pkt_type(pktout.type),
1104 pktout.body, pktout.length);
1106 if (ssh1_compressing) {
1107 unsigned char *compblk;
1109 zlib_compress_block(pktout.body - 1, pktout.length + 1,
1110 &compblk, &complen);
1111 ssh1_pktout_size(complen - 1);
1112 memcpy(pktout.body - 1, compblk, complen);
1116 len = pktout.length + 5; /* type and CRC */
1117 pad = 8 - (len % 8);
1120 for (i = 0; i < pad; i++)
1121 pktout.data[i + 4] = random_byte();
1122 crc = crc32(pktout.data + 4, biglen - 4);
1123 PUT_32BIT(pktout.data + biglen, crc);
1124 PUT_32BIT(pktout.data, len);
1127 cipher->encrypt(pktout.data + 4, biglen);
1132 static void s_wrpkt(void)
1135 len = s_wrpkt_prepare();
1136 backlog = sk_write(s, pktout.data, len);
1137 if (backlog > SSH_MAX_BACKLOG)
1138 ssh_throttle_all(1, backlog);
1141 static void s_wrpkt_defer(void)
1144 len = s_wrpkt_prepare();
1145 if (deferred_len + len > deferred_size) {
1146 deferred_size = deferred_len + len + 128;
1147 deferred_send_data = srealloc(deferred_send_data, deferred_size);
1149 memcpy(deferred_send_data + deferred_len, pktout.data, len);
1150 deferred_len += len;
1154 * Construct a packet with the specified contents.
1156 static void construct_packet(int pkttype, va_list ap1, va_list ap2)
1158 unsigned char *p, *argp, argchar;
1159 unsigned long argint;
1160 int pktlen, argtype, arglen;
1164 while ((argtype = va_arg(ap1, int)) != PKT_END) {
1167 (void) va_arg(ap1, int);
1171 (void) va_arg(ap1, char);
1175 (void) va_arg(ap1, unsigned char *);
1176 arglen = va_arg(ap1, int);
1180 argp = va_arg(ap1, unsigned char *);
1181 arglen = strlen(argp);
1182 pktlen += 4 + arglen;
1185 bn = va_arg(ap1, Bignum);
1186 pktlen += ssh1_bignum_length(bn);
1193 s_wrpkt_start(pkttype, pktlen);
1196 while ((argtype = va_arg(ap2, int)) != PKT_END) {
1199 argint = va_arg(ap2, int);
1200 PUT_32BIT(p, argint);
1204 argchar = va_arg(ap2, unsigned char);
1209 argp = va_arg(ap2, unsigned char *);
1210 arglen = va_arg(ap2, int);
1211 memcpy(p, argp, arglen);
1215 argp = va_arg(ap2, unsigned char *);
1216 arglen = strlen(argp);
1217 PUT_32BIT(p, arglen);
1218 memcpy(p + 4, argp, arglen);
1222 bn = va_arg(ap2, Bignum);
1223 p += ssh1_write_bignum(p, bn);
1229 static void send_packet(int pkttype, ...)
1232 va_start(ap1, pkttype);
1233 va_start(ap2, pkttype);
1234 construct_packet(pkttype, ap1, ap2);
1238 static void defer_packet(int pkttype, ...)
1241 va_start(ap1, pkttype);
1242 va_start(ap2, pkttype);
1243 construct_packet(pkttype, ap1, ap2);
1247 static int ssh_versioncmp(char *a, char *b)
1250 unsigned long av, bv;
1252 av = strtoul(a, &ae, 10);
1253 bv = strtoul(b, &be, 10);
1255 return (av < bv ? -1 : +1);
1260 av = strtoul(ae, &ae, 10);
1261 bv = strtoul(be, &be, 10);
1263 return (av < bv ? -1 : +1);
1269 * Utility routines for putting an SSH-protocol `string' and
1270 * `uint32' into a SHA state.
1273 static void sha_string(SHA_State * s, void *str, int len)
1275 unsigned char lenblk[4];
1276 PUT_32BIT(lenblk, len);
1277 SHA_Bytes(s, lenblk, 4);
1278 SHA_Bytes(s, str, len);
1281 static void sha_uint32(SHA_State * s, unsigned i)
1283 unsigned char intblk[4];
1284 PUT_32BIT(intblk, i);
1285 SHA_Bytes(s, intblk, 4);
1289 * SSH2 packet construction functions.
1291 static void ssh2_pkt_ensure(int length)
1293 if (pktout.maxlen < length) {
1294 pktout.maxlen = length + 256;
1297 NULL ? smalloc(pktout.maxlen +
1298 APIEXTRA) : srealloc(pktout.data,
1302 fatalbox("Out of memory");
1305 static void ssh2_pkt_adddata(void *data, int len)
1307 pktout.length += len;
1308 ssh2_pkt_ensure(pktout.length);
1309 memcpy(pktout.data + pktout.length - len, data, len);
1311 static void ssh2_pkt_addbyte(unsigned char byte)
1313 ssh2_pkt_adddata(&byte, 1);
1315 static void ssh2_pkt_init(int pkt_type)
1318 ssh2_pkt_addbyte((unsigned char) pkt_type);
1320 static void ssh2_pkt_addbool(unsigned char value)
1322 ssh2_pkt_adddata(&value, 1);
1324 static void ssh2_pkt_adduint32(unsigned long value)
1327 PUT_32BIT(x, value);
1328 ssh2_pkt_adddata(x, 4);
1330 static void ssh2_pkt_addstring_start(void)
1332 ssh2_pkt_adduint32(0);
1333 pktout.savedpos = pktout.length;
1335 static void ssh2_pkt_addstring_str(char *data)
1337 ssh2_pkt_adddata(data, strlen(data));
1338 PUT_32BIT(pktout.data + pktout.savedpos - 4,
1339 pktout.length - pktout.savedpos);
1341 static void ssh2_pkt_addstring_data(char *data, int len)
1343 ssh2_pkt_adddata(data, len);
1344 PUT_32BIT(pktout.data + pktout.savedpos - 4,
1345 pktout.length - pktout.savedpos);
1347 static void ssh2_pkt_addstring(char *data)
1349 ssh2_pkt_addstring_start();
1350 ssh2_pkt_addstring_str(data);
1352 static char *ssh2_mpint_fmt(Bignum b, int *len)
1355 int i, n = (bignum_bitcount(b) + 7) / 8;
1358 fatalbox("out of memory");
1360 for (i = 1; i <= n; i++)
1361 p[i] = bignum_byte(b, n - i);
1363 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1365 memmove(p, p + i, n + 1 - i);
1369 static void ssh2_pkt_addmp(Bignum b)
1373 p = ssh2_mpint_fmt(b, &len);
1374 ssh2_pkt_addstring_start();
1375 ssh2_pkt_addstring_data(p, len);
1380 * Construct an SSH2 final-form packet: compress it, encrypt it,
1381 * put the MAC on it. Final packet, ready to be sent, is stored in
1382 * pktout.data. Total length is returned.
1384 static int ssh2_pkt_construct(void)
1386 int cipherblk, maclen, padding, i;
1387 static unsigned long outgoing_sequence = 0;
1389 log_packet(PKT_OUTGOING, pktout.data[5], ssh2_pkt_type(pktout.data[5]),
1390 pktout.data + 6, pktout.length - 6);
1393 * Compress packet payload.
1396 unsigned char *newpayload;
1398 if (cscomp && cscomp->compress(pktout.data + 5, pktout.length - 5,
1399 &newpayload, &newlen)) {
1401 ssh2_pkt_adddata(newpayload, newlen);
1407 * Add padding. At least four bytes, and must also bring total
1408 * length (minus MAC) up to a multiple of the block size.
1410 cipherblk = cscipher ? cscipher->blksize : 8; /* block size */
1411 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1414 (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
1415 maclen = csmac ? csmac->len : 0;
1416 ssh2_pkt_ensure(pktout.length + padding + maclen);
1417 pktout.data[4] = padding;
1418 for (i = 0; i < padding; i++)
1419 pktout.data[pktout.length + i] = random_byte();
1420 PUT_32BIT(pktout.data, pktout.length + padding - 4);
1422 csmac->generate(pktout.data, pktout.length + padding,
1424 outgoing_sequence++; /* whether or not we MACed */
1427 cscipher->encrypt(pktout.data, pktout.length + padding);
1429 /* Ready-to-send packet starts at pktout.data. We return length. */
1430 return pktout.length + padding + maclen;
1434 * Construct and send an SSH2 packet immediately.
1436 static void ssh2_pkt_send(void)
1440 len = ssh2_pkt_construct();
1441 backlog = sk_write(s, pktout.data, len);
1442 if (backlog > SSH_MAX_BACKLOG)
1443 ssh_throttle_all(1, backlog);
1447 * Construct an SSH2 packet and add it to a deferred data block.
1448 * Useful for sending multiple packets in a single sk_write() call,
1449 * to prevent a traffic-analysing listener from being able to work
1450 * out the length of any particular packet (such as the password
1453 * Note that because SSH2 sequence-numbers its packets, this can
1454 * NOT be used as an m4-style `defer' allowing packets to be
1455 * constructed in one order and sent in another.
1457 static void ssh2_pkt_defer(void)
1459 int len = ssh2_pkt_construct();
1460 if (deferred_len + len > deferred_size) {
1461 deferred_size = deferred_len + len + 128;
1462 deferred_send_data = srealloc(deferred_send_data, deferred_size);
1464 memcpy(deferred_send_data + deferred_len, pktout.data, len);
1465 deferred_len += len;
1469 * Send the whole deferred data block constructed by
1470 * ssh2_pkt_defer() or SSH1's defer_packet().
1472 static void ssh_pkt_defersend(void)
1475 backlog = sk_write(s, deferred_send_data, deferred_len);
1476 deferred_len = deferred_size = 0;
1477 sfree(deferred_send_data);
1478 deferred_send_data = NULL;
1479 if (backlog > SSH_MAX_BACKLOG)
1480 ssh_throttle_all(1, backlog);
1484 void bndebug(char *string, Bignum b)
1488 p = ssh2_mpint_fmt(b, &len);
1489 debug(("%s", string));
1490 for (i = 0; i < len; i++)
1491 debug((" %02x", p[i]));
1497 static void sha_mpint(SHA_State * s, Bignum b)
1501 p = ssh2_mpint_fmt(b, &len);
1502 sha_string(s, p, len);
1507 * SSH2 packet decode functions.
1509 static unsigned long ssh2_pkt_getuint32(void)
1511 unsigned long value;
1512 if (pktin.length - pktin.savedpos < 4)
1513 return 0; /* arrgh, no way to decline (FIXME?) */
1514 value = GET_32BIT(pktin.data + pktin.savedpos);
1515 pktin.savedpos += 4;
1518 static int ssh2_pkt_getbool(void)
1520 unsigned long value;
1521 if (pktin.length - pktin.savedpos < 1)
1522 return 0; /* arrgh, no way to decline (FIXME?) */
1523 value = pktin.data[pktin.savedpos] != 0;
1527 static void ssh2_pkt_getstring(char **p, int *length)
1530 if (pktin.length - pktin.savedpos < 4)
1532 *length = GET_32BIT(pktin.data + pktin.savedpos);
1533 pktin.savedpos += 4;
1534 if (pktin.length - pktin.savedpos < *length)
1536 *p = pktin.data + pktin.savedpos;
1537 pktin.savedpos += *length;
1539 static Bignum ssh2_pkt_getmp(void)
1545 ssh2_pkt_getstring(&p, &length);
1549 bombout(("internal error: Can't handle negative mpints"));
1552 b = bignum_from_bytes(p, length);
1557 * Examine the remote side's version string and compare it against
1558 * a list of known buggy implementations.
1560 static void ssh_detect_bugs(char *vstring)
1562 char *imp; /* pointer to implementation part */
1564 imp += strcspn(imp, "-");
1566 imp += strcspn(imp, "-");
1569 ssh_remote_bugs = 0;
1571 if (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1572 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1573 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25")) {
1575 * These versions don't support SSH1_MSG_IGNORE, so we have
1576 * to use a different defence against password length
1579 ssh_remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1580 logevent("We believe remote version has SSH1 ignore bug");
1583 if (!strcmp(imp, "Cisco-1.25")) {
1585 * These versions need a plain password sent; they can't
1586 * handle having a null and a random length of data after
1589 ssh_remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
1590 logevent("We believe remote version needs a plain SSH1 password");
1593 if (!strncmp(imp, "2.1.0", 5) || !strncmp(imp, "2.0.", 4) ||
1594 !strncmp(imp, "2.2.0", 5) || !strncmp(imp, "2.3.0", 5) ||
1595 !strncmp(imp, "2.1 ", 4)) {
1597 * These versions have the HMAC bug.
1599 ssh_remote_bugs |= BUG_SSH2_HMAC;
1600 logevent("We believe remote version has SSH2 HMAC bug");
1604 static int do_ssh_init(unsigned char c)
1607 static char version[10];
1608 static char *vstring;
1609 static int vstrsize;
1615 /* Search for the string "SSH-" in the input. */
1618 static const int transS[] = { 1, 2, 2, 1 };
1619 static const int transH[] = { 0, 0, 3, 0 };
1620 static const int transminus[] = { 0, 0, 0, -1 };
1631 crReturn(1); /* get another character */
1635 vstring = smalloc(vstrsize);
1636 strcpy(vstring, "SSH-");
1640 crReturn(1); /* get another char */
1641 if (vslen >= vstrsize - 1) {
1643 vstring = srealloc(vstring, vstrsize);
1645 vstring[vslen++] = c;
1650 } else if (i < sizeof(version) - 1)
1652 } else if (c == '\n')
1656 ssh_agentfwd_enabled = FALSE;
1657 rdpkt2_state.incoming_sequence = 0;
1660 vlog = smalloc(20 + vslen);
1661 vstring[strcspn (vstring, "\r\n")] = '\0'; /* remove end-of-line chars */
1662 sprintf(vlog, "Server version: %s", vstring);
1664 ssh_detect_bugs(vstring);
1668 * Server version "1.99" means we can choose whether we use v1
1669 * or v2 protocol. Choice is based on cfg.sshprot.
1671 if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
1673 * This is a v2 server. Begin v2 protocol.
1675 char verstring[80], vlog[100];
1676 sprintf(verstring, "SSH-2.0-%s", sshver);
1677 SHA_Init(&exhashbase);
1679 * Hash our version string and their version string.
1681 sha_string(&exhashbase, verstring, strlen(verstring));
1682 sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
1683 sprintf(vlog, "We claim version: %s", verstring);
1685 strcat(verstring, "\n");
1686 logevent("Using SSH protocol version 2");
1687 sk_write(s, verstring, strlen(verstring));
1688 ssh_protocol = ssh2_protocol;
1690 s_rdpkt = ssh2_rdpkt;
1693 * This is a v1 server. Begin v1 protocol.
1695 char verstring[80], vlog[100];
1696 sprintf(verstring, "SSH-%s-%s",
1697 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"),
1699 sprintf(vlog, "We claim version: %s", verstring);
1701 strcat(verstring, "\n");
1702 logevent("Using SSH protocol version 1");
1703 sk_write(s, verstring, strlen(verstring));
1704 ssh_protocol = ssh1_protocol;
1706 s_rdpkt = ssh1_rdpkt;
1708 ssh_state = SSH_STATE_BEFORE_SIZE;
1715 static void ssh_gotdata(unsigned char *data, int datalen)
1720 * To begin with, feed the characters one by one to the
1721 * protocol initialisation / selection function do_ssh_init().
1722 * When that returns 0, we're done with the initial greeting
1723 * exchange and can move on to packet discipline.
1728 crReturnV; /* more data please */
1729 ret = do_ssh_init(*data);
1737 * We emerge from that loop when the initial negotiation is
1738 * over and we have selected an s_rdpkt function. Now pass
1739 * everything to s_rdpkt, and then pass the resulting packets
1740 * to the proper protocol handler.
1745 while (datalen > 0) {
1746 if (s_rdpkt(&data, &datalen) == 0) {
1747 if (ssh_state == SSH_STATE_CLOSED) {
1750 ssh_protocol(NULL, 0, 1);
1751 if (ssh_state == SSH_STATE_CLOSED) {
1761 static int ssh_closing(Plug plug, char *error_msg, int error_code,
1764 ssh_state = SSH_STATE_CLOSED;
1770 /* A socket error has occurred. */
1771 connection_fatal(error_msg);
1773 /* Otherwise, the remote side closed the connection normally. */
1778 static int ssh_receive(Plug plug, int urgent, char *data, int len)
1780 ssh_gotdata(data, len);
1781 if (ssh_state == SSH_STATE_CLOSED) {
1791 static void ssh_sent(Plug plug, int bufsize)
1794 * If the send backlog on the SSH socket itself clears, we
1795 * should unthrottle the whole world if it was throttled.
1797 if (bufsize < SSH_MAX_BACKLOG)
1798 ssh_throttle_all(0, bufsize);
1802 * Connect to specified host and port.
1803 * Returns an error message, or NULL on success.
1804 * Also places the canonical host name into `realhost'. It must be
1805 * freed by the caller.
1807 static char *connect_to_host(char *host, int port, char **realhost, int nodelay)
1809 static struct plug_function_table fn_table = {
1814 }, *fn_table_ptr = &fn_table;
1823 savedhost = smalloc(1 + strlen(host));
1825 fatalbox("Out of memory");
1826 strcpy(savedhost, host);
1829 port = 22; /* default ssh port */
1844 sprintf(buf, "Looking up host \"%.170s\"", host);
1847 addr = sk_namelookup(host, realhost);
1848 if ((err = sk_addr_error(addr)))
1852 *realhost = strdup(FWhost);
1859 char buf[200], addrbuf[100];
1860 sk_getaddr(addr, addrbuf, 100);
1861 sprintf(buf, "Connecting to %.100s port %d", addrbuf, port);
1864 s = sk_new(addr, port, 0, 1, nodelay, &fn_table_ptr);
1865 if ((err = sk_socket_error(s)))
1869 sk_write(s, "connect ", 8);
1870 sk_write(s, FWhost, strlen(FWhost));
1873 sprintf(buf, " %d\n", FWport);
1874 sk_write(s, buf, strlen(buf));
1882 * Throttle or unthrottle the SSH connection.
1884 static void ssh1_throttle(int adjust)
1886 int old_count = ssh1_throttle_count;
1887 ssh1_throttle_count += adjust;
1888 assert(ssh1_throttle_count >= 0);
1889 if (ssh1_throttle_count && !old_count) {
1890 sk_set_frozen(s, 1);
1891 } else if (!ssh1_throttle_count && old_count) {
1892 sk_set_frozen(s, 0);
1897 * Throttle or unthrottle _all_ local data streams (for when sends
1898 * on the SSH connection itself back up).
1900 static void ssh_throttle_all(int enable, int bufsize)
1903 struct ssh_channel *c;
1905 if (enable == ssh_throttled_all)
1907 ssh_throttled_all = enable;
1908 ssh_overall_bufsize = bufsize;
1911 for (i = 0; NULL != (c = index234(ssh_channels, i)); i++) {
1913 case CHAN_MAINSESSION:
1915 * This is treated separately, outside the switch.
1919 x11_override_throttle(c->u.x11.s, enable);
1922 /* Agent channels require no buffer management. */
1925 pfd_override_throttle(c->u.x11.s, enable);
1932 * Handle the key exchange and user authentication phases.
1934 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1938 static unsigned char *rsabuf, *keystr1, *keystr2;
1939 unsigned char cookie[8];
1940 struct RSAKey servkey, hostkey;
1941 struct MD5Context md5c;
1942 static unsigned long supported_ciphers_mask, supported_auths_mask;
1943 static int tried_publickey, tried_agent;
1944 static int tis_auth_refused, ccard_auth_refused;
1945 static unsigned char session_id[16];
1946 static int cipher_type;
1947 static char username[100];
1948 static void *publickey_blob;
1949 int publickey_bloblen;
1956 if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
1957 bombout(("Public key packet not received"));
1961 logevent("Received public keys");
1963 memcpy(cookie, pktin.body, 8);
1965 i = makekey(pktin.body + 8, &servkey, &keystr1, 0);
1966 j = makekey(pktin.body + 8 + i, &hostkey, &keystr2, 0);
1969 * Log the host key fingerprint.
1973 logevent("Host key fingerprint is:");
1974 strcpy(logmsg, " ");
1975 hostkey.comment = NULL;
1976 rsa_fingerprint(logmsg + strlen(logmsg),
1977 sizeof(logmsg) - strlen(logmsg), &hostkey);
1981 ssh1_remote_protoflags = GET_32BIT(pktin.body + 8 + i + j);
1982 supported_ciphers_mask = GET_32BIT(pktin.body + 12 + i + j);
1983 supported_auths_mask = GET_32BIT(pktin.body + 16 + i + j);
1985 ssh1_local_protoflags =
1986 ssh1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
1987 ssh1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
1990 MD5Update(&md5c, keystr2, hostkey.bytes);
1991 MD5Update(&md5c, keystr1, servkey.bytes);
1992 MD5Update(&md5c, pktin.body, 8);
1993 MD5Final(session_id, &md5c);
1995 for (i = 0; i < 32; i++)
1996 session_key[i] = random_byte();
1998 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
2000 rsabuf = smalloc(len);
2002 fatalbox("Out of memory");
2005 * Verify the host key.
2009 * First format the key into a string.
2011 int len = rsastr_len(&hostkey);
2012 char fingerprint[100];
2013 char *keystr = smalloc(len);
2015 fatalbox("Out of memory");
2016 rsastr_fmt(keystr, &hostkey);
2017 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
2018 verify_ssh_host_key(savedhost, savedport, "rsa", keystr,
2023 for (i = 0; i < 32; i++) {
2024 rsabuf[i] = session_key[i];
2026 rsabuf[i] ^= session_id[i];
2029 if (hostkey.bytes > servkey.bytes) {
2030 rsaencrypt(rsabuf, 32, &servkey);
2031 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
2033 rsaencrypt(rsabuf, 32, &hostkey);
2034 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
2037 logevent("Encrypted session key");
2040 int cipher_chosen = 0, warn = 0;
2041 char *cipher_string = NULL;
2042 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
2043 int next_cipher = cfg.ssh_cipherlist[i];
2044 if (next_cipher == CIPHER_WARN) {
2045 /* If/when we choose a cipher, warn about it */
2047 } else if (next_cipher == CIPHER_AES) {
2048 /* XXX Probably don't need to mention this. */
2049 logevent("AES not supported in SSH1, skipping");
2051 switch (next_cipher) {
2052 case CIPHER_3DES: cipher_type = SSH_CIPHER_3DES;
2053 cipher_string = "3DES"; break;
2054 case CIPHER_BLOWFISH: cipher_type = SSH_CIPHER_BLOWFISH;
2055 cipher_string = "Blowfish"; break;
2056 case CIPHER_DES: cipher_type = SSH_CIPHER_DES;
2057 cipher_string = "single-DES"; break;
2059 if (supported_ciphers_mask & (1 << cipher_type))
2063 if (!cipher_chosen) {
2064 if ((supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
2065 bombout(("Server violates SSH 1 protocol by not "
2066 "supporting 3DES encryption"));
2068 /* shouldn't happen */
2069 bombout(("No supported ciphers found"));
2073 /* Warn about chosen cipher if necessary. */
2075 askcipher(cipher_string, 0);
2078 switch (cipher_type) {
2079 case SSH_CIPHER_3DES:
2080 logevent("Using 3DES encryption");
2082 case SSH_CIPHER_DES:
2083 logevent("Using single-DES encryption");
2085 case SSH_CIPHER_BLOWFISH:
2086 logevent("Using Blowfish encryption");
2090 send_packet(SSH1_CMSG_SESSION_KEY,
2091 PKT_CHAR, cipher_type,
2092 PKT_DATA, cookie, 8,
2093 PKT_CHAR, (len * 8) >> 8, PKT_CHAR, (len * 8) & 0xFF,
2094 PKT_DATA, rsabuf, len,
2095 PKT_INT, ssh1_local_protoflags, PKT_END);
2097 logevent("Trying to enable encryption...");
2101 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
2102 cipher_type == SSH_CIPHER_DES ? &ssh_des : &ssh_3des;
2103 cipher->sesskey(session_key);
2107 if (pktin.type != SSH1_SMSG_SUCCESS) {
2108 bombout(("Encryption not successfully enabled"));
2112 logevent("Successfully started encryption");
2118 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2120 if (!ssh_get_line("login as: ",
2121 username, sizeof(username), FALSE)) {
2123 * get_line failed to get a username.
2126 logevent("No username provided. Abandoning session.");
2127 ssh_state = SSH_STATE_CLOSED;
2131 c_write_str("login as: ");
2134 crWaitUntil(!ispkt);
2136 switch (c = *in++) {
2145 c_write_str("\b \b");
2152 c_write_str("\b \b");
2162 if (((c >= ' ' && c <= '~') ||
2163 ((unsigned char) c >= 160))
2164 && pos < sizeof(username)-1) {
2165 username[pos++] = c;
2171 c_write_str("\r\n");
2172 username[strcspn(username, "\n\r")] = '\0';
2175 strncpy(username, cfg.username, 99);
2176 username[99] = '\0';
2179 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
2181 char userlog[22 + sizeof(username)];
2182 sprintf(userlog, "Sent username \"%s\"", username);
2184 if (flags & FLAG_INTERACTIVE &&
2185 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
2186 strcat(userlog, "\r\n");
2187 c_write_str(userlog);
2194 tried_publickey = tried_agent = 0;
2195 tis_auth_refused = ccard_auth_refused = 0;
2196 /* Load the public half of cfg.keyfile so we notice if it's in Pageant */
2198 if (!rsakey_pubblob(cfg.keyfile, &publickey_blob, &publickey_bloblen))
2199 publickey_blob = NULL;
2201 publickey_blob = NULL;
2203 while (pktin.type == SSH1_SMSG_FAILURE) {
2204 static char password[100];
2205 static char prompt[200];
2208 static int pwpkt_type;
2209 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2211 if (agent_exists() && !tried_agent) {
2213 * Attempt RSA authentication using Pageant.
2215 static unsigned char request[5], *response, *p;
2216 static int responselen;
2217 static int i, nkeys;
2218 static int authed = FALSE;
2222 logevent("Pageant is running. Requesting keys.");
2224 /* Request the keys held by the agent. */
2225 PUT_32BIT(request, 1);
2226 request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2227 agent_query(request, 5, &r, &responselen);
2228 response = (unsigned char *) r;
2229 if (response && responselen >= 5 &&
2230 response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2232 nkeys = GET_32BIT(p);
2236 sprintf(buf, "Pageant has %d SSH1 keys", nkeys);
2239 for (i = 0; i < nkeys; i++) {
2240 static struct RSAKey key;
2241 static Bignum challenge;
2242 static char *commentp;
2243 static int commentlen;
2247 sprintf(buf, "Trying Pageant key #%d", i);
2250 if (publickey_blob &&
2251 !memcmp(p, publickey_blob, publickey_bloblen)) {
2252 logevent("This key matches configured key file");
2253 tried_publickey = 1;
2256 p += ssh1_read_bignum(p, &key.exponent);
2257 p += ssh1_read_bignum(p, &key.modulus);
2258 commentlen = GET_32BIT(p);
2262 send_packet(SSH1_CMSG_AUTH_RSA,
2263 PKT_BIGNUM, key.modulus, PKT_END);
2265 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2266 logevent("Key refused");
2269 logevent("Received RSA challenge");
2270 ssh1_read_bignum(pktin.body, &challenge);
2272 char *agentreq, *q, *ret;
2275 len = 1 + 4; /* message type, bit count */
2276 len += ssh1_bignum_length(key.exponent);
2277 len += ssh1_bignum_length(key.modulus);
2278 len += ssh1_bignum_length(challenge);
2279 len += 16; /* session id */
2280 len += 4; /* response format */
2281 agentreq = smalloc(4 + len);
2282 PUT_32BIT(agentreq, len);
2284 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
2285 PUT_32BIT(q, bignum_bitcount(key.modulus));
2287 q += ssh1_write_bignum(q, key.exponent);
2288 q += ssh1_write_bignum(q, key.modulus);
2289 q += ssh1_write_bignum(q, challenge);
2290 memcpy(q, session_id, 16);
2292 PUT_32BIT(q, 1); /* response format */
2293 agent_query(agentreq, len + 4, &vret, &retlen);
2297 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
2298 logevent("Sending Pageant's response");
2299 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
2300 PKT_DATA, ret + 5, 16,
2304 if (pktin.type == SSH1_SMSG_SUCCESS) {
2306 ("Pageant's response accepted");
2307 if (flags & FLAG_VERBOSE) {
2309 ("Authenticated using RSA key \"");
2310 c_write(commentp, commentlen);
2311 c_write_str("\" from agent\r\n");
2316 ("Pageant's response not accepted");
2319 ("Pageant failed to answer challenge");
2323 logevent("No reply received from Pageant");
2326 freebn(key.exponent);
2327 freebn(key.modulus);
2336 if (*cfg.keyfile && !tried_publickey)
2337 pwpkt_type = SSH1_CMSG_AUTH_RSA;
2339 if (cfg.try_tis_auth &&
2340 (supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
2341 !tis_auth_refused) {
2342 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
2343 logevent("Requested TIS authentication");
2344 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
2346 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
2347 logevent("TIS authentication declined");
2348 if (flags & FLAG_INTERACTIVE)
2349 c_write_str("TIS authentication refused.\r\n");
2350 tis_auth_refused = 1;
2353 int challengelen = ((pktin.body[0] << 24) |
2354 (pktin.body[1] << 16) |
2355 (pktin.body[2] << 8) |
2357 logevent("Received TIS challenge");
2358 if (challengelen > sizeof(prompt) - 1)
2359 challengelen = sizeof(prompt) - 1; /* prevent overrun */
2360 memcpy(prompt, pktin.body + 4, challengelen);
2361 /* Prompt heuristic comes from OpenSSH */
2362 strncpy(prompt + challengelen,
2363 memchr(prompt, '\n', challengelen) ?
2364 "": "\r\nResponse: ",
2365 (sizeof prompt) - challengelen);
2366 prompt[(sizeof prompt) - 1] = '\0';
2369 if (cfg.try_tis_auth &&
2370 (supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
2371 !ccard_auth_refused) {
2372 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
2373 logevent("Requested CryptoCard authentication");
2374 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
2376 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
2377 logevent("CryptoCard authentication declined");
2378 c_write_str("CryptoCard authentication refused.\r\n");
2379 ccard_auth_refused = 1;
2382 int challengelen = ((pktin.body[0] << 24) |
2383 (pktin.body[1] << 16) |
2384 (pktin.body[2] << 8) |
2386 logevent("Received CryptoCard challenge");
2387 if (challengelen > sizeof(prompt) - 1)
2388 challengelen = sizeof(prompt) - 1; /* prevent overrun */
2389 memcpy(prompt, pktin.body + 4, challengelen);
2390 strncpy(prompt + challengelen,
2391 memchr(prompt, '\n', challengelen) ?
2392 "" : "\r\nResponse: ",
2393 sizeof(prompt) - challengelen);
2394 prompt[sizeof(prompt) - 1] = '\0';
2397 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2398 sprintf(prompt, "%.90s@%.90s's password: ",
2399 username, savedhost);
2401 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2402 char *comment = NULL;
2403 if (flags & FLAG_VERBOSE)
2404 c_write_str("Trying public key authentication.\r\n");
2405 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
2406 if (flags & FLAG_VERBOSE)
2407 c_write_str("No passphrase required.\r\n");
2410 sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
2415 * Show password prompt, having first obtained it via a TIS
2416 * or CryptoCard exchange if we're doing TIS or CryptoCard
2420 if (!ssh_get_line(prompt, password, sizeof(password), TRUE)) {
2422 * get_line failed to get a password (for example
2423 * because one was supplied on the command line
2424 * which has already failed to work). Terminate.
2426 send_packet(SSH1_MSG_DISCONNECT,
2427 PKT_STR, "No more passwords available to try",
2429 connection_fatal("Unable to authenticate");
2430 ssh_state = SSH_STATE_CLOSED;
2434 /* Prompt may have come from server. We've munged it a bit, so
2435 * we know it to be zero-terminated at least once. */
2436 c_write_untrusted(prompt, strlen(prompt));
2440 crWaitUntil(!ispkt);
2442 switch (c = *in++) {
2463 if (pos < sizeof(password)-1)
2464 password[pos++] = c;
2468 c_write_str("\r\n");
2472 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2474 * Try public key authentication with the specified
2477 static struct RSAKey pubkey;
2478 static Bignum challenge, response;
2480 static unsigned char buffer[32];
2482 tried_publickey = 1;
2483 i = loadrsakey(cfg.keyfile, &pubkey, password);
2485 c_write_str("Couldn't load private key from ");
2486 c_write_str(cfg.keyfile);
2487 c_write_str(".\r\n");
2488 continue; /* go and try password */
2491 c_write_str("Wrong passphrase.\r\n");
2492 tried_publickey = 0;
2493 continue; /* try again */
2497 * Send a public key attempt.
2499 send_packet(SSH1_CMSG_AUTH_RSA,
2500 PKT_BIGNUM, pubkey.modulus, PKT_END);
2503 if (pktin.type == SSH1_SMSG_FAILURE) {
2504 c_write_str("Server refused our public key.\r\n");
2505 continue; /* go and try password */
2507 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2508 bombout(("Bizarre response to offer of public key"));
2511 ssh1_read_bignum(pktin.body, &challenge);
2512 response = rsadecrypt(challenge, &pubkey);
2513 freebn(pubkey.private_exponent); /* burn the evidence */
2515 for (i = 0; i < 32; i++) {
2516 buffer[i] = bignum_byte(response, 31 - i);
2520 MD5Update(&md5c, buffer, 32);
2521 MD5Update(&md5c, session_id, 16);
2522 MD5Final(buffer, &md5c);
2524 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
2525 PKT_DATA, buffer, 16, PKT_END);
2528 if (pktin.type == SSH1_SMSG_FAILURE) {
2529 if (flags & FLAG_VERBOSE)
2531 ("Failed to authenticate with our public key.\r\n");
2532 continue; /* go and try password */
2533 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
2535 ("Bizarre response to RSA authentication response"));
2539 break; /* we're through! */
2541 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2543 * Defence against traffic analysis: we send a
2544 * whole bunch of packets containing strings of
2545 * different lengths. One of these strings is the
2546 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2547 * The others are all random data in
2548 * SSH1_MSG_IGNORE packets. This way a passive
2549 * listener can't tell which is the password, and
2550 * hence can't deduce the password length.
2552 * Anybody with a password length greater than 16
2553 * bytes is going to have enough entropy in their
2554 * password that a listener won't find it _that_
2555 * much help to know how long it is. So what we'll
2558 * - if password length < 16, we send 15 packets
2559 * containing string lengths 1 through 15
2561 * - otherwise, we let N be the nearest multiple
2562 * of 8 below the password length, and send 8
2563 * packets containing string lengths N through
2564 * N+7. This won't obscure the order of
2565 * magnitude of the password length, but it will
2566 * introduce a bit of extra uncertainty.
2568 * A few servers (the old 1.2.18 through 1.2.22)
2569 * can't deal with SSH1_MSG_IGNORE. For these
2570 * servers, we need an alternative defence. We make
2571 * use of the fact that the password is interpreted
2572 * as a C string: so we can append a NUL, then some
2575 * One server (a Cisco one) can deal with neither
2576 * SSH1_MSG_IGNORE _nor_ a padded password string.
2577 * For this server we are left with no defences
2578 * against password length sniffing.
2580 if (!(ssh_remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
2582 * The server can deal with SSH1_MSG_IGNORE, so
2583 * we can use the primary defence.
2585 int bottom, top, pwlen, i;
2588 pwlen = strlen(password);
2590 bottom = 0; /* zero length passwords are OK! :-) */
2593 bottom = pwlen & ~7;
2597 assert(pwlen >= bottom && pwlen <= top);
2599 randomstr = smalloc(top + 1);
2601 for (i = bottom; i <= top; i++) {
2603 defer_packet(pwpkt_type, PKT_STR, password,
2606 for (j = 0; j < i; j++) {
2608 randomstr[j] = random_byte();
2609 } while (randomstr[j] == '\0');
2611 randomstr[i] = '\0';
2612 defer_packet(SSH1_MSG_IGNORE,
2613 PKT_STR, randomstr, PKT_END);
2616 logevent("Sending password with camouflage packets");
2617 ssh_pkt_defersend();
2619 else if (!(ssh_remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
2621 * The server can't deal with SSH1_MSG_IGNORE
2622 * but can deal with padded passwords, so we
2623 * can use the secondary defence.
2629 len = strlen(password);
2630 if (len < sizeof(string)) {
2632 strcpy(string, password);
2633 len++; /* cover the zero byte */
2634 while (len < sizeof(string)) {
2635 string[len++] = (char) random_byte();
2640 logevent("Sending length-padded password");
2641 send_packet(pwpkt_type, PKT_INT, len,
2642 PKT_DATA, s, len, PKT_END);
2645 * The server has _both_
2646 * BUG_CHOKES_ON_SSH1_IGNORE and
2647 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2648 * therefore nothing we can do.
2651 len = strlen(password);
2652 logevent("Sending unpadded password");
2653 send_packet(pwpkt_type, PKT_INT, len,
2654 PKT_DATA, password, len, PKT_END);
2657 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
2660 logevent("Sent password");
2661 memset(password, 0, strlen(password));
2663 if (pktin.type == SSH1_SMSG_FAILURE) {
2664 if (flags & FLAG_VERBOSE)
2665 c_write_str("Access denied\r\n");
2666 logevent("Authentication refused");
2667 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2668 logevent("Received disconnect request");
2669 ssh_state = SSH_STATE_CLOSED;
2671 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
2672 bombout(("Strange packet received, type %d", pktin.type));
2677 logevent("Authentication successful");
2682 void sshfwd_close(struct ssh_channel *c)
2684 if (c && !c->closes) {
2686 * If the channel's remoteid is -1, we have sent
2687 * CHANNEL_OPEN for this channel, but it hasn't even been
2688 * acknowledged by the server. So we must set a close flag
2689 * on it now, and then when the server acks the channel
2690 * open, we can close it then.
2692 if (c->remoteid != -1) {
2693 if (ssh_version == 1) {
2694 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
2697 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2698 ssh2_pkt_adduint32(c->remoteid);
2703 if (c->type == CHAN_X11) {
2705 logevent("Forwarded X11 connection terminated");
2706 } else if (c->type == CHAN_SOCKDATA ||
2707 c->type == CHAN_SOCKDATA_DORMANT) {
2709 logevent("Forwarded port closed");
2714 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
2716 if (ssh_version == 1) {
2717 send_packet(SSH1_MSG_CHANNEL_DATA,
2718 PKT_INT, c->remoteid,
2719 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2721 * In SSH1 we can return 0 here - implying that forwarded
2722 * connections are never individually throttled - because
2723 * the only circumstance that can cause throttling will be
2724 * the whole SSH connection backing up, in which case
2725 * _everything_ will be throttled as a whole.
2729 ssh2_add_channel_data(c, buf, len);
2730 return ssh2_try_send(c);
2734 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
2736 if (ssh_version == 1) {
2737 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
2738 c->v.v1.throttling = 0;
2742 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
2746 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt)
2752 while (!do_ssh1_login(in, inlen, ispkt)) {
2755 if (ssh_state == SSH_STATE_CLOSED)
2758 if (cfg.agentfwd && agent_exists()) {
2759 logevent("Requesting agent forwarding");
2760 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
2764 if (pktin.type != SSH1_SMSG_SUCCESS
2765 && pktin.type != SSH1_SMSG_FAILURE) {
2766 bombout(("Protocol confusion"));
2768 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2769 logevent("Agent forwarding refused");
2771 logevent("Agent forwarding enabled");
2772 ssh_agentfwd_enabled = TRUE;
2776 if (cfg.x11_forward) {
2777 char proto[20], data[64];
2778 logevent("Requesting X11 forwarding");
2779 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
2780 if (ssh1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
2781 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2782 PKT_STR, proto, PKT_STR, data,
2783 PKT_INT, 0, PKT_END);
2785 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2786 PKT_STR, proto, PKT_STR, data, PKT_END);
2791 if (pktin.type != SSH1_SMSG_SUCCESS
2792 && pktin.type != SSH1_SMSG_FAILURE) {
2793 bombout(("Protocol confusion"));
2795 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2796 logevent("X11 forwarding refused");
2798 logevent("X11 forwarding enabled");
2799 ssh_X11_fwd_enabled = TRUE;
2807 char sports[256], dports[256], host[256];
2810 ssh_rportfwds = newtree234(ssh_rportcmp_ssh1);
2811 /* Add port forwardings. */
2816 while (*e && *e != '\t')
2822 while (*e && *e != ':')
2832 dport = atoi(dports);
2833 sport = atoi(sports);
2834 if (sport && dport) {
2836 pfd_addforward(host, dport, sport);
2837 sprintf(buf, "Local port %d forwarding to %s:%d",
2838 sport, host, dport);
2841 struct ssh_rportfwd *pf;
2842 pf = smalloc(sizeof(*pf));
2843 strcpy(pf->dhost, host);
2845 if (add234(ssh_rportfwds, pf) != pf) {
2847 "Duplicate remote port forwarding to %s:%d",
2852 sprintf(buf, "Requesting remote port %d forward to %s:%d",
2853 sport, host, dport);
2855 send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST,
2867 send_packet(SSH1_CMSG_REQUEST_PTY,
2868 PKT_STR, cfg.termtype,
2869 PKT_INT, rows, PKT_INT, cols,
2870 PKT_INT, 0, PKT_INT, 0, PKT_CHAR, 0, PKT_END);
2871 ssh_state = SSH_STATE_INTERMED;
2875 if (pktin.type != SSH1_SMSG_SUCCESS
2876 && pktin.type != SSH1_SMSG_FAILURE) {
2877 bombout(("Protocol confusion"));
2879 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2880 c_write_str("Server refused to allocate pty\r\n");
2881 ssh_editing = ssh_echoing = 1;
2883 logevent("Allocated pty");
2885 ssh_editing = ssh_echoing = 1;
2888 if (cfg.compression) {
2889 send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
2893 if (pktin.type != SSH1_SMSG_SUCCESS
2894 && pktin.type != SSH1_SMSG_FAILURE) {
2895 bombout(("Protocol confusion"));
2897 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2898 c_write_str("Server refused to compress\r\n");
2900 logevent("Started compression");
2901 ssh1_compressing = TRUE;
2902 zlib_compress_init();
2903 zlib_decompress_init();
2907 * Start the shell or command.
2909 * Special case: if the first-choice command is an SSH2
2910 * subsystem (hence not usable here) and the second choice
2911 * exists, we fall straight back to that.
2914 char *cmd = cfg.remote_cmd_ptr;
2916 if (cfg.ssh_subsys && cfg.remote_cmd_ptr2) {
2917 cmd = cfg.remote_cmd_ptr2;
2918 ssh_fallback_cmd = TRUE;
2921 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
2923 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
2924 logevent("Started session");
2927 ssh_state = SSH_STATE_SESSION;
2931 ssh_special(TS_EOF);
2933 ldisc_send(NULL, 0, 0); /* cause ldisc to notice changes */
2935 ssh_channels = newtree234(ssh_channelcmp);
2939 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
2940 pktin.type == SSH1_SMSG_STDERR_DATA) {
2941 long len = GET_32BIT(pktin.body);
2943 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
2944 pktin.body + 4, len);
2945 if (!ssh1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
2946 ssh1_stdout_throttling = 1;
2949 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2950 ssh_state = SSH_STATE_CLOSED;
2951 logevent("Received disconnect request");
2953 } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
2954 /* Remote side is trying to open a channel to talk to our
2955 * X-Server. Give them back a local channel number. */
2956 struct ssh_channel *c;
2958 logevent("Received X11 connect request");
2959 /* Refuse if X11 forwarding is disabled. */
2960 if (!ssh_X11_fwd_enabled) {
2961 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2962 PKT_INT, GET_32BIT(pktin.body), PKT_END);
2963 logevent("Rejected X11 connect request");
2965 c = smalloc(sizeof(struct ssh_channel));
2967 if (x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL) {
2968 logevent("opening X11 forward connection failed");
2970 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2971 PKT_INT, GET_32BIT(pktin.body),
2975 ("opening X11 forward connection succeeded");
2976 c->remoteid = GET_32BIT(pktin.body);
2977 c->localid = alloc_channel_id();
2979 c->v.v1.throttling = 0;
2980 c->type = CHAN_X11; /* identify channel type */
2981 add234(ssh_channels, c);
2982 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2983 PKT_INT, c->remoteid, PKT_INT,
2984 c->localid, PKT_END);
2985 logevent("Opened X11 forward channel");
2988 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
2989 /* Remote side is trying to open a channel to talk to our
2990 * agent. Give them back a local channel number. */
2991 struct ssh_channel *c;
2993 /* Refuse if agent forwarding is disabled. */
2994 if (!ssh_agentfwd_enabled) {
2995 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2996 PKT_INT, GET_32BIT(pktin.body), PKT_END);
2998 c = smalloc(sizeof(struct ssh_channel));
2999 c->remoteid = GET_32BIT(pktin.body);
3000 c->localid = alloc_channel_id();
3002 c->v.v1.throttling = 0;
3003 c->type = CHAN_AGENT; /* identify channel type */
3004 c->u.a.lensofar = 0;
3005 add234(ssh_channels, c);
3006 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3007 PKT_INT, c->remoteid, PKT_INT, c->localid,
3010 } else if (pktin.type == SSH1_MSG_PORT_OPEN) {
3011 /* Remote side is trying to open a channel to talk to a
3012 * forwarded port. Give them back a local channel number. */
3013 struct ssh_channel *c;
3014 struct ssh_rportfwd pf;
3016 char host[256], buf[1024];
3018 c = smalloc(sizeof(struct ssh_channel));
3020 hostsize = GET_32BIT(pktin.body+4);
3021 for(h = host, p = pktin.body+8; hostsize != 0; hostsize--) {
3022 if (h+1 < host+sizeof(host))
3027 port = GET_32BIT(p);
3029 strcpy(pf.dhost, host);
3032 if (find234(ssh_rportfwds, &pf, NULL) == NULL) {
3033 sprintf(buf, "Rejected remote port open request for %s:%d",
3036 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3037 PKT_INT, GET_32BIT(pktin.body), PKT_END);
3039 sprintf(buf, "Received remote port open request for %s:%d",
3042 e = pfd_newconnect(&c->u.pfd.s, host, port, c);
3045 sprintf(buf, "Port open failed: %s", e);
3048 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3049 PKT_INT, GET_32BIT(pktin.body),
3052 c->remoteid = GET_32BIT(pktin.body);
3053 c->localid = alloc_channel_id();
3055 c->v.v1.throttling = 0;
3056 c->type = CHAN_SOCKDATA; /* identify channel type */
3057 add234(ssh_channels, c);
3058 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3059 PKT_INT, c->remoteid, PKT_INT,
3060 c->localid, PKT_END);
3061 logevent("Forwarded port opened successfully");
3065 } else if (pktin.type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
3066 unsigned int remoteid = GET_32BIT(pktin.body);
3067 unsigned int localid = GET_32BIT(pktin.body+4);
3068 struct ssh_channel *c;
3070 c = find234(ssh_channels, &remoteid, ssh_channelfind);
3071 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3072 c->remoteid = localid;
3073 c->type = CHAN_SOCKDATA;
3074 c->v.v1.throttling = 0;
3075 pfd_confirm(c->u.pfd.s);
3078 if (c && c->closes) {
3080 * We have a pending close on this channel,
3081 * which we decided on before the server acked
3082 * the channel open. So now we know the
3083 * remoteid, we can close it again.
3085 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
3089 } else if (pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
3090 unsigned int remoteid = GET_32BIT(pktin.body);
3091 unsigned int localid = GET_32BIT(pktin.body+4);
3092 struct ssh_channel *c;
3094 c = find234(ssh_channels, &remoteid, ssh_channelfind);
3095 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3096 logevent("Forwarded connection refused by server");
3097 pfd_close(c->u.pfd.s);
3098 del234(ssh_channels, c);
3102 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
3103 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
3104 /* Remote side closes a channel. */
3105 unsigned i = GET_32BIT(pktin.body);
3106 struct ssh_channel *c;
3107 c = find234(ssh_channels, &i, ssh_channelfind);
3111 (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
3112 if (!(c->closes & closetype))
3113 send_packet(pktin.type, PKT_INT, c->remoteid,
3115 if ((c->closes == 0) && (c->type == CHAN_X11)) {
3116 logevent("Forwarded X11 connection terminated");
3117 assert(c->u.x11.s != NULL);
3118 x11_close(c->u.x11.s);
3121 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
3122 logevent("Forwarded port closed");
3123 assert(c->u.pfd.s != NULL);
3124 pfd_close(c->u.pfd.s);
3127 c->closes |= closetype;
3128 if (c->closes == 3) {
3129 del234(ssh_channels, c);
3133 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
3134 /* Data sent down one of our channels. */
3135 int i = GET_32BIT(pktin.body);
3136 int len = GET_32BIT(pktin.body + 4);
3137 unsigned char *p = pktin.body + 8;
3138 struct ssh_channel *c;
3139 c = find234(ssh_channels, &i, ssh_channelfind);
3144 bufsize = x11_send(c->u.x11.s, p, len);
3147 bufsize = pfd_send(c->u.pfd.s, p, len);
3150 /* Data for an agent message. Buffer it. */
3152 if (c->u.a.lensofar < 4) {
3153 int l = min(4 - c->u.a.lensofar, len);
3154 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
3158 c->u.a.lensofar += l;
3160 if (c->u.a.lensofar == 4) {
3162 4 + GET_32BIT(c->u.a.msglen);
3163 c->u.a.message = smalloc(c->u.a.totallen);
3164 memcpy(c->u.a.message, c->u.a.msglen, 4);
3166 if (c->u.a.lensofar >= 4 && len > 0) {
3168 min(c->u.a.totallen - c->u.a.lensofar,
3170 memcpy(c->u.a.message + c->u.a.lensofar, p,
3174 c->u.a.lensofar += l;
3176 if (c->u.a.lensofar == c->u.a.totallen) {
3177 void *reply, *sentreply;
3179 agent_query(c->u.a.message,
3180 c->u.a.totallen, &reply,
3185 /* Fake SSH_AGENT_FAILURE. */
3186 sentreply = "\0\0\0\1\5";
3189 send_packet(SSH1_MSG_CHANNEL_DATA,
3190 PKT_INT, c->remoteid,
3192 PKT_DATA, sentreply, replylen,
3196 sfree(c->u.a.message);
3197 c->u.a.lensofar = 0;
3200 bufsize = 0; /* agent channels never back up */
3203 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
3204 c->v.v1.throttling = 1;
3208 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
3209 /* may be from EXEC_SHELL on some servers */
3210 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3211 /* may be from EXEC_SHELL on some servers
3212 * if no pty is available or in other odd cases. Ignore */
3213 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
3215 ssh_exitcode = GET_32BIT(pktin.body);
3216 sprintf(buf, "Server sent command exit status %d",
3219 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
3221 * In case `helpful' firewalls or proxies tack
3222 * extra human-readable text on the end of the
3223 * session which we might mistake for another
3224 * encrypted packet, we close the session once
3225 * we've sent EXIT_CONFIRMATION.
3227 ssh_state = SSH_STATE_CLOSED;
3230 bombout(("Strange packet received: type %d", pktin.type));
3235 int len = min(inlen, 512);
3236 send_packet(SSH1_CMSG_STDIN_DATA,
3237 PKT_INT, len, PKT_DATA, in, len, PKT_END);
3248 * Utility routine for decoding comma-separated strings in KEXINIT.
3250 static int in_commasep_string(char *needle, char *haystack, int haylen)
3252 int needlen = strlen(needle);
3255 * Is it at the start of the string?
3257 if (haylen >= needlen && /* haystack is long enough */
3258 !memcmp(needle, haystack, needlen) && /* initial match */
3259 (haylen == needlen || haystack[needlen] == ',')
3260 /* either , or EOS follows */
3264 * If not, search for the next comma and resume after that.
3265 * If no comma found, terminate.
3267 while (haylen > 0 && *haystack != ',')
3268 haylen--, haystack++;
3271 haylen--, haystack++; /* skip over comma itself */
3276 * SSH2 key creation method.
3278 static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr,
3282 /* First 20 bytes. */
3285 SHA_Bytes(&s, H, 20);
3286 SHA_Bytes(&s, &chr, 1);
3287 SHA_Bytes(&s, sessid, 20);
3288 SHA_Final(&s, keyspace);
3289 /* Next 20 bytes. */
3292 SHA_Bytes(&s, H, 20);
3293 SHA_Bytes(&s, keyspace, 20);
3294 SHA_Final(&s, keyspace + 20);
3298 * Handle the SSH2 transport layer.
3300 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
3302 static int i, j, len, nbits, pbits, warn;
3304 static Bignum p, g, e, f, K;
3305 static int kex_init_value, kex_reply_value;
3306 static const struct ssh_mac **maclist;
3308 static const struct ssh2_cipher *cscipher_tobe = NULL;
3309 static const struct ssh2_cipher *sccipher_tobe = NULL;
3310 static const struct ssh_mac *csmac_tobe = NULL;
3311 static const struct ssh_mac *scmac_tobe = NULL;
3312 static const struct ssh_compress *cscomp_tobe = NULL;
3313 static const struct ssh_compress *sccomp_tobe = NULL;
3314 static char *hostkeydata, *sigdata, *keystr, *fingerprint;
3315 static int hostkeylen, siglen;
3316 static void *hkey; /* actual host key */
3317 static unsigned char exchange_hash[20];
3318 static unsigned char keyspace[40];
3319 static int n_preferred_ciphers;
3320 static const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
3321 static const struct ssh_compress *preferred_comp;
3322 static int cipherstr_started;
3323 static int first_kex;
3330 * Set up the preferred ciphers. (NULL => warn below here)
3332 n_preferred_ciphers = 0;
3333 for (i = 0; i < CIPHER_MAX; i++) {
3334 switch (cfg.ssh_cipherlist[i]) {
3335 case CIPHER_BLOWFISH:
3336 preferred_ciphers[n_preferred_ciphers] = &ssh2_blowfish;
3337 n_preferred_ciphers++;
3340 if (cfg.ssh2_des_cbc) {
3341 preferred_ciphers[n_preferred_ciphers] = &ssh2_des;
3342 n_preferred_ciphers++;
3346 preferred_ciphers[n_preferred_ciphers] = &ssh2_3des;
3347 n_preferred_ciphers++;
3350 preferred_ciphers[n_preferred_ciphers] = &ssh2_aes;
3351 n_preferred_ciphers++;
3354 /* Flag for later. Don't bother if it's the last in
3356 if (i < CIPHER_MAX - 1) {
3357 preferred_ciphers[n_preferred_ciphers] = NULL;
3358 n_preferred_ciphers++;
3365 * Set up preferred compression.
3367 if (cfg.compression)
3368 preferred_comp = &ssh_zlib;
3370 preferred_comp = &ssh_comp_none;
3373 * Be prepared to work around the buggy MAC problem.
3375 if (cfg.buggymac || (ssh_remote_bugs & BUG_SSH2_HMAC))
3376 maclist = buggymacs, nmacs = lenof(buggymacs);
3378 maclist = macs, nmacs = lenof(macs);
3382 * Construct and send our key exchange packet.
3384 ssh2_pkt_init(SSH2_MSG_KEXINIT);
3385 for (i = 0; i < 16; i++)
3386 ssh2_pkt_addbyte((unsigned char) random_byte());
3387 /* List key exchange algorithms. */
3388 ssh2_pkt_addstring_start();
3389 for (i = 0; i < lenof(kex_algs); i++) {
3390 ssh2_pkt_addstring_str(kex_algs[i]->name);
3391 if (i < lenof(kex_algs) - 1)
3392 ssh2_pkt_addstring_str(",");
3394 /* List server host key algorithms. */
3395 ssh2_pkt_addstring_start();
3396 for (i = 0; i < lenof(hostkey_algs); i++) {
3397 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
3398 if (i < lenof(hostkey_algs) - 1)
3399 ssh2_pkt_addstring_str(",");
3401 /* List client->server encryption algorithms. */
3402 ssh2_pkt_addstring_start();
3403 cipherstr_started = 0;
3404 for (i = 0; i < n_preferred_ciphers; i++) {
3405 const struct ssh2_ciphers *c = preferred_ciphers[i];
3406 if (!c) continue; /* warning flag */
3407 for (j = 0; j < c->nciphers; j++) {
3408 if (cipherstr_started)
3409 ssh2_pkt_addstring_str(",");
3410 ssh2_pkt_addstring_str(c->list[j]->name);
3411 cipherstr_started = 1;
3414 /* List server->client encryption algorithms. */
3415 ssh2_pkt_addstring_start();
3416 cipherstr_started = 0;
3417 for (i = 0; i < n_preferred_ciphers; i++) {
3418 const struct ssh2_ciphers *c = preferred_ciphers[i];
3419 if (!c) continue; /* warning flag */
3420 for (j = 0; j < c->nciphers; j++) {
3421 if (cipherstr_started)
3422 ssh2_pkt_addstring_str(",");
3423 ssh2_pkt_addstring_str(c->list[j]->name);
3424 cipherstr_started = 1;
3427 /* List client->server MAC algorithms. */
3428 ssh2_pkt_addstring_start();
3429 for (i = 0; i < nmacs; i++) {
3430 ssh2_pkt_addstring_str(maclist[i]->name);
3432 ssh2_pkt_addstring_str(",");
3434 /* List server->client MAC algorithms. */
3435 ssh2_pkt_addstring_start();
3436 for (i = 0; i < nmacs; i++) {
3437 ssh2_pkt_addstring_str(maclist[i]->name);
3439 ssh2_pkt_addstring_str(",");
3441 /* List client->server compression algorithms. */
3442 ssh2_pkt_addstring_start();
3443 for (i = 0; i < lenof(compressions) + 1; i++) {
3444 const struct ssh_compress *c =
3445 i == 0 ? preferred_comp : compressions[i - 1];
3446 ssh2_pkt_addstring_str(c->name);
3447 if (i < lenof(compressions))
3448 ssh2_pkt_addstring_str(",");
3450 /* List server->client compression algorithms. */
3451 ssh2_pkt_addstring_start();
3452 for (i = 0; i < lenof(compressions) + 1; i++) {
3453 const struct ssh_compress *c =
3454 i == 0 ? preferred_comp : compressions[i - 1];
3455 ssh2_pkt_addstring_str(c->name);
3456 if (i < lenof(compressions))
3457 ssh2_pkt_addstring_str(",");
3459 /* List client->server languages. Empty list. */
3460 ssh2_pkt_addstring_start();
3461 /* List server->client languages. Empty list. */
3462 ssh2_pkt_addstring_start();
3463 /* First KEX packet does _not_ follow, because we're not that brave. */
3464 ssh2_pkt_addbool(FALSE);
3466 ssh2_pkt_adduint32(0);
3468 exhash = exhashbase;
3469 sha_string(&exhash, pktout.data + 5, pktout.length - 5);
3475 sha_string(&exhash, pktin.data + 5, pktin.length - 5);
3478 * Now examine the other side's KEXINIT to see what we're up
3481 if (pktin.type != SSH2_MSG_KEXINIT) {
3482 bombout(("expected key exchange packet from server"));
3487 cscipher_tobe = NULL;
3488 sccipher_tobe = NULL;
3493 pktin.savedpos += 16; /* skip garbage cookie */
3494 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
3495 for (i = 0; i < lenof(kex_algs); i++) {
3496 if (in_commasep_string(kex_algs[i]->name, str, len)) {
3501 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
3502 for (i = 0; i < lenof(hostkey_algs); i++) {
3503 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
3504 hostkey = hostkey_algs[i];
3508 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
3510 for (i = 0; i < n_preferred_ciphers; i++) {
3511 const struct ssh2_ciphers *c = preferred_ciphers[i];
3515 for (j = 0; j < c->nciphers; j++) {
3516 if (in_commasep_string(c->list[j]->name, str, len)) {
3517 cscipher_tobe = c->list[j];
3522 if (cscipher_tobe) {
3524 askcipher(cscipher_tobe->name, 1);
3528 if (!cscipher_tobe) {
3529 bombout(("Couldn't agree a client-to-server cipher (available: %s)", str));
3533 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
3535 for (i = 0; i < n_preferred_ciphers; i++) {
3536 const struct ssh2_ciphers *c = preferred_ciphers[i];
3540 for (j = 0; j < c->nciphers; j++) {
3541 if (in_commasep_string(c->list[j]->name, str, len)) {
3542 sccipher_tobe = c->list[j];
3547 if (sccipher_tobe) {
3549 askcipher(sccipher_tobe->name, 2);
3553 if (!sccipher_tobe) {
3554 bombout(("Couldn't agree a server-to-client cipher (available: %s)", str));
3558 ssh2_pkt_getstring(&str, &len); /* client->server mac */
3559 for (i = 0; i < nmacs; i++) {
3560 if (in_commasep_string(maclist[i]->name, str, len)) {
3561 csmac_tobe = maclist[i];
3565 ssh2_pkt_getstring(&str, &len); /* server->client mac */
3566 for (i = 0; i < nmacs; i++) {
3567 if (in_commasep_string(maclist[i]->name, str, len)) {
3568 scmac_tobe = maclist[i];
3572 ssh2_pkt_getstring(&str, &len); /* client->server compression */
3573 for (i = 0; i < lenof(compressions) + 1; i++) {
3574 const struct ssh_compress *c =
3575 i == 0 ? preferred_comp : compressions[i - 1];
3576 if (in_commasep_string(c->name, str, len)) {
3581 ssh2_pkt_getstring(&str, &len); /* server->client compression */
3582 for (i = 0; i < lenof(compressions) + 1; i++) {
3583 const struct ssh_compress *c =
3584 i == 0 ? preferred_comp : compressions[i - 1];
3585 if (in_commasep_string(c->name, str, len)) {
3592 * Work out the number of bits of key we will need from the key
3593 * exchange. We start with the maximum key length of either
3599 csbits = cscipher_tobe->keylen;
3600 scbits = sccipher_tobe->keylen;
3601 nbits = (csbits > scbits ? csbits : scbits);
3603 /* The keys only have 160-bit entropy, since they're based on
3604 * a SHA-1 hash. So cap the key size at 160 bits. */
3609 * If we're doing Diffie-Hellman group exchange, start by
3610 * requesting a group.
3612 if (kex == &ssh_diffiehellman_gex) {
3613 logevent("Doing Diffie-Hellman group exchange");
3614 ssh_pkt_ctx |= SSH2_PKTCTX_DHGEX;
3616 * Work out how big a DH group we will need to allow that
3619 pbits = 512 << ((nbits - 1) / 64);
3620 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
3621 ssh2_pkt_adduint32(pbits);
3625 if (pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
3626 bombout(("expected key exchange group packet from server"));
3629 p = ssh2_pkt_getmp();
3630 g = ssh2_pkt_getmp();
3631 dh_setup_group(p, g);
3632 kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
3633 kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
3635 ssh_pkt_ctx |= SSH2_PKTCTX_DHGROUP1;
3637 kex_init_value = SSH2_MSG_KEXDH_INIT;
3638 kex_reply_value = SSH2_MSG_KEXDH_REPLY;
3641 logevent("Doing Diffie-Hellman key exchange");
3643 * Now generate and send e for Diffie-Hellman.
3645 e = dh_create_e(nbits * 2);
3646 ssh2_pkt_init(kex_init_value);
3651 if (pktin.type != kex_reply_value) {
3652 bombout(("expected key exchange reply packet from server"));
3655 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
3656 f = ssh2_pkt_getmp();
3657 ssh2_pkt_getstring(&sigdata, &siglen);
3661 sha_string(&exhash, hostkeydata, hostkeylen);
3662 if (kex == &ssh_diffiehellman_gex) {
3663 sha_uint32(&exhash, pbits);
3664 sha_mpint(&exhash, p);
3665 sha_mpint(&exhash, g);
3667 sha_mpint(&exhash, e);
3668 sha_mpint(&exhash, f);
3669 sha_mpint(&exhash, K);
3670 SHA_Final(&exhash, exchange_hash);
3675 debug(("Exchange hash is:\n"));
3676 dmemdump(exchange_hash, 20);
3679 hkey = hostkey->newkey(hostkeydata, hostkeylen);
3681 !hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
3682 bombout(("Server's host key did not match the signature supplied"));
3687 * Authenticate remote host: verify host key. (We've already
3688 * checked the signature of the exchange hash.)
3690 keystr = hostkey->fmtkey(hkey);
3691 fingerprint = hostkey->fingerprint(hkey);
3692 verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
3693 keystr, fingerprint);
3694 if (first_kex) { /* don't bother logging this in rekeys */
3695 logevent("Host key fingerprint is:");
3696 logevent(fingerprint);
3700 hostkey->freekey(hkey);
3703 * Send SSH2_MSG_NEWKEYS.
3705 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
3709 * Expect SSH2_MSG_NEWKEYS from server.
3712 if (pktin.type != SSH2_MSG_NEWKEYS) {
3713 bombout(("expected new-keys packet from server"));
3718 * Create and initialise session keys.
3720 cscipher = cscipher_tobe;
3721 sccipher = sccipher_tobe;
3724 cscomp = cscomp_tobe;
3725 sccomp = sccomp_tobe;
3726 cscomp->compress_init();
3727 sccomp->decompress_init();
3729 * Set IVs after keys. Here we use the exchange hash from the
3730 * _first_ key exchange.
3733 memcpy(ssh2_session_id, exchange_hash, sizeof(exchange_hash));
3734 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'C', keyspace);
3735 cscipher->setcskey(keyspace);
3736 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'D', keyspace);
3737 sccipher->setsckey(keyspace);
3738 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'A', keyspace);
3739 cscipher->setcsiv(keyspace);
3740 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'B', keyspace);
3741 sccipher->setsciv(keyspace);
3742 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'E', keyspace);
3743 csmac->setcskey(keyspace);
3744 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'F', keyspace);
3745 scmac->setsckey(keyspace);
3748 * If this is the first key exchange phase, we must pass the
3749 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
3750 * wants to see it but because it will need time to initialise
3751 * itself before it sees an actual packet. In subsequent key
3752 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
3753 * it would only confuse the layer above.
3761 * Now we're encrypting. Begin returning 1 to the protocol main
3762 * function so that other things can run on top of the
3763 * transport. If we ever see a KEXINIT, we must go back to the
3766 while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
3769 logevent("Server initiated key re-exchange");
3770 goto begin_key_exchange;
3776 * Add data to an SSH2 channel output buffer.
3778 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
3781 bufchain_add(&c->v.v2.outbuffer, buf, len);
3785 * Attempt to send data on an SSH2 channel.
3787 static int ssh2_try_send(struct ssh_channel *c)
3789 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
3792 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
3793 if ((unsigned)len > c->v.v2.remwindow)
3794 len = c->v.v2.remwindow;
3795 if ((unsigned)len > c->v.v2.remmaxpkt)
3796 len = c->v.v2.remmaxpkt;
3797 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
3798 ssh2_pkt_adduint32(c->remoteid);
3799 ssh2_pkt_addstring_start();
3800 ssh2_pkt_addstring_data(data, len);
3802 bufchain_consume(&c->v.v2.outbuffer, len);
3803 c->v.v2.remwindow -= len;
3807 * After having sent as much data as we can, return the amount
3810 return bufchain_size(&c->v.v2.outbuffer);
3814 * Potentially enlarge the window on an SSH2 channel.
3816 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
3819 * Never send WINDOW_ADJUST for a channel that the remote side
3820 * already thinks it's closed; there's no point, since it won't
3821 * be sending any more data anyway.
3826 if (newwin > c->v.v2.locwindow) {
3827 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3828 ssh2_pkt_adduint32(c->remoteid);
3829 ssh2_pkt_adduint32(newwin - c->v.v2.locwindow);
3831 c->v.v2.locwindow = newwin;
3836 * Handle the SSH2 userauth and connection layers.
3838 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
3841 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
3843 AUTH_KEYBOARD_INTERACTIVE
3847 AUTH_TYPE_PUBLICKEY,
3848 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
3849 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
3851 AUTH_TYPE_KEYBOARD_INTERACTIVE,
3852 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
3854 static int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
3855 static int tried_pubkey_config, tried_agent, tried_keyb_inter;
3856 static int kbd_inter_running;
3857 static int we_are_in;
3858 static int num_prompts, echo;
3859 static char username[100];
3860 static char pwprompt[200];
3861 static char password[100];
3862 static void *publickey_blob;
3863 static int publickey_bloblen;
3868 * Request userauth protocol, and await a response to it.
3870 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
3871 ssh2_pkt_addstring("ssh-userauth");
3873 crWaitUntilV(ispkt);
3874 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
3875 bombout(("Server refused user authentication protocol"));
3880 * We repeat this whole loop, including the username prompt,
3881 * until we manage a successful authentication. If the user
3882 * types the wrong _password_, they are sent back to the
3883 * beginning to try another username. (If they specify a
3884 * username in the config, they are never asked, even if they
3885 * do give a wrong password.)
3887 * I think this best serves the needs of
3889 * - the people who have no configuration, no keys, and just
3890 * want to try repeated (username,password) pairs until they
3891 * type both correctly
3893 * - people who have keys and configuration but occasionally
3894 * need to fall back to passwords
3896 * - people with a key held in Pageant, who might not have
3897 * logged in to a particular machine before; so they want to
3898 * type a username, and then _either_ their key will be
3899 * accepted, _or_ they will type a password. If they mistype
3900 * the username they will want to be able to get back and
3912 if (*username && !cfg.change_username) {
3914 * We got a username last time round this loop, and
3915 * with change_username turned off we don't try to get
3918 } else if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
3920 if (!ssh_get_line("login as: ",
3921 username, sizeof(username), FALSE)) {
3923 * get_line failed to get a username.
3926 logevent("No username provided. Abandoning session.");
3927 ssh_state = SSH_STATE_CLOSED;
3931 c_write_str("login as: ");
3934 crWaitUntilV(!ispkt);
3936 switch (c = *in++) {
3945 c_write_str("\b \b");
3952 c_write_str("\b \b");
3962 if (((c >= ' ' && c <= '~') ||
3963 ((unsigned char) c >= 160))
3964 && pos < sizeof(username)-1) {
3965 username[pos++] = c;
3972 c_write_str("\r\n");
3973 username[strcspn(username, "\n\r")] = '\0';
3976 strncpy(username, cfg.username, 99);
3977 username[99] = '\0';
3978 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3979 sprintf(stuff, "Using username \"%s\".\r\n", username);
3985 * Send an authentication request using method "none": (a)
3986 * just in case it succeeds, and (b) so that we know what
3987 * authentication methods we can usefully try next.
3989 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
3991 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3992 ssh2_pkt_addstring(username);
3993 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3994 ssh2_pkt_addstring("none"); /* method */
3996 type = AUTH_TYPE_NONE;
4000 tried_pubkey_config = FALSE;
4001 tried_agent = FALSE;
4002 tried_keyb_inter = FALSE;
4003 kbd_inter_running = FALSE;
4004 /* Load the pub half of cfg.keyfile so we notice if it's in Pageant */
4006 publickey_blob = ssh2_userkey_loadpub(cfg.keyfile, NULL,
4007 &publickey_bloblen);
4009 publickey_blob = NULL;
4013 * Wait for the result of the last authentication request.
4016 crWaitUntilV(ispkt);
4017 while (pktin.type == SSH2_MSG_USERAUTH_BANNER) {
4021 * Don't show the banner if we're operating in
4022 * non-verbose non-interactive mode. (It's probably
4023 * a script, which means nobody will read the
4024 * banner _anyway_, and moreover the printing of
4025 * the banner will screw up processing on the
4026 * output of (say) plink.)
4028 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
4029 ssh2_pkt_getstring(&banner, &size);
4031 c_write_untrusted(banner, size);
4033 crWaitUntilV(ispkt);
4035 if (pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
4036 logevent("Access granted");
4041 if (kbd_inter_running &&
4042 pktin.type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
4044 * This is a further prompt in keyboard-interactive
4045 * authentication. Do nothing.
4047 } else if (pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
4048 bombout(("Strange packet received during authentication: type %d",
4056 * OK, we're now sitting on a USERAUTH_FAILURE message, so
4057 * we can look at the string in it and know what we can
4058 * helpfully try next.
4060 if (pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
4063 ssh2_pkt_getstring(&methods, &methlen);
4064 kbd_inter_running = FALSE;
4065 if (!ssh2_pkt_getbool()) {
4067 * We have received an unequivocal Access
4068 * Denied. This can translate to a variety of
4071 * - if we'd just tried "none" authentication,
4072 * it's not worth printing anything at all
4074 * - if we'd just tried a public key _offer_,
4075 * the message should be "Server refused our
4076 * key" (or no message at all if the key
4077 * came from Pageant)
4079 * - if we'd just tried anything else, the
4080 * message really should be "Access denied".
4082 * Additionally, if we'd just tried password
4083 * authentication, we should break out of this
4084 * whole loop so as to go back to the username
4087 if (type == AUTH_TYPE_NONE) {
4089 } else if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
4090 type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
4091 if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
4092 c_write_str("Server refused our key\r\n");
4093 logevent("Server refused public key");
4094 } else if (type == AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
4095 /* server declined keyboard-interactive; ignore */
4097 c_write_str("Access denied\r\n");
4098 logevent("Access denied");
4099 if (type == AUTH_TYPE_PASSWORD) {
4105 c_write_str("Further authentication required\r\n");
4106 logevent("Further authentication required");
4110 in_commasep_string("publickey", methods, methlen);
4112 in_commasep_string("password", methods, methlen);
4113 can_keyb_inter = cfg.try_ki_auth &&
4114 in_commasep_string("keyboard-interactive", methods, methlen);
4118 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4120 if (!method && can_pubkey && agent_exists() && !tried_agent) {
4122 * Attempt public-key authentication using Pageant.
4124 static unsigned char request[5], *response, *p;
4125 static int responselen;
4126 static int i, nkeys;
4127 static int authed = FALSE;
4130 ssh_pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4134 logevent("Pageant is running. Requesting keys.");
4136 /* Request the keys held by the agent. */
4137 PUT_32BIT(request, 1);
4138 request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
4139 agent_query(request, 5, &r, &responselen);
4140 response = (unsigned char *) r;
4141 if (response && responselen >= 5 &&
4142 response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
4144 nkeys = GET_32BIT(p);
4148 sprintf(buf, "Pageant has %d SSH2 keys", nkeys);
4151 for (i = 0; i < nkeys; i++) {
4152 static char *pkblob, *alg, *commentp;
4153 static int pklen, alglen, commentlen;
4154 static int siglen, retlen, len;
4155 static char *q, *agentreq, *ret;
4160 sprintf(buf, "Trying Pageant key #%d", i);
4163 pklen = GET_32BIT(p);
4165 if (publickey_blob &&
4166 pklen == publickey_bloblen &&
4167 !memcmp(p, publickey_blob, publickey_bloblen)) {
4168 logevent("This key matches configured key file");
4169 tried_pubkey_config = 1;
4173 alglen = GET_32BIT(pkblob);
4175 commentlen = GET_32BIT(p);
4179 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4180 ssh2_pkt_addstring(username);
4181 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4182 ssh2_pkt_addstring("publickey"); /* method */
4183 ssh2_pkt_addbool(FALSE); /* no signature included */
4184 ssh2_pkt_addstring_start();
4185 ssh2_pkt_addstring_data(alg, alglen);
4186 ssh2_pkt_addstring_start();
4187 ssh2_pkt_addstring_data(pkblob, pklen);
4190 crWaitUntilV(ispkt);
4191 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4192 logevent("Key refused");
4196 if (flags & FLAG_VERBOSE) {
4198 ("Authenticating with public key \"");
4199 c_write(commentp, commentlen);
4200 c_write_str("\" from agent\r\n");
4204 * Server is willing to accept the key.
4205 * Construct a SIGN_REQUEST.
4207 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4208 ssh2_pkt_addstring(username);
4209 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4210 ssh2_pkt_addstring("publickey"); /* method */
4211 ssh2_pkt_addbool(TRUE);
4212 ssh2_pkt_addstring_start();
4213 ssh2_pkt_addstring_data(alg, alglen);
4214 ssh2_pkt_addstring_start();
4215 ssh2_pkt_addstring_data(pkblob, pklen);
4217 siglen = pktout.length - 5 + 4 + 20;
4218 len = 1; /* message type */
4219 len += 4 + pklen; /* key blob */
4220 len += 4 + siglen; /* data to sign */
4221 len += 4; /* flags */
4222 agentreq = smalloc(4 + len);
4223 PUT_32BIT(agentreq, len);
4225 *q++ = SSH2_AGENTC_SIGN_REQUEST;
4226 PUT_32BIT(q, pklen);
4228 memcpy(q, pkblob, pklen);
4230 PUT_32BIT(q, siglen);
4232 /* Now the data to be signed... */
4235 memcpy(q, ssh2_session_id, 20);
4237 memcpy(q, pktout.data + 5, pktout.length - 5);
4238 q += pktout.length - 5;
4239 /* And finally the (zero) flags word. */
4241 agent_query(agentreq, len + 4, &vret, &retlen);
4245 if (ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
4246 logevent("Sending Pageant's response");
4247 ssh2_pkt_addstring_start();
4248 ssh2_pkt_addstring_data(ret + 9,
4256 ("Pageant failed to answer challenge");
4266 if (!method && can_pubkey && *cfg.keyfile
4267 && !tried_pubkey_config) {
4268 unsigned char *pub_blob;
4269 char *algorithm, *comment;
4272 tried_pubkey_config = TRUE;
4274 ssh_pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4277 * Try the public key supplied in the configuration.
4279 * First, offer the public blob to see if the server is
4280 * willing to accept it.
4282 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
4285 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4286 ssh2_pkt_addstring(username);
4287 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4288 ssh2_pkt_addstring("publickey"); /* method */
4289 ssh2_pkt_addbool(FALSE); /* no signature included */
4290 ssh2_pkt_addstring(algorithm);
4291 ssh2_pkt_addstring_start();
4292 ssh2_pkt_addstring_data(pub_blob, pub_blob_len);
4294 logevent("Offered public key"); /* FIXME */
4296 crWaitUntilV(ispkt);
4297 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4299 type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
4300 continue; /* key refused; give up on it */
4303 logevent("Offer of public key accepted");
4305 * Actually attempt a serious authentication using
4308 if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
4310 "Passphrase for key \"%.100s\": ",
4316 c_write_str("Authenticating with public key \"");
4317 c_write_str(comment);
4318 c_write_str("\"\r\n");
4319 method = AUTH_PUBLICKEY_FILE;
4323 if (!method && can_keyb_inter && !tried_keyb_inter) {
4324 method = AUTH_KEYBOARD_INTERACTIVE;
4325 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4326 tried_keyb_inter = TRUE;
4328 ssh_pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4330 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4331 ssh2_pkt_addstring(username);
4332 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4333 ssh2_pkt_addstring("keyboard-interactive"); /* method */
4334 ssh2_pkt_addstring(""); /* lang */
4335 ssh2_pkt_addstring("");
4338 crWaitUntilV(ispkt);
4339 if (pktin.type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
4340 if (pktin.type == SSH2_MSG_USERAUTH_FAILURE)
4342 logevent("Keyboard-interactive authentication refused");
4343 type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
4347 kbd_inter_running = TRUE;
4350 if (kbd_inter_running) {
4351 method = AUTH_KEYBOARD_INTERACTIVE;
4352 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4353 tried_keyb_inter = TRUE;
4355 ssh_pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4357 /* We've got packet with that "interactive" info
4358 dump banners, and set its prompt as ours */
4360 char *name, *inst, *lang, *prompt;
4361 int name_len, inst_len, lang_len, prompt_len;
4362 ssh2_pkt_getstring(&name, &name_len);
4363 ssh2_pkt_getstring(&inst, &inst_len);
4364 ssh2_pkt_getstring(&lang, &lang_len);
4366 c_write_untrusted(name, name_len);
4368 c_write_untrusted(inst, inst_len);
4369 num_prompts = ssh2_pkt_getuint32();
4371 ssh2_pkt_getstring(&prompt, &prompt_len);
4372 strncpy(pwprompt, prompt, sizeof(pwprompt));
4373 pwprompt[prompt_len < sizeof(pwprompt) ?
4374 prompt_len : sizeof(pwprompt)-1] = '\0';
4377 echo = ssh2_pkt_getbool();
4381 if (!method && can_passwd) {
4382 method = AUTH_PASSWORD;
4383 ssh_pkt_ctx |= SSH2_PKTCTX_PASSWORD;
4384 sprintf(pwprompt, "%.90s@%.90s's password: ", username,
4391 if (!ssh_get_line(pwprompt, password,
4392 sizeof(password), TRUE)) {
4394 * get_line failed to get a password (for
4395 * example because one was supplied on the
4396 * command line which has already failed to
4399 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4400 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4402 ("No more passwords available to try");
4403 ssh2_pkt_addstring("en"); /* language tag */
4405 connection_fatal("Unable to authenticate");
4406 ssh_state = SSH_STATE_CLOSED;
4413 c_write_untrusted(pwprompt, strlen(pwprompt));
4418 crWaitUntilV(!ispkt);
4420 switch (c = *in++) {
4441 if (pos < sizeof(password)-1)
4442 password[pos++] = c;
4446 c_write_str("\r\n");
4450 if (method == AUTH_PUBLICKEY_FILE) {
4452 * We have our passphrase. Now try the actual authentication.
4454 struct ssh2_userkey *key;
4456 key = ssh2_load_userkey(cfg.keyfile, password);
4457 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
4458 if (key == SSH2_WRONG_PASSPHRASE) {
4459 c_write_str("Wrong passphrase\r\n");
4460 tried_pubkey_config = FALSE;
4462 c_write_str("Unable to load private key\r\n");
4463 tried_pubkey_config = TRUE;
4465 /* Send a spurious AUTH_NONE to return to the top. */
4466 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4467 ssh2_pkt_addstring(username);
4468 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4469 ssh2_pkt_addstring("none"); /* method */
4471 type = AUTH_TYPE_NONE;
4473 unsigned char *blob, *sigdata;
4474 int blob_len, sigdata_len;
4477 * We have loaded the private key and the server
4478 * has announced that it's willing to accept it.
4479 * Hallelujah. Generate a signature and send it.
4481 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4482 ssh2_pkt_addstring(username);
4483 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4484 ssh2_pkt_addstring("publickey"); /* method */
4485 ssh2_pkt_addbool(TRUE);
4486 ssh2_pkt_addstring(key->alg->name);
4487 blob = key->alg->public_blob(key->data, &blob_len);
4488 ssh2_pkt_addstring_start();
4489 ssh2_pkt_addstring_data(blob, blob_len);
4493 * The data to be signed is:
4497 * followed by everything so far placed in the
4500 sigdata_len = pktout.length - 5 + 4 + 20;
4501 sigdata = smalloc(sigdata_len);
4502 PUT_32BIT(sigdata, 20);
4503 memcpy(sigdata + 4, ssh2_session_id, 20);
4504 memcpy(sigdata + 24, pktout.data + 5,
4507 key->alg->sign(key->data, sigdata, sigdata_len,
4509 ssh2_pkt_addstring_start();
4510 ssh2_pkt_addstring_data(blob, blob_len);
4515 type = AUTH_TYPE_PUBLICKEY;
4517 } else if (method == AUTH_PASSWORD) {
4519 * We send the password packet lumped tightly together with
4520 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4521 * string long enough to make the total length of the two
4522 * packets constant. This should ensure that a passive
4523 * listener doing traffic analyis can't work out the length
4526 * For this to work, we need an assumption about the
4527 * maximum length of the password packet. I think 256 is
4528 * pretty conservative. Anyone using a password longer than
4529 * that probably doesn't have much to worry about from
4530 * people who find out how long their password is!
4532 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4533 ssh2_pkt_addstring(username);
4534 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4535 ssh2_pkt_addstring("password");
4536 ssh2_pkt_addbool(FALSE);
4537 ssh2_pkt_addstring(password);
4540 * We'll include a string that's an exact multiple of the
4541 * cipher block size. If the cipher is NULL for some
4542 * reason, we don't do this trick at all because we gain
4548 stringlen = (256 - deferred_len);
4549 stringlen += cscipher->blksize - 1;
4550 stringlen -= (stringlen % cscipher->blksize);
4553 * Temporarily disable actual compression,
4554 * so we can guarantee to get this string
4555 * exactly the length we want it. The
4556 * compression-disabling routine should
4557 * return an integer indicating how many
4558 * bytes we should adjust our string length
4561 stringlen -= cscomp->disable_compression();
4563 ssh2_pkt_init(SSH2_MSG_IGNORE);
4564 ssh2_pkt_addstring_start();
4565 for (i = 0; i < stringlen; i++) {
4566 char c = (char) random_byte();
4567 ssh2_pkt_addstring_data(&c, 1);
4571 ssh_pkt_defersend();
4572 logevent("Sent password");
4573 type = AUTH_TYPE_PASSWORD;
4574 } else if (method == AUTH_KEYBOARD_INTERACTIVE) {
4575 ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
4576 ssh2_pkt_adduint32(num_prompts);
4577 ssh2_pkt_addstring(password);
4578 memset(password, 0, sizeof(password));
4580 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4583 ("No supported authentication methods left to try!\r\n");
4585 ("No supported authentications offered. Disconnecting");
4586 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4587 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4589 ("No supported authentication methods available");
4590 ssh2_pkt_addstring("en"); /* language tag */
4592 ssh_state = SSH_STATE_CLOSED;
4596 } while (!we_are_in);
4599 * Now we're authenticated for the connection protocol. The
4600 * connection protocol will automatically have started at this
4601 * point; there's no need to send SERVICE_REQUEST.
4605 * So now create a channel with a session in it.
4607 ssh_channels = newtree234(ssh_channelcmp);
4608 mainchan = smalloc(sizeof(struct ssh_channel));
4609 mainchan->localid = alloc_channel_id();
4610 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
4611 ssh2_pkt_addstring("session");
4612 ssh2_pkt_adduint32(mainchan->localid);
4613 mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
4614 ssh2_pkt_adduint32(mainchan->v.v2.locwindow); /* our window size */
4615 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
4617 crWaitUntilV(ispkt);
4618 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
4619 bombout(("Server refused to open a session"));
4621 /* FIXME: error data comes back in FAILURE packet */
4623 if (ssh2_pkt_getuint32() != mainchan->localid) {
4624 bombout(("Server's channel confirmation cited wrong channel"));
4627 mainchan->remoteid = ssh2_pkt_getuint32();
4628 mainchan->type = CHAN_MAINSESSION;
4629 mainchan->closes = 0;
4630 mainchan->v.v2.remwindow = ssh2_pkt_getuint32();
4631 mainchan->v.v2.remmaxpkt = ssh2_pkt_getuint32();
4632 bufchain_init(&mainchan->v.v2.outbuffer);
4633 add234(ssh_channels, mainchan);
4634 logevent("Opened channel for session");
4637 * Potentially enable X11 forwarding.
4639 if (cfg.x11_forward) {
4640 char proto[20], data[64];
4641 logevent("Requesting X11 forwarding");
4642 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
4643 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4644 ssh2_pkt_adduint32(mainchan->remoteid);
4645 ssh2_pkt_addstring("x11-req");
4646 ssh2_pkt_addbool(1); /* want reply */
4647 ssh2_pkt_addbool(0); /* many connections */
4648 ssh2_pkt_addstring(proto);
4649 ssh2_pkt_addstring(data);
4650 ssh2_pkt_adduint32(0); /* screen number */
4654 crWaitUntilV(ispkt);
4655 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4656 unsigned i = ssh2_pkt_getuint32();
4657 struct ssh_channel *c;
4658 c = find234(ssh_channels, &i, ssh_channelfind);
4660 continue; /* nonexistent channel */
4661 c->v.v2.remwindow += ssh2_pkt_getuint32();
4663 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4665 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4666 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4667 bombout(("Unexpected response to X11 forwarding request:"
4668 " packet type %d", pktin.type));
4671 logevent("X11 forwarding refused");
4673 logevent("X11 forwarding enabled");
4674 ssh_X11_fwd_enabled = TRUE;
4679 * Enable port forwardings.
4682 static char *e; /* preserve across crReturn */
4686 char sports[256], dports[256], host[256];
4689 ssh_rportfwds = newtree234(ssh_rportcmp_ssh2);
4690 /* Add port forwardings. */
4695 while (*e && *e != '\t')
4701 while (*e && *e != ':')
4711 dport = atoi(dports);
4712 sport = atoi(sports);
4713 if (sport && dport) {
4715 pfd_addforward(host, dport, sport);
4716 sprintf(buf, "Local port %d forwarding to %s:%d",
4717 sport, host, dport);
4720 struct ssh_rportfwd *pf;
4721 pf = smalloc(sizeof(*pf));
4722 strcpy(pf->dhost, host);
4725 if (add234(ssh_rportfwds, pf) != pf) {
4727 "Duplicate remote port forwarding to %s:%d",
4732 sprintf(buf, "Requesting remote port %d (forwarded to %s:%d)",
4733 sport, host, dport);
4735 ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4736 ssh2_pkt_addstring("tcpip-forward");
4737 ssh2_pkt_addbool(1);/* want reply */
4738 if (cfg.rport_acceptall)
4739 ssh2_pkt_addstring("0.0.0.0");
4741 ssh2_pkt_addstring("127.0.0.1");
4742 ssh2_pkt_adduint32(sport);
4746 crWaitUntilV(ispkt);
4747 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4748 unsigned i = ssh2_pkt_getuint32();
4749 struct ssh_channel *c;
4750 c = find234(ssh_channels, &i, ssh_channelfind);
4752 continue;/* nonexistent channel */
4753 c->v.v2.remwindow += ssh2_pkt_getuint32();
4755 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4757 if (pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
4758 if (pktin.type != SSH2_MSG_REQUEST_FAILURE) {
4759 bombout(("Unexpected response to port "
4760 "forwarding request: packet type %d",
4764 logevent("Server refused this port forwarding");
4766 logevent("Remote port forwarding enabled");
4775 * Potentially enable agent forwarding.
4777 if (cfg.agentfwd && agent_exists()) {
4778 logevent("Requesting OpenSSH-style agent forwarding");
4779 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4780 ssh2_pkt_adduint32(mainchan->remoteid);
4781 ssh2_pkt_addstring("auth-agent-req@openssh.com");
4782 ssh2_pkt_addbool(1); /* want reply */
4786 crWaitUntilV(ispkt);
4787 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4788 unsigned i = ssh2_pkt_getuint32();
4789 struct ssh_channel *c;
4790 c = find234(ssh_channels, &i, ssh_channelfind);
4792 continue; /* nonexistent channel */
4793 c->v.v2.remwindow += ssh2_pkt_getuint32();
4795 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4797 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4798 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4799 bombout(("Unexpected response to agent forwarding request:"
4800 " packet type %d", pktin.type));
4803 logevent("Agent forwarding refused");
4805 logevent("Agent forwarding enabled");
4806 ssh_agentfwd_enabled = TRUE;
4811 * Now allocate a pty for the session.
4814 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4815 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
4816 ssh2_pkt_addstring("pty-req");
4817 ssh2_pkt_addbool(1); /* want reply */
4818 ssh2_pkt_addstring(cfg.termtype);
4819 ssh2_pkt_adduint32(cols);
4820 ssh2_pkt_adduint32(rows);
4821 ssh2_pkt_adduint32(0); /* pixel width */
4822 ssh2_pkt_adduint32(0); /* pixel height */
4823 ssh2_pkt_addstring_start();
4824 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
4826 ssh_state = SSH_STATE_INTERMED;
4829 crWaitUntilV(ispkt);
4830 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4831 unsigned i = ssh2_pkt_getuint32();
4832 struct ssh_channel *c;
4833 c = find234(ssh_channels, &i, ssh_channelfind);
4835 continue; /* nonexistent channel */
4836 c->v.v2.remwindow += ssh2_pkt_getuint32();
4838 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4840 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4841 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4842 bombout(("Unexpected response to pty request:"
4843 " packet type %d", pktin.type));
4846 c_write_str("Server refused to allocate pty\r\n");
4847 ssh_editing = ssh_echoing = 1;
4849 logevent("Allocated pty");
4852 ssh_editing = ssh_echoing = 1;
4856 * Start a shell or a remote command. We may have to attempt
4857 * this twice if the config data has provided a second choice
4864 if (ssh_fallback_cmd) {
4865 subsys = cfg.ssh_subsys2;
4866 cmd = cfg.remote_cmd_ptr2;
4868 subsys = cfg.ssh_subsys;
4869 cmd = cfg.remote_cmd_ptr;
4872 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4873 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
4875 ssh2_pkt_addstring("subsystem");
4876 ssh2_pkt_addbool(1); /* want reply */
4877 ssh2_pkt_addstring(cmd);
4879 ssh2_pkt_addstring("exec");
4880 ssh2_pkt_addbool(1); /* want reply */
4881 ssh2_pkt_addstring(cmd);
4883 ssh2_pkt_addstring("shell");
4884 ssh2_pkt_addbool(1); /* want reply */
4888 crWaitUntilV(ispkt);
4889 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4890 unsigned i = ssh2_pkt_getuint32();
4891 struct ssh_channel *c;
4892 c = find234(ssh_channels, &i, ssh_channelfind);
4894 continue; /* nonexistent channel */
4895 c->v.v2.remwindow += ssh2_pkt_getuint32();
4897 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4898 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4899 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4900 bombout(("Unexpected response to shell/command request:"
4901 " packet type %d", pktin.type));
4905 * We failed to start the command. If this is the
4906 * fallback command, we really are finished; if it's
4907 * not, and if the fallback command exists, try falling
4908 * back to it before complaining.
4910 if (!ssh_fallback_cmd && cfg.remote_cmd_ptr2 != NULL) {
4911 logevent("Primary command failed; attempting fallback");
4912 ssh_fallback_cmd = TRUE;
4915 bombout(("Server refused to start a shell/command"));
4918 logevent("Started a shell/command");
4923 ssh_state = SSH_STATE_SESSION;
4927 ssh_special(TS_EOF);
4932 ldisc_send(NULL, 0, 0); /* cause ldisc to notice changes */
4935 static int try_send;
4939 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
4940 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
4943 unsigned i = ssh2_pkt_getuint32();
4944 struct ssh_channel *c;
4945 c = find234(ssh_channels, &i, ssh_channelfind);
4947 continue; /* nonexistent channel */
4948 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
4949 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
4950 continue; /* extended but not stderr */
4951 ssh2_pkt_getstring(&data, &length);
4954 c->v.v2.locwindow -= length;
4956 case CHAN_MAINSESSION:
4958 from_backend(pktin.type ==
4959 SSH2_MSG_CHANNEL_EXTENDED_DATA,
4963 bufsize = x11_send(c->u.x11.s, data, length);
4966 bufsize = pfd_send(c->u.pfd.s, data, length);
4969 while (length > 0) {
4970 if (c->u.a.lensofar < 4) {
4971 int l = min(4 - c->u.a.lensofar, length);
4972 memcpy(c->u.a.msglen + c->u.a.lensofar,
4976 c->u.a.lensofar += l;
4978 if (c->u.a.lensofar == 4) {
4980 4 + GET_32BIT(c->u.a.msglen);
4981 c->u.a.message = smalloc(c->u.a.totallen);
4982 memcpy(c->u.a.message, c->u.a.msglen, 4);
4984 if (c->u.a.lensofar >= 4 && length > 0) {
4986 min(c->u.a.totallen - c->u.a.lensofar,
4988 memcpy(c->u.a.message + c->u.a.lensofar,
4992 c->u.a.lensofar += l;
4994 if (c->u.a.lensofar == c->u.a.totallen) {
4995 void *reply, *sentreply;
4997 agent_query(c->u.a.message,
4998 c->u.a.totallen, &reply,
5003 /* Fake SSH_AGENT_FAILURE. */
5004 sentreply = "\0\0\0\1\5";
5007 ssh2_add_channel_data(c, sentreply,
5012 sfree(c->u.a.message);
5013 c->u.a.lensofar = 0;
5020 * If we are not buffering too much data,
5021 * enlarge the window again at the remote side.
5023 if (bufsize < OUR_V2_WINSIZE)
5024 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
5026 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
5027 ssh_state = SSH_STATE_CLOSED;
5028 logevent("Received disconnect message");
5030 } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
5031 unsigned i = ssh2_pkt_getuint32();
5032 struct ssh_channel *c;
5034 c = find234(ssh_channels, &i, ssh_channelfind);
5036 continue; /* nonexistent channel */
5038 if (c->type == CHAN_X11) {
5040 * Remote EOF on an X11 channel means we should
5041 * wrap up and close the channel ourselves.
5043 x11_close(c->u.x11.s);
5045 } else if (c->type == CHAN_AGENT) {
5047 } else if (c->type == CHAN_SOCKDATA) {
5048 pfd_close(c->u.pfd.s);
5051 } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
5052 unsigned i = ssh2_pkt_getuint32();
5053 struct ssh_channel *c;
5055 c = find234(ssh_channels, &i, ssh_channelfind);
5057 continue; /* nonexistent channel */
5058 /* Do pre-close processing on the channel. */
5060 case CHAN_MAINSESSION:
5061 break; /* nothing to see here, move along */
5063 if (c->u.x11.s != NULL)
5064 x11_close(c->u.x11.s);
5071 if (c->u.pfd.s != NULL)
5072 pfd_close(c->u.pfd.s);
5076 if (c->closes == 0) {
5077 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5078 ssh2_pkt_adduint32(c->remoteid);
5081 del234(ssh_channels, c);
5082 bufchain_clear(&c->v.v2.outbuffer);
5086 * See if that was the last channel left open.
5088 if (count234(ssh_channels) == 0) {
5091 * We used to send SSH_MSG_DISCONNECT here,
5092 * because I'd believed that _every_ conforming
5093 * SSH2 connection had to end with a disconnect
5094 * being sent by at least one side; apparently
5095 * I was wrong and it's perfectly OK to
5096 * unceremoniously slam the connection shut
5097 * when you're done, and indeed OpenSSH feels
5098 * this is more polite than sending a
5099 * DISCONNECT. So now we don't.
5101 logevent("All channels closed. Disconnecting");
5102 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5103 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
5104 ssh2_pkt_addstring("All open channels closed");
5105 ssh2_pkt_addstring("en"); /* language tag */
5108 ssh_state = SSH_STATE_CLOSED;
5111 continue; /* remote sends close; ignore (FIXME) */
5112 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5113 unsigned i = ssh2_pkt_getuint32();
5114 struct ssh_channel *c;
5115 c = find234(ssh_channels, &i, ssh_channelfind);
5117 continue; /* nonexistent channel */
5118 c->v.v2.remwindow += ssh2_pkt_getuint32();
5120 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
5121 unsigned i = ssh2_pkt_getuint32();
5122 struct ssh_channel *c;
5123 c = find234(ssh_channels, &i, ssh_channelfind);
5125 continue; /* nonexistent channel */
5126 if (c->type != CHAN_SOCKDATA_DORMANT)
5127 continue; /* dunno why they're confirming this */
5128 c->remoteid = ssh2_pkt_getuint32();
5129 c->type = CHAN_SOCKDATA;
5130 c->v.v2.remwindow = ssh2_pkt_getuint32();
5131 c->v.v2.remmaxpkt = ssh2_pkt_getuint32();
5132 bufchain_init(&c->v.v2.outbuffer);
5134 pfd_confirm(c->u.pfd.s);
5137 * We have a pending close on this channel,
5138 * which we decided on before the server acked
5139 * the channel open. So now we know the
5140 * remoteid, we can close it again.
5142 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5143 ssh2_pkt_adduint32(c->remoteid);
5146 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
5147 unsigned i = ssh2_pkt_getuint32();
5148 struct ssh_channel *c;
5149 c = find234(ssh_channels, &i, ssh_channelfind);
5151 continue; /* nonexistent channel */
5152 if (c->type != CHAN_SOCKDATA_DORMANT)
5153 continue; /* dunno why they're failing this */
5155 logevent("Forwarded connection refused by server");
5157 pfd_close(c->u.pfd.s);
5159 del234(ssh_channels, c);
5161 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
5164 int typelen, want_reply;
5165 struct ssh_channel *c;
5167 localid = ssh2_pkt_getuint32();
5168 ssh2_pkt_getstring(&type, &typelen);
5169 want_reply = ssh2_pkt_getbool();
5172 * First, check that the channel exists. Otherwise,
5173 * we can instantly disconnect with a rude message.
5175 c = find234(ssh_channels, &localid, ssh_channelfind);
5178 sprintf(buf, "Received channel request for nonexistent"
5179 " channel %d", localid);
5181 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5182 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
5183 ssh2_pkt_addstring(buf);
5184 ssh2_pkt_addstring("en"); /* language tag */
5186 connection_fatal(buf);
5187 ssh_state = SSH_STATE_CLOSED;
5192 * Having got the channel number, we now look at
5193 * the request type string to see if it's something
5196 if (typelen == 11 && !memcmp(type, "exit-status", 11) &&
5198 /* We recognise "exit-status" on the primary channel. */
5200 ssh_exitcode = ssh2_pkt_getuint32();
5201 sprintf(buf, "Server sent command exit status %d",
5205 ssh2_pkt_init(SSH2_MSG_CHANNEL_SUCCESS);
5206 ssh2_pkt_adduint32(c->remoteid);
5211 * This is a channel request we don't know
5212 * about, so we now either ignore the request
5213 * or respond with CHANNEL_FAILURE, depending
5217 ssh2_pkt_init(SSH2_MSG_CHANNEL_FAILURE);
5218 ssh2_pkt_adduint32(c->remoteid);
5222 } else if (pktin.type == SSH2_MSG_GLOBAL_REQUEST) {
5224 int typelen, want_reply;
5226 ssh2_pkt_getstring(&type, &typelen);
5227 want_reply = ssh2_pkt_getbool();
5230 * We currently don't support any global requests
5231 * at all, so we either ignore the request or
5232 * respond with REQUEST_FAILURE, depending on
5236 ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
5239 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
5243 struct ssh_channel *c;
5244 unsigned remid, winsize, pktsize;
5245 ssh2_pkt_getstring(&type, &typelen);
5246 c = smalloc(sizeof(struct ssh_channel));
5248 remid = ssh2_pkt_getuint32();
5249 winsize = ssh2_pkt_getuint32();
5250 pktsize = ssh2_pkt_getuint32();
5252 if (typelen == 3 && !memcmp(type, "x11", 3)) {
5253 if (!ssh_X11_fwd_enabled)
5254 error = "X11 forwarding is not enabled";
5255 else if (x11_init(&c->u.x11.s, cfg.x11_display, c) !=
5257 error = "Unable to open an X11 connection";
5261 } else if (typelen == 15 &&
5262 !memcmp(type, "forwarded-tcpip", 15)) {
5263 struct ssh_rportfwd pf, *realpf;
5266 ssh2_pkt_getstring(&dummy, &dummylen);/* skip address */
5267 pf.sport = ssh2_pkt_getuint32();
5268 realpf = find234(ssh_rportfwds, &pf, NULL);
5269 if (realpf == NULL) {
5270 error = "Remote port is not recognised";
5272 char *e = pfd_newconnect(&c->u.pfd.s, realpf->dhost,
5275 sprintf(buf, "Received remote port open request for %s:%d",
5276 realpf->dhost, realpf->dport);
5279 sprintf(buf, "Port open failed: %s", e);
5281 error = "Port open failed";
5283 logevent("Forwarded port opened successfully");
5284 c->type = CHAN_SOCKDATA;
5287 } else if (typelen == 22 &&
5288 !memcmp(type, "auth-agent@openssh.com", 3)) {
5289 if (!ssh_agentfwd_enabled)
5290 error = "Agent forwarding is not enabled";
5292 c->type = CHAN_AGENT; /* identify channel type */
5293 c->u.a.lensofar = 0;
5296 error = "Unsupported channel type requested";
5299 c->remoteid = remid;
5301 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
5302 ssh2_pkt_adduint32(c->remoteid);
5303 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
5304 ssh2_pkt_addstring(error);
5305 ssh2_pkt_addstring("en"); /* language tag */
5309 c->localid = alloc_channel_id();
5311 c->v.v2.locwindow = OUR_V2_WINSIZE;
5312 c->v.v2.remwindow = winsize;
5313 c->v.v2.remmaxpkt = pktsize;
5314 bufchain_init(&c->v.v2.outbuffer);
5315 add234(ssh_channels, c);
5316 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
5317 ssh2_pkt_adduint32(c->remoteid);
5318 ssh2_pkt_adduint32(c->localid);
5319 ssh2_pkt_adduint32(c->v.v2.locwindow);
5320 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
5324 bombout(("Strange packet received: type %d", pktin.type));
5329 * We have spare data. Add it to the channel buffer.
5331 ssh2_add_channel_data(mainchan, in, inlen);
5336 struct ssh_channel *c;
5338 * Try to send data on all channels if we can.
5340 for (i = 0; NULL != (c = index234(ssh_channels, i)); i++) {
5341 int bufsize = ssh2_try_send(c);
5344 case CHAN_MAINSESSION:
5345 /* stdin need not receive an unthrottle
5346 * notification since it will be polled */
5349 x11_unthrottle(c->u.x11.s);
5352 /* agent sockets are request/response and need no
5353 * buffer management */
5356 pfd_unthrottle(c->u.pfd.s);
5368 * Handle the top-level SSH2 protocol.
5370 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
5372 if (do_ssh2_transport(in, inlen, ispkt) == 0)
5374 do_ssh2_authconn(in, inlen, ispkt);
5378 * Called to set up the connection.
5380 * Returns an error message, or NULL on success.
5382 static char *ssh_init(char *host, int port, char **realhost, int nodelay)
5387 if (crypto_startup() == 0)
5388 return "Microsoft high encryption pack not installed!";
5394 ssh1_throttle_count = 0;
5395 ssh_overall_bufsize = 0;
5396 ssh_fallback_cmd = 0;
5398 p = connect_to_host(host, port, realhost, nodelay);
5406 * Called to send data down the Telnet connection.
5408 static int ssh_send(char *buf, int len)
5410 if (s == NULL || ssh_protocol == NULL)
5413 ssh_protocol(buf, len, 0);
5415 return ssh_sendbuffer();
5419 * Called to query the current amount of buffered stdin data.
5421 static int ssh_sendbuffer(void)
5425 if (s == NULL || ssh_protocol == NULL)
5429 * If the SSH socket itself has backed up, add the total backup
5430 * size on that to any individual buffer on the stdin channel.
5433 if (ssh_throttled_all)
5434 override_value = ssh_overall_bufsize;
5436 if (ssh_version == 1) {
5437 return override_value;
5438 } else if (ssh_version == 2) {
5439 if (!mainchan || mainchan->closes > 0)
5440 return override_value;
5442 return override_value + bufchain_size(&mainchan->v.v2.outbuffer);
5449 * Called to set the size of the window from SSH's POV.
5451 static void ssh_size(void)
5453 switch (ssh_state) {
5454 case SSH_STATE_BEFORE_SIZE:
5455 case SSH_STATE_PREPACKET:
5456 case SSH_STATE_CLOSED:
5457 break; /* do nothing */
5458 case SSH_STATE_INTERMED:
5459 size_needed = TRUE; /* buffer for later */
5461 case SSH_STATE_SESSION:
5463 if (ssh_version == 1) {
5464 send_packet(SSH1_CMSG_WINDOW_SIZE,
5465 PKT_INT, rows, PKT_INT, cols,
5466 PKT_INT, 0, PKT_INT, 0, PKT_END);
5468 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5469 ssh2_pkt_adduint32(mainchan->remoteid);
5470 ssh2_pkt_addstring("window-change");
5471 ssh2_pkt_addbool(0);
5472 ssh2_pkt_adduint32(cols);
5473 ssh2_pkt_adduint32(rows);
5474 ssh2_pkt_adduint32(0);
5475 ssh2_pkt_adduint32(0);
5484 * Send Telnet special codes. TS_EOF is useful for `plink', so you
5485 * can send an EOF and collect resulting output (e.g. `plink
5488 static void ssh_special(Telnet_Special code)
5490 if (code == TS_EOF) {
5491 if (ssh_state != SSH_STATE_SESSION) {
5493 * Buffer the EOF in case we are pre-SESSION, so we can
5494 * send it as soon as we reach SESSION.
5500 if (ssh_version == 1) {
5501 send_packet(SSH1_CMSG_EOF, PKT_END);
5503 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
5504 ssh2_pkt_adduint32(mainchan->remoteid);
5507 logevent("Sent EOF message");
5508 } else if (code == TS_PING) {
5509 if (ssh_state == SSH_STATE_CLOSED
5510 || ssh_state == SSH_STATE_PREPACKET) return;
5511 if (ssh_version == 1) {
5512 send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
5514 ssh2_pkt_init(SSH2_MSG_IGNORE);
5515 ssh2_pkt_addstring_start();
5523 void *new_sock_channel(Socket s)
5525 struct ssh_channel *c;
5526 c = smalloc(sizeof(struct ssh_channel));
5529 c->remoteid = -1; /* to be set when open confirmed */
5530 c->localid = alloc_channel_id();
5532 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
5534 add234(ssh_channels, c);
5540 * This is called when stdout/stderr (the entity to which
5541 * from_backend sends data) manages to clear some backlog.
5543 void ssh_unthrottle(int bufsize)
5545 if (ssh_version == 1) {
5546 if (ssh1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
5547 ssh1_stdout_throttling = 0;
5551 if (mainchan && mainchan->closes == 0)
5552 ssh2_set_window(mainchan, OUR_V2_WINSIZE - bufsize);
5556 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
5558 struct ssh_channel *c = (struct ssh_channel *)channel;
5561 sprintf(buf, "Opening forwarded connection to %.512s:%d", hostname, port);
5564 if (ssh_version == 1) {
5565 send_packet(SSH1_MSG_PORT_OPEN,
5566 PKT_INT, c->localid,
5569 //PKT_STR, <org:orgport>,
5572 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
5573 ssh2_pkt_addstring("direct-tcpip");
5574 ssh2_pkt_adduint32(c->localid);
5575 c->v.v2.locwindow = OUR_V2_WINSIZE;
5576 ssh2_pkt_adduint32(c->v.v2.locwindow);/* our window size */
5577 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
5578 ssh2_pkt_addstring(hostname);
5579 ssh2_pkt_adduint32(port);
5581 * We make up values for the originator data; partly it's
5582 * too much hassle to keep track, and partly I'm not
5583 * convinced the server should be told details like that
5584 * about my local network configuration.
5586 ssh2_pkt_addstring("client-side-connection");
5587 ssh2_pkt_adduint32(0);
5593 static Socket ssh_socket(void)
5598 static int ssh_sendok(void)
5603 static int ssh_ldisc(int option)
5605 if (option == LD_ECHO)
5607 if (option == LD_EDIT)
5612 static int ssh_return_exitcode(void)
5614 return ssh_exitcode;
5617 Backend ssh_backend = {
5624 ssh_return_exitcode,