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
);
313 * Buffer management constants. There are several of these for
314 * various different purposes:
316 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
317 * on a local data stream before we throttle the whole SSH
318 * connection (in SSH1 only). Throttling the whole connection is
319 * pretty drastic so we set this high in the hope it won't
322 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
323 * on the SSH connection itself before we defensively throttle
324 * _all_ local data streams. This is pretty drastic too (though
325 * thankfully unlikely in SSH2 since the window mechanism should
326 * ensure that the server never has any need to throttle its end
327 * of the connection), so we set this high as well.
329 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
333 #define SSH1_BUFFER_LIMIT 32768
334 #define SSH_MAX_BACKLOG 32768
335 #define OUR_V2_WINSIZE 16384
337 const static struct ssh_kex
*kex_algs
[] = {
338 &ssh_diffiehellman_gex
,
342 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
344 static void nullmac_key(unsigned char *key
)
347 static void nullmac_generate(unsigned char *blk
, int len
,
351 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
)
355 const static struct ssh_mac ssh_mac_none
= {
356 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
358 const static struct ssh_mac
*macs
[] = {
359 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
361 const static struct ssh_mac
*buggymacs
[] = {
362 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
365 static void ssh_comp_none_init(void)
368 static int ssh_comp_none_block(unsigned char *block
, int len
,
369 unsigned char **outblock
, int *outlen
)
373 static int ssh_comp_none_disable(void)
377 const static struct ssh_compress ssh_comp_none
= {
379 ssh_comp_none_init
, ssh_comp_none_block
,
380 ssh_comp_none_init
, ssh_comp_none_block
,
381 ssh_comp_none_disable
383 extern const struct ssh_compress ssh_zlib
;
384 const static struct ssh_compress
*compressions
[] = {
385 &ssh_zlib
, &ssh_comp_none
388 enum { /* channel types */
393 CHAN_SOCKDATA_DORMANT
/* one the remote hasn't confirmed */
397 * 2-3-4 tree storing channels.
400 unsigned remoteid
, localid
;
404 struct ssh1_data_channel
{
407 struct ssh2_data_channel
{
409 unsigned remwindow
, remmaxpkt
;
414 struct ssh_agent_channel
{
415 unsigned char *message
;
416 unsigned char msglen
[4];
417 int lensofar
, totallen
;
419 struct ssh_x11_channel
{
422 struct ssh_pfd_channel
{
429 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
430 * 2 use this structure in different ways, reflecting SSH 2's
431 * altogether saner approach to port forwarding.
433 * In SSH 1, you arrange a remote forwarding by sending the server
434 * the remote port number, and the local destination host:port.
435 * When a connection comes in, the server sends you back that
436 * host:port pair, and you connect to it. This is a ready-made
437 * security hole if you're not on the ball: a malicious server
438 * could send you back _any_ host:port pair, so if you trustingly
439 * connect to the address it gives you then you've just opened the
440 * entire inside of your corporate network just by connecting
441 * through it to a dodgy SSH server. Hence, we must store a list of
442 * host:port pairs we _are_ trying to forward to, and reject a
443 * connection request from the server if it's not in the list.
445 * In SSH 2, each side of the connection minds its own business and
446 * doesn't send unnecessary information to the other. You arrange a
447 * remote forwarding by sending the server just the remote port
448 * number. When a connection comes in, the server tells you which
449 * of its ports was connected to; and _you_ have to remember what
450 * local host:port pair went with that port number.
452 * Hence: in SSH 1 this structure stores host:port pairs we intend
453 * to allow connections to, and is indexed by those host:port
454 * pairs. In SSH 2 it stores a mapping from source port to
455 * destination host:port pair, and is indexed by source port.
457 struct ssh_rportfwd
{
458 unsigned sport
, dport
;
471 static SHA_State exhash
, exhashbase
;
473 static Socket s
= NULL
;
475 static unsigned char session_key
[32];
476 static int ssh1_compressing
;
477 static int ssh1_remote_protoflags
;
478 static int ssh1_local_protoflags
;
479 static int ssh_agentfwd_enabled
;
480 static int ssh_X11_fwd_enabled
;
481 static int ssh_remote_bugs
;
482 static const struct ssh_cipher
*cipher
= NULL
;
483 static const struct ssh2_cipher
*cscipher
= NULL
;
484 static const struct ssh2_cipher
*sccipher
= NULL
;
485 static const struct ssh_mac
*csmac
= NULL
;
486 static const struct ssh_mac
*scmac
= NULL
;
487 static const struct ssh_compress
*cscomp
= NULL
;
488 static const struct ssh_compress
*sccomp
= NULL
;
489 static const struct ssh_kex
*kex
= NULL
;
490 static const struct ssh_signkey
*hostkey
= NULL
;
491 static unsigned char ssh2_session_id
[20];
492 int (*ssh_get_line
) (const char *prompt
, char *str
, int maxlen
,
495 static char *savedhost
;
496 static int savedport
;
497 static int ssh_send_ok
;
498 static int ssh_echoing
, ssh_editing
;
500 static tree234
*ssh_channels
; /* indexed by local id */
501 static struct ssh_channel
*mainchan
; /* primary session channel */
502 static int ssh_exitcode
= -1;
504 static tree234
*ssh_rportfwds
;
508 SSH_STATE_BEFORE_SIZE
,
512 } ssh_state
= SSH_STATE_PREPACKET
;
514 static int size_needed
= FALSE
, eof_needed
= FALSE
;
516 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
517 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
518 static unsigned char *deferred_send_data
= NULL
;
519 static int deferred_len
= 0, deferred_size
= 0;
522 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
523 * that fails. This variable is the means by which scp.c can reach
524 * into the SSH code and find out which one it got.
526 int ssh_fallback_cmd
= 0;
528 static int ssh_version
;
529 static int ssh1_throttle_count
;
530 static int ssh_overall_bufsize
;
531 static int ssh_throttled_all
;
532 static int ssh1_stdout_throttling
;
533 static void (*ssh_protocol
) (unsigned char *in
, int inlen
, int ispkt
);
534 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
535 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
536 static void ssh_size(void);
537 static void ssh_special(Telnet_Special
);
538 static int ssh2_try_send(struct ssh_channel
*c
);
539 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
541 static void ssh_throttle_all(int enable
, int bufsize
);
542 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
);
543 static int (*s_rdpkt
) (unsigned char **data
, int *datalen
);
544 static int ssh_sendbuffer(void);
546 static struct rdpkt1_state_tag
{
547 long len
, pad
, biglen
, to_read
;
548 unsigned long realcrc
, gotcrc
;
554 static struct rdpkt2_state_tag
{
555 long len
, pad
, payload
, packetlen
, maclen
;
558 unsigned long incoming_sequence
;
561 static int ssh_channelcmp(void *av
, void *bv
)
563 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
564 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
565 if (a
->localid
< b
->localid
)
567 if (a
->localid
> b
->localid
)
571 static int ssh_channelfind(void *av
, void *bv
)
573 unsigned *a
= (unsigned *) av
;
574 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
582 static int ssh_rportcmp_ssh1(void *av
, void *bv
)
584 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
585 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
587 if ( (i
= strcmp(a
->dhost
, b
->dhost
)) != 0)
588 return i
< 0 ?
-1 : +1;
589 if (a
->dport
> b
->dport
)
591 if (a
->dport
< b
->dport
)
596 static int ssh_rportcmp_ssh2(void *av
, void *bv
)
598 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
599 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
601 if (a
->sport
> b
->sport
)
603 if (a
->sport
< b
->sport
)
608 static int alloc_channel_id(void)
610 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
611 unsigned low
, high
, mid
;
613 struct ssh_channel
*c
;
616 * First-fit allocation of channel numbers: always pick the
617 * lowest unused one. To do this, binary-search using the
618 * counted B-tree to find the largest channel ID which is in a
619 * contiguous sequence from the beginning. (Precisely
620 * everything in that sequence must have ID equal to its tree
621 * index plus CHANNEL_NUMBER_OFFSET.)
623 tsize
= count234(ssh_channels
);
627 while (high
- low
> 1) {
628 mid
= (high
+ low
) / 2;
629 c
= index234(ssh_channels
, mid
);
630 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
631 low
= mid
; /* this one is fine */
633 high
= mid
; /* this one is past it */
636 * Now low points to either -1, or the tree index of the
637 * largest ID in the initial sequence.
640 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
641 assert(NULL
== find234(ssh_channels
, &i
, ssh_channelfind
));
643 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
646 static void c_write(char *buf
, int len
)
648 if ((flags
& FLAG_STDERR
)) {
650 for (i
= 0; i
< len
; i
++)
652 fputc(buf
[i
], stderr
);
655 from_backend(1, buf
, len
);
658 static void c_write_untrusted(char *buf
, int len
)
661 for (i
= 0; i
< len
; i
++) {
664 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
669 static void c_write_str(char *buf
)
671 c_write(buf
, strlen(buf
));
675 * Collect incoming data in the incoming packet buffer.
676 * Decipher and verify the packet when it is completely read.
677 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
678 * Update the *data and *datalen variables.
679 * Return the additional nr of bytes needed, or 0 when
680 * a complete packet is available.
682 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
684 struct rdpkt1_state_tag
*st
= &rdpkt1_state
;
693 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
694 while ((*datalen
) == 0)
696 st
->len
= (st
->len
<< 8) + **data
;
697 (*data
)++, (*datalen
)--;
700 st
->pad
= 8 - (st
->len
% 8);
701 st
->biglen
= st
->len
+ st
->pad
;
702 pktin
.length
= st
->len
- 5;
704 if (pktin
.maxlen
< st
->biglen
) {
705 pktin
.maxlen
= st
->biglen
;
706 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->biglen
+ APIEXTRA
) :
707 srealloc(pktin
.data
, st
->biglen
+ APIEXTRA
));
709 fatalbox("Out of memory");
712 st
->to_read
= st
->biglen
;
714 while (st
->to_read
> 0) {
715 st
->chunk
= st
->to_read
;
716 while ((*datalen
) == 0)
717 crReturn(st
->to_read
);
718 if (st
->chunk
> (*datalen
))
719 st
->chunk
= (*datalen
);
720 memcpy(st
->p
, *data
, st
->chunk
);
722 *datalen
-= st
->chunk
;
724 st
->to_read
-= st
->chunk
;
728 cipher
->decrypt(pktin
.data
, st
->biglen
);
730 st
->realcrc
= crc32(pktin
.data
, st
->biglen
- 4);
731 st
->gotcrc
= GET_32BIT(pktin
.data
+ st
->biglen
- 4);
732 if (st
->gotcrc
!= st
->realcrc
) {
733 bombout(("Incorrect CRC received on packet"));
737 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
739 if (ssh1_compressing
) {
740 unsigned char *decompblk
;
742 zlib_decompress_block(pktin
.body
- 1, pktin
.length
+ 1,
743 &decompblk
, &decomplen
);
745 if (pktin
.maxlen
< st
->pad
+ decomplen
) {
746 pktin
.maxlen
= st
->pad
+ decomplen
;
747 pktin
.data
= srealloc(pktin
.data
, pktin
.maxlen
+ APIEXTRA
);
748 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
750 fatalbox("Out of memory");
753 memcpy(pktin
.body
- 1, decompblk
, decomplen
);
755 pktin
.length
= decomplen
- 1;
758 pktin
.type
= pktin
.body
[-1];
760 log_packet(PKT_INCOMING
, pktin
.type
, ssh1_pkt_type(pktin
.type
),
761 pktin
.body
, pktin
.length
);
763 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
764 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
765 pktin
.type
== SSH1_MSG_DEBUG
||
766 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
767 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
768 long strlen
= GET_32BIT(pktin
.body
);
769 if (strlen
+ 4 != pktin
.length
) {
770 bombout(("Received data packet with bogus string length"));
775 if (pktin
.type
== SSH1_MSG_DEBUG
) {
776 /* log debug message */
778 int strlen
= GET_32BIT(pktin
.body
);
779 strcpy(buf
, "Remote: ");
782 memcpy(buf
+ 8, pktin
.body
+ 4, strlen
);
783 buf
[8 + strlen
] = '\0';
786 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
791 if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
792 /* log reason code in disconnect message */
794 unsigned msglen
= GET_32BIT(pktin
.body
);
796 strcpy(buf
, "Remote sent disconnect: ");
797 nowlen
= strlen(buf
);
798 if (msglen
> sizeof(buf
) - nowlen
- 1)
799 msglen
= sizeof(buf
) - nowlen
- 1;
800 memcpy(buf
+ nowlen
, pktin
.body
+ 4, msglen
);
801 buf
[nowlen
+ msglen
] = '\0';
803 bombout(("Server sent disconnect message:\n\"%s\"", buf
+nowlen
));
810 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
812 struct rdpkt2_state_tag
*st
= &rdpkt2_state
;
820 st
->cipherblk
= sccipher
->blksize
;
823 if (st
->cipherblk
< 8)
826 if (pktin
.maxlen
< st
->cipherblk
) {
827 pktin
.maxlen
= st
->cipherblk
;
830 NULL ?
smalloc(st
->cipherblk
+
831 APIEXTRA
) : srealloc(pktin
.data
,
835 fatalbox("Out of memory");
839 * Acquire and decrypt the first block of the packet. This will
840 * contain the length and padding details.
842 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
843 while ((*datalen
) == 0)
844 crReturn(st
->cipherblk
- st
->i
);
845 pktin
.data
[st
->i
] = *(*data
)++;
850 sccipher
->decrypt(pktin
.data
, st
->cipherblk
);
853 * Now get the length and padding figures.
855 st
->len
= GET_32BIT(pktin
.data
);
856 st
->pad
= pktin
.data
[4];
859 * This enables us to deduce the payload length.
861 st
->payload
= st
->len
- st
->pad
- 1;
863 pktin
.length
= st
->payload
+ 5;
866 * So now we can work out the total packet length.
868 st
->packetlen
= st
->len
+ 4;
869 st
->maclen
= scmac ? scmac
->len
: 0;
872 * Adjust memory allocation if packet is too big.
874 if (pktin
.maxlen
< st
->packetlen
+ st
->maclen
) {
875 pktin
.maxlen
= st
->packetlen
+ st
->maclen
;
878 NULL ?
smalloc(pktin
.maxlen
+ APIEXTRA
) : srealloc(pktin
.data
,
883 fatalbox("Out of memory");
887 * Read and decrypt the remainder of the packet.
889 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
891 while ((*datalen
) == 0)
892 crReturn(st
->packetlen
+ st
->maclen
- st
->i
);
893 pktin
.data
[st
->i
] = *(*data
)++;
896 /* Decrypt everything _except_ the MAC. */
898 sccipher
->decrypt(pktin
.data
+ st
->cipherblk
,
899 st
->packetlen
- st
->cipherblk
);
905 && !scmac
->verify(pktin
.data
, st
->len
+ 4,
906 st
->incoming_sequence
)) {
907 bombout(("Incorrect MAC received on packet"));
910 st
->incoming_sequence
++; /* whether or not we MACed */
913 * Decompress packet payload.
916 unsigned char *newpayload
;
918 if (sccomp
&& sccomp
->decompress(pktin
.data
+ 5, pktin
.length
- 5,
919 &newpayload
, &newlen
)) {
920 if (pktin
.maxlen
< newlen
+ 5) {
921 pktin
.maxlen
= newlen
+ 5;
924 NULL ?
smalloc(pktin
.maxlen
+
925 APIEXTRA
) : srealloc(pktin
.data
,
929 fatalbox("Out of memory");
931 pktin
.length
= 5 + newlen
;
932 memcpy(pktin
.data
+ 5, newpayload
, newlen
);
938 pktin
.type
= pktin
.data
[5];
940 log_packet(PKT_INCOMING
, pktin
.type
, ssh2_pkt_type(pktin
.type
),
941 pktin
.data
+6, pktin
.length
-6);
943 if (pktin
.type
== SSH2_MSG_IGNORE
|| pktin
.type
== SSH2_MSG_DEBUG
)
944 goto next_packet
; /* FIXME: print DEBUG message */
946 if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
947 /* log reason code in disconnect message */
949 int reason
= GET_32BIT(pktin
.data
+ 6);
950 unsigned msglen
= GET_32BIT(pktin
.data
+ 10);
952 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
953 sprintf(buf
, "Received disconnect message (%s)",
954 ssh2_disconnect_reasons
[reason
]);
956 sprintf(buf
, "Received disconnect message (unknown type %d)",
960 strcpy(buf
, "Disconnection message text: ");
961 nowlen
= strlen(buf
);
962 if (msglen
> sizeof(buf
) - nowlen
- 1)
963 msglen
= sizeof(buf
) - nowlen
- 1;
964 memcpy(buf
+ nowlen
, pktin
.data
+ 14, msglen
);
965 buf
[nowlen
+ msglen
] = '\0';
967 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
969 (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) ?
970 ssh2_disconnect_reasons
[reason
] : "unknown",
978 static void ssh1_pktout_size(int len
)
982 len
+= 5; /* type and CRC */
986 pktout
.length
= len
- 5;
987 if (pktout
.maxlen
< biglen
) {
988 pktout
.maxlen
= biglen
;
990 /* Allocate enough buffer space for extra block
991 * for MS CryptEncrypt() */
992 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+ 12) :
993 srealloc(pktout
.data
, biglen
+ 12));
995 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+ 4) :
996 srealloc(pktout
.data
, biglen
+ 4));
999 fatalbox("Out of memory");
1001 pktout
.body
= pktout
.data
+ 4 + pad
+ 1;
1004 static void s_wrpkt_start(int type
, int len
)
1006 ssh1_pktout_size(len
);
1010 static int s_wrpkt_prepare(void)
1012 int pad
, len
, biglen
, i
;
1015 pktout
.body
[-1] = pktout
.type
;
1017 log_packet(PKT_OUTGOING
, pktout
.type
, ssh1_pkt_type(pktout
.type
),
1018 pktout
.body
, pktout
.length
);
1020 if (ssh1_compressing
) {
1021 unsigned char *compblk
;
1023 zlib_compress_block(pktout
.body
- 1, pktout
.length
+ 1,
1024 &compblk
, &complen
);
1025 ssh1_pktout_size(complen
- 1);
1026 memcpy(pktout
.body
- 1, compblk
, complen
);
1030 len
= pktout
.length
+ 5; /* type and CRC */
1031 pad
= 8 - (len
% 8);
1034 for (i
= 0; i
< pad
; i
++)
1035 pktout
.data
[i
+ 4] = random_byte();
1036 crc
= crc32(pktout
.data
+ 4, biglen
- 4);
1037 PUT_32BIT(pktout
.data
+ biglen
, crc
);
1038 PUT_32BIT(pktout
.data
, len
);
1041 cipher
->encrypt(pktout
.data
+ 4, biglen
);
1046 static void s_wrpkt(void)
1049 len
= s_wrpkt_prepare();
1050 backlog
= sk_write(s
, pktout
.data
, len
);
1051 if (backlog
> SSH_MAX_BACKLOG
)
1052 ssh_throttle_all(1, backlog
);
1055 static void s_wrpkt_defer(void)
1058 len
= s_wrpkt_prepare();
1059 if (deferred_len
+ len
> deferred_size
) {
1060 deferred_size
= deferred_len
+ len
+ 128;
1061 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1063 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
1064 deferred_len
+= len
;
1068 * Construct a packet with the specified contents.
1070 static void construct_packet(int pkttype
, va_list ap1
, va_list ap2
)
1072 unsigned char *p
, *argp
, argchar
;
1073 unsigned long argint
;
1074 int pktlen
, argtype
, arglen
;
1078 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
1081 (void) va_arg(ap1
, int);
1085 (void) va_arg(ap1
, char);
1089 (void) va_arg(ap1
, unsigned char *);
1090 arglen
= va_arg(ap1
, int);
1094 argp
= va_arg(ap1
, unsigned char *);
1095 arglen
= strlen(argp
);
1096 pktlen
+= 4 + arglen
;
1099 bn
= va_arg(ap1
, Bignum
);
1100 pktlen
+= ssh1_bignum_length(bn
);
1107 s_wrpkt_start(pkttype
, pktlen
);
1110 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
1113 argint
= va_arg(ap2
, int);
1114 PUT_32BIT(p
, argint
);
1118 argchar
= va_arg(ap2
, unsigned char);
1123 argp
= va_arg(ap2
, unsigned char *);
1124 arglen
= va_arg(ap2
, int);
1125 memcpy(p
, argp
, arglen
);
1129 argp
= va_arg(ap2
, unsigned char *);
1130 arglen
= strlen(argp
);
1131 PUT_32BIT(p
, arglen
);
1132 memcpy(p
+ 4, argp
, arglen
);
1136 bn
= va_arg(ap2
, Bignum
);
1137 p
+= ssh1_write_bignum(p
, bn
);
1143 static void send_packet(int pkttype
, ...)
1146 va_start(ap1
, pkttype
);
1147 va_start(ap2
, pkttype
);
1148 construct_packet(pkttype
, ap1
, ap2
);
1152 static void defer_packet(int pkttype
, ...)
1155 va_start(ap1
, pkttype
);
1156 va_start(ap2
, pkttype
);
1157 construct_packet(pkttype
, ap1
, ap2
);
1161 static int ssh_versioncmp(char *a
, char *b
)
1164 unsigned long av
, bv
;
1166 av
= strtoul(a
, &ae
, 10);
1167 bv
= strtoul(b
, &be
, 10);
1169 return (av
< bv ?
-1 : +1);
1174 av
= strtoul(ae
, &ae
, 10);
1175 bv
= strtoul(be
, &be
, 10);
1177 return (av
< bv ?
-1 : +1);
1183 * Utility routines for putting an SSH-protocol `string' and
1184 * `uint32' into a SHA state.
1187 static void sha_string(SHA_State
* s
, void *str
, int len
)
1189 unsigned char lenblk
[4];
1190 PUT_32BIT(lenblk
, len
);
1191 SHA_Bytes(s
, lenblk
, 4);
1192 SHA_Bytes(s
, str
, len
);
1195 static void sha_uint32(SHA_State
* s
, unsigned i
)
1197 unsigned char intblk
[4];
1198 PUT_32BIT(intblk
, i
);
1199 SHA_Bytes(s
, intblk
, 4);
1203 * SSH2 packet construction functions.
1205 static void ssh2_pkt_ensure(int length
)
1207 if (pktout
.maxlen
< length
) {
1208 pktout
.maxlen
= length
+ 256;
1211 NULL ?
smalloc(pktout
.maxlen
+
1212 APIEXTRA
) : srealloc(pktout
.data
,
1216 fatalbox("Out of memory");
1219 static void ssh2_pkt_adddata(void *data
, int len
)
1221 pktout
.length
+= len
;
1222 ssh2_pkt_ensure(pktout
.length
);
1223 memcpy(pktout
.data
+ pktout
.length
- len
, data
, len
);
1225 static void ssh2_pkt_addbyte(unsigned char byte
)
1227 ssh2_pkt_adddata(&byte
, 1);
1229 static void ssh2_pkt_init(int pkt_type
)
1232 ssh2_pkt_addbyte((unsigned char) pkt_type
);
1234 static void ssh2_pkt_addbool(unsigned char value
)
1236 ssh2_pkt_adddata(&value
, 1);
1238 static void ssh2_pkt_adduint32(unsigned long value
)
1241 PUT_32BIT(x
, value
);
1242 ssh2_pkt_adddata(x
, 4);
1244 static void ssh2_pkt_addstring_start(void)
1246 ssh2_pkt_adduint32(0);
1247 pktout
.savedpos
= pktout
.length
;
1249 static void ssh2_pkt_addstring_str(char *data
)
1251 ssh2_pkt_adddata(data
, strlen(data
));
1252 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1253 pktout
.length
- pktout
.savedpos
);
1255 static void ssh2_pkt_addstring_data(char *data
, int len
)
1257 ssh2_pkt_adddata(data
, len
);
1258 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1259 pktout
.length
- pktout
.savedpos
);
1261 static void ssh2_pkt_addstring(char *data
)
1263 ssh2_pkt_addstring_start();
1264 ssh2_pkt_addstring_str(data
);
1266 static char *ssh2_mpint_fmt(Bignum b
, int *len
)
1269 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1272 fatalbox("out of memory");
1274 for (i
= 1; i
<= n
; i
++)
1275 p
[i
] = bignum_byte(b
, n
- i
);
1277 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1279 memmove(p
, p
+ i
, n
+ 1 - i
);
1283 static void ssh2_pkt_addmp(Bignum b
)
1287 p
= ssh2_mpint_fmt(b
, &len
);
1288 ssh2_pkt_addstring_start();
1289 ssh2_pkt_addstring_data(p
, len
);
1294 * Construct an SSH2 final-form packet: compress it, encrypt it,
1295 * put the MAC on it. Final packet, ready to be sent, is stored in
1296 * pktout.data. Total length is returned.
1298 static int ssh2_pkt_construct(void)
1300 int cipherblk
, maclen
, padding
, i
;
1301 static unsigned long outgoing_sequence
= 0;
1303 log_packet(PKT_OUTGOING
, pktout
.data
[5], ssh2_pkt_type(pktout
.data
[5]),
1304 pktout
.data
+ 6, pktout
.length
- 6);
1307 * Compress packet payload.
1310 unsigned char *newpayload
;
1312 if (cscomp
&& cscomp
->compress(pktout
.data
+ 5, pktout
.length
- 5,
1313 &newpayload
, &newlen
)) {
1315 ssh2_pkt_adddata(newpayload
, newlen
);
1321 * Add padding. At least four bytes, and must also bring total
1322 * length (minus MAC) up to a multiple of the block size.
1324 cipherblk
= cscipher ? cscipher
->blksize
: 8; /* block size */
1325 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1328 (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
1329 maclen
= csmac ? csmac
->len
: 0;
1330 ssh2_pkt_ensure(pktout
.length
+ padding
+ maclen
);
1331 pktout
.data
[4] = padding
;
1332 for (i
= 0; i
< padding
; i
++)
1333 pktout
.data
[pktout
.length
+ i
] = random_byte();
1334 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
1336 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
1338 outgoing_sequence
++; /* whether or not we MACed */
1341 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
1343 /* Ready-to-send packet starts at pktout.data. We return length. */
1344 return pktout
.length
+ padding
+ maclen
;
1348 * Construct and send an SSH2 packet immediately.
1350 static void ssh2_pkt_send(void)
1354 len
= ssh2_pkt_construct();
1355 backlog
= sk_write(s
, pktout
.data
, len
);
1356 if (backlog
> SSH_MAX_BACKLOG
)
1357 ssh_throttle_all(1, backlog
);
1361 * Construct an SSH2 packet and add it to a deferred data block.
1362 * Useful for sending multiple packets in a single sk_write() call,
1363 * to prevent a traffic-analysing listener from being able to work
1364 * out the length of any particular packet (such as the password
1367 * Note that because SSH2 sequence-numbers its packets, this can
1368 * NOT be used as an m4-style `defer' allowing packets to be
1369 * constructed in one order and sent in another.
1371 static void ssh2_pkt_defer(void)
1373 int len
= ssh2_pkt_construct();
1374 if (deferred_len
+ len
> deferred_size
) {
1375 deferred_size
= deferred_len
+ len
+ 128;
1376 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1378 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
1379 deferred_len
+= len
;
1383 * Send the whole deferred data block constructed by
1384 * ssh2_pkt_defer() or SSH1's defer_packet().
1386 static void ssh_pkt_defersend(void)
1389 backlog
= sk_write(s
, deferred_send_data
, deferred_len
);
1390 deferred_len
= deferred_size
= 0;
1391 sfree(deferred_send_data
);
1392 deferred_send_data
= NULL
;
1393 if (backlog
> SSH_MAX_BACKLOG
)
1394 ssh_throttle_all(1, backlog
);
1398 void bndebug(char *string
, Bignum b
)
1402 p
= ssh2_mpint_fmt(b
, &len
);
1403 debug(("%s", string
));
1404 for (i
= 0; i
< len
; i
++)
1405 debug((" %02x", p
[i
]));
1411 static void sha_mpint(SHA_State
* s
, Bignum b
)
1415 p
= ssh2_mpint_fmt(b
, &len
);
1416 sha_string(s
, p
, len
);
1421 * SSH2 packet decode functions.
1423 static unsigned long ssh2_pkt_getuint32(void)
1425 unsigned long value
;
1426 if (pktin
.length
- pktin
.savedpos
< 4)
1427 return 0; /* arrgh, no way to decline (FIXME?) */
1428 value
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1429 pktin
.savedpos
+= 4;
1432 static int ssh2_pkt_getbool(void)
1434 unsigned long value
;
1435 if (pktin
.length
- pktin
.savedpos
< 1)
1436 return 0; /* arrgh, no way to decline (FIXME?) */
1437 value
= pktin
.data
[pktin
.savedpos
] != 0;
1441 static void ssh2_pkt_getstring(char **p
, int *length
)
1444 if (pktin
.length
- pktin
.savedpos
< 4)
1446 *length
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1447 pktin
.savedpos
+= 4;
1448 if (pktin
.length
- pktin
.savedpos
< *length
)
1450 *p
= pktin
.data
+ pktin
.savedpos
;
1451 pktin
.savedpos
+= *length
;
1453 static Bignum
ssh2_pkt_getmp(void)
1459 ssh2_pkt_getstring(&p
, &length
);
1463 bombout(("internal error: Can't handle negative mpints"));
1466 b
= bignum_from_bytes(p
, length
);
1471 * Examine the remote side's version string and compare it against
1472 * a list of known buggy implementations.
1474 static void ssh_detect_bugs(char *vstring
)
1476 char *imp
; /* pointer to implementation part */
1478 imp
+= strcspn(imp
, "-");
1480 imp
+= strcspn(imp
, "-");
1483 ssh_remote_bugs
= 0;
1485 if (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
1486 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
1487 !strcmp(imp
, "1.2.22") || !strcmp(imp
, "Cisco-1.25")) {
1489 * These versions don't support SSH1_MSG_IGNORE, so we have
1490 * to use a different defence against password length
1493 ssh_remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
1494 logevent("We believe remote version has SSH1 ignore bug");
1497 if (!strcmp(imp
, "Cisco-1.25")) {
1499 * These versions need a plain password sent; they can't
1500 * handle having a null and a random length of data after
1503 ssh_remote_bugs
|= BUG_NEEDS_SSH1_PLAIN_PASSWORD
;
1504 logevent("We believe remote version needs a plain SSH1 password");
1507 if (!strncmp(imp
, "2.1.0", 5) || !strncmp(imp
, "2.0.", 4) ||
1508 !strncmp(imp
, "2.2.0", 5) || !strncmp(imp
, "2.3.0", 5) ||
1509 !strncmp(imp
, "2.1 ", 4)) {
1511 * These versions have the HMAC bug.
1513 ssh_remote_bugs
|= BUG_SSH2_HMAC
;
1514 logevent("We believe remote version has SSH2 HMAC bug");
1518 static int do_ssh_init(unsigned char c
)
1521 static char version
[10];
1522 static char *vstring
;
1523 static int vstrsize
;
1529 /* Search for the string "SSH-" in the input. */
1532 static const int transS
[] = { 1, 2, 2, 1 };
1533 static const int transH
[] = { 0, 0, 3, 0 };
1534 static const int transminus
[] = { 0, 0, 0, -1 };
1545 crReturn(1); /* get another character */
1549 vstring
= smalloc(vstrsize
);
1550 strcpy(vstring
, "SSH-");
1554 crReturn(1); /* get another char */
1555 if (vslen
>= vstrsize
- 1) {
1557 vstring
= srealloc(vstring
, vstrsize
);
1559 vstring
[vslen
++] = c
;
1564 } else if (i
< sizeof(version
) - 1)
1566 } else if (c
== '\n')
1570 ssh_agentfwd_enabled
= FALSE
;
1571 rdpkt2_state
.incoming_sequence
= 0;
1574 vlog
= smalloc(20 + vslen
);
1575 vstring
[strcspn (vstring
, "\r\n")] = '\0'; /* remove end-of-line chars */
1576 sprintf(vlog
, "Server version: %s", vstring
);
1578 ssh_detect_bugs(vstring
);
1582 * Server version "1.99" means we can choose whether we use v1
1583 * or v2 protocol. Choice is based on cfg.sshprot.
1585 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1587 * This is a v2 server. Begin v2 protocol.
1589 char verstring
[80], vlog
[100];
1590 sprintf(verstring
, "SSH-2.0-%s", sshver
);
1591 SHA_Init(&exhashbase
);
1593 * Hash our version string and their version string.
1595 sha_string(&exhashbase
, verstring
, strlen(verstring
));
1596 sha_string(&exhashbase
, vstring
, strcspn(vstring
, "\r\n"));
1597 sprintf(vlog
, "We claim version: %s", verstring
);
1599 strcat(verstring
, "\n");
1600 logevent("Using SSH protocol version 2");
1601 sk_write(s
, verstring
, strlen(verstring
));
1602 ssh_protocol
= ssh2_protocol
;
1604 s_rdpkt
= ssh2_rdpkt
;
1607 * This is a v1 server. Begin v1 protocol.
1609 char verstring
[80], vlog
[100];
1610 sprintf(verstring
, "SSH-%s-%s",
1611 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"),
1613 sprintf(vlog
, "We claim version: %s", verstring
);
1615 strcat(verstring
, "\n");
1616 logevent("Using SSH protocol version 1");
1617 sk_write(s
, verstring
, strlen(verstring
));
1618 ssh_protocol
= ssh1_protocol
;
1620 s_rdpkt
= ssh1_rdpkt
;
1622 ssh_state
= SSH_STATE_BEFORE_SIZE
;
1629 static void ssh_gotdata(unsigned char *data
, int datalen
)
1634 * To begin with, feed the characters one by one to the
1635 * protocol initialisation / selection function do_ssh_init().
1636 * When that returns 0, we're done with the initial greeting
1637 * exchange and can move on to packet discipline.
1642 crReturnV
; /* more data please */
1643 ret
= do_ssh_init(*data
);
1651 * We emerge from that loop when the initial negotiation is
1652 * over and we have selected an s_rdpkt function. Now pass
1653 * everything to s_rdpkt, and then pass the resulting packets
1654 * to the proper protocol handler.
1659 while (datalen
> 0) {
1660 if (s_rdpkt(&data
, &datalen
) == 0) {
1661 if (ssh_state
== SSH_STATE_CLOSED
) {
1664 ssh_protocol(NULL
, 0, 1);
1665 if (ssh_state
== SSH_STATE_CLOSED
) {
1675 static int ssh_closing(Plug plug
, char *error_msg
, int error_code
,
1678 ssh_state
= SSH_STATE_CLOSED
;
1684 /* A socket error has occurred. */
1685 connection_fatal(error_msg
);
1687 /* Otherwise, the remote side closed the connection normally. */
1692 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
1694 ssh_gotdata(data
, len
);
1695 if (ssh_state
== SSH_STATE_CLOSED
) {
1705 static void ssh_sent(Plug plug
, int bufsize
)
1708 * If the send backlog on the SSH socket itself clears, we
1709 * should unthrottle the whole world if it was throttled.
1711 if (bufsize
< SSH_MAX_BACKLOG
)
1712 ssh_throttle_all(0, bufsize
);
1716 * Connect to specified host and port.
1717 * Returns an error message, or NULL on success.
1718 * Also places the canonical host name into `realhost'. It must be
1719 * freed by the caller.
1721 static char *connect_to_host(char *host
, int port
, char **realhost
, int nodelay
)
1723 static struct plug_function_table fn_table
= {
1728 }, *fn_table_ptr
= &fn_table
;
1737 savedhost
= smalloc(1 + strlen(host
));
1739 fatalbox("Out of memory");
1740 strcpy(savedhost
, host
);
1743 port
= 22; /* default ssh port */
1758 sprintf(buf
, "Looking up host \"%.170s\"", host
);
1761 addr
= sk_namelookup(host
, realhost
);
1762 if ((err
= sk_addr_error(addr
)))
1766 *realhost
= strdup(FWhost
);
1773 char buf
[200], addrbuf
[100];
1774 sk_getaddr(addr
, addrbuf
, 100);
1775 sprintf(buf
, "Connecting to %.100s port %d", addrbuf
, port
);
1778 s
= sk_new(addr
, port
, 0, 1, nodelay
, &fn_table_ptr
);
1779 if ((err
= sk_socket_error(s
)))
1783 sk_write(s
, "connect ", 8);
1784 sk_write(s
, FWhost
, strlen(FWhost
));
1787 sprintf(buf
, " %d\n", FWport
);
1788 sk_write(s
, buf
, strlen(buf
));
1796 * Throttle or unthrottle the SSH connection.
1798 static void ssh1_throttle(int adjust
)
1800 int old_count
= ssh1_throttle_count
;
1801 ssh1_throttle_count
+= adjust
;
1802 assert(ssh1_throttle_count
>= 0);
1803 if (ssh1_throttle_count
&& !old_count
) {
1804 sk_set_frozen(s
, 1);
1805 } else if (!ssh1_throttle_count
&& old_count
) {
1806 sk_set_frozen(s
, 0);
1811 * Throttle or unthrottle _all_ local data streams (for when sends
1812 * on the SSH connection itself back up).
1814 static void ssh_throttle_all(int enable
, int bufsize
)
1817 struct ssh_channel
*c
;
1819 if (enable
== ssh_throttled_all
)
1821 ssh_throttled_all
= enable
;
1822 ssh_overall_bufsize
= bufsize
;
1825 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++) {
1827 case CHAN_MAINSESSION
:
1829 * This is treated separately, outside the switch.
1833 x11_override_throttle(c
->u
.x11
.s
, enable
);
1836 /* Agent channels require no buffer management. */
1839 pfd_override_throttle(c
->u
.x11
.s
, enable
);
1846 * Handle the key exchange and user authentication phases.
1848 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1852 static unsigned char *rsabuf
, *keystr1
, *keystr2
;
1853 unsigned char cookie
[8];
1854 struct RSAKey servkey
, hostkey
;
1855 struct MD5Context md5c
;
1856 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1857 static int tried_publickey
;
1858 static int tis_auth_refused
, ccard_auth_refused
;
1859 static unsigned char session_id
[16];
1860 static int cipher_type
;
1861 static char username
[100];
1862 static void *publickey_blob
;
1863 int publickey_bloblen
;
1870 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1871 bombout(("Public key packet not received"));
1875 logevent("Received public keys");
1877 memcpy(cookie
, pktin
.body
, 8);
1879 i
= makekey(pktin
.body
+ 8, &servkey
, &keystr1
, 0);
1880 j
= makekey(pktin
.body
+ 8 + i
, &hostkey
, &keystr2
, 0);
1883 * Log the host key fingerprint.
1887 logevent("Host key fingerprint is:");
1888 strcpy(logmsg
, " ");
1889 hostkey
.comment
= NULL
;
1890 rsa_fingerprint(logmsg
+ strlen(logmsg
),
1891 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
1895 ssh1_remote_protoflags
= GET_32BIT(pktin
.body
+ 8 + i
+ j
);
1896 supported_ciphers_mask
= GET_32BIT(pktin
.body
+ 12 + i
+ j
);
1897 supported_auths_mask
= GET_32BIT(pktin
.body
+ 16 + i
+ j
);
1899 ssh1_local_protoflags
=
1900 ssh1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
1901 ssh1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
1904 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1905 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1906 MD5Update(&md5c
, pktin
.body
, 8);
1907 MD5Final(session_id
, &md5c
);
1909 for (i
= 0; i
< 32; i
++)
1910 session_key
[i
] = random_byte();
1912 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1914 rsabuf
= smalloc(len
);
1916 fatalbox("Out of memory");
1919 * Verify the host key.
1923 * First format the key into a string.
1925 int len
= rsastr_len(&hostkey
);
1926 char fingerprint
[100];
1927 char *keystr
= smalloc(len
);
1929 fatalbox("Out of memory");
1930 rsastr_fmt(keystr
, &hostkey
);
1931 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
1932 verify_ssh_host_key(savedhost
, savedport
, "rsa", keystr
,
1937 for (i
= 0; i
< 32; i
++) {
1938 rsabuf
[i
] = session_key
[i
];
1940 rsabuf
[i
] ^= session_id
[i
];
1943 if (hostkey
.bytes
> servkey
.bytes
) {
1944 rsaencrypt(rsabuf
, 32, &servkey
);
1945 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1947 rsaencrypt(rsabuf
, 32, &hostkey
);
1948 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1951 logevent("Encrypted session key");
1954 int cipher_chosen
= 0, warn
= 0;
1955 char *cipher_string
= NULL
;
1956 for (i
= 0; !cipher_chosen
&& i
< CIPHER_MAX
; i
++) {
1957 int next_cipher
= cfg
.ssh_cipherlist
[i
];
1958 if (next_cipher
== CIPHER_WARN
) {
1959 /* If/when we choose a cipher, warn about it */
1961 } else if (next_cipher
== CIPHER_AES
) {
1962 /* XXX Probably don't need to mention this. */
1963 logevent("AES not supported in SSH1, skipping");
1965 switch (next_cipher
) {
1966 case CIPHER_3DES
: cipher_type
= SSH_CIPHER_3DES
;
1967 cipher_string
= "3DES"; break;
1968 case CIPHER_BLOWFISH
: cipher_type
= SSH_CIPHER_BLOWFISH
;
1969 cipher_string
= "Blowfish"; break;
1970 case CIPHER_DES
: cipher_type
= SSH_CIPHER_DES
;
1971 cipher_string
= "single-DES"; break;
1973 if (supported_ciphers_mask
& (1 << cipher_type
))
1977 if (!cipher_chosen
) {
1978 if ((supported_ciphers_mask
& (1 << SSH_CIPHER_3DES
)) == 0)
1979 bombout(("Server violates SSH 1 protocol by not "
1980 "supporting 3DES encryption"));
1982 /* shouldn't happen */
1983 bombout(("No supported ciphers found"));
1987 /* Warn about chosen cipher if necessary. */
1989 askcipher(cipher_string
, 0);
1992 switch (cipher_type
) {
1993 case SSH_CIPHER_3DES
:
1994 logevent("Using 3DES encryption");
1996 case SSH_CIPHER_DES
:
1997 logevent("Using single-DES encryption");
1999 case SSH_CIPHER_BLOWFISH
:
2000 logevent("Using Blowfish encryption");
2004 send_packet(SSH1_CMSG_SESSION_KEY
,
2005 PKT_CHAR
, cipher_type
,
2006 PKT_DATA
, cookie
, 8,
2007 PKT_CHAR
, (len
* 8) >> 8, PKT_CHAR
, (len
* 8) & 0xFF,
2008 PKT_DATA
, rsabuf
, len
,
2009 PKT_INT
, ssh1_local_protoflags
, PKT_END
);
2011 logevent("Trying to enable encryption...");
2015 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
2016 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
: &ssh_3des
;
2017 cipher
->sesskey(session_key
);
2021 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2022 bombout(("Encryption not successfully enabled"));
2026 logevent("Successfully started encryption");
2032 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
2034 if (!ssh_get_line("login as: ",
2035 username
, sizeof(username
), FALSE
)) {
2037 * get_line failed to get a username.
2040 logevent("No username provided. Abandoning session.");
2041 ssh_state
= SSH_STATE_CLOSED
;
2045 c_write_str("login as: ");
2048 crWaitUntil(!ispkt
);
2050 switch (c
= *in
++) {
2059 c_write_str("\b \b");
2066 c_write_str("\b \b");
2076 if (((c
>= ' ' && c
<= '~') ||
2077 ((unsigned char) c
>= 160))
2078 && pos
< sizeof(username
)-1) {
2079 username
[pos
++] = c
;
2085 c_write_str("\r\n");
2086 username
[strcspn(username
, "\n\r")] = '\0';
2089 strncpy(username
, cfg
.username
, 99);
2090 username
[99] = '\0';
2093 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
2095 char userlog
[22 + sizeof(username
)];
2096 sprintf(userlog
, "Sent username \"%s\"", username
);
2098 if (flags
& FLAG_INTERACTIVE
&&
2099 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
2100 strcat(userlog
, "\r\n");
2101 c_write_str(userlog
);
2108 tried_publickey
= 0;
2109 tis_auth_refused
= ccard_auth_refused
= 0;
2110 /* Load the public half of cfg.keyfile so we notice if it's in Pageant */
2112 if (!rsakey_pubblob(cfg
.keyfile
, &publickey_blob
, &publickey_bloblen
))
2113 publickey_blob
= NULL
;
2115 publickey_blob
= NULL
;
2117 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
2118 static char password
[100];
2119 static char prompt
[200];
2122 static int pwpkt_type
;
2123 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
2125 if (agent_exists()) {
2127 * Attempt RSA authentication using Pageant.
2129 static unsigned char request
[5], *response
, *p
;
2130 static int responselen
;
2131 static int i
, nkeys
;
2132 static int authed
= FALSE
;
2135 logevent("Pageant is running. Requesting keys.");
2137 /* Request the keys held by the agent. */
2138 PUT_32BIT(request
, 1);
2139 request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
2140 agent_query(request
, 5, &r
, &responselen
);
2141 response
= (unsigned char *) r
;
2142 if (response
&& responselen
>= 5 &&
2143 response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
2145 nkeys
= GET_32BIT(p
);
2149 sprintf(buf
, "Pageant has %d SSH1 keys", nkeys
);
2152 for (i
= 0; i
< nkeys
; i
++) {
2153 static struct RSAKey key
;
2154 static Bignum challenge
;
2155 static char *commentp
;
2156 static int commentlen
;
2160 sprintf(buf
, "Trying Pageant key #%d", i
);
2163 if (publickey_blob
&&
2164 !memcmp(p
, publickey_blob
, publickey_bloblen
)) {
2165 logevent("This key matches configured key file");
2166 tried_publickey
= 1;
2169 p
+= ssh1_read_bignum(p
, &key
.exponent
);
2170 p
+= ssh1_read_bignum(p
, &key
.modulus
);
2171 commentlen
= GET_32BIT(p
);
2175 send_packet(SSH1_CMSG_AUTH_RSA
,
2176 PKT_BIGNUM
, key
.modulus
, PKT_END
);
2178 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2179 logevent("Key refused");
2182 logevent("Received RSA challenge");
2183 ssh1_read_bignum(pktin
.body
, &challenge
);
2185 char *agentreq
, *q
, *ret
;
2188 len
= 1 + 4; /* message type, bit count */
2189 len
+= ssh1_bignum_length(key
.exponent
);
2190 len
+= ssh1_bignum_length(key
.modulus
);
2191 len
+= ssh1_bignum_length(challenge
);
2192 len
+= 16; /* session id */
2193 len
+= 4; /* response format */
2194 agentreq
= smalloc(4 + len
);
2195 PUT_32BIT(agentreq
, len
);
2197 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
2198 PUT_32BIT(q
, bignum_bitcount(key
.modulus
));
2200 q
+= ssh1_write_bignum(q
, key
.exponent
);
2201 q
+= ssh1_write_bignum(q
, key
.modulus
);
2202 q
+= ssh1_write_bignum(q
, challenge
);
2203 memcpy(q
, session_id
, 16);
2205 PUT_32BIT(q
, 1); /* response format */
2206 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
2210 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
2211 logevent("Sending Pageant's response");
2212 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2213 PKT_DATA
, ret
+ 5, 16,
2217 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2219 ("Pageant's response accepted");
2220 if (flags
& FLAG_VERBOSE
) {
2222 ("Authenticated using RSA key \"");
2223 c_write(commentp
, commentlen
);
2224 c_write_str("\" from agent\r\n");
2229 ("Pageant's response not accepted");
2232 ("Pageant failed to answer challenge");
2236 logevent("No reply received from Pageant");
2239 freebn(key
.exponent
);
2240 freebn(key
.modulus
);
2249 if (*cfg
.keyfile
&& !tried_publickey
)
2250 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
2252 if (cfg
.try_tis_auth
&&
2253 (supported_auths_mask
& (1 << SSH1_AUTH_TIS
)) &&
2254 !tis_auth_refused
) {
2255 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
2256 logevent("Requested TIS authentication");
2257 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
2259 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
2260 logevent("TIS authentication declined");
2261 if (flags
& FLAG_INTERACTIVE
)
2262 c_write_str("TIS authentication refused.\r\n");
2263 tis_auth_refused
= 1;
2266 int challengelen
= ((pktin
.body
[0] << 24) |
2267 (pktin
.body
[1] << 16) |
2268 (pktin
.body
[2] << 8) |
2270 logevent("Received TIS challenge");
2271 if (challengelen
> sizeof(prompt
) - 1)
2272 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2273 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2274 /* Prompt heuristic comes from OpenSSH */
2275 strncpy(prompt
+ challengelen
,
2276 memchr(prompt
, '\n', challengelen
) ?
2277 "": "\r\nResponse: ",
2278 (sizeof prompt
) - challengelen
);
2279 prompt
[(sizeof prompt
) - 1] = '\0';
2282 if (cfg
.try_tis_auth
&&
2283 (supported_auths_mask
& (1 << SSH1_AUTH_CCARD
)) &&
2284 !ccard_auth_refused
) {
2285 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
2286 logevent("Requested CryptoCard authentication");
2287 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
2289 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
2290 logevent("CryptoCard authentication declined");
2291 c_write_str("CryptoCard authentication refused.\r\n");
2292 ccard_auth_refused
= 1;
2295 int challengelen
= ((pktin
.body
[0] << 24) |
2296 (pktin
.body
[1] << 16) |
2297 (pktin
.body
[2] << 8) |
2299 logevent("Received CryptoCard challenge");
2300 if (challengelen
> sizeof(prompt
) - 1)
2301 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2302 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2303 strncpy(prompt
+ challengelen
,
2304 memchr(prompt
, '\n', challengelen
) ?
2305 "" : "\r\nResponse: ",
2306 sizeof(prompt
) - challengelen
);
2307 prompt
[sizeof(prompt
) - 1] = '\0';
2310 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2311 sprintf(prompt
, "%.90s@%.90s's password: ",
2312 username
, savedhost
);
2314 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2315 char *comment
= NULL
;
2316 if (flags
& FLAG_VERBOSE
)
2317 c_write_str("Trying public key authentication.\r\n");
2318 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
2319 if (flags
& FLAG_VERBOSE
)
2320 c_write_str("No passphrase required.\r\n");
2323 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
2328 * Show password prompt, having first obtained it via a TIS
2329 * or CryptoCard exchange if we're doing TIS or CryptoCard
2333 if (!ssh_get_line(prompt
, password
, sizeof(password
), TRUE
)) {
2335 * get_line failed to get a password (for example
2336 * because one was supplied on the command line
2337 * which has already failed to work). Terminate.
2339 send_packet(SSH1_MSG_DISCONNECT
,
2340 PKT_STR
, "No more passwords available to try",
2342 connection_fatal("Unable to authenticate");
2343 ssh_state
= SSH_STATE_CLOSED
;
2347 /* Prompt may have come from server. We've munged it a bit, so
2348 * we know it to be zero-terminated at least once. */
2349 c_write_untrusted(prompt
, strlen(prompt
));
2353 crWaitUntil(!ispkt
);
2355 switch (c
= *in
++) {
2376 if (pos
< sizeof(password
)-1)
2377 password
[pos
++] = c
;
2381 c_write_str("\r\n");
2385 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2387 * Try public key authentication with the specified
2390 static struct RSAKey pubkey
;
2391 static Bignum challenge
, response
;
2393 static unsigned char buffer
[32];
2395 tried_publickey
= 1;
2396 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
2398 c_write_str("Couldn't load private key from ");
2399 c_write_str(cfg
.keyfile
);
2400 c_write_str(".\r\n");
2401 continue; /* go and try password */
2404 c_write_str("Wrong passphrase.\r\n");
2405 tried_publickey
= 0;
2406 continue; /* try again */
2410 * Send a public key attempt.
2412 send_packet(SSH1_CMSG_AUTH_RSA
,
2413 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
2416 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2417 c_write_str("Server refused our public key.\r\n");
2418 continue; /* go and try password */
2420 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2421 bombout(("Bizarre response to offer of public key"));
2424 ssh1_read_bignum(pktin
.body
, &challenge
);
2425 response
= rsadecrypt(challenge
, &pubkey
);
2426 freebn(pubkey
.private_exponent
); /* burn the evidence */
2428 for (i
= 0; i
< 32; i
++) {
2429 buffer
[i
] = bignum_byte(response
, 31 - i
);
2433 MD5Update(&md5c
, buffer
, 32);
2434 MD5Update(&md5c
, session_id
, 16);
2435 MD5Final(buffer
, &md5c
);
2437 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2438 PKT_DATA
, buffer
, 16, PKT_END
);
2441 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2442 if (flags
& FLAG_VERBOSE
)
2444 ("Failed to authenticate with our public key.\r\n");
2445 continue; /* go and try password */
2446 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2448 ("Bizarre response to RSA authentication response"));
2452 break; /* we're through! */
2454 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2456 * Defence against traffic analysis: we send a
2457 * whole bunch of packets containing strings of
2458 * different lengths. One of these strings is the
2459 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2460 * The others are all random data in
2461 * SSH1_MSG_IGNORE packets. This way a passive
2462 * listener can't tell which is the password, and
2463 * hence can't deduce the password length.
2465 * Anybody with a password length greater than 16
2466 * bytes is going to have enough entropy in their
2467 * password that a listener won't find it _that_
2468 * much help to know how long it is. So what we'll
2471 * - if password length < 16, we send 15 packets
2472 * containing string lengths 1 through 15
2474 * - otherwise, we let N be the nearest multiple
2475 * of 8 below the password length, and send 8
2476 * packets containing string lengths N through
2477 * N+7. This won't obscure the order of
2478 * magnitude of the password length, but it will
2479 * introduce a bit of extra uncertainty.
2481 * A few servers (the old 1.2.18 through 1.2.22)
2482 * can't deal with SSH1_MSG_IGNORE. For these
2483 * servers, we need an alternative defence. We make
2484 * use of the fact that the password is interpreted
2485 * as a C string: so we can append a NUL, then some
2488 * One server (a Cisco one) can deal with neither
2489 * SSH1_MSG_IGNORE _nor_ a padded password string.
2490 * For this server we are left with no defences
2491 * against password length sniffing.
2493 if (!(ssh_remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
)) {
2495 * The server can deal with SSH1_MSG_IGNORE, so
2496 * we can use the primary defence.
2498 int bottom
, top
, pwlen
, i
;
2501 pwlen
= strlen(password
);
2503 bottom
= 0; /* zero length passwords are OK! :-) */
2506 bottom
= pwlen
& ~7;
2510 assert(pwlen
>= bottom
&& pwlen
<= top
);
2512 randomstr
= smalloc(top
+ 1);
2514 for (i
= bottom
; i
<= top
; i
++) {
2516 defer_packet(pwpkt_type
, PKT_STR
, password
,
2519 for (j
= 0; j
< i
; j
++) {
2521 randomstr
[j
] = random_byte();
2522 } while (randomstr
[j
] == '\0');
2524 randomstr
[i
] = '\0';
2525 defer_packet(SSH1_MSG_IGNORE
,
2526 PKT_STR
, randomstr
, PKT_END
);
2529 logevent("Sending password with camouflage packets");
2530 ssh_pkt_defersend();
2532 else if (!(ssh_remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
2534 * The server can't deal with SSH1_MSG_IGNORE
2535 * but can deal with padded passwords, so we
2536 * can use the secondary defence.
2542 len
= strlen(password
);
2543 if (len
< sizeof(string
)) {
2545 strcpy(string
, password
);
2546 len
++; /* cover the zero byte */
2547 while (len
< sizeof(string
)) {
2548 string
[len
++] = (char) random_byte();
2553 logevent("Sending length-padded password");
2554 send_packet(pwpkt_type
, PKT_INT
, len
,
2555 PKT_DATA
, s
, len
, PKT_END
);
2558 * The server has _both_
2559 * BUG_CHOKES_ON_SSH1_IGNORE and
2560 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2561 * therefore nothing we can do.
2564 len
= strlen(password
);
2565 logevent("Sending unpadded password");
2566 send_packet(pwpkt_type
, PKT_INT
, len
,
2567 PKT_DATA
, password
, len
, PKT_END
);
2570 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
2573 logevent("Sent password");
2574 memset(password
, 0, strlen(password
));
2576 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2577 if (flags
& FLAG_VERBOSE
)
2578 c_write_str("Access denied\r\n");
2579 logevent("Authentication refused");
2580 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2581 logevent("Received disconnect request");
2582 ssh_state
= SSH_STATE_CLOSED
;
2584 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2585 bombout(("Strange packet received, type %d", pktin
.type
));
2590 logevent("Authentication successful");
2595 void sshfwd_close(struct ssh_channel
*c
)
2597 if (c
&& !c
->closes
) {
2599 * If the channel's remoteid is -1, we have sent
2600 * CHANNEL_OPEN for this channel, but it hasn't even been
2601 * acknowledged by the server. So we must set a close flag
2602 * on it now, and then when the server acks the channel
2603 * open, we can close it then.
2605 if (c
->remoteid
!= -1) {
2606 if (ssh_version
== 1) {
2607 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
2610 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2611 ssh2_pkt_adduint32(c
->remoteid
);
2616 if (c
->type
== CHAN_X11
) {
2618 logevent("Forwarded X11 connection terminated");
2619 } else if (c
->type
== CHAN_SOCKDATA
||
2620 c
->type
== CHAN_SOCKDATA_DORMANT
) {
2622 logevent("Forwarded port closed");
2627 int sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
2629 if (ssh_version
== 1) {
2630 send_packet(SSH1_MSG_CHANNEL_DATA
,
2631 PKT_INT
, c
->remoteid
,
2632 PKT_INT
, len
, PKT_DATA
, buf
, len
, PKT_END
);
2634 * In SSH1 we can return 0 here - implying that forwarded
2635 * connections are never individually throttled - because
2636 * the only circumstance that can cause throttling will be
2637 * the whole SSH connection backing up, in which case
2638 * _everything_ will be throttled as a whole.
2642 ssh2_add_channel_data(c
, buf
, len
);
2643 return ssh2_try_send(c
);
2647 void sshfwd_unthrottle(struct ssh_channel
*c
, int bufsize
)
2649 if (ssh_version
== 1) {
2650 if (c
->v
.v1
.throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
2651 c
->v
.v1
.throttling
= 0;
2655 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
2659 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
)
2665 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
2668 if (ssh_state
== SSH_STATE_CLOSED
)
2671 if (cfg
.agentfwd
&& agent_exists()) {
2672 logevent("Requesting agent forwarding");
2673 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
2677 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2678 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2679 bombout(("Protocol confusion"));
2681 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2682 logevent("Agent forwarding refused");
2684 logevent("Agent forwarding enabled");
2685 ssh_agentfwd_enabled
= TRUE
;
2689 if (cfg
.x11_forward
) {
2690 char proto
[20], data
[64];
2691 logevent("Requesting X11 forwarding");
2692 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
2693 if (ssh1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
2694 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2695 PKT_STR
, proto
, PKT_STR
, data
,
2696 PKT_INT
, 0, PKT_END
);
2698 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2699 PKT_STR
, proto
, PKT_STR
, data
, PKT_END
);
2704 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2705 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2706 bombout(("Protocol confusion"));
2708 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2709 logevent("X11 forwarding refused");
2711 logevent("X11 forwarding enabled");
2712 ssh_X11_fwd_enabled
= TRUE
;
2720 char sports
[256], dports
[256], host
[256];
2723 ssh_rportfwds
= newtree234(ssh_rportcmp_ssh1
);
2724 /* Add port forwardings. */
2729 while (*e
&& *e
!= '\t')
2735 while (*e
&& *e
!= ':')
2745 dport
= atoi(dports
);
2746 sport
= atoi(sports
);
2747 if (sport
&& dport
) {
2749 pfd_addforward(host
, dport
, sport
);
2750 sprintf(buf
, "Local port %d forwarding to %s:%d",
2751 sport
, host
, dport
);
2754 struct ssh_rportfwd
*pf
;
2755 pf
= smalloc(sizeof(*pf
));
2756 strcpy(pf
->dhost
, host
);
2758 if (add234(ssh_rportfwds
, pf
) != pf
) {
2760 "Duplicate remote port forwarding to %s:%d",
2765 sprintf(buf
, "Requesting remote port %d forward to %s:%d",
2766 sport
, host
, dport
);
2768 send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST
,
2780 send_packet(SSH1_CMSG_REQUEST_PTY
,
2781 PKT_STR
, cfg
.termtype
,
2782 PKT_INT
, rows
, PKT_INT
, cols
,
2783 PKT_INT
, 0, PKT_INT
, 0, PKT_CHAR
, 0, PKT_END
);
2784 ssh_state
= SSH_STATE_INTERMED
;
2788 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2789 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2790 bombout(("Protocol confusion"));
2792 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2793 c_write_str("Server refused to allocate pty\r\n");
2794 ssh_editing
= ssh_echoing
= 1;
2796 logevent("Allocated pty");
2798 ssh_editing
= ssh_echoing
= 1;
2801 if (cfg
.compression
) {
2802 send_packet(SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
2806 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2807 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2808 bombout(("Protocol confusion"));
2810 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2811 c_write_str("Server refused to compress\r\n");
2813 logevent("Started compression");
2814 ssh1_compressing
= TRUE
;
2815 zlib_compress_init();
2816 zlib_decompress_init();
2820 * Start the shell or command.
2822 * Special case: if the first-choice command is an SSH2
2823 * subsystem (hence not usable here) and the second choice
2824 * exists, we fall straight back to that.
2827 char *cmd
= cfg
.remote_cmd_ptr
;
2829 if (cfg
.ssh_subsys
&& cfg
.remote_cmd_ptr2
) {
2830 cmd
= cfg
.remote_cmd_ptr2
;
2831 ssh_fallback_cmd
= TRUE
;
2834 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
2836 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
2837 logevent("Started session");
2840 ssh_state
= SSH_STATE_SESSION
;
2844 ssh_special(TS_EOF
);
2846 ldisc_send(NULL
, 0, 0); /* cause ldisc to notice changes */
2848 ssh_channels
= newtree234(ssh_channelcmp
);
2852 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
2853 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
2854 long len
= GET_32BIT(pktin
.body
);
2856 from_backend(pktin
.type
== SSH1_SMSG_STDERR_DATA
,
2857 pktin
.body
+ 4, len
);
2858 if (!ssh1_stdout_throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
2859 ssh1_stdout_throttling
= 1;
2862 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2863 ssh_state
= SSH_STATE_CLOSED
;
2864 logevent("Received disconnect request");
2866 } else if (pktin
.type
== SSH1_SMSG_X11_OPEN
) {
2867 /* Remote side is trying to open a channel to talk to our
2868 * X-Server. Give them back a local channel number. */
2869 struct ssh_channel
*c
;
2871 logevent("Received X11 connect request");
2872 /* Refuse if X11 forwarding is disabled. */
2873 if (!ssh_X11_fwd_enabled
) {
2874 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2875 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2876 logevent("Rejected X11 connect request");
2878 c
= smalloc(sizeof(struct ssh_channel
));
2880 if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
2881 logevent("opening X11 forward connection failed");
2883 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2884 PKT_INT
, GET_32BIT(pktin
.body
),
2888 ("opening X11 forward connection succeeded");
2889 c
->remoteid
= GET_32BIT(pktin
.body
);
2890 c
->localid
= alloc_channel_id();
2892 c
->v
.v1
.throttling
= 0;
2893 c
->type
= CHAN_X11
; /* identify channel type */
2894 add234(ssh_channels
, c
);
2895 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2896 PKT_INT
, c
->remoteid
, PKT_INT
,
2897 c
->localid
, PKT_END
);
2898 logevent("Opened X11 forward channel");
2901 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
2902 /* Remote side is trying to open a channel to talk to our
2903 * agent. Give them back a local channel number. */
2904 struct ssh_channel
*c
;
2906 /* Refuse if agent forwarding is disabled. */
2907 if (!ssh_agentfwd_enabled
) {
2908 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2909 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2911 c
= smalloc(sizeof(struct ssh_channel
));
2912 c
->remoteid
= GET_32BIT(pktin
.body
);
2913 c
->localid
= alloc_channel_id();
2915 c
->v
.v1
.throttling
= 0;
2916 c
->type
= CHAN_AGENT
; /* identify channel type */
2917 c
->u
.a
.lensofar
= 0;
2918 add234(ssh_channels
, c
);
2919 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2920 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2923 } else if (pktin
.type
== SSH1_MSG_PORT_OPEN
) {
2924 /* Remote side is trying to open a channel to talk to a
2925 * forwarded port. Give them back a local channel number. */
2926 struct ssh_channel
*c
;
2927 struct ssh_rportfwd pf
;
2929 char host
[256], buf
[1024];
2931 c
= smalloc(sizeof(struct ssh_channel
));
2933 hostsize
= GET_32BIT(pktin
.body
+4);
2934 for(h
= host
, p
= pktin
.body
+8; hostsize
!= 0; hostsize
--) {
2935 if (h
+1 < host
+sizeof(host
))
2940 port
= GET_32BIT(p
);
2942 strcpy(pf
.dhost
, host
);
2945 if (find234(ssh_rportfwds
, &pf
, NULL
) == NULL
) {
2946 sprintf(buf
, "Rejected remote port open request for %s:%d",
2949 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2950 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2952 sprintf(buf
, "Received remote port open request for %s:%d",
2955 e
= pfd_newconnect(&c
->u
.pfd
.s
, host
, port
, c
);
2958 sprintf(buf
, "Port open failed: %s", e
);
2961 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2962 PKT_INT
, GET_32BIT(pktin
.body
),
2965 c
->remoteid
= GET_32BIT(pktin
.body
);
2966 c
->localid
= alloc_channel_id();
2968 c
->v
.v1
.throttling
= 0;
2969 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
2970 add234(ssh_channels
, c
);
2971 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2972 PKT_INT
, c
->remoteid
, PKT_INT
,
2973 c
->localid
, PKT_END
);
2974 logevent("Forwarded port opened successfully");
2978 } else if (pktin
.type
== SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
) {
2979 unsigned int remoteid
= GET_32BIT(pktin
.body
);
2980 unsigned int localid
= GET_32BIT(pktin
.body
+4);
2981 struct ssh_channel
*c
;
2983 c
= find234(ssh_channels
, &remoteid
, ssh_channelfind
);
2984 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
2985 c
->remoteid
= localid
;
2986 c
->type
= CHAN_SOCKDATA
;
2987 c
->v
.v1
.throttling
= 0;
2988 pfd_confirm(c
->u
.pfd
.s
);
2991 if (c
&& c
->closes
) {
2993 * We have a pending close on this channel,
2994 * which we decided on before the server acked
2995 * the channel open. So now we know the
2996 * remoteid, we can close it again.
2998 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
3002 } else if (pktin
.type
== SSH1_MSG_CHANNEL_OPEN_FAILURE
) {
3003 unsigned int remoteid
= GET_32BIT(pktin
.body
);
3004 unsigned int localid
= GET_32BIT(pktin
.body
+4);
3005 struct ssh_channel
*c
;
3007 c
= find234(ssh_channels
, &remoteid
, ssh_channelfind
);
3008 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
3009 logevent("Forwarded connection refused by server");
3010 pfd_close(c
->u
.pfd
.s
);
3011 del234(ssh_channels
, c
);
3015 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
3016 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
3017 /* Remote side closes a channel. */
3018 unsigned i
= GET_32BIT(pktin
.body
);
3019 struct ssh_channel
*c
;
3020 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3024 (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
3025 if (!(c
->closes
& closetype
))
3026 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
,
3028 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
3029 logevent("Forwarded X11 connection terminated");
3030 assert(c
->u
.x11
.s
!= NULL
);
3031 x11_close(c
->u
.x11
.s
);
3034 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
3035 logevent("Forwarded port closed");
3036 assert(c
->u
.pfd
.s
!= NULL
);
3037 pfd_close(c
->u
.pfd
.s
);
3040 c
->closes
|= closetype
;
3041 if (c
->closes
== 3) {
3042 del234(ssh_channels
, c
);
3046 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
3047 /* Data sent down one of our channels. */
3048 int i
= GET_32BIT(pktin
.body
);
3049 int len
= GET_32BIT(pktin
.body
+ 4);
3050 unsigned char *p
= pktin
.body
+ 8;
3051 struct ssh_channel
*c
;
3052 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3057 bufsize
= x11_send(c
->u
.x11
.s
, p
, len
);
3060 bufsize
= pfd_send(c
->u
.pfd
.s
, p
, len
);
3063 /* Data for an agent message. Buffer it. */
3065 if (c
->u
.a
.lensofar
< 4) {
3066 int l
= min(4 - c
->u
.a
.lensofar
, len
);
3067 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
3071 c
->u
.a
.lensofar
+= l
;
3073 if (c
->u
.a
.lensofar
== 4) {
3075 4 + GET_32BIT(c
->u
.a
.msglen
);
3076 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
3077 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
3079 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
3081 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
3083 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
3087 c
->u
.a
.lensofar
+= l
;
3089 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
3090 void *reply
, *sentreply
;
3092 agent_query(c
->u
.a
.message
,
3093 c
->u
.a
.totallen
, &reply
,
3098 /* Fake SSH_AGENT_FAILURE. */
3099 sentreply
= "\0\0\0\1\5";
3102 send_packet(SSH1_MSG_CHANNEL_DATA
,
3103 PKT_INT
, c
->remoteid
,
3105 PKT_DATA
, sentreply
, replylen
,
3109 sfree(c
->u
.a
.message
);
3110 c
->u
.a
.lensofar
= 0;
3113 bufsize
= 0; /* agent channels never back up */
3116 if (!c
->v
.v1
.throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
3117 c
->v
.v1
.throttling
= 1;
3121 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
3122 /* may be from EXEC_SHELL on some servers */
3123 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
3124 /* may be from EXEC_SHELL on some servers
3125 * if no pty is available or in other odd cases. Ignore */
3126 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
3128 ssh_exitcode
= GET_32BIT(pktin
.body
);
3129 sprintf(buf
, "Server sent command exit status %d",
3132 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
3134 * In case `helpful' firewalls or proxies tack
3135 * extra human-readable text on the end of the
3136 * session which we might mistake for another
3137 * encrypted packet, we close the session once
3138 * we've sent EXIT_CONFIRMATION.
3140 ssh_state
= SSH_STATE_CLOSED
;
3143 bombout(("Strange packet received: type %d", pktin
.type
));
3148 int len
= min(inlen
, 512);
3149 send_packet(SSH1_CMSG_STDIN_DATA
,
3150 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
3161 * Utility routine for decoding comma-separated strings in KEXINIT.
3163 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
3165 int needlen
= strlen(needle
);
3168 * Is it at the start of the string?
3170 if (haylen
>= needlen
&& /* haystack is long enough */
3171 !memcmp(needle
, haystack
, needlen
) && /* initial match */
3172 (haylen
== needlen
|| haystack
[needlen
] == ',')
3173 /* either , or EOS follows */
3177 * If not, search for the next comma and resume after that.
3178 * If no comma found, terminate.
3180 while (haylen
> 0 && *haystack
!= ',')
3181 haylen
--, haystack
++;
3184 haylen
--, haystack
++; /* skip over comma itself */
3189 * SSH2 key creation method.
3191 static void ssh2_mkkey(Bignum K
, char *H
, char *sessid
, char chr
,
3195 /* First 20 bytes. */
3198 SHA_Bytes(&s
, H
, 20);
3199 SHA_Bytes(&s
, &chr
, 1);
3200 SHA_Bytes(&s
, sessid
, 20);
3201 SHA_Final(&s
, keyspace
);
3202 /* Next 20 bytes. */
3205 SHA_Bytes(&s
, H
, 20);
3206 SHA_Bytes(&s
, keyspace
, 20);
3207 SHA_Final(&s
, keyspace
+ 20);
3211 * Handle the SSH2 transport layer.
3213 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
3215 static int i
, j
, len
, nbits
, pbits
, warn
;
3217 static Bignum p
, g
, e
, f
, K
;
3218 static int kex_init_value
, kex_reply_value
;
3219 static const struct ssh_mac
**maclist
;
3221 static const struct ssh2_cipher
*cscipher_tobe
= NULL
;
3222 static const struct ssh2_cipher
*sccipher_tobe
= NULL
;
3223 static const struct ssh_mac
*csmac_tobe
= NULL
;
3224 static const struct ssh_mac
*scmac_tobe
= NULL
;
3225 static const struct ssh_compress
*cscomp_tobe
= NULL
;
3226 static const struct ssh_compress
*sccomp_tobe
= NULL
;
3227 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
3228 static int hostkeylen
, siglen
;
3229 static void *hkey
; /* actual host key */
3230 static unsigned char exchange_hash
[20];
3231 static unsigned char keyspace
[40];
3232 static int n_preferred_ciphers
;
3233 static const struct ssh2_ciphers
*preferred_ciphers
[CIPHER_MAX
];
3234 static const struct ssh_compress
*preferred_comp
;
3235 static int cipherstr_started
;
3236 static int first_kex
;
3243 * Set up the preferred ciphers. (NULL => warn below here)
3245 n_preferred_ciphers
= 0;
3246 for (i
= 0; i
< CIPHER_MAX
; i
++) {
3247 switch (cfg
.ssh_cipherlist
[i
]) {
3248 case CIPHER_BLOWFISH
:
3249 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_blowfish
;
3250 n_preferred_ciphers
++;
3253 if (cfg
.ssh2_des_cbc
) {
3254 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_des
;
3255 n_preferred_ciphers
++;
3259 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_3des
;
3260 n_preferred_ciphers
++;
3263 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_aes
;
3264 n_preferred_ciphers
++;
3267 /* Flag for later. Don't bother if it's the last in
3269 if (i
< CIPHER_MAX
- 1) {
3270 preferred_ciphers
[n_preferred_ciphers
] = NULL
;
3271 n_preferred_ciphers
++;
3278 * Set up preferred compression.
3280 if (cfg
.compression
)
3281 preferred_comp
= &ssh_zlib
;
3283 preferred_comp
= &ssh_comp_none
;
3286 * Be prepared to work around the buggy MAC problem.
3288 if (cfg
.buggymac
|| (ssh_remote_bugs
& BUG_SSH2_HMAC
))
3289 maclist
= buggymacs
, nmacs
= lenof(buggymacs
);
3291 maclist
= macs
, nmacs
= lenof(macs
);
3295 * Construct and send our key exchange packet.
3297 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
3298 for (i
= 0; i
< 16; i
++)
3299 ssh2_pkt_addbyte((unsigned char) random_byte());
3300 /* List key exchange algorithms. */
3301 ssh2_pkt_addstring_start();
3302 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3303 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
3304 if (i
< lenof(kex_algs
) - 1)
3305 ssh2_pkt_addstring_str(",");
3307 /* List server host key algorithms. */
3308 ssh2_pkt_addstring_start();
3309 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3310 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
3311 if (i
< lenof(hostkey_algs
) - 1)
3312 ssh2_pkt_addstring_str(",");
3314 /* List client->server encryption algorithms. */
3315 ssh2_pkt_addstring_start();
3316 cipherstr_started
= 0;
3317 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3318 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3319 if (!c
) continue; /* warning flag */
3320 for (j
= 0; j
< c
->nciphers
; j
++) {
3321 if (cipherstr_started
)
3322 ssh2_pkt_addstring_str(",");
3323 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
3324 cipherstr_started
= 1;
3327 /* List server->client encryption algorithms. */
3328 ssh2_pkt_addstring_start();
3329 cipherstr_started
= 0;
3330 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3331 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3332 if (!c
) continue; /* warning flag */
3333 for (j
= 0; j
< c
->nciphers
; j
++) {
3334 if (cipherstr_started
)
3335 ssh2_pkt_addstring_str(",");
3336 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
3337 cipherstr_started
= 1;
3340 /* List client->server MAC algorithms. */
3341 ssh2_pkt_addstring_start();
3342 for (i
= 0; i
< nmacs
; i
++) {
3343 ssh2_pkt_addstring_str(maclist
[i
]->name
);
3345 ssh2_pkt_addstring_str(",");
3347 /* List server->client MAC algorithms. */
3348 ssh2_pkt_addstring_start();
3349 for (i
= 0; i
< nmacs
; i
++) {
3350 ssh2_pkt_addstring_str(maclist
[i
]->name
);
3352 ssh2_pkt_addstring_str(",");
3354 /* List client->server compression algorithms. */
3355 ssh2_pkt_addstring_start();
3356 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3357 const struct ssh_compress
*c
=
3358 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3359 ssh2_pkt_addstring_str(c
->name
);
3360 if (i
< lenof(compressions
))
3361 ssh2_pkt_addstring_str(",");
3363 /* List server->client compression algorithms. */
3364 ssh2_pkt_addstring_start();
3365 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3366 const struct ssh_compress
*c
=
3367 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3368 ssh2_pkt_addstring_str(c
->name
);
3369 if (i
< lenof(compressions
))
3370 ssh2_pkt_addstring_str(",");
3372 /* List client->server languages. Empty list. */
3373 ssh2_pkt_addstring_start();
3374 /* List server->client languages. Empty list. */
3375 ssh2_pkt_addstring_start();
3376 /* First KEX packet does _not_ follow, because we're not that brave. */
3377 ssh2_pkt_addbool(FALSE
);
3379 ssh2_pkt_adduint32(0);
3381 exhash
= exhashbase
;
3382 sha_string(&exhash
, pktout
.data
+ 5, pktout
.length
- 5);
3388 sha_string(&exhash
, pktin
.data
+ 5, pktin
.length
- 5);
3391 * Now examine the other side's KEXINIT to see what we're up
3394 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
3395 bombout(("expected key exchange packet from server"));
3400 cscipher_tobe
= NULL
;
3401 sccipher_tobe
= NULL
;
3406 pktin
.savedpos
+= 16; /* skip garbage cookie */
3407 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
3408 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3409 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
3414 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
3415 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3416 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
3417 hostkey
= hostkey_algs
[i
];
3421 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
3423 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3424 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3428 for (j
= 0; j
< c
->nciphers
; j
++) {
3429 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3430 cscipher_tobe
= c
->list
[j
];
3435 if (cscipher_tobe
) {
3437 askcipher(cscipher_tobe
->name
, 1);
3441 if (!cscipher_tobe
) {
3442 bombout(("Couldn't agree a client-to-server cipher (available: %s)", str
));
3446 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
3448 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3449 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3453 for (j
= 0; j
< c
->nciphers
; j
++) {
3454 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3455 sccipher_tobe
= c
->list
[j
];
3460 if (sccipher_tobe
) {
3462 askcipher(sccipher_tobe
->name
, 2);
3466 if (!sccipher_tobe
) {
3467 bombout(("Couldn't agree a server-to-client cipher (available: %s)", str
));
3471 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
3472 for (i
= 0; i
< nmacs
; i
++) {
3473 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3474 csmac_tobe
= maclist
[i
];
3478 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
3479 for (i
= 0; i
< nmacs
; i
++) {
3480 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3481 scmac_tobe
= maclist
[i
];
3485 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
3486 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3487 const struct ssh_compress
*c
=
3488 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3489 if (in_commasep_string(c
->name
, str
, len
)) {
3494 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
3495 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3496 const struct ssh_compress
*c
=
3497 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3498 if (in_commasep_string(c
->name
, str
, len
)) {
3505 * Work out the number of bits of key we will need from the key
3506 * exchange. We start with the maximum key length of either
3512 csbits
= cscipher_tobe
->keylen
;
3513 scbits
= sccipher_tobe
->keylen
;
3514 nbits
= (csbits
> scbits ? csbits
: scbits
);
3516 /* The keys only have 160-bit entropy, since they're based on
3517 * a SHA-1 hash. So cap the key size at 160 bits. */
3522 * If we're doing Diffie-Hellman group exchange, start by
3523 * requesting a group.
3525 if (kex
== &ssh_diffiehellman_gex
) {
3526 logevent("Doing Diffie-Hellman group exchange");
3527 ssh_pkt_ctx
|= SSH2_PKTCTX_DHGEX
;
3529 * Work out how big a DH group we will need to allow that
3532 pbits
= 512 << ((nbits
- 1) / 64);
3533 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
3534 ssh2_pkt_adduint32(pbits
);
3538 if (pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
3539 bombout(("expected key exchange group packet from server"));
3542 p
= ssh2_pkt_getmp();
3543 g
= ssh2_pkt_getmp();
3544 dh_setup_group(p
, g
);
3545 kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
3546 kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
3548 ssh_pkt_ctx
|= SSH2_PKTCTX_DHGROUP1
;
3550 kex_init_value
= SSH2_MSG_KEXDH_INIT
;
3551 kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
3554 logevent("Doing Diffie-Hellman key exchange");
3556 * Now generate and send e for Diffie-Hellman.
3558 e
= dh_create_e(nbits
* 2);
3559 ssh2_pkt_init(kex_init_value
);
3564 if (pktin
.type
!= kex_reply_value
) {
3565 bombout(("expected key exchange reply packet from server"));
3568 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
3569 f
= ssh2_pkt_getmp();
3570 ssh2_pkt_getstring(&sigdata
, &siglen
);
3574 sha_string(&exhash
, hostkeydata
, hostkeylen
);
3575 if (kex
== &ssh_diffiehellman_gex
) {
3576 sha_uint32(&exhash
, pbits
);
3577 sha_mpint(&exhash
, p
);
3578 sha_mpint(&exhash
, g
);
3580 sha_mpint(&exhash
, e
);
3581 sha_mpint(&exhash
, f
);
3582 sha_mpint(&exhash
, K
);
3583 SHA_Final(&exhash
, exchange_hash
);
3588 debug(("Exchange hash is:\n"));
3589 dmemdump(exchange_hash
, 20);
3592 hkey
= hostkey
->newkey(hostkeydata
, hostkeylen
);
3594 !hostkey
->verifysig(hkey
, sigdata
, siglen
, exchange_hash
, 20)) {
3595 bombout(("Server's host key did not match the signature supplied"));
3600 * Authenticate remote host: verify host key. (We've already
3601 * checked the signature of the exchange hash.)
3603 keystr
= hostkey
->fmtkey(hkey
);
3604 fingerprint
= hostkey
->fingerprint(hkey
);
3605 verify_ssh_host_key(savedhost
, savedport
, hostkey
->keytype
,
3606 keystr
, fingerprint
);
3607 if (first_kex
) { /* don't bother logging this in rekeys */
3608 logevent("Host key fingerprint is:");
3609 logevent(fingerprint
);
3613 hostkey
->freekey(hkey
);
3616 * Send SSH2_MSG_NEWKEYS.
3618 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
3622 * Expect SSH2_MSG_NEWKEYS from server.
3625 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
3626 bombout(("expected new-keys packet from server"));
3631 * Create and initialise session keys.
3633 cscipher
= cscipher_tobe
;
3634 sccipher
= sccipher_tobe
;
3637 cscomp
= cscomp_tobe
;
3638 sccomp
= sccomp_tobe
;
3639 cscomp
->compress_init();
3640 sccomp
->decompress_init();
3642 * Set IVs after keys. Here we use the exchange hash from the
3643 * _first_ key exchange.
3646 memcpy(ssh2_session_id
, exchange_hash
, sizeof(exchange_hash
));
3647 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'C', keyspace
);
3648 cscipher
->setcskey(keyspace
);
3649 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'D', keyspace
);
3650 sccipher
->setsckey(keyspace
);
3651 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'A', keyspace
);
3652 cscipher
->setcsiv(keyspace
);
3653 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'B', keyspace
);
3654 sccipher
->setsciv(keyspace
);
3655 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'E', keyspace
);
3656 csmac
->setcskey(keyspace
);
3657 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'F', keyspace
);
3658 scmac
->setsckey(keyspace
);
3661 * If this is the first key exchange phase, we must pass the
3662 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
3663 * wants to see it but because it will need time to initialise
3664 * itself before it sees an actual packet. In subsequent key
3665 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
3666 * it would only confuse the layer above.
3674 * Now we're encrypting. Begin returning 1 to the protocol main
3675 * function so that other things can run on top of the
3676 * transport. If we ever see a KEXINIT, we must go back to the
3679 while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
)) {
3682 logevent("Server initiated key re-exchange");
3683 goto begin_key_exchange
;
3689 * Add data to an SSH2 channel output buffer.
3691 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
3694 bufchain_add(&c
->v
.v2
.outbuffer
, buf
, len
);
3698 * Attempt to send data on an SSH2 channel.
3700 static int ssh2_try_send(struct ssh_channel
*c
)
3702 while (c
->v
.v2
.remwindow
> 0 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0) {
3705 bufchain_prefix(&c
->v
.v2
.outbuffer
, &data
, &len
);
3706 if ((unsigned)len
> c
->v
.v2
.remwindow
)
3707 len
= c
->v
.v2
.remwindow
;
3708 if ((unsigned)len
> c
->v
.v2
.remmaxpkt
)
3709 len
= c
->v
.v2
.remmaxpkt
;
3710 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
3711 ssh2_pkt_adduint32(c
->remoteid
);
3712 ssh2_pkt_addstring_start();
3713 ssh2_pkt_addstring_data(data
, len
);
3715 bufchain_consume(&c
->v
.v2
.outbuffer
, len
);
3716 c
->v
.v2
.remwindow
-= len
;
3720 * After having sent as much data as we can, return the amount
3723 return bufchain_size(&c
->v
.v2
.outbuffer
);
3727 * Potentially enlarge the window on an SSH2 channel.
3729 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
)
3731 if (newwin
> c
->v
.v2
.locwindow
) {
3732 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3733 ssh2_pkt_adduint32(c
->remoteid
);
3734 ssh2_pkt_adduint32(newwin
- c
->v
.v2
.locwindow
);
3736 c
->v
.v2
.locwindow
= newwin
;
3741 * Handle the SSH2 userauth and connection layers.
3743 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
3746 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
,
3748 AUTH_KEYBOARD_INTERACTIVE
3752 AUTH_TYPE_PUBLICKEY
,
3753 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
3754 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
3756 AUTH_TYPE_KEYBOARD_INTERACTIVE
,
3757 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
3759 static int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
3760 static int tried_pubkey_config
, tried_agent
, tried_keyb_inter
;
3761 static int kbd_inter_running
;
3762 static int we_are_in
;
3763 static int num_prompts
, echo
;
3764 static char username
[100];
3765 static char pwprompt
[200];
3766 static char password
[100];
3767 static void *publickey_blob
;
3768 static int publickey_bloblen
;
3773 * Request userauth protocol, and await a response to it.
3775 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
3776 ssh2_pkt_addstring("ssh-userauth");
3778 crWaitUntilV(ispkt
);
3779 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
3780 bombout(("Server refused user authentication protocol"));
3785 * We repeat this whole loop, including the username prompt,
3786 * until we manage a successful authentication. If the user
3787 * types the wrong _password_, they are sent back to the
3788 * beginning to try another username. (If they specify a
3789 * username in the config, they are never asked, even if they
3790 * do give a wrong password.)
3792 * I think this best serves the needs of
3794 * - the people who have no configuration, no keys, and just
3795 * want to try repeated (username,password) pairs until they
3796 * type both correctly
3798 * - people who have keys and configuration but occasionally
3799 * need to fall back to passwords
3801 * - people with a key held in Pageant, who might not have
3802 * logged in to a particular machine before; so they want to
3803 * type a username, and then _either_ their key will be
3804 * accepted, _or_ they will type a password. If they mistype
3805 * the username they will want to be able to get back and
3817 if (*username
&& !cfg
.change_username
) {
3819 * We got a username last time round this loop, and
3820 * with change_username turned off we don't try to get
3823 } else if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
3825 if (!ssh_get_line("login as: ",
3826 username
, sizeof(username
), FALSE
)) {
3828 * get_line failed to get a username.
3831 logevent("No username provided. Abandoning session.");
3832 ssh_state
= SSH_STATE_CLOSED
;
3836 c_write_str("login as: ");
3839 crWaitUntilV(!ispkt
);
3841 switch (c
= *in
++) {
3850 c_write_str("\b \b");
3857 c_write_str("\b \b");
3867 if (((c
>= ' ' && c
<= '~') ||
3868 ((unsigned char) c
>= 160))
3869 && pos
< sizeof(username
)-1) {
3870 username
[pos
++] = c
;
3877 c_write_str("\r\n");
3878 username
[strcspn(username
, "\n\r")] = '\0';
3881 strncpy(username
, cfg
.username
, 99);
3882 username
[99] = '\0';
3883 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
3884 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
3890 * Send an authentication request using method "none": (a)
3891 * just in case it succeeds, and (b) so that we know what
3892 * authentication methods we can usefully try next.
3894 ssh_pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
3896 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3897 ssh2_pkt_addstring(username
);
3898 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3899 ssh2_pkt_addstring("none"); /* method */
3901 type
= AUTH_TYPE_NONE
;
3905 tried_pubkey_config
= FALSE
;
3906 tried_agent
= FALSE
;
3907 tried_keyb_inter
= FALSE
;
3908 kbd_inter_running
= FALSE
;
3909 /* Load the pub half of cfg.keyfile so we notice if it's in Pageant */
3911 publickey_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, NULL
,
3912 &publickey_bloblen
);
3914 publickey_blob
= NULL
;
3918 * Wait for the result of the last authentication request.
3921 crWaitUntilV(ispkt
);
3922 while (pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
3926 * Don't show the banner if we're operating in
3927 * non-verbose non-interactive mode. (It's probably
3928 * a script, which means nobody will read the
3929 * banner _anyway_, and moreover the printing of
3930 * the banner will screw up processing on the
3931 * output of (say) plink.)
3933 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
3934 ssh2_pkt_getstring(&banner
, &size
);
3936 c_write_untrusted(banner
, size
);
3938 crWaitUntilV(ispkt
);
3940 if (pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
3941 logevent("Access granted");
3946 if (kbd_inter_running
&&
3947 pktin
.type
== SSH2_MSG_USERAUTH_INFO_REQUEST
) {
3949 * This is a further prompt in keyboard-interactive
3950 * authentication. Do nothing.
3952 } else if (pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
3953 bombout(("Strange packet received during authentication: type %d",
3961 * OK, we're now sitting on a USERAUTH_FAILURE message, so
3962 * we can look at the string in it and know what we can
3963 * helpfully try next.
3965 if (pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
) {
3968 ssh2_pkt_getstring(&methods
, &methlen
);
3969 kbd_inter_running
= FALSE
;
3970 if (!ssh2_pkt_getbool()) {
3972 * We have received an unequivocal Access
3973 * Denied. This can translate to a variety of
3976 * - if we'd just tried "none" authentication,
3977 * it's not worth printing anything at all
3979 * - if we'd just tried a public key _offer_,
3980 * the message should be "Server refused our
3981 * key" (or no message at all if the key
3982 * came from Pageant)
3984 * - if we'd just tried anything else, the
3985 * message really should be "Access denied".
3987 * Additionally, if we'd just tried password
3988 * authentication, we should break out of this
3989 * whole loop so as to go back to the username
3992 if (type
== AUTH_TYPE_NONE
) {
3994 } else if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
3995 type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
3996 if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
3997 c_write_str("Server refused our key\r\n");
3998 logevent("Server refused public key");
3999 } else if (type
== AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
) {
4000 /* server declined keyboard-interactive; ignore */
4002 c_write_str("Access denied\r\n");
4003 logevent("Access denied");
4004 if (type
== AUTH_TYPE_PASSWORD
) {
4010 c_write_str("Further authentication required\r\n");
4011 logevent("Further authentication required");
4015 in_commasep_string("publickey", methods
, methlen
);
4017 in_commasep_string("password", methods
, methlen
);
4018 can_keyb_inter
= cfg
.try_ki_auth
&&
4019 in_commasep_string("keyboard-interactive", methods
, methlen
);
4023 ssh_pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4025 if (!method
&& can_pubkey
&& agent_exists() && !tried_agent
) {
4027 * Attempt public-key authentication using Pageant.
4029 static unsigned char request
[5], *response
, *p
;
4030 static int responselen
;
4031 static int i
, nkeys
;
4032 static int authed
= FALSE
;
4035 ssh_pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
4039 logevent("Pageant is running. Requesting keys.");
4041 /* Request the keys held by the agent. */
4042 PUT_32BIT(request
, 1);
4043 request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
4044 agent_query(request
, 5, &r
, &responselen
);
4045 response
= (unsigned char *) r
;
4046 if (response
&& responselen
>= 5 &&
4047 response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
4049 nkeys
= GET_32BIT(p
);
4053 sprintf(buf
, "Pageant has %d SSH2 keys", nkeys
);
4056 for (i
= 0; i
< nkeys
; i
++) {
4057 static char *pkblob
, *alg
, *commentp
;
4058 static int pklen
, alglen
, commentlen
;
4059 static int siglen
, retlen
, len
;
4060 static char *q
, *agentreq
, *ret
;
4065 sprintf(buf
, "Trying Pageant key #%d", i
);
4068 pklen
= GET_32BIT(p
);
4070 if (publickey_blob
&&
4071 pklen
== publickey_bloblen
&&
4072 !memcmp(p
, publickey_blob
, publickey_bloblen
)) {
4073 logevent("This key matches configured key file");
4074 tried_pubkey_config
= 1;
4078 alglen
= GET_32BIT(pkblob
);
4080 commentlen
= GET_32BIT(p
);
4084 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4085 ssh2_pkt_addstring(username
);
4086 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4087 ssh2_pkt_addstring("publickey"); /* method */
4088 ssh2_pkt_addbool(FALSE
); /* no signature included */
4089 ssh2_pkt_addstring_start();
4090 ssh2_pkt_addstring_data(alg
, alglen
);
4091 ssh2_pkt_addstring_start();
4092 ssh2_pkt_addstring_data(pkblob
, pklen
);
4095 crWaitUntilV(ispkt
);
4096 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
4097 logevent("Key refused");
4101 if (flags
& FLAG_VERBOSE
) {
4103 ("Authenticating with public key \"");
4104 c_write(commentp
, commentlen
);
4105 c_write_str("\" from agent\r\n");
4109 * Server is willing to accept the key.
4110 * Construct a SIGN_REQUEST.
4112 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4113 ssh2_pkt_addstring(username
);
4114 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4115 ssh2_pkt_addstring("publickey"); /* method */
4116 ssh2_pkt_addbool(TRUE
);
4117 ssh2_pkt_addstring_start();
4118 ssh2_pkt_addstring_data(alg
, alglen
);
4119 ssh2_pkt_addstring_start();
4120 ssh2_pkt_addstring_data(pkblob
, pklen
);
4122 siglen
= pktout
.length
- 5 + 4 + 20;
4123 len
= 1; /* message type */
4124 len
+= 4 + pklen
; /* key blob */
4125 len
+= 4 + siglen
; /* data to sign */
4126 len
+= 4; /* flags */
4127 agentreq
= smalloc(4 + len
);
4128 PUT_32BIT(agentreq
, len
);
4130 *q
++ = SSH2_AGENTC_SIGN_REQUEST
;
4131 PUT_32BIT(q
, pklen
);
4133 memcpy(q
, pkblob
, pklen
);
4135 PUT_32BIT(q
, siglen
);
4137 /* Now the data to be signed... */
4140 memcpy(q
, ssh2_session_id
, 20);
4142 memcpy(q
, pktout
.data
+ 5, pktout
.length
- 5);
4143 q
+= pktout
.length
- 5;
4144 /* And finally the (zero) flags word. */
4146 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
4150 if (ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
4151 logevent("Sending Pageant's response");
4152 ssh2_pkt_addstring_start();
4153 ssh2_pkt_addstring_data(ret
+ 9,
4161 ("Pageant failed to answer challenge");
4171 if (!method
&& can_pubkey
&& *cfg
.keyfile
4172 && !tried_pubkey_config
) {
4173 unsigned char *pub_blob
;
4174 char *algorithm
, *comment
;
4177 tried_pubkey_config
= TRUE
;
4179 ssh_pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
4182 * Try the public key supplied in the configuration.
4184 * First, offer the public blob to see if the server is
4185 * willing to accept it.
4187 pub_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, &algorithm
,
4190 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4191 ssh2_pkt_addstring(username
);
4192 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4193 ssh2_pkt_addstring("publickey"); /* method */
4194 ssh2_pkt_addbool(FALSE
); /* no signature included */
4195 ssh2_pkt_addstring(algorithm
);
4196 ssh2_pkt_addstring_start();
4197 ssh2_pkt_addstring_data(pub_blob
, pub_blob_len
);
4199 logevent("Offered public key"); /* FIXME */
4201 crWaitUntilV(ispkt
);
4202 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
4204 type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
4205 continue; /* key refused; give up on it */
4208 logevent("Offer of public key accepted");
4210 * Actually attempt a serious authentication using
4213 if (ssh2_userkey_encrypted(cfg
.keyfile
, &comment
)) {
4215 "Passphrase for key \"%.100s\": ",
4221 c_write_str("Authenticating with public key \"");
4222 c_write_str(comment
);
4223 c_write_str("\"\r\n");
4224 method
= AUTH_PUBLICKEY_FILE
;
4228 if (!method
&& can_keyb_inter
&& !tried_keyb_inter
) {
4229 method
= AUTH_KEYBOARD_INTERACTIVE
;
4230 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4231 tried_keyb_inter
= TRUE
;
4233 ssh_pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
4235 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4236 ssh2_pkt_addstring(username
);
4237 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4238 ssh2_pkt_addstring("keyboard-interactive"); /* method */
4239 ssh2_pkt_addstring(""); /* lang */
4240 ssh2_pkt_addstring("");
4243 crWaitUntilV(ispkt
);
4244 if (pktin
.type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
4245 if (pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
)
4247 logevent("Keyboard-interactive authentication refused");
4248 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
;
4252 kbd_inter_running
= TRUE
;
4255 if (kbd_inter_running
) {
4256 method
= AUTH_KEYBOARD_INTERACTIVE
;
4257 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4258 tried_keyb_inter
= TRUE
;
4260 ssh_pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
4262 /* We've got packet with that "interactive" info
4263 dump banners, and set its prompt as ours */
4265 char *name
, *inst
, *lang
, *prompt
;
4266 int name_len
, inst_len
, lang_len
, prompt_len
;
4267 ssh2_pkt_getstring(&name
, &name_len
);
4268 ssh2_pkt_getstring(&inst
, &inst_len
);
4269 ssh2_pkt_getstring(&lang
, &lang_len
);
4271 c_write_untrusted(name
, name_len
);
4273 c_write_untrusted(inst
, inst_len
);
4274 num_prompts
= ssh2_pkt_getuint32();
4276 ssh2_pkt_getstring(&prompt
, &prompt_len
);
4277 strncpy(pwprompt
, prompt
, sizeof(pwprompt
));
4278 pwprompt
[prompt_len
< sizeof(pwprompt
) ?
4279 prompt_len
: sizeof(pwprompt
)-1] = '\0';
4282 echo
= ssh2_pkt_getbool();
4286 if (!method
&& can_passwd
) {
4287 method
= AUTH_PASSWORD
;
4288 ssh_pkt_ctx
|= SSH2_PKTCTX_PASSWORD
;
4289 sprintf(pwprompt
, "%.90s@%.90s's password: ", username
,
4296 if (!ssh_get_line(pwprompt
, password
,
4297 sizeof(password
), TRUE
)) {
4299 * get_line failed to get a password (for
4300 * example because one was supplied on the
4301 * command line which has already failed to
4304 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4305 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4307 ("No more passwords available to try");
4308 ssh2_pkt_addstring("en"); /* language tag */
4310 connection_fatal("Unable to authenticate");
4311 ssh_state
= SSH_STATE_CLOSED
;
4318 c_write_untrusted(pwprompt
, strlen(pwprompt
));
4323 crWaitUntilV(!ispkt
);
4325 switch (c
= *in
++) {
4346 if (pos
< sizeof(password
)-1)
4347 password
[pos
++] = c
;
4351 c_write_str("\r\n");
4355 if (method
== AUTH_PUBLICKEY_FILE
) {
4357 * We have our passphrase. Now try the actual authentication.
4359 struct ssh2_userkey
*key
;
4361 key
= ssh2_load_userkey(cfg
.keyfile
, password
);
4362 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
4363 if (key
== SSH2_WRONG_PASSPHRASE
) {
4364 c_write_str("Wrong passphrase\r\n");
4365 tried_pubkey_config
= FALSE
;
4367 c_write_str("Unable to load private key\r\n");
4368 tried_pubkey_config
= TRUE
;
4370 /* Send a spurious AUTH_NONE to return to the top. */
4371 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4372 ssh2_pkt_addstring(username
);
4373 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4374 ssh2_pkt_addstring("none"); /* method */
4376 type
= AUTH_TYPE_NONE
;
4378 unsigned char *blob
, *sigdata
;
4379 int blob_len
, sigdata_len
;
4382 * We have loaded the private key and the server
4383 * has announced that it's willing to accept it.
4384 * Hallelujah. Generate a signature and send it.
4386 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4387 ssh2_pkt_addstring(username
);
4388 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4389 ssh2_pkt_addstring("publickey"); /* method */
4390 ssh2_pkt_addbool(TRUE
);
4391 ssh2_pkt_addstring(key
->alg
->name
);
4392 blob
= key
->alg
->public_blob(key
->data
, &blob_len
);
4393 ssh2_pkt_addstring_start();
4394 ssh2_pkt_addstring_data(blob
, blob_len
);
4398 * The data to be signed is:
4402 * followed by everything so far placed in the
4405 sigdata_len
= pktout
.length
- 5 + 4 + 20;
4406 sigdata
= smalloc(sigdata_len
);
4407 PUT_32BIT(sigdata
, 20);
4408 memcpy(sigdata
+ 4, ssh2_session_id
, 20);
4409 memcpy(sigdata
+ 24, pktout
.data
+ 5,
4412 key
->alg
->sign(key
->data
, sigdata
, sigdata_len
,
4414 ssh2_pkt_addstring_start();
4415 ssh2_pkt_addstring_data(blob
, blob_len
);
4420 type
= AUTH_TYPE_PUBLICKEY
;
4422 } else if (method
== AUTH_PASSWORD
) {
4424 * We send the password packet lumped tightly together with
4425 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4426 * string long enough to make the total length of the two
4427 * packets constant. This should ensure that a passive
4428 * listener doing traffic analyis can't work out the length
4431 * For this to work, we need an assumption about the
4432 * maximum length of the password packet. I think 256 is
4433 * pretty conservative. Anyone using a password longer than
4434 * that probably doesn't have much to worry about from
4435 * people who find out how long their password is!
4437 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4438 ssh2_pkt_addstring(username
);
4439 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4440 ssh2_pkt_addstring("password");
4441 ssh2_pkt_addbool(FALSE
);
4442 ssh2_pkt_addstring(password
);
4445 * We'll include a string that's an exact multiple of the
4446 * cipher block size. If the cipher is NULL for some
4447 * reason, we don't do this trick at all because we gain
4453 stringlen
= (256 - deferred_len
);
4454 stringlen
+= cscipher
->blksize
- 1;
4455 stringlen
-= (stringlen
% cscipher
->blksize
);
4458 * Temporarily disable actual compression,
4459 * so we can guarantee to get this string
4460 * exactly the length we want it. The
4461 * compression-disabling routine should
4462 * return an integer indicating how many
4463 * bytes we should adjust our string length
4466 stringlen
-= cscomp
->disable_compression();
4468 ssh2_pkt_init(SSH2_MSG_IGNORE
);
4469 ssh2_pkt_addstring_start();
4470 for (i
= 0; i
< stringlen
; i
++) {
4471 char c
= (char) random_byte();
4472 ssh2_pkt_addstring_data(&c
, 1);
4476 ssh_pkt_defersend();
4477 logevent("Sent password");
4478 type
= AUTH_TYPE_PASSWORD
;
4479 } else if (method
== AUTH_KEYBOARD_INTERACTIVE
) {
4480 ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE
);
4481 ssh2_pkt_adduint32(num_prompts
);
4482 ssh2_pkt_addstring(password
);
4483 memset(password
, 0, sizeof(password
));
4485 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4488 ("No supported authentication methods left to try!\r\n");
4490 ("No supported authentications offered. Disconnecting");
4491 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4492 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4494 ("No supported authentication methods available");
4495 ssh2_pkt_addstring("en"); /* language tag */
4497 ssh_state
= SSH_STATE_CLOSED
;
4501 } while (!we_are_in
);
4504 * Now we're authenticated for the connection protocol. The
4505 * connection protocol will automatically have started at this
4506 * point; there's no need to send SERVICE_REQUEST.
4510 * So now create a channel with a session in it.
4512 ssh_channels
= newtree234(ssh_channelcmp
);
4513 mainchan
= smalloc(sizeof(struct ssh_channel
));
4514 mainchan
->localid
= alloc_channel_id();
4515 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
4516 ssh2_pkt_addstring("session");
4517 ssh2_pkt_adduint32(mainchan
->localid
);
4518 mainchan
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
4519 ssh2_pkt_adduint32(mainchan
->v
.v2
.locwindow
); /* our window size */
4520 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
4522 crWaitUntilV(ispkt
);
4523 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
4524 bombout(("Server refused to open a session"));
4526 /* FIXME: error data comes back in FAILURE packet */
4528 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
4529 bombout(("Server's channel confirmation cited wrong channel"));
4532 mainchan
->remoteid
= ssh2_pkt_getuint32();
4533 mainchan
->type
= CHAN_MAINSESSION
;
4534 mainchan
->closes
= 0;
4535 mainchan
->v
.v2
.remwindow
= ssh2_pkt_getuint32();
4536 mainchan
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
4537 bufchain_init(&mainchan
->v
.v2
.outbuffer
);
4538 add234(ssh_channels
, mainchan
);
4539 logevent("Opened channel for session");
4542 * Potentially enable X11 forwarding.
4544 if (cfg
.x11_forward
) {
4545 char proto
[20], data
[64];
4546 logevent("Requesting X11 forwarding");
4547 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
4548 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4549 ssh2_pkt_adduint32(mainchan
->remoteid
);
4550 ssh2_pkt_addstring("x11-req");
4551 ssh2_pkt_addbool(1); /* want reply */
4552 ssh2_pkt_addbool(0); /* many connections */
4553 ssh2_pkt_addstring(proto
);
4554 ssh2_pkt_addstring(data
);
4555 ssh2_pkt_adduint32(0); /* screen number */
4559 crWaitUntilV(ispkt
);
4560 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4561 unsigned i
= ssh2_pkt_getuint32();
4562 struct ssh_channel
*c
;
4563 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4565 continue; /* nonexistent channel */
4566 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4568 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4570 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4571 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4572 bombout(("Unexpected response to X11 forwarding request:"
4573 " packet type %d", pktin
.type
));
4576 logevent("X11 forwarding refused");
4578 logevent("X11 forwarding enabled");
4579 ssh_X11_fwd_enabled
= TRUE
;
4584 * Enable port forwardings.
4587 static char *e
; /* preserve across crReturn */
4591 char sports
[256], dports
[256], host
[256];
4594 ssh_rportfwds
= newtree234(ssh_rportcmp_ssh2
);
4595 /* Add port forwardings. */
4600 while (*e
&& *e
!= '\t')
4606 while (*e
&& *e
!= ':')
4616 dport
= atoi(dports
);
4617 sport
= atoi(sports
);
4618 if (sport
&& dport
) {
4620 pfd_addforward(host
, dport
, sport
);
4621 sprintf(buf
, "Local port %d forwarding to %s:%d",
4622 sport
, host
, dport
);
4625 struct ssh_rportfwd
*pf
;
4626 pf
= smalloc(sizeof(*pf
));
4627 strcpy(pf
->dhost
, host
);
4630 if (add234(ssh_rportfwds
, pf
) != pf
) {
4632 "Duplicate remote port forwarding to %s:%d",
4637 sprintf(buf
, "Requesting remote port %d (forwarded to %s:%d)",
4638 sport
, host
, dport
);
4640 ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
4641 ssh2_pkt_addstring("tcpip-forward");
4642 ssh2_pkt_addbool(1);/* want reply */
4643 if (cfg
.rport_acceptall
)
4644 ssh2_pkt_addstring("0.0.0.0");
4646 ssh2_pkt_addstring("127.0.0.1");
4647 ssh2_pkt_adduint32(sport
);
4651 crWaitUntilV(ispkt
);
4652 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4653 unsigned i
= ssh2_pkt_getuint32();
4654 struct ssh_channel
*c
;
4655 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4657 continue;/* nonexistent channel */
4658 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4660 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4662 if (pktin
.type
!= SSH2_MSG_REQUEST_SUCCESS
) {
4663 if (pktin
.type
!= SSH2_MSG_REQUEST_FAILURE
) {
4664 bombout(("Unexpected response to port "
4665 "forwarding request: packet type %d",
4669 logevent("Server refused this port forwarding");
4671 logevent("Remote port forwarding enabled");
4680 * Potentially enable agent forwarding.
4682 if (cfg
.agentfwd
&& agent_exists()) {
4683 logevent("Requesting OpenSSH-style agent forwarding");
4684 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4685 ssh2_pkt_adduint32(mainchan
->remoteid
);
4686 ssh2_pkt_addstring("auth-agent-req@openssh.com");
4687 ssh2_pkt_addbool(1); /* want reply */
4691 crWaitUntilV(ispkt
);
4692 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4693 unsigned i
= ssh2_pkt_getuint32();
4694 struct ssh_channel
*c
;
4695 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4697 continue; /* nonexistent channel */
4698 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4700 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4702 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4703 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4704 bombout(("Unexpected response to agent forwarding request:"
4705 " packet type %d", pktin
.type
));
4708 logevent("Agent forwarding refused");
4710 logevent("Agent forwarding enabled");
4711 ssh_agentfwd_enabled
= TRUE
;
4716 * Now allocate a pty for the session.
4719 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4720 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
4721 ssh2_pkt_addstring("pty-req");
4722 ssh2_pkt_addbool(1); /* want reply */
4723 ssh2_pkt_addstring(cfg
.termtype
);
4724 ssh2_pkt_adduint32(cols
);
4725 ssh2_pkt_adduint32(rows
);
4726 ssh2_pkt_adduint32(0); /* pixel width */
4727 ssh2_pkt_adduint32(0); /* pixel height */
4728 ssh2_pkt_addstring_start();
4729 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
4731 ssh_state
= SSH_STATE_INTERMED
;
4734 crWaitUntilV(ispkt
);
4735 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4736 unsigned i
= ssh2_pkt_getuint32();
4737 struct ssh_channel
*c
;
4738 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4740 continue; /* nonexistent channel */
4741 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4743 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4745 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4746 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4747 bombout(("Unexpected response to pty request:"
4748 " packet type %d", pktin
.type
));
4751 c_write_str("Server refused to allocate pty\r\n");
4752 ssh_editing
= ssh_echoing
= 1;
4754 logevent("Allocated pty");
4757 ssh_editing
= ssh_echoing
= 1;
4761 * Start a shell or a remote command. We may have to attempt
4762 * this twice if the config data has provided a second choice
4769 if (ssh_fallback_cmd
) {
4770 subsys
= cfg
.ssh_subsys2
;
4771 cmd
= cfg
.remote_cmd_ptr2
;
4773 subsys
= cfg
.ssh_subsys
;
4774 cmd
= cfg
.remote_cmd_ptr
;
4777 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4778 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
4780 ssh2_pkt_addstring("subsystem");
4781 ssh2_pkt_addbool(1); /* want reply */
4782 ssh2_pkt_addstring(cmd
);
4784 ssh2_pkt_addstring("exec");
4785 ssh2_pkt_addbool(1); /* want reply */
4786 ssh2_pkt_addstring(cmd
);
4788 ssh2_pkt_addstring("shell");
4789 ssh2_pkt_addbool(1); /* want reply */
4793 crWaitUntilV(ispkt
);
4794 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4795 unsigned i
= ssh2_pkt_getuint32();
4796 struct ssh_channel
*c
;
4797 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4799 continue; /* nonexistent channel */
4800 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4802 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4803 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4804 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4805 bombout(("Unexpected response to shell/command request:"
4806 " packet type %d", pktin
.type
));
4810 * We failed to start the command. If this is the
4811 * fallback command, we really are finished; if it's
4812 * not, and if the fallback command exists, try falling
4813 * back to it before complaining.
4815 if (!ssh_fallback_cmd
&& cfg
.remote_cmd_ptr2
!= NULL
) {
4816 logevent("Primary command failed; attempting fallback");
4817 ssh_fallback_cmd
= TRUE
;
4820 bombout(("Server refused to start a shell/command"));
4823 logevent("Started a shell/command");
4828 ssh_state
= SSH_STATE_SESSION
;
4832 ssh_special(TS_EOF
);
4837 ldisc_send(NULL
, 0, 0); /* cause ldisc to notice changes */
4840 static int try_send
;
4844 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
4845 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
4848 unsigned i
= ssh2_pkt_getuint32();
4849 struct ssh_channel
*c
;
4850 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4852 continue; /* nonexistent channel */
4853 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
4854 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
4855 continue; /* extended but not stderr */
4856 ssh2_pkt_getstring(&data
, &length
);
4859 c
->v
.v2
.locwindow
-= length
;
4861 case CHAN_MAINSESSION
:
4863 from_backend(pktin
.type
==
4864 SSH2_MSG_CHANNEL_EXTENDED_DATA
,
4868 bufsize
= x11_send(c
->u
.x11
.s
, data
, length
);
4871 bufsize
= pfd_send(c
->u
.pfd
.s
, data
, length
);
4874 while (length
> 0) {
4875 if (c
->u
.a
.lensofar
< 4) {
4876 int l
= min(4 - c
->u
.a
.lensofar
, length
);
4877 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
4881 c
->u
.a
.lensofar
+= l
;
4883 if (c
->u
.a
.lensofar
== 4) {
4885 4 + GET_32BIT(c
->u
.a
.msglen
);
4886 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
4887 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
4889 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
4891 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
4893 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
4897 c
->u
.a
.lensofar
+= l
;
4899 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
4900 void *reply
, *sentreply
;
4902 agent_query(c
->u
.a
.message
,
4903 c
->u
.a
.totallen
, &reply
,
4908 /* Fake SSH_AGENT_FAILURE. */
4909 sentreply
= "\0\0\0\1\5";
4912 ssh2_add_channel_data(c
, sentreply
,
4917 sfree(c
->u
.a
.message
);
4918 c
->u
.a
.lensofar
= 0;
4925 * If we are not buffering too much data,
4926 * enlarge the window again at the remote side.
4928 if (bufsize
< OUR_V2_WINSIZE
)
4929 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
4931 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
4932 ssh_state
= SSH_STATE_CLOSED
;
4933 logevent("Received disconnect message");
4935 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
4936 unsigned i
= ssh2_pkt_getuint32();
4937 struct ssh_channel
*c
;
4939 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4941 continue; /* nonexistent channel */
4943 if (c
->type
== CHAN_X11
) {
4945 * Remote EOF on an X11 channel means we should
4946 * wrap up and close the channel ourselves.
4948 x11_close(c
->u
.x11
.s
);
4950 } else if (c
->type
== CHAN_AGENT
) {
4952 } else if (c
->type
== CHAN_SOCKDATA
) {
4953 pfd_close(c
->u
.pfd
.s
);
4956 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
4957 unsigned i
= ssh2_pkt_getuint32();
4958 struct ssh_channel
*c
;
4960 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4962 continue; /* nonexistent channel */
4963 /* Do pre-close processing on the channel. */
4965 case CHAN_MAINSESSION
:
4966 break; /* nothing to see here, move along */
4968 if (c
->u
.x11
.s
!= NULL
)
4969 x11_close(c
->u
.x11
.s
);
4976 if (c
->u
.pfd
.s
!= NULL
)
4977 pfd_close(c
->u
.pfd
.s
);
4981 if (c
->closes
== 0) {
4982 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
4983 ssh2_pkt_adduint32(c
->remoteid
);
4986 del234(ssh_channels
, c
);
4987 bufchain_clear(&c
->v
.v2
.outbuffer
);
4991 * See if that was the last channel left open.
4993 if (count234(ssh_channels
) == 0) {
4996 * We used to send SSH_MSG_DISCONNECT here,
4997 * because I'd believed that _every_ conforming
4998 * SSH2 connection had to end with a disconnect
4999 * being sent by at least one side; apparently
5000 * I was wrong and it's perfectly OK to
5001 * unceremoniously slam the connection shut
5002 * when you're done, and indeed OpenSSH feels
5003 * this is more polite than sending a
5004 * DISCONNECT. So now we don't.
5006 logevent("All channels closed. Disconnecting");
5007 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
5008 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
5009 ssh2_pkt_addstring("All open channels closed");
5010 ssh2_pkt_addstring("en"); /* language tag */
5013 ssh_state
= SSH_STATE_CLOSED
;
5016 continue; /* remote sends close; ignore (FIXME) */
5017 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
5018 unsigned i
= ssh2_pkt_getuint32();
5019 struct ssh_channel
*c
;
5020 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5022 continue; /* nonexistent channel */
5023 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
5025 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
5026 unsigned i
= ssh2_pkt_getuint32();
5027 struct ssh_channel
*c
;
5028 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5030 continue; /* nonexistent channel */
5031 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
5032 continue; /* dunno why they're confirming this */
5033 c
->remoteid
= ssh2_pkt_getuint32();
5034 c
->type
= CHAN_SOCKDATA
;
5035 c
->v
.v2
.remwindow
= ssh2_pkt_getuint32();
5036 c
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
5037 bufchain_init(&c
->v
.v2
.outbuffer
);
5039 pfd_confirm(c
->u
.pfd
.s
);
5042 * We have a pending close on this channel,
5043 * which we decided on before the server acked
5044 * the channel open. So now we know the
5045 * remoteid, we can close it again.
5047 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
5048 ssh2_pkt_adduint32(c
->remoteid
);
5051 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN_FAILURE
) {
5052 unsigned i
= ssh2_pkt_getuint32();
5053 struct ssh_channel
*c
;
5054 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5056 continue; /* nonexistent channel */
5057 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
5058 continue; /* dunno why they're failing this */
5060 logevent("Forwarded connection refused by server");
5062 pfd_close(c
->u
.pfd
.s
);
5064 del234(ssh_channels
, c
);
5066 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
5069 int typelen
, want_reply
;
5070 struct ssh_channel
*c
;
5072 localid
= ssh2_pkt_getuint32();
5073 ssh2_pkt_getstring(&type
, &typelen
);
5074 want_reply
= ssh2_pkt_getbool();
5077 * First, check that the channel exists. Otherwise,
5078 * we can instantly disconnect with a rude message.
5080 c
= find234(ssh_channels
, &localid
, ssh_channelfind
);
5083 sprintf(buf
, "Received channel request for nonexistent"
5084 " channel %d", localid
);
5086 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
5087 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
5088 ssh2_pkt_addstring(buf
);
5089 ssh2_pkt_addstring("en"); /* language tag */
5091 connection_fatal(buf
);
5092 ssh_state
= SSH_STATE_CLOSED
;
5097 * Having got the channel number, we now look at
5098 * the request type string to see if it's something
5101 if (typelen
== 11 && !memcmp(type
, "exit-status", 11) &&
5103 /* We recognise "exit-status" on the primary channel. */
5105 ssh_exitcode
= ssh2_pkt_getuint32();
5106 sprintf(buf
, "Server sent command exit status %d",
5110 ssh2_pkt_init(SSH2_MSG_CHANNEL_SUCCESS
);
5111 ssh2_pkt_adduint32(c
->remoteid
);
5116 * This is a channel request we don't know
5117 * about, so we now either ignore the request
5118 * or respond with CHANNEL_FAILURE, depending
5122 ssh2_pkt_init(SSH2_MSG_CHANNEL_FAILURE
);
5123 ssh2_pkt_adduint32(c
->remoteid
);
5127 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
5131 struct ssh_channel
*c
;
5132 unsigned remid
, winsize
, pktsize
;
5133 ssh2_pkt_getstring(&type
, &typelen
);
5134 c
= smalloc(sizeof(struct ssh_channel
));
5136 remid
= ssh2_pkt_getuint32();
5137 winsize
= ssh2_pkt_getuint32();
5138 pktsize
= ssh2_pkt_getuint32();
5140 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
5141 if (!ssh_X11_fwd_enabled
)
5142 error
= "X11 forwarding is not enabled";
5143 else if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) !=
5145 error
= "Unable to open an X11 connection";
5149 } else if (typelen
== 15 &&
5150 !memcmp(type
, "forwarded-tcpip", 15)) {
5151 struct ssh_rportfwd pf
, *realpf
;
5154 ssh2_pkt_getstring(&dummy
, &dummylen
);/* skip address */
5155 pf
.sport
= ssh2_pkt_getuint32();
5156 realpf
= find234(ssh_rportfwds
, &pf
, NULL
);
5157 if (realpf
== NULL
) {
5158 error
= "Remote port is not recognised";
5160 char *e
= pfd_newconnect(&c
->u
.pfd
.s
, realpf
->dhost
,
5163 sprintf(buf
, "Received remote port open request for %s:%d",
5164 realpf
->dhost
, realpf
->dport
);
5167 sprintf(buf
, "Port open failed: %s", e
);
5169 error
= "Port open failed";
5171 logevent("Forwarded port opened successfully");
5172 c
->type
= CHAN_SOCKDATA
;
5175 } else if (typelen
== 22 &&
5176 !memcmp(type
, "auth-agent@openssh.com", 3)) {
5177 if (!ssh_agentfwd_enabled
)
5178 error
= "Agent forwarding is not enabled";
5180 c
->type
= CHAN_AGENT
; /* identify channel type */
5181 c
->u
.a
.lensofar
= 0;
5184 error
= "Unsupported channel type requested";
5187 c
->remoteid
= remid
;
5189 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
5190 ssh2_pkt_adduint32(c
->remoteid
);
5191 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED
);
5192 ssh2_pkt_addstring(error
);
5193 ssh2_pkt_addstring("en"); /* language tag */
5197 c
->localid
= alloc_channel_id();
5199 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
5200 c
->v
.v2
.remwindow
= winsize
;
5201 c
->v
.v2
.remmaxpkt
= pktsize
;
5202 bufchain_init(&c
->v
.v2
.outbuffer
);
5203 add234(ssh_channels
, c
);
5204 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
5205 ssh2_pkt_adduint32(c
->remoteid
);
5206 ssh2_pkt_adduint32(c
->localid
);
5207 ssh2_pkt_adduint32(c
->v
.v2
.locwindow
);
5208 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
5212 bombout(("Strange packet received: type %d", pktin
.type
));
5217 * We have spare data. Add it to the channel buffer.
5219 ssh2_add_channel_data(mainchan
, in
, inlen
);
5224 struct ssh_channel
*c
;
5226 * Try to send data on all channels if we can.
5228 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++) {
5229 int bufsize
= ssh2_try_send(c
);
5232 case CHAN_MAINSESSION
:
5233 /* stdin need not receive an unthrottle
5234 * notification since it will be polled */
5237 x11_unthrottle(c
->u
.x11
.s
);
5240 /* agent sockets are request/response and need no
5241 * buffer management */
5244 pfd_unthrottle(c
->u
.pfd
.s
);
5256 * Handle the top-level SSH2 protocol.
5258 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
5260 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
5262 do_ssh2_authconn(in
, inlen
, ispkt
);
5266 * Called to set up the connection.
5268 * Returns an error message, or NULL on success.
5270 static char *ssh_init(char *host
, int port
, char **realhost
, int nodelay
)
5275 if (crypto_startup() == 0)
5276 return "Microsoft high encryption pack not installed!";
5282 ssh1_throttle_count
= 0;
5283 ssh_overall_bufsize
= 0;
5284 ssh_fallback_cmd
= 0;
5286 p
= connect_to_host(host
, port
, realhost
, nodelay
);
5294 * Called to send data down the Telnet connection.
5296 static int ssh_send(char *buf
, int len
)
5298 if (s
== NULL
|| ssh_protocol
== NULL
)
5301 ssh_protocol(buf
, len
, 0);
5303 return ssh_sendbuffer();
5307 * Called to query the current amount of buffered stdin data.
5309 static int ssh_sendbuffer(void)
5313 if (s
== NULL
|| ssh_protocol
== NULL
)
5317 * If the SSH socket itself has backed up, add the total backup
5318 * size on that to any individual buffer on the stdin channel.
5321 if (ssh_throttled_all
)
5322 override_value
= ssh_overall_bufsize
;
5324 if (ssh_version
== 1) {
5325 return override_value
;
5326 } else if (ssh_version
== 2) {
5327 if (!mainchan
|| mainchan
->closes
> 0)
5328 return override_value
;
5330 return override_value
+ bufchain_size(&mainchan
->v
.v2
.outbuffer
);
5337 * Called to set the size of the window from SSH's POV.
5339 static void ssh_size(void)
5341 switch (ssh_state
) {
5342 case SSH_STATE_BEFORE_SIZE
:
5343 case SSH_STATE_PREPACKET
:
5344 case SSH_STATE_CLOSED
:
5345 break; /* do nothing */
5346 case SSH_STATE_INTERMED
:
5347 size_needed
= TRUE
; /* buffer for later */
5349 case SSH_STATE_SESSION
:
5351 if (ssh_version
== 1) {
5352 send_packet(SSH1_CMSG_WINDOW_SIZE
,
5353 PKT_INT
, rows
, PKT_INT
, cols
,
5354 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
5356 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
5357 ssh2_pkt_adduint32(mainchan
->remoteid
);
5358 ssh2_pkt_addstring("window-change");
5359 ssh2_pkt_addbool(0);
5360 ssh2_pkt_adduint32(cols
);
5361 ssh2_pkt_adduint32(rows
);
5362 ssh2_pkt_adduint32(0);
5363 ssh2_pkt_adduint32(0);
5372 * Send Telnet special codes. TS_EOF is useful for `plink', so you
5373 * can send an EOF and collect resulting output (e.g. `plink
5376 static void ssh_special(Telnet_Special code
)
5378 if (code
== TS_EOF
) {
5379 if (ssh_state
!= SSH_STATE_SESSION
) {
5381 * Buffer the EOF in case we are pre-SESSION, so we can
5382 * send it as soon as we reach SESSION.
5388 if (ssh_version
== 1) {
5389 send_packet(SSH1_CMSG_EOF
, PKT_END
);
5391 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
5392 ssh2_pkt_adduint32(mainchan
->remoteid
);
5395 logevent("Sent EOF message");
5396 } else if (code
== TS_PING
) {
5397 if (ssh_state
== SSH_STATE_CLOSED
5398 || ssh_state
== SSH_STATE_PREPACKET
) return;
5399 if (ssh_version
== 1) {
5400 send_packet(SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
5402 ssh2_pkt_init(SSH2_MSG_IGNORE
);
5403 ssh2_pkt_addstring_start();
5411 void *new_sock_channel(Socket s
)
5413 struct ssh_channel
*c
;
5414 c
= smalloc(sizeof(struct ssh_channel
));
5417 c
->remoteid
= -1; /* to be set when open confirmed */
5418 c
->localid
= alloc_channel_id();
5420 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
5422 add234(ssh_channels
, c
);
5428 * This is called when stdout/stderr (the entity to which
5429 * from_backend sends data) manages to clear some backlog.
5431 void ssh_unthrottle(int bufsize
)
5433 if (ssh_version
== 1) {
5434 if (ssh1_stdout_throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
5435 ssh1_stdout_throttling
= 0;
5439 if (mainchan
&& mainchan
->closes
== 0)
5440 ssh2_set_window(mainchan
, OUR_V2_WINSIZE
- bufsize
);
5444 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
5446 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
5449 sprintf(buf
, "Opening forwarded connection to %.512s:%d", hostname
, port
);
5452 if (ssh_version
== 1) {
5453 send_packet(SSH1_MSG_PORT_OPEN
,
5454 PKT_INT
, c
->localid
,
5457 //PKT_STR, <org:orgport>,
5460 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
5461 ssh2_pkt_addstring("direct-tcpip");
5462 ssh2_pkt_adduint32(c
->localid
);
5463 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
5464 ssh2_pkt_adduint32(c
->v
.v2
.locwindow
);/* our window size */
5465 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
5466 ssh2_pkt_addstring(hostname
);
5467 ssh2_pkt_adduint32(port
);
5469 * We make up values for the originator data; partly it's
5470 * too much hassle to keep track, and partly I'm not
5471 * convinced the server should be told details like that
5472 * about my local network configuration.
5474 ssh2_pkt_addstring("client-side-connection");
5475 ssh2_pkt_adduint32(0);
5481 static Socket
ssh_socket(void)
5486 static int ssh_sendok(void)
5491 static int ssh_ldisc(int option
)
5493 if (option
== LD_ECHO
)
5495 if (option
== LD_EDIT
)
5500 static int ssh_return_exitcode(void)
5502 return ssh_exitcode
;
5505 Backend ssh_backend
= {
5512 ssh_return_exitcode
,