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
171 #define BUG_CHOKES_ON_RSA 8
173 static int ssh_pkt_ctx
= 0;
175 #define translate(x) if (type == x) return #x
176 #define translatec(x,ctx) if (type == x && (ssh_pkt_ctx & ctx)) return #x
177 char *ssh1_pkt_type(int type
)
179 translate(SSH1_MSG_DISCONNECT
);
180 translate(SSH1_SMSG_PUBLIC_KEY
);
181 translate(SSH1_CMSG_SESSION_KEY
);
182 translate(SSH1_CMSG_USER
);
183 translate(SSH1_CMSG_AUTH_RSA
);
184 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE
);
185 translate(SSH1_CMSG_AUTH_RSA_RESPONSE
);
186 translate(SSH1_CMSG_AUTH_PASSWORD
);
187 translate(SSH1_CMSG_REQUEST_PTY
);
188 translate(SSH1_CMSG_WINDOW_SIZE
);
189 translate(SSH1_CMSG_EXEC_SHELL
);
190 translate(SSH1_CMSG_EXEC_CMD
);
191 translate(SSH1_SMSG_SUCCESS
);
192 translate(SSH1_SMSG_FAILURE
);
193 translate(SSH1_CMSG_STDIN_DATA
);
194 translate(SSH1_SMSG_STDOUT_DATA
);
195 translate(SSH1_SMSG_STDERR_DATA
);
196 translate(SSH1_CMSG_EOF
);
197 translate(SSH1_SMSG_EXIT_STATUS
);
198 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
);
199 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE
);
200 translate(SSH1_MSG_CHANNEL_DATA
);
201 translate(SSH1_MSG_CHANNEL_CLOSE
);
202 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
);
203 translate(SSH1_SMSG_X11_OPEN
);
204 translate(SSH1_CMSG_PORT_FORWARD_REQUEST
);
205 translate(SSH1_MSG_PORT_OPEN
);
206 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING
);
207 translate(SSH1_SMSG_AGENT_OPEN
);
208 translate(SSH1_MSG_IGNORE
);
209 translate(SSH1_CMSG_EXIT_CONFIRMATION
);
210 translate(SSH1_CMSG_X11_REQUEST_FORWARDING
);
211 translate(SSH1_CMSG_AUTH_RHOSTS_RSA
);
212 translate(SSH1_MSG_DEBUG
);
213 translate(SSH1_CMSG_REQUEST_COMPRESSION
);
214 translate(SSH1_CMSG_AUTH_TIS
);
215 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE
);
216 translate(SSH1_CMSG_AUTH_TIS_RESPONSE
);
217 translate(SSH1_CMSG_AUTH_CCARD
);
218 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE
);
219 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE
);
222 char *ssh2_pkt_type(int type
)
224 translate(SSH2_MSG_DISCONNECT
);
225 translate(SSH2_MSG_IGNORE
);
226 translate(SSH2_MSG_UNIMPLEMENTED
);
227 translate(SSH2_MSG_DEBUG
);
228 translate(SSH2_MSG_SERVICE_REQUEST
);
229 translate(SSH2_MSG_SERVICE_ACCEPT
);
230 translate(SSH2_MSG_KEXINIT
);
231 translate(SSH2_MSG_NEWKEYS
);
232 translatec(SSH2_MSG_KEXDH_INIT
, SSH2_PKTCTX_DHGROUP1
);
233 translatec(SSH2_MSG_KEXDH_REPLY
, SSH2_PKTCTX_DHGROUP1
);
234 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST
, SSH2_PKTCTX_DHGEX
);
235 translatec(SSH2_MSG_KEX_DH_GEX_GROUP
, SSH2_PKTCTX_DHGEX
);
236 translatec(SSH2_MSG_KEX_DH_GEX_INIT
, SSH2_PKTCTX_DHGEX
);
237 translatec(SSH2_MSG_KEX_DH_GEX_REPLY
, SSH2_PKTCTX_DHGEX
);
238 translate(SSH2_MSG_USERAUTH_REQUEST
);
239 translate(SSH2_MSG_USERAUTH_FAILURE
);
240 translate(SSH2_MSG_USERAUTH_SUCCESS
);
241 translate(SSH2_MSG_USERAUTH_BANNER
);
242 translatec(SSH2_MSG_USERAUTH_PK_OK
, SSH2_PKTCTX_PUBLICKEY
);
243 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ
, SSH2_PKTCTX_PASSWORD
);
244 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST
, SSH2_PKTCTX_KBDINTER
);
245 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE
, SSH2_PKTCTX_KBDINTER
);
246 translate(SSH2_MSG_GLOBAL_REQUEST
);
247 translate(SSH2_MSG_REQUEST_SUCCESS
);
248 translate(SSH2_MSG_REQUEST_FAILURE
);
249 translate(SSH2_MSG_CHANNEL_OPEN
);
250 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
251 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
252 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
253 translate(SSH2_MSG_CHANNEL_DATA
);
254 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA
);
255 translate(SSH2_MSG_CHANNEL_EOF
);
256 translate(SSH2_MSG_CHANNEL_CLOSE
);
257 translate(SSH2_MSG_CHANNEL_REQUEST
);
258 translate(SSH2_MSG_CHANNEL_SUCCESS
);
259 translate(SSH2_MSG_CHANNEL_FAILURE
);
265 #define GET_32BIT(cp) \
266 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
267 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
268 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
269 ((unsigned long)(unsigned char)(cp)[3]))
271 #define PUT_32BIT(cp, value) { \
272 (cp)[0] = (unsigned char)((value) >> 24); \
273 (cp)[1] = (unsigned char)((value) >> 16); \
274 (cp)[2] = (unsigned char)((value) >> 8); \
275 (cp)[3] = (unsigned char)(value); }
277 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
279 /* Coroutine mechanics for the sillier bits of the code */
280 #define crBegin1 static int crLine = 0;
281 #define crBegin2 switch(crLine) { case 0:;
282 #define crBegin crBegin1; crBegin2;
283 #define crFinish(z) } crLine = 0; return (z)
284 #define crFinishV } crLine = 0; return
285 #define crReturn(z) \
287 crLine=__LINE__; return (z); case __LINE__:;\
291 crLine=__LINE__; return; case __LINE__:;\
293 #define crStop(z) do{ crLine = 0; return (z); }while(0)
294 #define crStopV do{ crLine = 0; return; }while(0)
295 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
296 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
298 extern char *x11_init(Socket
*, char *, void *);
299 extern void x11_close(Socket
);
300 extern int x11_send(Socket
, char *, int);
301 extern void x11_invent_auth(char *, int, char *, int);
302 extern void x11_unthrottle(Socket s
);
303 extern void x11_override_throttle(Socket s
, int enable
);
305 extern char *pfd_newconnect(Socket
* s
, char *hostname
, int port
, void *c
);
306 extern char *pfd_addforward(char *desthost
, int destport
, int port
);
307 extern void pfd_close(Socket s
);
308 extern int pfd_send(Socket s
, char *data
, int len
);
309 extern void pfd_confirm(Socket s
);
310 extern void pfd_unthrottle(Socket s
);
311 extern void pfd_override_throttle(Socket s
, int enable
);
313 static void ssh2_pkt_init(int pkt_type
);
314 static void ssh2_pkt_addbool(unsigned char value
);
315 static void ssh2_pkt_adduint32(unsigned long value
);
316 static void ssh2_pkt_addstring_start(void);
317 static void ssh2_pkt_addstring_str(char *data
);
318 static void ssh2_pkt_addstring_data(char *data
, int len
);
319 static void ssh2_pkt_addstring(char *data
);
320 static char *ssh2_mpint_fmt(Bignum b
, int *len
);
321 static void ssh2_pkt_addmp(Bignum b
);
322 static int ssh2_pkt_construct(void);
323 static void ssh2_pkt_send(void);
326 * Buffer management constants. There are several of these for
327 * various different purposes:
329 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
330 * on a local data stream before we throttle the whole SSH
331 * connection (in SSH1 only). Throttling the whole connection is
332 * pretty drastic so we set this high in the hope it won't
335 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
336 * on the SSH connection itself before we defensively throttle
337 * _all_ local data streams. This is pretty drastic too (though
338 * thankfully unlikely in SSH2 since the window mechanism should
339 * ensure that the server never has any need to throttle its end
340 * of the connection), so we set this high as well.
342 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
346 #define SSH1_BUFFER_LIMIT 32768
347 #define SSH_MAX_BACKLOG 32768
348 #define OUR_V2_WINSIZE 16384
350 const static struct ssh_kex
*kex_algs
[] = {
351 &ssh_diffiehellman_gex
,
355 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
357 static void nullmac_key(unsigned char *key
)
360 static void nullmac_generate(unsigned char *blk
, int len
,
364 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
)
368 const static struct ssh_mac ssh_mac_none
= {
369 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
371 const static struct ssh_mac
*macs
[] = {
372 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
374 const static struct ssh_mac
*buggymacs
[] = {
375 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
378 static void ssh_comp_none_init(void)
381 static int ssh_comp_none_block(unsigned char *block
, int len
,
382 unsigned char **outblock
, int *outlen
)
386 static int ssh_comp_none_disable(void)
390 const static struct ssh_compress ssh_comp_none
= {
392 ssh_comp_none_init
, ssh_comp_none_block
,
393 ssh_comp_none_init
, ssh_comp_none_block
,
394 ssh_comp_none_disable
396 extern const struct ssh_compress ssh_zlib
;
397 const static struct ssh_compress
*compressions
[] = {
398 &ssh_zlib
, &ssh_comp_none
401 enum { /* channel types */
406 CHAN_SOCKDATA_DORMANT
/* one the remote hasn't confirmed */
410 * 2-3-4 tree storing channels.
413 unsigned remoteid
, localid
;
417 struct ssh1_data_channel
{
420 struct ssh2_data_channel
{
422 unsigned remwindow
, remmaxpkt
;
427 struct ssh_agent_channel
{
428 unsigned char *message
;
429 unsigned char msglen
[4];
430 int lensofar
, totallen
;
432 struct ssh_x11_channel
{
435 struct ssh_pfd_channel
{
442 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
443 * 2 use this structure in different ways, reflecting SSH 2's
444 * altogether saner approach to port forwarding.
446 * In SSH 1, you arrange a remote forwarding by sending the server
447 * the remote port number, and the local destination host:port.
448 * When a connection comes in, the server sends you back that
449 * host:port pair, and you connect to it. This is a ready-made
450 * security hole if you're not on the ball: a malicious server
451 * could send you back _any_ host:port pair, so if you trustingly
452 * connect to the address it gives you then you've just opened the
453 * entire inside of your corporate network just by connecting
454 * through it to a dodgy SSH server. Hence, we must store a list of
455 * host:port pairs we _are_ trying to forward to, and reject a
456 * connection request from the server if it's not in the list.
458 * In SSH 2, each side of the connection minds its own business and
459 * doesn't send unnecessary information to the other. You arrange a
460 * remote forwarding by sending the server just the remote port
461 * number. When a connection comes in, the server tells you which
462 * of its ports was connected to; and _you_ have to remember what
463 * local host:port pair went with that port number.
465 * Hence: in SSH 1 this structure stores host:port pairs we intend
466 * to allow connections to, and is indexed by those host:port
467 * pairs. In SSH 2 it stores a mapping from source port to
468 * destination host:port pair, and is indexed by source port.
470 struct ssh_rportfwd
{
471 unsigned sport
, dport
;
484 static SHA_State exhash
, exhashbase
;
486 static Socket s
= NULL
;
488 static unsigned char session_key
[32];
489 static int ssh1_compressing
;
490 static int ssh1_remote_protoflags
;
491 static int ssh1_local_protoflags
;
492 static int ssh_agentfwd_enabled
;
493 static int ssh_X11_fwd_enabled
;
494 static int ssh_remote_bugs
;
495 static const struct ssh_cipher
*cipher
= NULL
;
496 static const struct ssh2_cipher
*cscipher
= NULL
;
497 static const struct ssh2_cipher
*sccipher
= NULL
;
498 static const struct ssh_mac
*csmac
= NULL
;
499 static const struct ssh_mac
*scmac
= NULL
;
500 static const struct ssh_compress
*cscomp
= NULL
;
501 static const struct ssh_compress
*sccomp
= NULL
;
502 static const struct ssh_kex
*kex
= NULL
;
503 static const struct ssh_signkey
*hostkey
= NULL
;
504 static unsigned char ssh2_session_id
[20];
505 int (*ssh_get_line
) (const char *prompt
, char *str
, int maxlen
,
508 static char *savedhost
;
509 static int savedport
;
510 static int ssh_send_ok
;
511 static int ssh_echoing
, ssh_editing
;
513 static tree234
*ssh_channels
; /* indexed by local id */
514 static struct ssh_channel
*mainchan
; /* primary session channel */
515 static int ssh_exitcode
= -1;
517 static tree234
*ssh_rportfwds
;
521 SSH_STATE_BEFORE_SIZE
,
525 } ssh_state
= SSH_STATE_PREPACKET
;
527 static int size_needed
= FALSE
, eof_needed
= FALSE
;
529 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
530 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
531 static unsigned char *deferred_send_data
= NULL
;
532 static int deferred_len
= 0, deferred_size
= 0;
535 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
536 * that fails. This variable is the means by which scp.c can reach
537 * into the SSH code and find out which one it got.
539 int ssh_fallback_cmd
= 0;
541 static int ssh_version
;
542 static int ssh1_throttle_count
;
543 static int ssh_overall_bufsize
;
544 static int ssh_throttled_all
;
545 static int ssh1_stdout_throttling
;
546 static void (*ssh_protocol
) (unsigned char *in
, int inlen
, int ispkt
);
547 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
548 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
549 static void ssh_size(void);
550 static void ssh_special(Telnet_Special
);
551 static int ssh2_try_send(struct ssh_channel
*c
);
552 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
554 static void ssh_throttle_all(int enable
, int bufsize
);
555 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
);
556 static int (*s_rdpkt
) (unsigned char **data
, int *datalen
);
557 static int ssh_sendbuffer(void);
559 static struct rdpkt1_state_tag
{
560 long len
, pad
, biglen
, to_read
;
561 unsigned long realcrc
, gotcrc
;
567 static struct rdpkt2_state_tag
{
568 long len
, pad
, payload
, packetlen
, maclen
;
571 unsigned long incoming_sequence
;
574 static int ssh_channelcmp(void *av
, void *bv
)
576 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
577 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
578 if (a
->localid
< b
->localid
)
580 if (a
->localid
> b
->localid
)
584 static int ssh_channelfind(void *av
, void *bv
)
586 unsigned *a
= (unsigned *) av
;
587 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
595 static int ssh_rportcmp_ssh1(void *av
, void *bv
)
597 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
598 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
600 if ( (i
= strcmp(a
->dhost
, b
->dhost
)) != 0)
601 return i
< 0 ?
-1 : +1;
602 if (a
->dport
> b
->dport
)
604 if (a
->dport
< b
->dport
)
609 static int ssh_rportcmp_ssh2(void *av
, void *bv
)
611 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
612 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
614 if (a
->sport
> b
->sport
)
616 if (a
->sport
< b
->sport
)
621 static int alloc_channel_id(void)
623 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
624 unsigned low
, high
, mid
;
626 struct ssh_channel
*c
;
629 * First-fit allocation of channel numbers: always pick the
630 * lowest unused one. To do this, binary-search using the
631 * counted B-tree to find the largest channel ID which is in a
632 * contiguous sequence from the beginning. (Precisely
633 * everything in that sequence must have ID equal to its tree
634 * index plus CHANNEL_NUMBER_OFFSET.)
636 tsize
= count234(ssh_channels
);
640 while (high
- low
> 1) {
641 mid
= (high
+ low
) / 2;
642 c
= index234(ssh_channels
, mid
);
643 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
644 low
= mid
; /* this one is fine */
646 high
= mid
; /* this one is past it */
649 * Now low points to either -1, or the tree index of the
650 * largest ID in the initial sequence.
653 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
654 assert(NULL
== find234(ssh_channels
, &i
, ssh_channelfind
));
656 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
659 static void c_write(char *buf
, int len
)
661 if ((flags
& FLAG_STDERR
)) {
663 for (i
= 0; i
< len
; i
++)
665 fputc(buf
[i
], stderr
);
668 from_backend(1, buf
, len
);
671 static void c_write_untrusted(char *buf
, int len
)
674 for (i
= 0; i
< len
; i
++) {
677 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
682 static void c_write_str(char *buf
)
684 c_write(buf
, strlen(buf
));
688 * Collect incoming data in the incoming packet buffer.
689 * Decipher and verify the packet when it is completely read.
690 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
691 * Update the *data and *datalen variables.
692 * Return the additional nr of bytes needed, or 0 when
693 * a complete packet is available.
695 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
697 struct rdpkt1_state_tag
*st
= &rdpkt1_state
;
706 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
707 while ((*datalen
) == 0)
709 st
->len
= (st
->len
<< 8) + **data
;
710 (*data
)++, (*datalen
)--;
713 st
->pad
= 8 - (st
->len
% 8);
714 st
->biglen
= st
->len
+ st
->pad
;
715 pktin
.length
= st
->len
- 5;
717 if (pktin
.maxlen
< st
->biglen
) {
718 pktin
.maxlen
= st
->biglen
;
719 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->biglen
+ APIEXTRA
) :
720 srealloc(pktin
.data
, st
->biglen
+ APIEXTRA
));
722 fatalbox("Out of memory");
725 st
->to_read
= st
->biglen
;
727 while (st
->to_read
> 0) {
728 st
->chunk
= st
->to_read
;
729 while ((*datalen
) == 0)
730 crReturn(st
->to_read
);
731 if (st
->chunk
> (*datalen
))
732 st
->chunk
= (*datalen
);
733 memcpy(st
->p
, *data
, st
->chunk
);
735 *datalen
-= st
->chunk
;
737 st
->to_read
-= st
->chunk
;
740 if (cipher
&& detect_attack(pktin
.data
, st
->biglen
, NULL
)) {
741 bombout(("Network attack (CRC compensation) detected!"));
746 cipher
->decrypt(pktin
.data
, st
->biglen
);
748 st
->realcrc
= crc32(pktin
.data
, st
->biglen
- 4);
749 st
->gotcrc
= GET_32BIT(pktin
.data
+ st
->biglen
- 4);
750 if (st
->gotcrc
!= st
->realcrc
) {
751 bombout(("Incorrect CRC received on packet"));
755 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
757 if (ssh1_compressing
) {
758 unsigned char *decompblk
;
760 zlib_decompress_block(pktin
.body
- 1, pktin
.length
+ 1,
761 &decompblk
, &decomplen
);
763 if (pktin
.maxlen
< st
->pad
+ decomplen
) {
764 pktin
.maxlen
= st
->pad
+ decomplen
;
765 pktin
.data
= srealloc(pktin
.data
, pktin
.maxlen
+ APIEXTRA
);
766 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
768 fatalbox("Out of memory");
771 memcpy(pktin
.body
- 1, decompblk
, decomplen
);
773 pktin
.length
= decomplen
- 1;
776 pktin
.type
= pktin
.body
[-1];
778 log_packet(PKT_INCOMING
, pktin
.type
, ssh1_pkt_type(pktin
.type
),
779 pktin
.body
, pktin
.length
);
781 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
782 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
783 pktin
.type
== SSH1_MSG_DEBUG
||
784 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
785 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
786 long stringlen
= GET_32BIT(pktin
.body
);
787 if (stringlen
+ 4 != pktin
.length
) {
788 bombout(("Received data packet with bogus string length"));
793 if (pktin
.type
== SSH1_MSG_DEBUG
) {
794 /* log debug message */
796 int stringlen
= GET_32BIT(pktin
.body
);
797 strcpy(buf
, "Remote: ");
800 memcpy(buf
+ 8, pktin
.body
+ 4, stringlen
);
801 buf
[8 + stringlen
] = '\0';
804 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
809 if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
810 /* log reason code in disconnect message */
812 unsigned msglen
= GET_32BIT(pktin
.body
);
814 strcpy(buf
, "Remote sent disconnect: ");
815 nowlen
= strlen(buf
);
816 if (msglen
> sizeof(buf
) - nowlen
- 1)
817 msglen
= sizeof(buf
) - nowlen
- 1;
818 memcpy(buf
+ nowlen
, pktin
.body
+ 4, msglen
);
819 buf
[nowlen
+ msglen
] = '\0';
821 bombout(("Server sent disconnect message:\n\"%s\"", buf
+nowlen
));
828 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
830 struct rdpkt2_state_tag
*st
= &rdpkt2_state
;
838 st
->cipherblk
= sccipher
->blksize
;
841 if (st
->cipherblk
< 8)
844 if (pktin
.maxlen
< st
->cipherblk
) {
845 pktin
.maxlen
= st
->cipherblk
;
848 NULL ?
smalloc(st
->cipherblk
+
849 APIEXTRA
) : srealloc(pktin
.data
,
853 fatalbox("Out of memory");
857 * Acquire and decrypt the first block of the packet. This will
858 * contain the length and padding details.
860 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
861 while ((*datalen
) == 0)
862 crReturn(st
->cipherblk
- st
->i
);
863 pktin
.data
[st
->i
] = *(*data
)++;
868 sccipher
->decrypt(pktin
.data
, st
->cipherblk
);
871 * Now get the length and padding figures.
873 st
->len
= GET_32BIT(pktin
.data
);
874 st
->pad
= pktin
.data
[4];
877 * This enables us to deduce the payload length.
879 st
->payload
= st
->len
- st
->pad
- 1;
881 pktin
.length
= st
->payload
+ 5;
884 * So now we can work out the total packet length.
886 st
->packetlen
= st
->len
+ 4;
887 st
->maclen
= scmac ? scmac
->len
: 0;
890 * Adjust memory allocation if packet is too big.
892 if (pktin
.maxlen
< st
->packetlen
+ st
->maclen
) {
893 pktin
.maxlen
= st
->packetlen
+ st
->maclen
;
896 NULL ?
smalloc(pktin
.maxlen
+ APIEXTRA
) : srealloc(pktin
.data
,
901 fatalbox("Out of memory");
905 * Read and decrypt the remainder of the packet.
907 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
909 while ((*datalen
) == 0)
910 crReturn(st
->packetlen
+ st
->maclen
- st
->i
);
911 pktin
.data
[st
->i
] = *(*data
)++;
914 /* Decrypt everything _except_ the MAC. */
916 sccipher
->decrypt(pktin
.data
+ st
->cipherblk
,
917 st
->packetlen
- st
->cipherblk
);
923 && !scmac
->verify(pktin
.data
, st
->len
+ 4,
924 st
->incoming_sequence
)) {
925 bombout(("Incorrect MAC received on packet"));
928 st
->incoming_sequence
++; /* whether or not we MACed */
931 * Decompress packet payload.
934 unsigned char *newpayload
;
936 if (sccomp
&& sccomp
->decompress(pktin
.data
+ 5, pktin
.length
- 5,
937 &newpayload
, &newlen
)) {
938 if (pktin
.maxlen
< newlen
+ 5) {
939 pktin
.maxlen
= newlen
+ 5;
942 NULL ?
smalloc(pktin
.maxlen
+
943 APIEXTRA
) : srealloc(pktin
.data
,
947 fatalbox("Out of memory");
949 pktin
.length
= 5 + newlen
;
950 memcpy(pktin
.data
+ 5, newpayload
, newlen
);
956 pktin
.type
= pktin
.data
[5];
958 log_packet(PKT_INCOMING
, pktin
.type
, ssh2_pkt_type(pktin
.type
),
959 pktin
.data
+6, pktin
.length
-6);
961 switch (pktin
.type
) {
963 * These packets we must handle instantly.
965 case SSH2_MSG_DISCONNECT
:
967 /* log reason code in disconnect message */
969 int reason
= GET_32BIT(pktin
.data
+ 6);
970 unsigned msglen
= GET_32BIT(pktin
.data
+ 10);
972 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
973 sprintf(buf
, "Received disconnect message (%s)",
974 ssh2_disconnect_reasons
[reason
]);
976 sprintf(buf
, "Received disconnect message (unknown type %d)",
980 strcpy(buf
, "Disconnection message text: ");
981 nowlen
= strlen(buf
);
982 if (msglen
> sizeof(buf
) - nowlen
- 1)
983 msglen
= sizeof(buf
) - nowlen
- 1;
984 memcpy(buf
+ nowlen
, pktin
.data
+ 14, msglen
);
985 buf
[nowlen
+ msglen
] = '\0';
987 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
989 (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) ?
990 ssh2_disconnect_reasons
[reason
] : "unknown",
995 case SSH2_MSG_IGNORE
:
999 /* log the debug message */
1001 /* int display = pktin.body[6]; */
1002 int stringlen
= GET_32BIT(pktin
.data
+7);
1004 strcpy(buf
, "Remote debug message: ");
1005 prefix
= strlen(buf
);
1006 if (stringlen
> sizeof(buf
)-prefix
-1)
1007 stringlen
= sizeof(buf
)-prefix
-1;
1008 memcpy(buf
+ prefix
, pktin
.data
+ 11, stringlen
);
1009 buf
[prefix
+ stringlen
] = '\0';
1012 goto next_packet
; /* FIXME: print the debug message */
1015 * These packets we need do nothing about here.
1017 case SSH2_MSG_UNIMPLEMENTED
:
1018 case SSH2_MSG_SERVICE_REQUEST
:
1019 case SSH2_MSG_SERVICE_ACCEPT
:
1020 case SSH2_MSG_KEXINIT
:
1021 case SSH2_MSG_NEWKEYS
:
1022 case SSH2_MSG_KEXDH_INIT
:
1023 case SSH2_MSG_KEXDH_REPLY
:
1024 /* case SSH2_MSG_KEX_DH_GEX_REQUEST: duplicate case value */
1025 /* case SSH2_MSG_KEX_DH_GEX_GROUP: duplicate case value */
1026 case SSH2_MSG_KEX_DH_GEX_INIT
:
1027 case SSH2_MSG_KEX_DH_GEX_REPLY
:
1028 case SSH2_MSG_USERAUTH_REQUEST
:
1029 case SSH2_MSG_USERAUTH_FAILURE
:
1030 case SSH2_MSG_USERAUTH_SUCCESS
:
1031 case SSH2_MSG_USERAUTH_BANNER
:
1032 case SSH2_MSG_USERAUTH_PK_OK
:
1033 /* case SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: duplicate case value */
1034 /* case SSH2_MSG_USERAUTH_INFO_REQUEST: duplicate case value */
1035 case SSH2_MSG_USERAUTH_INFO_RESPONSE
:
1036 case SSH2_MSG_GLOBAL_REQUEST
:
1037 case SSH2_MSG_REQUEST_SUCCESS
:
1038 case SSH2_MSG_REQUEST_FAILURE
:
1039 case SSH2_MSG_CHANNEL_OPEN
:
1040 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
:
1041 case SSH2_MSG_CHANNEL_OPEN_FAILURE
:
1042 case SSH2_MSG_CHANNEL_WINDOW_ADJUST
:
1043 case SSH2_MSG_CHANNEL_DATA
:
1044 case SSH2_MSG_CHANNEL_EXTENDED_DATA
:
1045 case SSH2_MSG_CHANNEL_EOF
:
1046 case SSH2_MSG_CHANNEL_CLOSE
:
1047 case SSH2_MSG_CHANNEL_REQUEST
:
1048 case SSH2_MSG_CHANNEL_SUCCESS
:
1049 case SSH2_MSG_CHANNEL_FAILURE
:
1053 * For anything else we send SSH2_MSG_UNIMPLEMENTED.
1056 ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED
);
1057 ssh2_pkt_adduint32(st
->incoming_sequence
- 1);
1065 static void ssh1_pktout_size(int len
)
1069 len
+= 5; /* type and CRC */
1070 pad
= 8 - (len
% 8);
1073 pktout
.length
= len
- 5;
1074 if (pktout
.maxlen
< biglen
) {
1075 pktout
.maxlen
= biglen
;
1077 /* Allocate enough buffer space for extra block
1078 * for MS CryptEncrypt() */
1079 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+ 12) :
1080 srealloc(pktout
.data
, biglen
+ 12));
1082 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+ 4) :
1083 srealloc(pktout
.data
, biglen
+ 4));
1086 fatalbox("Out of memory");
1088 pktout
.body
= pktout
.data
+ 4 + pad
+ 1;
1091 static void s_wrpkt_start(int type
, int len
)
1093 ssh1_pktout_size(len
);
1097 static int s_wrpkt_prepare(void)
1099 int pad
, len
, biglen
, i
;
1102 pktout
.body
[-1] = pktout
.type
;
1104 log_packet(PKT_OUTGOING
, pktout
.type
, ssh1_pkt_type(pktout
.type
),
1105 pktout
.body
, pktout
.length
);
1107 if (ssh1_compressing
) {
1108 unsigned char *compblk
;
1110 zlib_compress_block(pktout
.body
- 1, pktout
.length
+ 1,
1111 &compblk
, &complen
);
1112 ssh1_pktout_size(complen
- 1);
1113 memcpy(pktout
.body
- 1, compblk
, complen
);
1117 len
= pktout
.length
+ 5; /* type and CRC */
1118 pad
= 8 - (len
% 8);
1121 for (i
= 0; i
< pad
; i
++)
1122 pktout
.data
[i
+ 4] = random_byte();
1123 crc
= crc32(pktout
.data
+ 4, biglen
- 4);
1124 PUT_32BIT(pktout
.data
+ biglen
, crc
);
1125 PUT_32BIT(pktout
.data
, len
);
1128 cipher
->encrypt(pktout
.data
+ 4, biglen
);
1133 static void s_wrpkt(void)
1136 len
= s_wrpkt_prepare();
1137 backlog
= sk_write(s
, pktout
.data
, len
);
1138 if (backlog
> SSH_MAX_BACKLOG
)
1139 ssh_throttle_all(1, backlog
);
1142 static void s_wrpkt_defer(void)
1145 len
= s_wrpkt_prepare();
1146 if (deferred_len
+ len
> deferred_size
) {
1147 deferred_size
= deferred_len
+ len
+ 128;
1148 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1150 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
1151 deferred_len
+= len
;
1155 * Construct a packet with the specified contents.
1157 static void construct_packet(int pkttype
, va_list ap1
, va_list ap2
)
1159 unsigned char *p
, *argp
, argchar
;
1160 unsigned long argint
;
1161 int pktlen
, argtype
, arglen
;
1165 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
1168 (void) va_arg(ap1
, int);
1172 (void) va_arg(ap1
, char);
1176 (void) va_arg(ap1
, unsigned char *);
1177 arglen
= va_arg(ap1
, int);
1181 argp
= va_arg(ap1
, unsigned char *);
1182 arglen
= strlen(argp
);
1183 pktlen
+= 4 + arglen
;
1186 bn
= va_arg(ap1
, Bignum
);
1187 pktlen
+= ssh1_bignum_length(bn
);
1194 s_wrpkt_start(pkttype
, pktlen
);
1197 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
1200 argint
= va_arg(ap2
, int);
1201 PUT_32BIT(p
, argint
);
1205 argchar
= va_arg(ap2
, unsigned char);
1210 argp
= va_arg(ap2
, unsigned char *);
1211 arglen
= va_arg(ap2
, int);
1212 memcpy(p
, argp
, arglen
);
1216 argp
= va_arg(ap2
, unsigned char *);
1217 arglen
= strlen(argp
);
1218 PUT_32BIT(p
, arglen
);
1219 memcpy(p
+ 4, argp
, arglen
);
1223 bn
= va_arg(ap2
, Bignum
);
1224 p
+= ssh1_write_bignum(p
, bn
);
1230 static void send_packet(int pkttype
, ...)
1233 va_start(ap1
, pkttype
);
1234 va_start(ap2
, pkttype
);
1235 construct_packet(pkttype
, ap1
, ap2
);
1239 static void defer_packet(int pkttype
, ...)
1242 va_start(ap1
, pkttype
);
1243 va_start(ap2
, pkttype
);
1244 construct_packet(pkttype
, ap1
, ap2
);
1248 static int ssh_versioncmp(char *a
, char *b
)
1251 unsigned long av
, bv
;
1253 av
= strtoul(a
, &ae
, 10);
1254 bv
= strtoul(b
, &be
, 10);
1256 return (av
< bv ?
-1 : +1);
1261 av
= strtoul(ae
, &ae
, 10);
1262 bv
= strtoul(be
, &be
, 10);
1264 return (av
< bv ?
-1 : +1);
1270 * Utility routines for putting an SSH-protocol `string' and
1271 * `uint32' into a SHA state.
1274 static void sha_string(SHA_State
* s
, void *str
, int len
)
1276 unsigned char lenblk
[4];
1277 PUT_32BIT(lenblk
, len
);
1278 SHA_Bytes(s
, lenblk
, 4);
1279 SHA_Bytes(s
, str
, len
);
1282 static void sha_uint32(SHA_State
* s
, unsigned i
)
1284 unsigned char intblk
[4];
1285 PUT_32BIT(intblk
, i
);
1286 SHA_Bytes(s
, intblk
, 4);
1290 * SSH2 packet construction functions.
1292 static void ssh2_pkt_ensure(int length
)
1294 if (pktout
.maxlen
< length
) {
1295 pktout
.maxlen
= length
+ 256;
1298 NULL ?
smalloc(pktout
.maxlen
+
1299 APIEXTRA
) : srealloc(pktout
.data
,
1303 fatalbox("Out of memory");
1306 static void ssh2_pkt_adddata(void *data
, int len
)
1308 pktout
.length
+= len
;
1309 ssh2_pkt_ensure(pktout
.length
);
1310 memcpy(pktout
.data
+ pktout
.length
- len
, data
, len
);
1312 static void ssh2_pkt_addbyte(unsigned char byte
)
1314 ssh2_pkt_adddata(&byte
, 1);
1316 static void ssh2_pkt_init(int pkt_type
)
1319 ssh2_pkt_addbyte((unsigned char) pkt_type
);
1321 static void ssh2_pkt_addbool(unsigned char value
)
1323 ssh2_pkt_adddata(&value
, 1);
1325 static void ssh2_pkt_adduint32(unsigned long value
)
1328 PUT_32BIT(x
, value
);
1329 ssh2_pkt_adddata(x
, 4);
1331 static void ssh2_pkt_addstring_start(void)
1333 ssh2_pkt_adduint32(0);
1334 pktout
.savedpos
= pktout
.length
;
1336 static void ssh2_pkt_addstring_str(char *data
)
1338 ssh2_pkt_adddata(data
, strlen(data
));
1339 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1340 pktout
.length
- pktout
.savedpos
);
1342 static void ssh2_pkt_addstring_data(char *data
, int len
)
1344 ssh2_pkt_adddata(data
, len
);
1345 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1346 pktout
.length
- pktout
.savedpos
);
1348 static void ssh2_pkt_addstring(char *data
)
1350 ssh2_pkt_addstring_start();
1351 ssh2_pkt_addstring_str(data
);
1353 static char *ssh2_mpint_fmt(Bignum b
, int *len
)
1356 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1359 fatalbox("out of memory");
1361 for (i
= 1; i
<= n
; i
++)
1362 p
[i
] = bignum_byte(b
, n
- i
);
1364 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1366 memmove(p
, p
+ i
, n
+ 1 - i
);
1370 static void ssh2_pkt_addmp(Bignum b
)
1374 p
= ssh2_mpint_fmt(b
, &len
);
1375 ssh2_pkt_addstring_start();
1376 ssh2_pkt_addstring_data(p
, len
);
1381 * Construct an SSH2 final-form packet: compress it, encrypt it,
1382 * put the MAC on it. Final packet, ready to be sent, is stored in
1383 * pktout.data. Total length is returned.
1385 static int ssh2_pkt_construct(void)
1387 int cipherblk
, maclen
, padding
, i
;
1388 static unsigned long outgoing_sequence
= 0;
1390 log_packet(PKT_OUTGOING
, pktout
.data
[5], ssh2_pkt_type(pktout
.data
[5]),
1391 pktout
.data
+ 6, pktout
.length
- 6);
1394 * Compress packet payload.
1397 unsigned char *newpayload
;
1399 if (cscomp
&& cscomp
->compress(pktout
.data
+ 5, pktout
.length
- 5,
1400 &newpayload
, &newlen
)) {
1402 ssh2_pkt_adddata(newpayload
, newlen
);
1408 * Add padding. At least four bytes, and must also bring total
1409 * length (minus MAC) up to a multiple of the block size.
1411 cipherblk
= cscipher ? cscipher
->blksize
: 8; /* block size */
1412 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1415 (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
1416 maclen
= csmac ? csmac
->len
: 0;
1417 ssh2_pkt_ensure(pktout
.length
+ padding
+ maclen
);
1418 pktout
.data
[4] = padding
;
1419 for (i
= 0; i
< padding
; i
++)
1420 pktout
.data
[pktout
.length
+ i
] = random_byte();
1421 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
1423 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
1425 outgoing_sequence
++; /* whether or not we MACed */
1428 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
1430 /* Ready-to-send packet starts at pktout.data. We return length. */
1431 return pktout
.length
+ padding
+ maclen
;
1435 * Construct and send an SSH2 packet immediately.
1437 static void ssh2_pkt_send(void)
1441 len
= ssh2_pkt_construct();
1442 backlog
= sk_write(s
, pktout
.data
, len
);
1443 if (backlog
> SSH_MAX_BACKLOG
)
1444 ssh_throttle_all(1, backlog
);
1448 * Construct an SSH2 packet and add it to a deferred data block.
1449 * Useful for sending multiple packets in a single sk_write() call,
1450 * to prevent a traffic-analysing listener from being able to work
1451 * out the length of any particular packet (such as the password
1454 * Note that because SSH2 sequence-numbers its packets, this can
1455 * NOT be used as an m4-style `defer' allowing packets to be
1456 * constructed in one order and sent in another.
1458 static void ssh2_pkt_defer(void)
1460 int len
= ssh2_pkt_construct();
1461 if (deferred_len
+ len
> deferred_size
) {
1462 deferred_size
= deferred_len
+ len
+ 128;
1463 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1465 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
1466 deferred_len
+= len
;
1470 * Send the whole deferred data block constructed by
1471 * ssh2_pkt_defer() or SSH1's defer_packet().
1473 static void ssh_pkt_defersend(void)
1476 backlog
= sk_write(s
, deferred_send_data
, deferred_len
);
1477 deferred_len
= deferred_size
= 0;
1478 sfree(deferred_send_data
);
1479 deferred_send_data
= NULL
;
1480 if (backlog
> SSH_MAX_BACKLOG
)
1481 ssh_throttle_all(1, backlog
);
1485 void bndebug(char *string
, Bignum b
)
1489 p
= ssh2_mpint_fmt(b
, &len
);
1490 debug(("%s", string
));
1491 for (i
= 0; i
< len
; i
++)
1492 debug((" %02x", p
[i
]));
1498 static void sha_mpint(SHA_State
* s
, Bignum b
)
1502 p
= ssh2_mpint_fmt(b
, &len
);
1503 sha_string(s
, p
, len
);
1508 * SSH2 packet decode functions.
1510 static unsigned long ssh2_pkt_getuint32(void)
1512 unsigned long value
;
1513 if (pktin
.length
- pktin
.savedpos
< 4)
1514 return 0; /* arrgh, no way to decline (FIXME?) */
1515 value
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1516 pktin
.savedpos
+= 4;
1519 static int ssh2_pkt_getbool(void)
1521 unsigned long value
;
1522 if (pktin
.length
- pktin
.savedpos
< 1)
1523 return 0; /* arrgh, no way to decline (FIXME?) */
1524 value
= pktin
.data
[pktin
.savedpos
] != 0;
1528 static void ssh2_pkt_getstring(char **p
, int *length
)
1531 if (pktin
.length
- pktin
.savedpos
< 4)
1533 *length
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1534 pktin
.savedpos
+= 4;
1535 if (pktin
.length
- pktin
.savedpos
< *length
)
1537 *p
= pktin
.data
+ pktin
.savedpos
;
1538 pktin
.savedpos
+= *length
;
1540 static Bignum
ssh2_pkt_getmp(void)
1546 ssh2_pkt_getstring(&p
, &length
);
1550 bombout(("internal error: Can't handle negative mpints"));
1553 b
= bignum_from_bytes(p
, length
);
1558 * Examine the remote side's version string and compare it against
1559 * a list of known buggy implementations.
1561 static void ssh_detect_bugs(char *vstring
)
1563 char *imp
; /* pointer to implementation part */
1565 imp
+= strcspn(imp
, "-");
1567 imp
+= strcspn(imp
, "-");
1570 ssh_remote_bugs
= 0;
1572 if (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
1573 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
1574 !strcmp(imp
, "1.2.22") || !strcmp(imp
, "Cisco-1.25")) {
1576 * These versions don't support SSH1_MSG_IGNORE, so we have
1577 * to use a different defence against password length
1580 ssh_remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
1581 logevent("We believe remote version has SSH1 ignore bug");
1584 if (!strcmp(imp
, "Cisco-1.25")) {
1586 * These versions need a plain password sent; they can't
1587 * handle having a null and a random length of data after
1590 ssh_remote_bugs
|= BUG_NEEDS_SSH1_PLAIN_PASSWORD
;
1591 logevent("We believe remote version needs a plain SSH1 password");
1594 if (!strcmp(imp
, "Cisco-1.25")) {
1596 * These versions apparently have no clue whatever about
1597 * RSA authentication and will panic and die if they see
1598 * an AUTH_RSA message.
1600 ssh_remote_bugs
|= BUG_CHOKES_ON_RSA
;
1601 logevent("We believe remote version can't handle RSA authentication");
1604 if (!strncmp(imp
, "2.1.0", 5) || !strncmp(imp
, "2.0.", 4) ||
1605 !strncmp(imp
, "2.2.0", 5) || !strncmp(imp
, "2.3.0", 5) ||
1606 !strncmp(imp
, "2.1 ", 4)) {
1608 * These versions have the HMAC bug.
1610 ssh_remote_bugs
|= BUG_SSH2_HMAC
;
1611 logevent("We believe remote version has SSH2 HMAC bug");
1615 static int do_ssh_init(unsigned char c
)
1618 static char version
[10];
1619 static char *vstring
;
1620 static int vstrsize
;
1626 /* Search for the string "SSH-" in the input. */
1629 static const int transS
[] = { 1, 2, 2, 1 };
1630 static const int transH
[] = { 0, 0, 3, 0 };
1631 static const int transminus
[] = { 0, 0, 0, -1 };
1642 crReturn(1); /* get another character */
1646 vstring
= smalloc(vstrsize
);
1647 strcpy(vstring
, "SSH-");
1651 crReturn(1); /* get another char */
1652 if (vslen
>= vstrsize
- 1) {
1654 vstring
= srealloc(vstring
, vstrsize
);
1656 vstring
[vslen
++] = c
;
1661 } else if (i
< sizeof(version
) - 1)
1663 } else if (c
== '\n')
1667 ssh_agentfwd_enabled
= FALSE
;
1668 rdpkt2_state
.incoming_sequence
= 0;
1671 vlog
= smalloc(20 + vslen
);
1672 vstring
[strcspn (vstring
, "\r\n")] = '\0'; /* remove end-of-line chars */
1673 sprintf(vlog
, "Server version: %s", vstring
);
1675 ssh_detect_bugs(vstring
);
1679 * Server version "1.99" means we can choose whether we use v1
1680 * or v2 protocol. Choice is based on cfg.sshprot.
1682 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1684 * This is a v2 server. Begin v2 protocol.
1686 char verstring
[80], vlog
[100];
1687 sprintf(verstring
, "SSH-2.0-%s", sshver
);
1688 SHA_Init(&exhashbase
);
1690 * Hash our version string and their version string.
1692 sha_string(&exhashbase
, verstring
, strlen(verstring
));
1693 sha_string(&exhashbase
, vstring
, strcspn(vstring
, "\r\n"));
1694 sprintf(vlog
, "We claim version: %s", verstring
);
1696 strcat(verstring
, "\n");
1697 logevent("Using SSH protocol version 2");
1698 sk_write(s
, verstring
, strlen(verstring
));
1699 ssh_protocol
= ssh2_protocol
;
1701 s_rdpkt
= ssh2_rdpkt
;
1704 * This is a v1 server. Begin v1 protocol.
1706 char verstring
[80], vlog
[100];
1707 sprintf(verstring
, "SSH-%s-%s",
1708 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"),
1710 sprintf(vlog
, "We claim version: %s", verstring
);
1712 strcat(verstring
, "\n");
1713 logevent("Using SSH protocol version 1");
1714 sk_write(s
, verstring
, strlen(verstring
));
1715 ssh_protocol
= ssh1_protocol
;
1717 s_rdpkt
= ssh1_rdpkt
;
1719 ssh_state
= SSH_STATE_BEFORE_SIZE
;
1726 static void ssh_gotdata(unsigned char *data
, int datalen
)
1731 * To begin with, feed the characters one by one to the
1732 * protocol initialisation / selection function do_ssh_init().
1733 * When that returns 0, we're done with the initial greeting
1734 * exchange and can move on to packet discipline.
1739 crReturnV
; /* more data please */
1740 ret
= do_ssh_init(*data
);
1748 * We emerge from that loop when the initial negotiation is
1749 * over and we have selected an s_rdpkt function. Now pass
1750 * everything to s_rdpkt, and then pass the resulting packets
1751 * to the proper protocol handler.
1756 while (datalen
> 0) {
1757 if (s_rdpkt(&data
, &datalen
) == 0) {
1758 if (ssh_state
== SSH_STATE_CLOSED
) {
1761 ssh_protocol(NULL
, 0, 1);
1762 if (ssh_state
== SSH_STATE_CLOSED
) {
1772 static int ssh_closing(Plug plug
, char *error_msg
, int error_code
,
1775 ssh_state
= SSH_STATE_CLOSED
;
1781 /* A socket error has occurred. */
1782 connection_fatal(error_msg
);
1784 /* Otherwise, the remote side closed the connection normally. */
1789 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
1791 ssh_gotdata(data
, len
);
1792 if (ssh_state
== SSH_STATE_CLOSED
) {
1802 static void ssh_sent(Plug plug
, int bufsize
)
1805 * If the send backlog on the SSH socket itself clears, we
1806 * should unthrottle the whole world if it was throttled.
1808 if (bufsize
< SSH_MAX_BACKLOG
)
1809 ssh_throttle_all(0, bufsize
);
1813 * Connect to specified host and port.
1814 * Returns an error message, or NULL on success.
1815 * Also places the canonical host name into `realhost'. It must be
1816 * freed by the caller.
1818 static char *connect_to_host(char *host
, int port
, char **realhost
, int nodelay
)
1820 static struct plug_function_table fn_table
= {
1825 }, *fn_table_ptr
= &fn_table
;
1834 savedhost
= smalloc(1 + strlen(host
));
1836 fatalbox("Out of memory");
1837 strcpy(savedhost
, host
);
1840 port
= 22; /* default ssh port */
1855 sprintf(buf
, "Looking up host \"%.170s\"", host
);
1858 addr
= sk_namelookup(host
, realhost
);
1859 if ((err
= sk_addr_error(addr
)))
1863 *realhost
= strdup(FWhost
);
1870 char buf
[200], addrbuf
[100];
1871 sk_getaddr(addr
, addrbuf
, 100);
1872 sprintf(buf
, "Connecting to %.100s port %d", addrbuf
, port
);
1875 s
= sk_new(addr
, port
, 0, 1, nodelay
, &fn_table_ptr
);
1876 if ((err
= sk_socket_error(s
))) {
1882 sk_write(s
, "connect ", 8);
1883 sk_write(s
, FWhost
, strlen(FWhost
));
1886 sprintf(buf
, " %d\n", FWport
);
1887 sk_write(s
, buf
, strlen(buf
));
1895 * Throttle or unthrottle the SSH connection.
1897 static void ssh1_throttle(int adjust
)
1899 int old_count
= ssh1_throttle_count
;
1900 ssh1_throttle_count
+= adjust
;
1901 assert(ssh1_throttle_count
>= 0);
1902 if (ssh1_throttle_count
&& !old_count
) {
1903 sk_set_frozen(s
, 1);
1904 } else if (!ssh1_throttle_count
&& old_count
) {
1905 sk_set_frozen(s
, 0);
1910 * Throttle or unthrottle _all_ local data streams (for when sends
1911 * on the SSH connection itself back up).
1913 static void ssh_throttle_all(int enable
, int bufsize
)
1916 struct ssh_channel
*c
;
1918 if (enable
== ssh_throttled_all
)
1920 ssh_throttled_all
= enable
;
1921 ssh_overall_bufsize
= bufsize
;
1924 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++) {
1926 case CHAN_MAINSESSION
:
1928 * This is treated separately, outside the switch.
1932 x11_override_throttle(c
->u
.x11
.s
, enable
);
1935 /* Agent channels require no buffer management. */
1938 pfd_override_throttle(c
->u
.x11
.s
, enable
);
1945 * Handle the key exchange and user authentication phases.
1947 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1951 static unsigned char *rsabuf
, *keystr1
, *keystr2
;
1952 unsigned char cookie
[8];
1953 struct RSAKey servkey
, hostkey
;
1954 struct MD5Context md5c
;
1955 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1956 static int tried_publickey
, tried_agent
;
1957 static int tis_auth_refused
, ccard_auth_refused
;
1958 static unsigned char session_id
[16];
1959 static int cipher_type
;
1960 static char username
[100];
1961 static void *publickey_blob
;
1962 int publickey_bloblen
;
1969 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1970 bombout(("Public key packet not received"));
1974 logevent("Received public keys");
1976 memcpy(cookie
, pktin
.body
, 8);
1978 i
= makekey(pktin
.body
+ 8, &servkey
, &keystr1
, 0);
1979 j
= makekey(pktin
.body
+ 8 + i
, &hostkey
, &keystr2
, 0);
1982 * Log the host key fingerprint.
1986 logevent("Host key fingerprint is:");
1987 strcpy(logmsg
, " ");
1988 hostkey
.comment
= NULL
;
1989 rsa_fingerprint(logmsg
+ strlen(logmsg
),
1990 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
1994 ssh1_remote_protoflags
= GET_32BIT(pktin
.body
+ 8 + i
+ j
);
1995 supported_ciphers_mask
= GET_32BIT(pktin
.body
+ 12 + i
+ j
);
1996 supported_auths_mask
= GET_32BIT(pktin
.body
+ 16 + i
+ j
);
1998 ssh1_local_protoflags
=
1999 ssh1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
2000 ssh1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
2003 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
2004 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
2005 MD5Update(&md5c
, pktin
.body
, 8);
2006 MD5Final(session_id
, &md5c
);
2008 for (i
= 0; i
< 32; i
++)
2009 session_key
[i
] = random_byte();
2011 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
2013 rsabuf
= smalloc(len
);
2015 fatalbox("Out of memory");
2018 * Verify the host key.
2022 * First format the key into a string.
2024 int len
= rsastr_len(&hostkey
);
2025 char fingerprint
[100];
2026 char *keystr
= smalloc(len
);
2028 fatalbox("Out of memory");
2029 rsastr_fmt(keystr
, &hostkey
);
2030 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
2031 verify_ssh_host_key(savedhost
, savedport
, "rsa", keystr
,
2036 for (i
= 0; i
< 32; i
++) {
2037 rsabuf
[i
] = session_key
[i
];
2039 rsabuf
[i
] ^= session_id
[i
];
2042 if (hostkey
.bytes
> servkey
.bytes
) {
2043 rsaencrypt(rsabuf
, 32, &servkey
);
2044 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
2046 rsaencrypt(rsabuf
, 32, &hostkey
);
2047 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
2050 logevent("Encrypted session key");
2053 int cipher_chosen
= 0, warn
= 0;
2054 char *cipher_string
= NULL
;
2055 for (i
= 0; !cipher_chosen
&& i
< CIPHER_MAX
; i
++) {
2056 int next_cipher
= cfg
.ssh_cipherlist
[i
];
2057 if (next_cipher
== CIPHER_WARN
) {
2058 /* If/when we choose a cipher, warn about it */
2060 } else if (next_cipher
== CIPHER_AES
) {
2061 /* XXX Probably don't need to mention this. */
2062 logevent("AES not supported in SSH1, skipping");
2064 switch (next_cipher
) {
2065 case CIPHER_3DES
: cipher_type
= SSH_CIPHER_3DES
;
2066 cipher_string
= "3DES"; break;
2067 case CIPHER_BLOWFISH
: cipher_type
= SSH_CIPHER_BLOWFISH
;
2068 cipher_string
= "Blowfish"; break;
2069 case CIPHER_DES
: cipher_type
= SSH_CIPHER_DES
;
2070 cipher_string
= "single-DES"; break;
2072 if (supported_ciphers_mask
& (1 << cipher_type
))
2076 if (!cipher_chosen
) {
2077 if ((supported_ciphers_mask
& (1 << SSH_CIPHER_3DES
)) == 0)
2078 bombout(("Server violates SSH 1 protocol by not "
2079 "supporting 3DES encryption"));
2081 /* shouldn't happen */
2082 bombout(("No supported ciphers found"));
2086 /* Warn about chosen cipher if necessary. */
2088 askcipher(cipher_string
, 0);
2091 switch (cipher_type
) {
2092 case SSH_CIPHER_3DES
:
2093 logevent("Using 3DES encryption");
2095 case SSH_CIPHER_DES
:
2096 logevent("Using single-DES encryption");
2098 case SSH_CIPHER_BLOWFISH
:
2099 logevent("Using Blowfish encryption");
2103 send_packet(SSH1_CMSG_SESSION_KEY
,
2104 PKT_CHAR
, cipher_type
,
2105 PKT_DATA
, cookie
, 8,
2106 PKT_CHAR
, (len
* 8) >> 8, PKT_CHAR
, (len
* 8) & 0xFF,
2107 PKT_DATA
, rsabuf
, len
,
2108 PKT_INT
, ssh1_local_protoflags
, PKT_END
);
2110 logevent("Trying to enable encryption...");
2114 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
2115 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
: &ssh_3des
;
2116 cipher
->sesskey(session_key
);
2120 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2121 bombout(("Encryption not successfully enabled"));
2125 logevent("Successfully started encryption");
2131 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
2133 if (!ssh_get_line("login as: ",
2134 username
, sizeof(username
), FALSE
)) {
2136 * get_line failed to get a username.
2139 logevent("No username provided. Abandoning session.");
2140 ssh_state
= SSH_STATE_CLOSED
;
2144 c_write_str("login as: ");
2147 crWaitUntil(!ispkt
);
2149 switch (c
= *in
++) {
2158 c_write_str("\b \b");
2165 c_write_str("\b \b");
2174 if (((c
>= ' ' && c
<= '~') ||
2175 ((unsigned char) c
>= 160))
2176 && pos
< sizeof(username
)-1) {
2177 username
[pos
++] = c
;
2183 c_write_str("\r\n");
2184 username
[strcspn(username
, "\n\r")] = '\0';
2187 strncpy(username
, cfg
.username
, 99);
2188 username
[99] = '\0';
2191 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
2193 char userlog
[22 + sizeof(username
)];
2194 sprintf(userlog
, "Sent username \"%s\"", username
);
2196 if (flags
& FLAG_INTERACTIVE
&&
2197 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
2198 strcat(userlog
, "\r\n");
2199 c_write_str(userlog
);
2206 if ((ssh_remote_bugs
& BUG_CHOKES_ON_RSA
)) {
2207 /* We must not attempt PK auth. Pretend we've already tried it. */
2208 tried_publickey
= tried_agent
= 1;
2210 tried_publickey
= tried_agent
= 0;
2212 tis_auth_refused
= ccard_auth_refused
= 0;
2213 /* Load the public half of cfg.keyfile so we notice if it's in Pageant */
2215 if (!rsakey_pubblob(cfg
.keyfile
, &publickey_blob
, &publickey_bloblen
))
2216 publickey_blob
= NULL
;
2218 publickey_blob
= NULL
;
2220 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
2221 static char password
[100];
2222 static char prompt
[200];
2225 static int pwpkt_type
;
2226 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
2228 if (agent_exists() && !tried_agent
) {
2230 * Attempt RSA authentication using Pageant.
2232 static unsigned char request
[5], *response
, *p
;
2233 static int responselen
;
2234 static int i
, nkeys
;
2235 static int authed
= FALSE
;
2239 logevent("Pageant is running. Requesting keys.");
2241 /* Request the keys held by the agent. */
2242 PUT_32BIT(request
, 1);
2243 request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
2244 agent_query(request
, 5, &r
, &responselen
);
2245 response
= (unsigned char *) r
;
2246 if (response
&& responselen
>= 5 &&
2247 response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
2249 nkeys
= GET_32BIT(p
);
2253 sprintf(buf
, "Pageant has %d SSH1 keys", nkeys
);
2256 for (i
= 0; i
< nkeys
; i
++) {
2257 static struct RSAKey key
;
2258 static Bignum challenge
;
2259 static char *commentp
;
2260 static int commentlen
;
2264 sprintf(buf
, "Trying Pageant key #%d", i
);
2267 if (publickey_blob
&&
2268 !memcmp(p
, publickey_blob
, publickey_bloblen
)) {
2269 logevent("This key matches configured key file");
2270 tried_publickey
= 1;
2273 p
+= ssh1_read_bignum(p
, &key
.exponent
);
2274 p
+= ssh1_read_bignum(p
, &key
.modulus
);
2275 commentlen
= GET_32BIT(p
);
2279 send_packet(SSH1_CMSG_AUTH_RSA
,
2280 PKT_BIGNUM
, key
.modulus
, PKT_END
);
2282 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2283 logevent("Key refused");
2286 logevent("Received RSA challenge");
2287 ssh1_read_bignum(pktin
.body
, &challenge
);
2289 char *agentreq
, *q
, *ret
;
2292 len
= 1 + 4; /* message type, bit count */
2293 len
+= ssh1_bignum_length(key
.exponent
);
2294 len
+= ssh1_bignum_length(key
.modulus
);
2295 len
+= ssh1_bignum_length(challenge
);
2296 len
+= 16; /* session id */
2297 len
+= 4; /* response format */
2298 agentreq
= smalloc(4 + len
);
2299 PUT_32BIT(agentreq
, len
);
2301 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
2302 PUT_32BIT(q
, bignum_bitcount(key
.modulus
));
2304 q
+= ssh1_write_bignum(q
, key
.exponent
);
2305 q
+= ssh1_write_bignum(q
, key
.modulus
);
2306 q
+= ssh1_write_bignum(q
, challenge
);
2307 memcpy(q
, session_id
, 16);
2309 PUT_32BIT(q
, 1); /* response format */
2310 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
2314 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
2315 logevent("Sending Pageant's response");
2316 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2317 PKT_DATA
, ret
+ 5, 16,
2321 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2323 ("Pageant's response accepted");
2324 if (flags
& FLAG_VERBOSE
) {
2326 ("Authenticated using RSA key \"");
2327 c_write(commentp
, commentlen
);
2328 c_write_str("\" from agent\r\n");
2333 ("Pageant's response not accepted");
2336 ("Pageant failed to answer challenge");
2340 logevent("No reply received from Pageant");
2343 freebn(key
.exponent
);
2344 freebn(key
.modulus
);
2353 if (*cfg
.keyfile
&& !tried_publickey
)
2354 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
2356 if (cfg
.try_tis_auth
&&
2357 (supported_auths_mask
& (1 << SSH1_AUTH_TIS
)) &&
2358 !tis_auth_refused
) {
2359 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
2360 logevent("Requested TIS authentication");
2361 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
2363 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
2364 logevent("TIS authentication declined");
2365 if (flags
& FLAG_INTERACTIVE
)
2366 c_write_str("TIS authentication refused.\r\n");
2367 tis_auth_refused
= 1;
2370 int challengelen
= ((pktin
.body
[0] << 24) |
2371 (pktin
.body
[1] << 16) |
2372 (pktin
.body
[2] << 8) |
2374 logevent("Received TIS challenge");
2375 if (challengelen
> sizeof(prompt
) - 1)
2376 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2377 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2378 /* Prompt heuristic comes from OpenSSH */
2379 strncpy(prompt
+ challengelen
,
2380 memchr(prompt
, '\n', challengelen
) ?
2381 "": "\r\nResponse: ",
2382 (sizeof prompt
) - challengelen
);
2383 prompt
[(sizeof prompt
) - 1] = '\0';
2386 if (cfg
.try_tis_auth
&&
2387 (supported_auths_mask
& (1 << SSH1_AUTH_CCARD
)) &&
2388 !ccard_auth_refused
) {
2389 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
2390 logevent("Requested CryptoCard authentication");
2391 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
2393 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
2394 logevent("CryptoCard authentication declined");
2395 c_write_str("CryptoCard authentication refused.\r\n");
2396 ccard_auth_refused
= 1;
2399 int challengelen
= ((pktin
.body
[0] << 24) |
2400 (pktin
.body
[1] << 16) |
2401 (pktin
.body
[2] << 8) |
2403 logevent("Received CryptoCard challenge");
2404 if (challengelen
> sizeof(prompt
) - 1)
2405 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2406 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2407 strncpy(prompt
+ challengelen
,
2408 memchr(prompt
, '\n', challengelen
) ?
2409 "" : "\r\nResponse: ",
2410 sizeof(prompt
) - challengelen
);
2411 prompt
[sizeof(prompt
) - 1] = '\0';
2414 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2415 sprintf(prompt
, "%.90s@%.90s's password: ",
2416 username
, savedhost
);
2418 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2419 char *comment
= NULL
;
2420 if (flags
& FLAG_VERBOSE
)
2421 c_write_str("Trying public key authentication.\r\n");
2422 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
2423 if (flags
& FLAG_VERBOSE
)
2424 c_write_str("No passphrase required.\r\n");
2427 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
2432 * Show password prompt, having first obtained it via a TIS
2433 * or CryptoCard exchange if we're doing TIS or CryptoCard
2437 if (!ssh_get_line(prompt
, password
, sizeof(password
), TRUE
)) {
2439 * get_line failed to get a password (for example
2440 * because one was supplied on the command line
2441 * which has already failed to work). Terminate.
2443 send_packet(SSH1_MSG_DISCONNECT
,
2444 PKT_STR
, "No more passwords available to try",
2446 connection_fatal("Unable to authenticate");
2447 ssh_state
= SSH_STATE_CLOSED
;
2451 /* Prompt may have come from server. We've munged it a bit, so
2452 * we know it to be zero-terminated at least once. */
2453 c_write_untrusted(prompt
, strlen(prompt
));
2457 crWaitUntil(!ispkt
);
2459 switch (c
= *in
++) {
2479 if (pos
< sizeof(password
)-1)
2480 password
[pos
++] = c
;
2484 c_write_str("\r\n");
2488 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2490 * Try public key authentication with the specified
2493 static struct RSAKey pubkey
;
2494 static Bignum challenge
, response
;
2496 static unsigned char buffer
[32];
2498 tried_publickey
= 1;
2499 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
2501 c_write_str("Couldn't load private key from ");
2502 c_write_str(cfg
.keyfile
);
2503 c_write_str(".\r\n");
2504 continue; /* go and try password */
2507 c_write_str("Wrong passphrase.\r\n");
2508 tried_publickey
= 0;
2509 continue; /* try again */
2513 * Send a public key attempt.
2515 send_packet(SSH1_CMSG_AUTH_RSA
,
2516 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
2519 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2520 c_write_str("Server refused our public key.\r\n");
2521 continue; /* go and try password */
2523 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2524 bombout(("Bizarre response to offer of public key"));
2527 ssh1_read_bignum(pktin
.body
, &challenge
);
2528 response
= rsadecrypt(challenge
, &pubkey
);
2529 freebn(pubkey
.private_exponent
); /* burn the evidence */
2531 for (i
= 0; i
< 32; i
++) {
2532 buffer
[i
] = bignum_byte(response
, 31 - i
);
2536 MD5Update(&md5c
, buffer
, 32);
2537 MD5Update(&md5c
, session_id
, 16);
2538 MD5Final(buffer
, &md5c
);
2540 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2541 PKT_DATA
, buffer
, 16, PKT_END
);
2544 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2545 if (flags
& FLAG_VERBOSE
)
2547 ("Failed to authenticate with our public key.\r\n");
2548 continue; /* go and try password */
2549 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2551 ("Bizarre response to RSA authentication response"));
2555 break; /* we're through! */
2557 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2559 * Defence against traffic analysis: we send a
2560 * whole bunch of packets containing strings of
2561 * different lengths. One of these strings is the
2562 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2563 * The others are all random data in
2564 * SSH1_MSG_IGNORE packets. This way a passive
2565 * listener can't tell which is the password, and
2566 * hence can't deduce the password length.
2568 * Anybody with a password length greater than 16
2569 * bytes is going to have enough entropy in their
2570 * password that a listener won't find it _that_
2571 * much help to know how long it is. So what we'll
2574 * - if password length < 16, we send 15 packets
2575 * containing string lengths 1 through 15
2577 * - otherwise, we let N be the nearest multiple
2578 * of 8 below the password length, and send 8
2579 * packets containing string lengths N through
2580 * N+7. This won't obscure the order of
2581 * magnitude of the password length, but it will
2582 * introduce a bit of extra uncertainty.
2584 * A few servers (the old 1.2.18 through 1.2.22)
2585 * can't deal with SSH1_MSG_IGNORE. For these
2586 * servers, we need an alternative defence. We make
2587 * use of the fact that the password is interpreted
2588 * as a C string: so we can append a NUL, then some
2591 * One server (a Cisco one) can deal with neither
2592 * SSH1_MSG_IGNORE _nor_ a padded password string.
2593 * For this server we are left with no defences
2594 * against password length sniffing.
2596 if (!(ssh_remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
)) {
2598 * The server can deal with SSH1_MSG_IGNORE, so
2599 * we can use the primary defence.
2601 int bottom
, top
, pwlen
, i
;
2604 pwlen
= strlen(password
);
2606 bottom
= 0; /* zero length passwords are OK! :-) */
2609 bottom
= pwlen
& ~7;
2613 assert(pwlen
>= bottom
&& pwlen
<= top
);
2615 randomstr
= smalloc(top
+ 1);
2617 for (i
= bottom
; i
<= top
; i
++) {
2619 defer_packet(pwpkt_type
, PKT_STR
, password
,
2622 for (j
= 0; j
< i
; j
++) {
2624 randomstr
[j
] = random_byte();
2625 } while (randomstr
[j
] == '\0');
2627 randomstr
[i
] = '\0';
2628 defer_packet(SSH1_MSG_IGNORE
,
2629 PKT_STR
, randomstr
, PKT_END
);
2632 logevent("Sending password with camouflage packets");
2633 ssh_pkt_defersend();
2635 else if (!(ssh_remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
2637 * The server can't deal with SSH1_MSG_IGNORE
2638 * but can deal with padded passwords, so we
2639 * can use the secondary defence.
2645 len
= strlen(password
);
2646 if (len
< sizeof(string
)) {
2648 strcpy(string
, password
);
2649 len
++; /* cover the zero byte */
2650 while (len
< sizeof(string
)) {
2651 string
[len
++] = (char) random_byte();
2656 logevent("Sending length-padded password");
2657 send_packet(pwpkt_type
, PKT_INT
, len
,
2658 PKT_DATA
, s
, len
, PKT_END
);
2661 * The server has _both_
2662 * BUG_CHOKES_ON_SSH1_IGNORE and
2663 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2664 * therefore nothing we can do.
2667 len
= strlen(password
);
2668 logevent("Sending unpadded password");
2669 send_packet(pwpkt_type
, PKT_INT
, len
,
2670 PKT_DATA
, password
, len
, PKT_END
);
2673 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
2676 logevent("Sent password");
2677 memset(password
, 0, strlen(password
));
2679 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2680 if (flags
& FLAG_VERBOSE
)
2681 c_write_str("Access denied\r\n");
2682 logevent("Authentication refused");
2683 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2684 logevent("Received disconnect request");
2685 ssh_state
= SSH_STATE_CLOSED
;
2687 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2688 bombout(("Strange packet received, type %d", pktin
.type
));
2693 logevent("Authentication successful");
2698 void sshfwd_close(struct ssh_channel
*c
)
2700 if (c
&& !c
->closes
) {
2702 * If the channel's remoteid is -1, we have sent
2703 * CHANNEL_OPEN for this channel, but it hasn't even been
2704 * acknowledged by the server. So we must set a close flag
2705 * on it now, and then when the server acks the channel
2706 * open, we can close it then.
2708 if (c
->remoteid
!= -1) {
2709 if (ssh_version
== 1) {
2710 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
2713 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2714 ssh2_pkt_adduint32(c
->remoteid
);
2719 if (c
->type
== CHAN_X11
) {
2721 logevent("Forwarded X11 connection terminated");
2722 } else if (c
->type
== CHAN_SOCKDATA
||
2723 c
->type
== CHAN_SOCKDATA_DORMANT
) {
2725 logevent("Forwarded port closed");
2730 int sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
2732 if (ssh_version
== 1) {
2733 send_packet(SSH1_MSG_CHANNEL_DATA
,
2734 PKT_INT
, c
->remoteid
,
2735 PKT_INT
, len
, PKT_DATA
, buf
, len
, PKT_END
);
2737 * In SSH1 we can return 0 here - implying that forwarded
2738 * connections are never individually throttled - because
2739 * the only circumstance that can cause throttling will be
2740 * the whole SSH connection backing up, in which case
2741 * _everything_ will be throttled as a whole.
2745 ssh2_add_channel_data(c
, buf
, len
);
2746 return ssh2_try_send(c
);
2750 void sshfwd_unthrottle(struct ssh_channel
*c
, int bufsize
)
2752 if (ssh_version
== 1) {
2753 if (c
->v
.v1
.throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
2754 c
->v
.v1
.throttling
= 0;
2758 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
2762 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
)
2768 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
2771 if (ssh_state
== SSH_STATE_CLOSED
)
2774 if (cfg
.agentfwd
&& agent_exists()) {
2775 logevent("Requesting agent forwarding");
2776 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
2780 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2781 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2782 bombout(("Protocol confusion"));
2784 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2785 logevent("Agent forwarding refused");
2787 logevent("Agent forwarding enabled");
2788 ssh_agentfwd_enabled
= TRUE
;
2792 if (cfg
.x11_forward
) {
2793 char proto
[20], data
[64];
2794 logevent("Requesting X11 forwarding");
2795 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
2796 if (ssh1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
2797 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2798 PKT_STR
, proto
, PKT_STR
, data
,
2799 PKT_INT
, 0, PKT_END
);
2801 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2802 PKT_STR
, proto
, PKT_STR
, data
, PKT_END
);
2807 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2808 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2809 bombout(("Protocol confusion"));
2811 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2812 logevent("X11 forwarding refused");
2814 logevent("X11 forwarding enabled");
2815 ssh_X11_fwd_enabled
= TRUE
;
2823 char sports
[256], dports
[256], host
[256];
2826 ssh_rportfwds
= newtree234(ssh_rportcmp_ssh1
);
2827 /* Add port forwardings. */
2832 while (*e
&& *e
!= '\t')
2838 while (*e
&& *e
!= ':')
2848 dport
= atoi(dports
);
2849 sport
= atoi(sports
);
2850 if (sport
&& dport
) {
2852 pfd_addforward(host
, dport
, sport
);
2853 sprintf(buf
, "Local port %d forwarding to %s:%d",
2854 sport
, host
, dport
);
2857 struct ssh_rportfwd
*pf
;
2858 pf
= smalloc(sizeof(*pf
));
2859 strcpy(pf
->dhost
, host
);
2861 if (add234(ssh_rportfwds
, pf
) != pf
) {
2863 "Duplicate remote port forwarding to %s:%d",
2868 sprintf(buf
, "Requesting remote port %d forward to %s:%d",
2869 sport
, host
, dport
);
2871 send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST
,
2883 send_packet(SSH1_CMSG_REQUEST_PTY
,
2884 PKT_STR
, cfg
.termtype
,
2885 PKT_INT
, rows
, PKT_INT
, cols
,
2886 PKT_INT
, 0, PKT_INT
, 0, PKT_CHAR
, 0, PKT_END
);
2887 ssh_state
= SSH_STATE_INTERMED
;
2891 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2892 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2893 bombout(("Protocol confusion"));
2895 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2896 c_write_str("Server refused to allocate pty\r\n");
2897 ssh_editing
= ssh_echoing
= 1;
2899 logevent("Allocated pty");
2901 ssh_editing
= ssh_echoing
= 1;
2904 if (cfg
.compression
) {
2905 send_packet(SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
2909 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2910 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2911 bombout(("Protocol confusion"));
2913 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2914 c_write_str("Server refused to compress\r\n");
2916 logevent("Started compression");
2917 ssh1_compressing
= TRUE
;
2918 zlib_compress_init();
2919 zlib_decompress_init();
2923 * Start the shell or command.
2925 * Special case: if the first-choice command is an SSH2
2926 * subsystem (hence not usable here) and the second choice
2927 * exists, we fall straight back to that.
2930 char *cmd
= cfg
.remote_cmd_ptr
;
2932 if (cfg
.ssh_subsys
&& cfg
.remote_cmd_ptr2
) {
2933 cmd
= cfg
.remote_cmd_ptr2
;
2934 ssh_fallback_cmd
= TRUE
;
2937 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
2939 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
2940 logevent("Started session");
2943 ssh_state
= SSH_STATE_SESSION
;
2947 ssh_special(TS_EOF
);
2949 ldisc_send(NULL
, 0, 0); /* cause ldisc to notice changes */
2951 ssh_channels
= newtree234(ssh_channelcmp
);
2955 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
2956 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
2957 long len
= GET_32BIT(pktin
.body
);
2959 from_backend(pktin
.type
== SSH1_SMSG_STDERR_DATA
,
2960 pktin
.body
+ 4, len
);
2961 if (!ssh1_stdout_throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
2962 ssh1_stdout_throttling
= 1;
2965 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2966 ssh_state
= SSH_STATE_CLOSED
;
2967 logevent("Received disconnect request");
2969 } else if (pktin
.type
== SSH1_SMSG_X11_OPEN
) {
2970 /* Remote side is trying to open a channel to talk to our
2971 * X-Server. Give them back a local channel number. */
2972 struct ssh_channel
*c
;
2974 logevent("Received X11 connect request");
2975 /* Refuse if X11 forwarding is disabled. */
2976 if (!ssh_X11_fwd_enabled
) {
2977 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2978 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2979 logevent("Rejected X11 connect request");
2981 c
= smalloc(sizeof(struct ssh_channel
));
2983 if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
2984 logevent("opening X11 forward connection failed");
2986 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2987 PKT_INT
, GET_32BIT(pktin
.body
),
2991 ("opening X11 forward connection succeeded");
2992 c
->remoteid
= GET_32BIT(pktin
.body
);
2993 c
->localid
= alloc_channel_id();
2995 c
->v
.v1
.throttling
= 0;
2996 c
->type
= CHAN_X11
; /* identify channel type */
2997 add234(ssh_channels
, c
);
2998 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2999 PKT_INT
, c
->remoteid
, PKT_INT
,
3000 c
->localid
, PKT_END
);
3001 logevent("Opened X11 forward channel");
3004 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
3005 /* Remote side is trying to open a channel to talk to our
3006 * agent. Give them back a local channel number. */
3007 struct ssh_channel
*c
;
3009 /* Refuse if agent forwarding is disabled. */
3010 if (!ssh_agentfwd_enabled
) {
3011 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3012 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
3014 c
= smalloc(sizeof(struct ssh_channel
));
3015 c
->remoteid
= GET_32BIT(pktin
.body
);
3016 c
->localid
= alloc_channel_id();
3018 c
->v
.v1
.throttling
= 0;
3019 c
->type
= CHAN_AGENT
; /* identify channel type */
3020 c
->u
.a
.lensofar
= 0;
3021 add234(ssh_channels
, c
);
3022 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
3023 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
3026 } else if (pktin
.type
== SSH1_MSG_PORT_OPEN
) {
3027 /* Remote side is trying to open a channel to talk to a
3028 * forwarded port. Give them back a local channel number. */
3029 struct ssh_channel
*c
;
3030 struct ssh_rportfwd pf
;
3032 char host
[256], buf
[1024];
3034 c
= smalloc(sizeof(struct ssh_channel
));
3036 hostsize
= GET_32BIT(pktin
.body
+4);
3037 for(h
= host
, p
= pktin
.body
+8; hostsize
!= 0; hostsize
--) {
3038 if (h
+1 < host
+sizeof(host
))
3043 port
= GET_32BIT(p
);
3045 strcpy(pf
.dhost
, host
);
3048 if (find234(ssh_rportfwds
, &pf
, NULL
) == NULL
) {
3049 sprintf(buf
, "Rejected remote port open request for %s:%d",
3052 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3053 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
3055 sprintf(buf
, "Received remote port open request for %s:%d",
3058 e
= pfd_newconnect(&c
->u
.pfd
.s
, host
, port
, c
);
3061 sprintf(buf
, "Port open failed: %s", e
);
3064 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3065 PKT_INT
, GET_32BIT(pktin
.body
),
3068 c
->remoteid
= GET_32BIT(pktin
.body
);
3069 c
->localid
= alloc_channel_id();
3071 c
->v
.v1
.throttling
= 0;
3072 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
3073 add234(ssh_channels
, c
);
3074 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
3075 PKT_INT
, c
->remoteid
, PKT_INT
,
3076 c
->localid
, PKT_END
);
3077 logevent("Forwarded port opened successfully");
3081 } else if (pktin
.type
== SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
) {
3082 unsigned int remoteid
= GET_32BIT(pktin
.body
);
3083 unsigned int localid
= GET_32BIT(pktin
.body
+4);
3084 struct ssh_channel
*c
;
3086 c
= find234(ssh_channels
, &remoteid
, ssh_channelfind
);
3087 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
3088 c
->remoteid
= localid
;
3089 c
->type
= CHAN_SOCKDATA
;
3090 c
->v
.v1
.throttling
= 0;
3091 pfd_confirm(c
->u
.pfd
.s
);
3094 if (c
&& c
->closes
) {
3096 * We have a pending close on this channel,
3097 * which we decided on before the server acked
3098 * the channel open. So now we know the
3099 * remoteid, we can close it again.
3101 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
3105 } else if (pktin
.type
== SSH1_MSG_CHANNEL_OPEN_FAILURE
) {
3106 unsigned int remoteid
= GET_32BIT(pktin
.body
);
3107 unsigned int localid
= GET_32BIT(pktin
.body
+4);
3108 struct ssh_channel
*c
;
3110 c
= find234(ssh_channels
, &remoteid
, ssh_channelfind
);
3111 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
3112 logevent("Forwarded connection refused by server");
3113 pfd_close(c
->u
.pfd
.s
);
3114 del234(ssh_channels
, c
);
3118 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
3119 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
3120 /* Remote side closes a channel. */
3121 unsigned i
= GET_32BIT(pktin
.body
);
3122 struct ssh_channel
*c
;
3123 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3127 (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
3128 if (!(c
->closes
& closetype
))
3129 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
,
3131 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
3132 logevent("Forwarded X11 connection terminated");
3133 assert(c
->u
.x11
.s
!= NULL
);
3134 x11_close(c
->u
.x11
.s
);
3137 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
3138 logevent("Forwarded port closed");
3139 assert(c
->u
.pfd
.s
!= NULL
);
3140 pfd_close(c
->u
.pfd
.s
);
3143 c
->closes
|= closetype
;
3144 if (c
->closes
== 3) {
3145 del234(ssh_channels
, c
);
3149 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
3150 /* Data sent down one of our channels. */
3151 int i
= GET_32BIT(pktin
.body
);
3152 int len
= GET_32BIT(pktin
.body
+ 4);
3153 unsigned char *p
= pktin
.body
+ 8;
3154 struct ssh_channel
*c
;
3155 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3160 bufsize
= x11_send(c
->u
.x11
.s
, p
, len
);
3163 bufsize
= pfd_send(c
->u
.pfd
.s
, p
, len
);
3166 /* Data for an agent message. Buffer it. */
3168 if (c
->u
.a
.lensofar
< 4) {
3169 int l
= min(4 - c
->u
.a
.lensofar
, len
);
3170 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
3174 c
->u
.a
.lensofar
+= l
;
3176 if (c
->u
.a
.lensofar
== 4) {
3178 4 + GET_32BIT(c
->u
.a
.msglen
);
3179 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
3180 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
3182 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
3184 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
3186 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
3190 c
->u
.a
.lensofar
+= l
;
3192 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
3193 void *reply
, *sentreply
;
3195 agent_query(c
->u
.a
.message
,
3196 c
->u
.a
.totallen
, &reply
,
3201 /* Fake SSH_AGENT_FAILURE. */
3202 sentreply
= "\0\0\0\1\5";
3205 send_packet(SSH1_MSG_CHANNEL_DATA
,
3206 PKT_INT
, c
->remoteid
,
3208 PKT_DATA
, sentreply
, replylen
,
3212 sfree(c
->u
.a
.message
);
3213 c
->u
.a
.lensofar
= 0;
3216 bufsize
= 0; /* agent channels never back up */
3219 if (!c
->v
.v1
.throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
3220 c
->v
.v1
.throttling
= 1;
3224 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
3225 /* may be from EXEC_SHELL on some servers */
3226 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
3227 /* may be from EXEC_SHELL on some servers
3228 * if no pty is available or in other odd cases. Ignore */
3229 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
3231 ssh_exitcode
= GET_32BIT(pktin
.body
);
3232 sprintf(buf
, "Server sent command exit status %d",
3235 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
3237 * In case `helpful' firewalls or proxies tack
3238 * extra human-readable text on the end of the
3239 * session which we might mistake for another
3240 * encrypted packet, we close the session once
3241 * we've sent EXIT_CONFIRMATION.
3243 ssh_state
= SSH_STATE_CLOSED
;
3246 bombout(("Strange packet received: type %d", pktin
.type
));
3251 int len
= min(inlen
, 512);
3252 send_packet(SSH1_CMSG_STDIN_DATA
,
3253 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
3264 * Utility routine for decoding comma-separated strings in KEXINIT.
3266 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
3268 int needlen
= strlen(needle
);
3271 * Is it at the start of the string?
3273 if (haylen
>= needlen
&& /* haystack is long enough */
3274 !memcmp(needle
, haystack
, needlen
) && /* initial match */
3275 (haylen
== needlen
|| haystack
[needlen
] == ',')
3276 /* either , or EOS follows */
3280 * If not, search for the next comma and resume after that.
3281 * If no comma found, terminate.
3283 while (haylen
> 0 && *haystack
!= ',')
3284 haylen
--, haystack
++;
3287 haylen
--, haystack
++; /* skip over comma itself */
3292 * SSH2 key creation method.
3294 static void ssh2_mkkey(Bignum K
, char *H
, char *sessid
, char chr
,
3298 /* First 20 bytes. */
3301 SHA_Bytes(&s
, H
, 20);
3302 SHA_Bytes(&s
, &chr
, 1);
3303 SHA_Bytes(&s
, sessid
, 20);
3304 SHA_Final(&s
, keyspace
);
3305 /* Next 20 bytes. */
3308 SHA_Bytes(&s
, H
, 20);
3309 SHA_Bytes(&s
, keyspace
, 20);
3310 SHA_Final(&s
, keyspace
+ 20);
3314 * Handle the SSH2 transport layer.
3316 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
3318 static int i
, j
, len
, nbits
, pbits
, warn
;
3320 static Bignum p
, g
, e
, f
, K
;
3321 static int kex_init_value
, kex_reply_value
;
3322 static const struct ssh_mac
**maclist
;
3324 static const struct ssh2_cipher
*cscipher_tobe
= NULL
;
3325 static const struct ssh2_cipher
*sccipher_tobe
= NULL
;
3326 static const struct ssh_mac
*csmac_tobe
= NULL
;
3327 static const struct ssh_mac
*scmac_tobe
= NULL
;
3328 static const struct ssh_compress
*cscomp_tobe
= NULL
;
3329 static const struct ssh_compress
*sccomp_tobe
= NULL
;
3330 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
3331 static int hostkeylen
, siglen
;
3332 static void *hkey
; /* actual host key */
3333 static unsigned char exchange_hash
[20];
3334 static unsigned char keyspace
[40];
3335 static int n_preferred_ciphers
;
3336 static const struct ssh2_ciphers
*preferred_ciphers
[CIPHER_MAX
];
3337 static const struct ssh_compress
*preferred_comp
;
3338 static int cipherstr_started
;
3339 static int first_kex
;
3346 * Set up the preferred ciphers. (NULL => warn below here)
3348 n_preferred_ciphers
= 0;
3349 for (i
= 0; i
< CIPHER_MAX
; i
++) {
3350 switch (cfg
.ssh_cipherlist
[i
]) {
3351 case CIPHER_BLOWFISH
:
3352 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_blowfish
;
3353 n_preferred_ciphers
++;
3356 if (cfg
.ssh2_des_cbc
) {
3357 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_des
;
3358 n_preferred_ciphers
++;
3362 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_3des
;
3363 n_preferred_ciphers
++;
3366 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_aes
;
3367 n_preferred_ciphers
++;
3370 /* Flag for later. Don't bother if it's the last in
3372 if (i
< CIPHER_MAX
- 1) {
3373 preferred_ciphers
[n_preferred_ciphers
] = NULL
;
3374 n_preferred_ciphers
++;
3381 * Set up preferred compression.
3383 if (cfg
.compression
)
3384 preferred_comp
= &ssh_zlib
;
3386 preferred_comp
= &ssh_comp_none
;
3389 * Be prepared to work around the buggy MAC problem.
3391 if (cfg
.buggymac
|| (ssh_remote_bugs
& BUG_SSH2_HMAC
))
3392 maclist
= buggymacs
, nmacs
= lenof(buggymacs
);
3394 maclist
= macs
, nmacs
= lenof(macs
);
3398 * Construct and send our key exchange packet.
3400 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
3401 for (i
= 0; i
< 16; i
++)
3402 ssh2_pkt_addbyte((unsigned char) random_byte());
3403 /* List key exchange algorithms. */
3404 ssh2_pkt_addstring_start();
3405 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3406 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
3407 if (i
< lenof(kex_algs
) - 1)
3408 ssh2_pkt_addstring_str(",");
3410 /* List server host key algorithms. */
3411 ssh2_pkt_addstring_start();
3412 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3413 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
3414 if (i
< lenof(hostkey_algs
) - 1)
3415 ssh2_pkt_addstring_str(",");
3417 /* List client->server encryption algorithms. */
3418 ssh2_pkt_addstring_start();
3419 cipherstr_started
= 0;
3420 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3421 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3422 if (!c
) continue; /* warning flag */
3423 for (j
= 0; j
< c
->nciphers
; j
++) {
3424 if (cipherstr_started
)
3425 ssh2_pkt_addstring_str(",");
3426 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
3427 cipherstr_started
= 1;
3430 /* List server->client encryption algorithms. */
3431 ssh2_pkt_addstring_start();
3432 cipherstr_started
= 0;
3433 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3434 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3435 if (!c
) continue; /* warning flag */
3436 for (j
= 0; j
< c
->nciphers
; j
++) {
3437 if (cipherstr_started
)
3438 ssh2_pkt_addstring_str(",");
3439 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
3440 cipherstr_started
= 1;
3443 /* List client->server MAC algorithms. */
3444 ssh2_pkt_addstring_start();
3445 for (i
= 0; i
< nmacs
; i
++) {
3446 ssh2_pkt_addstring_str(maclist
[i
]->name
);
3448 ssh2_pkt_addstring_str(",");
3450 /* List server->client MAC algorithms. */
3451 ssh2_pkt_addstring_start();
3452 for (i
= 0; i
< nmacs
; i
++) {
3453 ssh2_pkt_addstring_str(maclist
[i
]->name
);
3455 ssh2_pkt_addstring_str(",");
3457 /* List client->server compression algorithms. */
3458 ssh2_pkt_addstring_start();
3459 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3460 const struct ssh_compress
*c
=
3461 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3462 ssh2_pkt_addstring_str(c
->name
);
3463 if (i
< lenof(compressions
))
3464 ssh2_pkt_addstring_str(",");
3466 /* List server->client compression algorithms. */
3467 ssh2_pkt_addstring_start();
3468 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3469 const struct ssh_compress
*c
=
3470 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3471 ssh2_pkt_addstring_str(c
->name
);
3472 if (i
< lenof(compressions
))
3473 ssh2_pkt_addstring_str(",");
3475 /* List client->server languages. Empty list. */
3476 ssh2_pkt_addstring_start();
3477 /* List server->client languages. Empty list. */
3478 ssh2_pkt_addstring_start();
3479 /* First KEX packet does _not_ follow, because we're not that brave. */
3480 ssh2_pkt_addbool(FALSE
);
3482 ssh2_pkt_adduint32(0);
3484 exhash
= exhashbase
;
3485 sha_string(&exhash
, pktout
.data
+ 5, pktout
.length
- 5);
3491 sha_string(&exhash
, pktin
.data
+ 5, pktin
.length
- 5);
3494 * Now examine the other side's KEXINIT to see what we're up
3497 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
3498 bombout(("expected key exchange packet from server"));
3503 cscipher_tobe
= NULL
;
3504 sccipher_tobe
= NULL
;
3509 pktin
.savedpos
+= 16; /* skip garbage cookie */
3510 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
3511 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3512 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
3517 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
3518 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3519 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
3520 hostkey
= hostkey_algs
[i
];
3524 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
3526 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3527 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3531 for (j
= 0; j
< c
->nciphers
; j
++) {
3532 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3533 cscipher_tobe
= c
->list
[j
];
3538 if (cscipher_tobe
) {
3540 askcipher(cscipher_tobe
->name
, 1);
3544 if (!cscipher_tobe
) {
3545 bombout(("Couldn't agree a client-to-server cipher (available: %s)", str
));
3549 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
3551 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3552 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3556 for (j
= 0; j
< c
->nciphers
; j
++) {
3557 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3558 sccipher_tobe
= c
->list
[j
];
3563 if (sccipher_tobe
) {
3565 askcipher(sccipher_tobe
->name
, 2);
3569 if (!sccipher_tobe
) {
3570 bombout(("Couldn't agree a server-to-client cipher (available: %s)", str
));
3574 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
3575 for (i
= 0; i
< nmacs
; i
++) {
3576 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3577 csmac_tobe
= maclist
[i
];
3581 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
3582 for (i
= 0; i
< nmacs
; i
++) {
3583 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3584 scmac_tobe
= maclist
[i
];
3588 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
3589 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3590 const struct ssh_compress
*c
=
3591 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3592 if (in_commasep_string(c
->name
, str
, len
)) {
3597 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
3598 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3599 const struct ssh_compress
*c
=
3600 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3601 if (in_commasep_string(c
->name
, str
, len
)) {
3608 * Work out the number of bits of key we will need from the key
3609 * exchange. We start with the maximum key length of either
3615 csbits
= cscipher_tobe
->keylen
;
3616 scbits
= sccipher_tobe
->keylen
;
3617 nbits
= (csbits
> scbits ? csbits
: scbits
);
3619 /* The keys only have 160-bit entropy, since they're based on
3620 * a SHA-1 hash. So cap the key size at 160 bits. */
3625 * If we're doing Diffie-Hellman group exchange, start by
3626 * requesting a group.
3628 if (kex
== &ssh_diffiehellman_gex
) {
3629 logevent("Doing Diffie-Hellman group exchange");
3630 ssh_pkt_ctx
|= SSH2_PKTCTX_DHGEX
;
3632 * Work out how big a DH group we will need to allow that
3635 pbits
= 512 << ((nbits
- 1) / 64);
3636 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
3637 ssh2_pkt_adduint32(pbits
);
3641 if (pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
3642 bombout(("expected key exchange group packet from server"));
3645 p
= ssh2_pkt_getmp();
3646 g
= ssh2_pkt_getmp();
3647 dh_setup_group(p
, g
);
3648 kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
3649 kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
3651 ssh_pkt_ctx
|= SSH2_PKTCTX_DHGROUP1
;
3653 kex_init_value
= SSH2_MSG_KEXDH_INIT
;
3654 kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
3657 logevent("Doing Diffie-Hellman key exchange");
3659 * Now generate and send e for Diffie-Hellman.
3661 e
= dh_create_e(nbits
* 2);
3662 ssh2_pkt_init(kex_init_value
);
3667 if (pktin
.type
!= kex_reply_value
) {
3668 bombout(("expected key exchange reply packet from server"));
3671 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
3672 f
= ssh2_pkt_getmp();
3673 ssh2_pkt_getstring(&sigdata
, &siglen
);
3677 sha_string(&exhash
, hostkeydata
, hostkeylen
);
3678 if (kex
== &ssh_diffiehellman_gex
) {
3679 sha_uint32(&exhash
, pbits
);
3680 sha_mpint(&exhash
, p
);
3681 sha_mpint(&exhash
, g
);
3683 sha_mpint(&exhash
, e
);
3684 sha_mpint(&exhash
, f
);
3685 sha_mpint(&exhash
, K
);
3686 SHA_Final(&exhash
, exchange_hash
);
3691 debug(("Exchange hash is:\n"));
3692 dmemdump(exchange_hash
, 20);
3695 hkey
= hostkey
->newkey(hostkeydata
, hostkeylen
);
3697 !hostkey
->verifysig(hkey
, sigdata
, siglen
, exchange_hash
, 20)) {
3698 bombout(("Server's host key did not match the signature supplied"));
3703 * Authenticate remote host: verify host key. (We've already
3704 * checked the signature of the exchange hash.)
3706 keystr
= hostkey
->fmtkey(hkey
);
3707 fingerprint
= hostkey
->fingerprint(hkey
);
3708 verify_ssh_host_key(savedhost
, savedport
, hostkey
->keytype
,
3709 keystr
, fingerprint
);
3710 if (first_kex
) { /* don't bother logging this in rekeys */
3711 logevent("Host key fingerprint is:");
3712 logevent(fingerprint
);
3716 hostkey
->freekey(hkey
);
3719 * Send SSH2_MSG_NEWKEYS.
3721 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
3725 * Expect SSH2_MSG_NEWKEYS from server.
3728 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
3729 bombout(("expected new-keys packet from server"));
3734 * Create and initialise session keys.
3736 cscipher
= cscipher_tobe
;
3737 sccipher
= sccipher_tobe
;
3740 cscomp
= cscomp_tobe
;
3741 sccomp
= sccomp_tobe
;
3742 cscomp
->compress_init();
3743 sccomp
->decompress_init();
3745 * Set IVs after keys. Here we use the exchange hash from the
3746 * _first_ key exchange.
3749 memcpy(ssh2_session_id
, exchange_hash
, sizeof(exchange_hash
));
3750 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'C', keyspace
);
3751 cscipher
->setcskey(keyspace
);
3752 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'D', keyspace
);
3753 sccipher
->setsckey(keyspace
);
3754 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'A', keyspace
);
3755 cscipher
->setcsiv(keyspace
);
3756 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'B', keyspace
);
3757 sccipher
->setsciv(keyspace
);
3758 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'E', keyspace
);
3759 csmac
->setcskey(keyspace
);
3760 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'F', keyspace
);
3761 scmac
->setsckey(keyspace
);
3764 * If this is the first key exchange phase, we must pass the
3765 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
3766 * wants to see it but because it will need time to initialise
3767 * itself before it sees an actual packet. In subsequent key
3768 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
3769 * it would only confuse the layer above.
3777 * Now we're encrypting. Begin returning 1 to the protocol main
3778 * function so that other things can run on top of the
3779 * transport. If we ever see a KEXINIT, we must go back to the
3782 while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
)) {
3785 logevent("Server initiated key re-exchange");
3786 goto begin_key_exchange
;
3792 * Add data to an SSH2 channel output buffer.
3794 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
3797 bufchain_add(&c
->v
.v2
.outbuffer
, buf
, len
);
3801 * Attempt to send data on an SSH2 channel.
3803 static int ssh2_try_send(struct ssh_channel
*c
)
3805 while (c
->v
.v2
.remwindow
> 0 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0) {
3808 bufchain_prefix(&c
->v
.v2
.outbuffer
, &data
, &len
);
3809 if ((unsigned)len
> c
->v
.v2
.remwindow
)
3810 len
= c
->v
.v2
.remwindow
;
3811 if ((unsigned)len
> c
->v
.v2
.remmaxpkt
)
3812 len
= c
->v
.v2
.remmaxpkt
;
3813 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
3814 ssh2_pkt_adduint32(c
->remoteid
);
3815 ssh2_pkt_addstring_start();
3816 ssh2_pkt_addstring_data(data
, len
);
3818 bufchain_consume(&c
->v
.v2
.outbuffer
, len
);
3819 c
->v
.v2
.remwindow
-= len
;
3823 * After having sent as much data as we can, return the amount
3826 return bufchain_size(&c
->v
.v2
.outbuffer
);
3830 * Potentially enlarge the window on an SSH2 channel.
3832 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
)
3835 * Never send WINDOW_ADJUST for a channel that the remote side
3836 * already thinks it's closed; there's no point, since it won't
3837 * be sending any more data anyway.
3842 if (newwin
> c
->v
.v2
.locwindow
) {
3843 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3844 ssh2_pkt_adduint32(c
->remoteid
);
3845 ssh2_pkt_adduint32(newwin
- c
->v
.v2
.locwindow
);
3847 c
->v
.v2
.locwindow
= newwin
;
3852 * Handle the SSH2 userauth and connection layers.
3854 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
3857 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
,
3859 AUTH_KEYBOARD_INTERACTIVE
3863 AUTH_TYPE_PUBLICKEY
,
3864 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
3865 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
3867 AUTH_TYPE_KEYBOARD_INTERACTIVE
,
3868 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
3870 static int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
3871 static int tried_pubkey_config
, tried_agent
, tried_keyb_inter
;
3872 static int kbd_inter_running
;
3873 static int we_are_in
;
3874 static int num_prompts
, echo
;
3875 static char username
[100];
3876 static char pwprompt
[200];
3877 static char password
[100];
3878 static void *publickey_blob
;
3879 static int publickey_bloblen
;
3884 * Request userauth protocol, and await a response to it.
3886 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
3887 ssh2_pkt_addstring("ssh-userauth");
3889 crWaitUntilV(ispkt
);
3890 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
3891 bombout(("Server refused user authentication protocol"));
3896 * We repeat this whole loop, including the username prompt,
3897 * until we manage a successful authentication. If the user
3898 * types the wrong _password_, they are sent back to the
3899 * beginning to try another username. (If they specify a
3900 * username in the config, they are never asked, even if they
3901 * do give a wrong password.)
3903 * I think this best serves the needs of
3905 * - the people who have no configuration, no keys, and just
3906 * want to try repeated (username,password) pairs until they
3907 * type both correctly
3909 * - people who have keys and configuration but occasionally
3910 * need to fall back to passwords
3912 * - people with a key held in Pageant, who might not have
3913 * logged in to a particular machine before; so they want to
3914 * type a username, and then _either_ their key will be
3915 * accepted, _or_ they will type a password. If they mistype
3916 * the username they will want to be able to get back and
3928 if (*username
&& !cfg
.change_username
) {
3930 * We got a username last time round this loop, and
3931 * with change_username turned off we don't try to get
3934 } else if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
3936 if (!ssh_get_line("login as: ",
3937 username
, sizeof(username
), FALSE
)) {
3939 * get_line failed to get a username.
3942 logevent("No username provided. Abandoning session.");
3943 ssh_state
= SSH_STATE_CLOSED
;
3947 c_write_str("login as: ");
3950 crWaitUntilV(!ispkt
);
3952 switch (c
= *in
++) {
3961 c_write_str("\b \b");
3968 c_write_str("\b \b");
3977 if (((c
>= ' ' && c
<= '~') ||
3978 ((unsigned char) c
>= 160))
3979 && pos
< sizeof(username
)-1) {
3980 username
[pos
++] = c
;
3987 c_write_str("\r\n");
3988 username
[strcspn(username
, "\n\r")] = '\0';
3991 strncpy(username
, cfg
.username
, 99);
3992 username
[99] = '\0';
3993 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
3994 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
4000 * Send an authentication request using method "none": (a)
4001 * just in case it succeeds, and (b) so that we know what
4002 * authentication methods we can usefully try next.
4004 ssh_pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4006 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4007 ssh2_pkt_addstring(username
);
4008 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4009 ssh2_pkt_addstring("none"); /* method */
4011 type
= AUTH_TYPE_NONE
;
4015 tried_pubkey_config
= FALSE
;
4016 tried_agent
= FALSE
;
4017 tried_keyb_inter
= FALSE
;
4018 kbd_inter_running
= FALSE
;
4019 /* Load the pub half of cfg.keyfile so we notice if it's in Pageant */
4021 publickey_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, NULL
,
4022 &publickey_bloblen
);
4024 publickey_blob
= NULL
;
4028 * Wait for the result of the last authentication request.
4031 crWaitUntilV(ispkt
);
4032 while (pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
4036 * Don't show the banner if we're operating in
4037 * non-verbose non-interactive mode. (It's probably
4038 * a script, which means nobody will read the
4039 * banner _anyway_, and moreover the printing of
4040 * the banner will screw up processing on the
4041 * output of (say) plink.)
4043 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
4044 ssh2_pkt_getstring(&banner
, &size
);
4046 c_write_untrusted(banner
, size
);
4048 crWaitUntilV(ispkt
);
4050 if (pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
4051 logevent("Access granted");
4056 if (kbd_inter_running
&&
4057 pktin
.type
== SSH2_MSG_USERAUTH_INFO_REQUEST
) {
4059 * This is a further prompt in keyboard-interactive
4060 * authentication. Do nothing.
4062 } else if (pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
4063 bombout(("Strange packet received during authentication: type %d",
4071 * OK, we're now sitting on a USERAUTH_FAILURE message, so
4072 * we can look at the string in it and know what we can
4073 * helpfully try next.
4075 if (pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
) {
4078 ssh2_pkt_getstring(&methods
, &methlen
);
4079 kbd_inter_running
= FALSE
;
4080 if (!ssh2_pkt_getbool()) {
4082 * We have received an unequivocal Access
4083 * Denied. This can translate to a variety of
4086 * - if we'd just tried "none" authentication,
4087 * it's not worth printing anything at all
4089 * - if we'd just tried a public key _offer_,
4090 * the message should be "Server refused our
4091 * key" (or no message at all if the key
4092 * came from Pageant)
4094 * - if we'd just tried anything else, the
4095 * message really should be "Access denied".
4097 * Additionally, if we'd just tried password
4098 * authentication, we should break out of this
4099 * whole loop so as to go back to the username
4102 if (type
== AUTH_TYPE_NONE
) {
4104 } else if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
4105 type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
4106 if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
4107 c_write_str("Server refused our key\r\n");
4108 logevent("Server refused public key");
4109 } else if (type
== AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
) {
4110 /* server declined keyboard-interactive; ignore */
4112 c_write_str("Access denied\r\n");
4113 logevent("Access denied");
4114 if (type
== AUTH_TYPE_PASSWORD
) {
4120 c_write_str("Further authentication required\r\n");
4121 logevent("Further authentication required");
4125 in_commasep_string("publickey", methods
, methlen
);
4127 in_commasep_string("password", methods
, methlen
);
4128 can_keyb_inter
= cfg
.try_ki_auth
&&
4129 in_commasep_string("keyboard-interactive", methods
, methlen
);
4133 ssh_pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4135 if (!method
&& can_pubkey
&& agent_exists() && !tried_agent
) {
4137 * Attempt public-key authentication using Pageant.
4139 static unsigned char request
[5], *response
, *p
;
4140 static int responselen
;
4141 static int i
, nkeys
;
4142 static int authed
= FALSE
;
4145 ssh_pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
4149 logevent("Pageant is running. Requesting keys.");
4151 /* Request the keys held by the agent. */
4152 PUT_32BIT(request
, 1);
4153 request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
4154 agent_query(request
, 5, &r
, &responselen
);
4155 response
= (unsigned char *) r
;
4156 if (response
&& responselen
>= 5 &&
4157 response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
4159 nkeys
= GET_32BIT(p
);
4163 sprintf(buf
, "Pageant has %d SSH2 keys", nkeys
);
4166 for (i
= 0; i
< nkeys
; i
++) {
4167 static char *pkblob
, *alg
, *commentp
;
4168 static int pklen
, alglen
, commentlen
;
4169 static int siglen
, retlen
, len
;
4170 static char *q
, *agentreq
, *ret
;
4175 sprintf(buf
, "Trying Pageant key #%d", i
);
4178 pklen
= GET_32BIT(p
);
4180 if (publickey_blob
&&
4181 pklen
== publickey_bloblen
&&
4182 !memcmp(p
, publickey_blob
, publickey_bloblen
)) {
4183 logevent("This key matches configured key file");
4184 tried_pubkey_config
= 1;
4188 alglen
= GET_32BIT(pkblob
);
4190 commentlen
= GET_32BIT(p
);
4194 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4195 ssh2_pkt_addstring(username
);
4196 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4197 ssh2_pkt_addstring("publickey"); /* method */
4198 ssh2_pkt_addbool(FALSE
); /* no signature included */
4199 ssh2_pkt_addstring_start();
4200 ssh2_pkt_addstring_data(alg
, alglen
);
4201 ssh2_pkt_addstring_start();
4202 ssh2_pkt_addstring_data(pkblob
, pklen
);
4205 crWaitUntilV(ispkt
);
4206 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
4207 logevent("Key refused");
4211 if (flags
& FLAG_VERBOSE
) {
4213 ("Authenticating with public key \"");
4214 c_write(commentp
, commentlen
);
4215 c_write_str("\" from agent\r\n");
4219 * Server is willing to accept the key.
4220 * Construct a SIGN_REQUEST.
4222 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4223 ssh2_pkt_addstring(username
);
4224 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4225 ssh2_pkt_addstring("publickey"); /* method */
4226 ssh2_pkt_addbool(TRUE
);
4227 ssh2_pkt_addstring_start();
4228 ssh2_pkt_addstring_data(alg
, alglen
);
4229 ssh2_pkt_addstring_start();
4230 ssh2_pkt_addstring_data(pkblob
, pklen
);
4232 siglen
= pktout
.length
- 5 + 4 + 20;
4233 len
= 1; /* message type */
4234 len
+= 4 + pklen
; /* key blob */
4235 len
+= 4 + siglen
; /* data to sign */
4236 len
+= 4; /* flags */
4237 agentreq
= smalloc(4 + len
);
4238 PUT_32BIT(agentreq
, len
);
4240 *q
++ = SSH2_AGENTC_SIGN_REQUEST
;
4241 PUT_32BIT(q
, pklen
);
4243 memcpy(q
, pkblob
, pklen
);
4245 PUT_32BIT(q
, siglen
);
4247 /* Now the data to be signed... */
4250 memcpy(q
, ssh2_session_id
, 20);
4252 memcpy(q
, pktout
.data
+ 5, pktout
.length
- 5);
4253 q
+= pktout
.length
- 5;
4254 /* And finally the (zero) flags word. */
4256 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
4260 if (ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
4261 logevent("Sending Pageant's response");
4262 ssh2_pkt_addstring_start();
4263 ssh2_pkt_addstring_data(ret
+ 9,
4271 ("Pageant failed to answer challenge");
4281 if (!method
&& can_pubkey
&& *cfg
.keyfile
4282 && !tried_pubkey_config
) {
4283 unsigned char *pub_blob
;
4284 char *algorithm
, *comment
;
4287 tried_pubkey_config
= TRUE
;
4289 ssh_pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
4292 * Try the public key supplied in the configuration.
4294 * First, offer the public blob to see if the server is
4295 * willing to accept it.
4297 pub_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, &algorithm
,
4300 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4301 ssh2_pkt_addstring(username
);
4302 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4303 ssh2_pkt_addstring("publickey"); /* method */
4304 ssh2_pkt_addbool(FALSE
); /* no signature included */
4305 ssh2_pkt_addstring(algorithm
);
4306 ssh2_pkt_addstring_start();
4307 ssh2_pkt_addstring_data(pub_blob
, pub_blob_len
);
4309 logevent("Offered public key"); /* FIXME */
4311 crWaitUntilV(ispkt
);
4312 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
4314 type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
4315 continue; /* key refused; give up on it */
4318 logevent("Offer of public key accepted");
4320 * Actually attempt a serious authentication using
4323 if (ssh2_userkey_encrypted(cfg
.keyfile
, &comment
)) {
4325 "Passphrase for key \"%.100s\": ",
4331 c_write_str("Authenticating with public key \"");
4332 c_write_str(comment
);
4333 c_write_str("\"\r\n");
4334 method
= AUTH_PUBLICKEY_FILE
;
4338 if (!method
&& can_keyb_inter
&& !tried_keyb_inter
) {
4339 method
= AUTH_KEYBOARD_INTERACTIVE
;
4340 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4341 tried_keyb_inter
= TRUE
;
4343 ssh_pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
4345 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4346 ssh2_pkt_addstring(username
);
4347 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4348 ssh2_pkt_addstring("keyboard-interactive"); /* method */
4349 ssh2_pkt_addstring(""); /* lang */
4350 ssh2_pkt_addstring("");
4353 crWaitUntilV(ispkt
);
4354 if (pktin
.type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
4355 if (pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
)
4357 logevent("Keyboard-interactive authentication refused");
4358 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
;
4362 kbd_inter_running
= TRUE
;
4365 if (kbd_inter_running
) {
4366 method
= AUTH_KEYBOARD_INTERACTIVE
;
4367 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4368 tried_keyb_inter
= TRUE
;
4370 ssh_pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
4372 /* We've got packet with that "interactive" info
4373 dump banners, and set its prompt as ours */
4375 char *name
, *inst
, *lang
, *prompt
;
4376 int name_len
, inst_len
, lang_len
, prompt_len
;
4377 ssh2_pkt_getstring(&name
, &name_len
);
4378 ssh2_pkt_getstring(&inst
, &inst_len
);
4379 ssh2_pkt_getstring(&lang
, &lang_len
);
4381 c_write_untrusted(name
, name_len
);
4383 c_write_untrusted(inst
, inst_len
);
4384 num_prompts
= ssh2_pkt_getuint32();
4386 ssh2_pkt_getstring(&prompt
, &prompt_len
);
4387 strncpy(pwprompt
, prompt
, sizeof(pwprompt
));
4388 pwprompt
[prompt_len
< sizeof(pwprompt
) ?
4389 prompt_len
: sizeof(pwprompt
)-1] = '\0';
4392 echo
= ssh2_pkt_getbool();
4396 if (!method
&& can_passwd
) {
4397 method
= AUTH_PASSWORD
;
4398 ssh_pkt_ctx
|= SSH2_PKTCTX_PASSWORD
;
4399 sprintf(pwprompt
, "%.90s@%.90s's password: ", username
,
4406 if (!ssh_get_line(pwprompt
, password
,
4407 sizeof(password
), TRUE
)) {
4409 * get_line failed to get a password (for
4410 * example because one was supplied on the
4411 * command line which has already failed to
4414 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4415 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4417 ("No more passwords available to try");
4418 ssh2_pkt_addstring("en"); /* language tag */
4420 connection_fatal("Unable to authenticate");
4421 ssh_state
= SSH_STATE_CLOSED
;
4428 c_write_untrusted(pwprompt
, strlen(pwprompt
));
4433 crWaitUntilV(!ispkt
);
4435 switch (c
= *in
++) {
4455 if (pos
< sizeof(password
)-1)
4456 password
[pos
++] = c
;
4460 c_write_str("\r\n");
4464 if (method
== AUTH_PUBLICKEY_FILE
) {
4466 * We have our passphrase. Now try the actual authentication.
4468 struct ssh2_userkey
*key
;
4470 key
= ssh2_load_userkey(cfg
.keyfile
, password
);
4471 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
4472 if (key
== SSH2_WRONG_PASSPHRASE
) {
4473 c_write_str("Wrong passphrase\r\n");
4474 tried_pubkey_config
= FALSE
;
4476 c_write_str("Unable to load private key\r\n");
4477 tried_pubkey_config
= TRUE
;
4479 /* Send a spurious AUTH_NONE to return to the top. */
4480 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4481 ssh2_pkt_addstring(username
);
4482 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4483 ssh2_pkt_addstring("none"); /* method */
4485 type
= AUTH_TYPE_NONE
;
4487 unsigned char *blob
, *sigdata
;
4488 int blob_len
, sigdata_len
;
4491 * We have loaded the private key and the server
4492 * has announced that it's willing to accept it.
4493 * Hallelujah. Generate a signature and send it.
4495 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4496 ssh2_pkt_addstring(username
);
4497 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4498 ssh2_pkt_addstring("publickey"); /* method */
4499 ssh2_pkt_addbool(TRUE
);
4500 ssh2_pkt_addstring(key
->alg
->name
);
4501 blob
= key
->alg
->public_blob(key
->data
, &blob_len
);
4502 ssh2_pkt_addstring_start();
4503 ssh2_pkt_addstring_data(blob
, blob_len
);
4507 * The data to be signed is:
4511 * followed by everything so far placed in the
4514 sigdata_len
= pktout
.length
- 5 + 4 + 20;
4515 sigdata
= smalloc(sigdata_len
);
4516 PUT_32BIT(sigdata
, 20);
4517 memcpy(sigdata
+ 4, ssh2_session_id
, 20);
4518 memcpy(sigdata
+ 24, pktout
.data
+ 5,
4521 key
->alg
->sign(key
->data
, sigdata
, sigdata_len
,
4523 ssh2_pkt_addstring_start();
4524 ssh2_pkt_addstring_data(blob
, blob_len
);
4529 type
= AUTH_TYPE_PUBLICKEY
;
4531 } else if (method
== AUTH_PASSWORD
) {
4533 * We send the password packet lumped tightly together with
4534 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4535 * string long enough to make the total length of the two
4536 * packets constant. This should ensure that a passive
4537 * listener doing traffic analyis can't work out the length
4540 * For this to work, we need an assumption about the
4541 * maximum length of the password packet. I think 256 is
4542 * pretty conservative. Anyone using a password longer than
4543 * that probably doesn't have much to worry about from
4544 * people who find out how long their password is!
4546 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4547 ssh2_pkt_addstring(username
);
4548 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4549 ssh2_pkt_addstring("password");
4550 ssh2_pkt_addbool(FALSE
);
4551 ssh2_pkt_addstring(password
);
4554 * We'll include a string that's an exact multiple of the
4555 * cipher block size. If the cipher is NULL for some
4556 * reason, we don't do this trick at all because we gain
4562 stringlen
= (256 - deferred_len
);
4563 stringlen
+= cscipher
->blksize
- 1;
4564 stringlen
-= (stringlen
% cscipher
->blksize
);
4567 * Temporarily disable actual compression,
4568 * so we can guarantee to get this string
4569 * exactly the length we want it. The
4570 * compression-disabling routine should
4571 * return an integer indicating how many
4572 * bytes we should adjust our string length
4575 stringlen
-= cscomp
->disable_compression();
4577 ssh2_pkt_init(SSH2_MSG_IGNORE
);
4578 ssh2_pkt_addstring_start();
4579 for (i
= 0; i
< stringlen
; i
++) {
4580 char c
= (char) random_byte();
4581 ssh2_pkt_addstring_data(&c
, 1);
4585 ssh_pkt_defersend();
4586 logevent("Sent password");
4587 type
= AUTH_TYPE_PASSWORD
;
4588 } else if (method
== AUTH_KEYBOARD_INTERACTIVE
) {
4589 ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE
);
4590 ssh2_pkt_adduint32(num_prompts
);
4591 ssh2_pkt_addstring(password
);
4592 memset(password
, 0, sizeof(password
));
4594 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4597 ("No supported authentication methods left to try!\r\n");
4599 ("No supported authentications offered. Disconnecting");
4600 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4601 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4603 ("No supported authentication methods available");
4604 ssh2_pkt_addstring("en"); /* language tag */
4606 ssh_state
= SSH_STATE_CLOSED
;
4610 } while (!we_are_in
);
4613 * Now we're authenticated for the connection protocol. The
4614 * connection protocol will automatically have started at this
4615 * point; there's no need to send SERVICE_REQUEST.
4619 * So now create a channel with a session in it.
4621 ssh_channels
= newtree234(ssh_channelcmp
);
4622 mainchan
= smalloc(sizeof(struct ssh_channel
));
4623 mainchan
->localid
= alloc_channel_id();
4624 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
4625 ssh2_pkt_addstring("session");
4626 ssh2_pkt_adduint32(mainchan
->localid
);
4627 mainchan
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
4628 ssh2_pkt_adduint32(mainchan
->v
.v2
.locwindow
); /* our window size */
4629 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
4631 crWaitUntilV(ispkt
);
4632 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
4633 bombout(("Server refused to open a session"));
4635 /* FIXME: error data comes back in FAILURE packet */
4637 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
4638 bombout(("Server's channel confirmation cited wrong channel"));
4641 mainchan
->remoteid
= ssh2_pkt_getuint32();
4642 mainchan
->type
= CHAN_MAINSESSION
;
4643 mainchan
->closes
= 0;
4644 mainchan
->v
.v2
.remwindow
= ssh2_pkt_getuint32();
4645 mainchan
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
4646 bufchain_init(&mainchan
->v
.v2
.outbuffer
);
4647 add234(ssh_channels
, mainchan
);
4648 logevent("Opened channel for session");
4651 * Potentially enable X11 forwarding.
4653 if (cfg
.x11_forward
) {
4654 char proto
[20], data
[64];
4655 logevent("Requesting X11 forwarding");
4656 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
4657 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4658 ssh2_pkt_adduint32(mainchan
->remoteid
);
4659 ssh2_pkt_addstring("x11-req");
4660 ssh2_pkt_addbool(1); /* want reply */
4661 ssh2_pkt_addbool(0); /* many connections */
4662 ssh2_pkt_addstring(proto
);
4663 ssh2_pkt_addstring(data
);
4664 ssh2_pkt_adduint32(0); /* screen number */
4668 crWaitUntilV(ispkt
);
4669 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4670 unsigned i
= ssh2_pkt_getuint32();
4671 struct ssh_channel
*c
;
4672 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4674 continue; /* nonexistent channel */
4675 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4677 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4679 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4680 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4681 bombout(("Unexpected response to X11 forwarding request:"
4682 " packet type %d", pktin
.type
));
4685 logevent("X11 forwarding refused");
4687 logevent("X11 forwarding enabled");
4688 ssh_X11_fwd_enabled
= TRUE
;
4693 * Enable port forwardings.
4696 static char *e
; /* preserve across crReturn */
4700 char sports
[256], dports
[256], host
[256];
4703 ssh_rportfwds
= newtree234(ssh_rportcmp_ssh2
);
4704 /* Add port forwardings. */
4709 while (*e
&& *e
!= '\t')
4715 while (*e
&& *e
!= ':')
4725 dport
= atoi(dports
);
4726 sport
= atoi(sports
);
4727 if (sport
&& dport
) {
4729 pfd_addforward(host
, dport
, sport
);
4730 sprintf(buf
, "Local port %d forwarding to %s:%d",
4731 sport
, host
, dport
);
4734 struct ssh_rportfwd
*pf
;
4735 pf
= smalloc(sizeof(*pf
));
4736 strcpy(pf
->dhost
, host
);
4739 if (add234(ssh_rportfwds
, pf
) != pf
) {
4741 "Duplicate remote port forwarding to %s:%d",
4746 sprintf(buf
, "Requesting remote port %d (forwarded to %s:%d)",
4747 sport
, host
, dport
);
4749 ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
4750 ssh2_pkt_addstring("tcpip-forward");
4751 ssh2_pkt_addbool(1);/* want reply */
4752 if (cfg
.rport_acceptall
)
4753 ssh2_pkt_addstring("0.0.0.0");
4755 ssh2_pkt_addstring("127.0.0.1");
4756 ssh2_pkt_adduint32(sport
);
4760 crWaitUntilV(ispkt
);
4761 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4762 unsigned i
= ssh2_pkt_getuint32();
4763 struct ssh_channel
*c
;
4764 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4766 continue;/* nonexistent channel */
4767 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4769 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4771 if (pktin
.type
!= SSH2_MSG_REQUEST_SUCCESS
) {
4772 if (pktin
.type
!= SSH2_MSG_REQUEST_FAILURE
) {
4773 bombout(("Unexpected response to port "
4774 "forwarding request: packet type %d",
4778 logevent("Server refused this port forwarding");
4780 logevent("Remote port forwarding enabled");
4789 * Potentially enable agent forwarding.
4791 if (cfg
.agentfwd
&& agent_exists()) {
4792 logevent("Requesting OpenSSH-style agent forwarding");
4793 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4794 ssh2_pkt_adduint32(mainchan
->remoteid
);
4795 ssh2_pkt_addstring("auth-agent-req@openssh.com");
4796 ssh2_pkt_addbool(1); /* want reply */
4800 crWaitUntilV(ispkt
);
4801 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4802 unsigned i
= ssh2_pkt_getuint32();
4803 struct ssh_channel
*c
;
4804 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4806 continue; /* nonexistent channel */
4807 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4809 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4811 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4812 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4813 bombout(("Unexpected response to agent forwarding request:"
4814 " packet type %d", pktin
.type
));
4817 logevent("Agent forwarding refused");
4819 logevent("Agent forwarding enabled");
4820 ssh_agentfwd_enabled
= TRUE
;
4825 * Now allocate a pty for the session.
4828 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4829 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
4830 ssh2_pkt_addstring("pty-req");
4831 ssh2_pkt_addbool(1); /* want reply */
4832 ssh2_pkt_addstring(cfg
.termtype
);
4833 ssh2_pkt_adduint32(cols
);
4834 ssh2_pkt_adduint32(rows
);
4835 ssh2_pkt_adduint32(0); /* pixel width */
4836 ssh2_pkt_adduint32(0); /* pixel height */
4837 ssh2_pkt_addstring_start();
4838 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
4840 ssh_state
= SSH_STATE_INTERMED
;
4843 crWaitUntilV(ispkt
);
4844 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4845 unsigned i
= ssh2_pkt_getuint32();
4846 struct ssh_channel
*c
;
4847 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4849 continue; /* nonexistent channel */
4850 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4852 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4854 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4855 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4856 bombout(("Unexpected response to pty request:"
4857 " packet type %d", pktin
.type
));
4860 c_write_str("Server refused to allocate pty\r\n");
4861 ssh_editing
= ssh_echoing
= 1;
4863 logevent("Allocated pty");
4866 ssh_editing
= ssh_echoing
= 1;
4870 * Start a shell or a remote command. We may have to attempt
4871 * this twice if the config data has provided a second choice
4878 if (ssh_fallback_cmd
) {
4879 subsys
= cfg
.ssh_subsys2
;
4880 cmd
= cfg
.remote_cmd_ptr2
;
4882 subsys
= cfg
.ssh_subsys
;
4883 cmd
= cfg
.remote_cmd_ptr
;
4886 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4887 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
4889 ssh2_pkt_addstring("subsystem");
4890 ssh2_pkt_addbool(1); /* want reply */
4891 ssh2_pkt_addstring(cmd
);
4893 ssh2_pkt_addstring("exec");
4894 ssh2_pkt_addbool(1); /* want reply */
4895 ssh2_pkt_addstring(cmd
);
4897 ssh2_pkt_addstring("shell");
4898 ssh2_pkt_addbool(1); /* want reply */
4902 crWaitUntilV(ispkt
);
4903 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4904 unsigned i
= ssh2_pkt_getuint32();
4905 struct ssh_channel
*c
;
4906 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4908 continue; /* nonexistent channel */
4909 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4911 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4912 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4913 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4914 bombout(("Unexpected response to shell/command request:"
4915 " packet type %d", pktin
.type
));
4919 * We failed to start the command. If this is the
4920 * fallback command, we really are finished; if it's
4921 * not, and if the fallback command exists, try falling
4922 * back to it before complaining.
4924 if (!ssh_fallback_cmd
&& cfg
.remote_cmd_ptr2
!= NULL
) {
4925 logevent("Primary command failed; attempting fallback");
4926 ssh_fallback_cmd
= TRUE
;
4929 bombout(("Server refused to start a shell/command"));
4932 logevent("Started a shell/command");
4937 ssh_state
= SSH_STATE_SESSION
;
4941 ssh_special(TS_EOF
);
4946 ldisc_send(NULL
, 0, 0); /* cause ldisc to notice changes */
4949 static int try_send
;
4953 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
4954 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
4957 unsigned i
= ssh2_pkt_getuint32();
4958 struct ssh_channel
*c
;
4959 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4961 continue; /* nonexistent channel */
4962 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
4963 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
4964 continue; /* extended but not stderr */
4965 ssh2_pkt_getstring(&data
, &length
);
4968 c
->v
.v2
.locwindow
-= length
;
4970 case CHAN_MAINSESSION
:
4972 from_backend(pktin
.type
==
4973 SSH2_MSG_CHANNEL_EXTENDED_DATA
,
4977 bufsize
= x11_send(c
->u
.x11
.s
, data
, length
);
4980 bufsize
= pfd_send(c
->u
.pfd
.s
, data
, length
);
4983 while (length
> 0) {
4984 if (c
->u
.a
.lensofar
< 4) {
4985 int l
= min(4 - c
->u
.a
.lensofar
, length
);
4986 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
4990 c
->u
.a
.lensofar
+= l
;
4992 if (c
->u
.a
.lensofar
== 4) {
4994 4 + GET_32BIT(c
->u
.a
.msglen
);
4995 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
4996 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
4998 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
5000 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
5002 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
5006 c
->u
.a
.lensofar
+= l
;
5008 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
5009 void *reply
, *sentreply
;
5011 agent_query(c
->u
.a
.message
,
5012 c
->u
.a
.totallen
, &reply
,
5017 /* Fake SSH_AGENT_FAILURE. */
5018 sentreply
= "\0\0\0\1\5";
5021 ssh2_add_channel_data(c
, sentreply
,
5026 sfree(c
->u
.a
.message
);
5027 c
->u
.a
.lensofar
= 0;
5034 * If we are not buffering too much data,
5035 * enlarge the window again at the remote side.
5037 if (bufsize
< OUR_V2_WINSIZE
)
5038 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
5040 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
5041 ssh_state
= SSH_STATE_CLOSED
;
5042 logevent("Received disconnect message");
5044 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
5045 unsigned i
= ssh2_pkt_getuint32();
5046 struct ssh_channel
*c
;
5048 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5050 continue; /* nonexistent channel */
5052 if (c
->type
== CHAN_X11
) {
5054 * Remote EOF on an X11 channel means we should
5055 * wrap up and close the channel ourselves.
5057 x11_close(c
->u
.x11
.s
);
5059 } else if (c
->type
== CHAN_AGENT
) {
5061 } else if (c
->type
== CHAN_SOCKDATA
) {
5062 pfd_close(c
->u
.pfd
.s
);
5065 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
5066 unsigned i
= ssh2_pkt_getuint32();
5067 struct ssh_channel
*c
;
5069 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5071 continue; /* nonexistent channel */
5072 /* Do pre-close processing on the channel. */
5074 case CHAN_MAINSESSION
:
5075 break; /* nothing to see here, move along */
5077 if (c
->u
.x11
.s
!= NULL
)
5078 x11_close(c
->u
.x11
.s
);
5085 if (c
->u
.pfd
.s
!= NULL
)
5086 pfd_close(c
->u
.pfd
.s
);
5090 if (c
->closes
== 0) {
5091 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
5092 ssh2_pkt_adduint32(c
->remoteid
);
5095 del234(ssh_channels
, c
);
5096 bufchain_clear(&c
->v
.v2
.outbuffer
);
5100 * See if that was the last channel left open.
5102 if (count234(ssh_channels
) == 0) {
5105 * We used to send SSH_MSG_DISCONNECT here,
5106 * because I'd believed that _every_ conforming
5107 * SSH2 connection had to end with a disconnect
5108 * being sent by at least one side; apparently
5109 * I was wrong and it's perfectly OK to
5110 * unceremoniously slam the connection shut
5111 * when you're done, and indeed OpenSSH feels
5112 * this is more polite than sending a
5113 * DISCONNECT. So now we don't.
5115 logevent("All channels closed. Disconnecting");
5116 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
5117 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
5118 ssh2_pkt_addstring("All open channels closed");
5119 ssh2_pkt_addstring("en"); /* language tag */
5122 ssh_state
= SSH_STATE_CLOSED
;
5125 continue; /* remote sends close; ignore (FIXME) */
5126 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
5127 unsigned i
= ssh2_pkt_getuint32();
5128 struct ssh_channel
*c
;
5129 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5131 continue; /* nonexistent channel */
5132 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
5134 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
5135 unsigned i
= ssh2_pkt_getuint32();
5136 struct ssh_channel
*c
;
5137 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5139 continue; /* nonexistent channel */
5140 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
5141 continue; /* dunno why they're confirming this */
5142 c
->remoteid
= ssh2_pkt_getuint32();
5143 c
->type
= CHAN_SOCKDATA
;
5144 c
->v
.v2
.remwindow
= ssh2_pkt_getuint32();
5145 c
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
5146 bufchain_init(&c
->v
.v2
.outbuffer
);
5148 pfd_confirm(c
->u
.pfd
.s
);
5151 * We have a pending close on this channel,
5152 * which we decided on before the server acked
5153 * the channel open. So now we know the
5154 * remoteid, we can close it again.
5156 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
5157 ssh2_pkt_adduint32(c
->remoteid
);
5160 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN_FAILURE
) {
5161 unsigned i
= ssh2_pkt_getuint32();
5162 struct ssh_channel
*c
;
5163 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5165 continue; /* nonexistent channel */
5166 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
5167 continue; /* dunno why they're failing this */
5169 logevent("Forwarded connection refused by server");
5171 pfd_close(c
->u
.pfd
.s
);
5173 del234(ssh_channels
, c
);
5175 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
5178 int typelen
, want_reply
;
5179 struct ssh_channel
*c
;
5181 localid
= ssh2_pkt_getuint32();
5182 ssh2_pkt_getstring(&type
, &typelen
);
5183 want_reply
= ssh2_pkt_getbool();
5186 * First, check that the channel exists. Otherwise,
5187 * we can instantly disconnect with a rude message.
5189 c
= find234(ssh_channels
, &localid
, ssh_channelfind
);
5192 sprintf(buf
, "Received channel request for nonexistent"
5193 " channel %d", localid
);
5195 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
5196 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
5197 ssh2_pkt_addstring(buf
);
5198 ssh2_pkt_addstring("en"); /* language tag */
5200 connection_fatal(buf
);
5201 ssh_state
= SSH_STATE_CLOSED
;
5206 * Having got the channel number, we now look at
5207 * the request type string to see if it's something
5210 if (typelen
== 11 && !memcmp(type
, "exit-status", 11) &&
5212 /* We recognise "exit-status" on the primary channel. */
5214 ssh_exitcode
= ssh2_pkt_getuint32();
5215 sprintf(buf
, "Server sent command exit status %d",
5219 ssh2_pkt_init(SSH2_MSG_CHANNEL_SUCCESS
);
5220 ssh2_pkt_adduint32(c
->remoteid
);
5225 * This is a channel request we don't know
5226 * about, so we now either ignore the request
5227 * or respond with CHANNEL_FAILURE, depending
5231 ssh2_pkt_init(SSH2_MSG_CHANNEL_FAILURE
);
5232 ssh2_pkt_adduint32(c
->remoteid
);
5236 } else if (pktin
.type
== SSH2_MSG_GLOBAL_REQUEST
) {
5238 int typelen
, want_reply
;
5240 ssh2_pkt_getstring(&type
, &typelen
);
5241 want_reply
= ssh2_pkt_getbool();
5244 * We currently don't support any global requests
5245 * at all, so we either ignore the request or
5246 * respond with REQUEST_FAILURE, depending on
5250 ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE
);
5253 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
5257 struct ssh_channel
*c
;
5258 unsigned remid
, winsize
, pktsize
;
5259 ssh2_pkt_getstring(&type
, &typelen
);
5260 c
= smalloc(sizeof(struct ssh_channel
));
5262 remid
= ssh2_pkt_getuint32();
5263 winsize
= ssh2_pkt_getuint32();
5264 pktsize
= ssh2_pkt_getuint32();
5266 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
5267 if (!ssh_X11_fwd_enabled
)
5268 error
= "X11 forwarding is not enabled";
5269 else if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) !=
5271 error
= "Unable to open an X11 connection";
5275 } else if (typelen
== 15 &&
5276 !memcmp(type
, "forwarded-tcpip", 15)) {
5277 struct ssh_rportfwd pf
, *realpf
;
5280 ssh2_pkt_getstring(&dummy
, &dummylen
);/* skip address */
5281 pf
.sport
= ssh2_pkt_getuint32();
5282 realpf
= find234(ssh_rportfwds
, &pf
, NULL
);
5283 if (realpf
== NULL
) {
5284 error
= "Remote port is not recognised";
5286 char *e
= pfd_newconnect(&c
->u
.pfd
.s
, realpf
->dhost
,
5289 sprintf(buf
, "Received remote port open request for %s:%d",
5290 realpf
->dhost
, realpf
->dport
);
5293 sprintf(buf
, "Port open failed: %s", e
);
5295 error
= "Port open failed";
5297 logevent("Forwarded port opened successfully");
5298 c
->type
= CHAN_SOCKDATA
;
5301 } else if (typelen
== 22 &&
5302 !memcmp(type
, "auth-agent@openssh.com", 3)) {
5303 if (!ssh_agentfwd_enabled
)
5304 error
= "Agent forwarding is not enabled";
5306 c
->type
= CHAN_AGENT
; /* identify channel type */
5307 c
->u
.a
.lensofar
= 0;
5310 error
= "Unsupported channel type requested";
5313 c
->remoteid
= remid
;
5315 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
5316 ssh2_pkt_adduint32(c
->remoteid
);
5317 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED
);
5318 ssh2_pkt_addstring(error
);
5319 ssh2_pkt_addstring("en"); /* language tag */
5323 c
->localid
= alloc_channel_id();
5325 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
5326 c
->v
.v2
.remwindow
= winsize
;
5327 c
->v
.v2
.remmaxpkt
= pktsize
;
5328 bufchain_init(&c
->v
.v2
.outbuffer
);
5329 add234(ssh_channels
, c
);
5330 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
5331 ssh2_pkt_adduint32(c
->remoteid
);
5332 ssh2_pkt_adduint32(c
->localid
);
5333 ssh2_pkt_adduint32(c
->v
.v2
.locwindow
);
5334 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
5338 bombout(("Strange packet received: type %d", pktin
.type
));
5343 * We have spare data. Add it to the channel buffer.
5345 ssh2_add_channel_data(mainchan
, in
, inlen
);
5350 struct ssh_channel
*c
;
5352 * Try to send data on all channels if we can.
5354 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++) {
5355 int bufsize
= ssh2_try_send(c
);
5358 case CHAN_MAINSESSION
:
5359 /* stdin need not receive an unthrottle
5360 * notification since it will be polled */
5363 x11_unthrottle(c
->u
.x11
.s
);
5366 /* agent sockets are request/response and need no
5367 * buffer management */
5370 pfd_unthrottle(c
->u
.pfd
.s
);
5382 * Handle the top-level SSH2 protocol.
5384 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
5386 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
5388 do_ssh2_authconn(in
, inlen
, ispkt
);
5392 * Called to set up the connection.
5394 * Returns an error message, or NULL on success.
5396 static char *ssh_init(char *host
, int port
, char **realhost
, int nodelay
)
5401 if (crypto_startup() == 0)
5402 return "Microsoft high encryption pack not installed!";
5408 ssh1_throttle_count
= 0;
5409 ssh_overall_bufsize
= 0;
5410 ssh_fallback_cmd
= 0;
5412 p
= connect_to_host(host
, port
, realhost
, nodelay
);
5420 * Called to send data down the Telnet connection.
5422 static int ssh_send(char *buf
, int len
)
5424 if (s
== NULL
|| ssh_protocol
== NULL
)
5427 ssh_protocol(buf
, len
, 0);
5429 return ssh_sendbuffer();
5433 * Called to query the current amount of buffered stdin data.
5435 static int ssh_sendbuffer(void)
5439 if (s
== NULL
|| ssh_protocol
== NULL
)
5443 * If the SSH socket itself has backed up, add the total backup
5444 * size on that to any individual buffer on the stdin channel.
5447 if (ssh_throttled_all
)
5448 override_value
= ssh_overall_bufsize
;
5450 if (ssh_version
== 1) {
5451 return override_value
;
5452 } else if (ssh_version
== 2) {
5453 if (!mainchan
|| mainchan
->closes
> 0)
5454 return override_value
;
5456 return override_value
+ bufchain_size(&mainchan
->v
.v2
.outbuffer
);
5463 * Called to set the size of the window from SSH's POV.
5465 static void ssh_size(void)
5467 switch (ssh_state
) {
5468 case SSH_STATE_BEFORE_SIZE
:
5469 case SSH_STATE_PREPACKET
:
5470 case SSH_STATE_CLOSED
:
5471 break; /* do nothing */
5472 case SSH_STATE_INTERMED
:
5473 size_needed
= TRUE
; /* buffer for later */
5475 case SSH_STATE_SESSION
:
5477 if (ssh_version
== 1) {
5478 send_packet(SSH1_CMSG_WINDOW_SIZE
,
5479 PKT_INT
, rows
, PKT_INT
, cols
,
5480 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
5482 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
5483 ssh2_pkt_adduint32(mainchan
->remoteid
);
5484 ssh2_pkt_addstring("window-change");
5485 ssh2_pkt_addbool(0);
5486 ssh2_pkt_adduint32(cols
);
5487 ssh2_pkt_adduint32(rows
);
5488 ssh2_pkt_adduint32(0);
5489 ssh2_pkt_adduint32(0);
5498 * Send Telnet special codes. TS_EOF is useful for `plink', so you
5499 * can send an EOF and collect resulting output (e.g. `plink
5502 static void ssh_special(Telnet_Special code
)
5504 if (code
== TS_EOF
) {
5505 if (ssh_state
!= SSH_STATE_SESSION
) {
5507 * Buffer the EOF in case we are pre-SESSION, so we can
5508 * send it as soon as we reach SESSION.
5514 if (ssh_version
== 1) {
5515 send_packet(SSH1_CMSG_EOF
, PKT_END
);
5517 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
5518 ssh2_pkt_adduint32(mainchan
->remoteid
);
5521 logevent("Sent EOF message");
5522 } else if (code
== TS_PING
) {
5523 if (ssh_state
== SSH_STATE_CLOSED
5524 || ssh_state
== SSH_STATE_PREPACKET
) return;
5525 if (ssh_version
== 1) {
5526 send_packet(SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
5528 ssh2_pkt_init(SSH2_MSG_IGNORE
);
5529 ssh2_pkt_addstring_start();
5537 void *new_sock_channel(Socket s
)
5539 struct ssh_channel
*c
;
5540 c
= smalloc(sizeof(struct ssh_channel
));
5543 c
->remoteid
= -1; /* to be set when open confirmed */
5544 c
->localid
= alloc_channel_id();
5546 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
5548 add234(ssh_channels
, c
);
5554 * This is called when stdout/stderr (the entity to which
5555 * from_backend sends data) manages to clear some backlog.
5557 void ssh_unthrottle(int bufsize
)
5559 if (ssh_version
== 1) {
5560 if (ssh1_stdout_throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
5561 ssh1_stdout_throttling
= 0;
5565 if (mainchan
&& mainchan
->closes
== 0)
5566 ssh2_set_window(mainchan
, OUR_V2_WINSIZE
- bufsize
);
5570 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
5572 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
5575 sprintf(buf
, "Opening forwarded connection to %.512s:%d", hostname
, port
);
5578 if (ssh_version
== 1) {
5579 send_packet(SSH1_MSG_PORT_OPEN
,
5580 PKT_INT
, c
->localid
,
5583 //PKT_STR, <org:orgport>,
5586 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
5587 ssh2_pkt_addstring("direct-tcpip");
5588 ssh2_pkt_adduint32(c
->localid
);
5589 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
5590 ssh2_pkt_adduint32(c
->v
.v2
.locwindow
);/* our window size */
5591 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
5592 ssh2_pkt_addstring(hostname
);
5593 ssh2_pkt_adduint32(port
);
5595 * We make up values for the originator data; partly it's
5596 * too much hassle to keep track, and partly I'm not
5597 * convinced the server should be told details like that
5598 * about my local network configuration.
5600 ssh2_pkt_addstring("client-side-connection");
5601 ssh2_pkt_adduint32(0);
5607 static Socket
ssh_socket(void)
5612 static int ssh_sendok(void)
5617 static int ssh_ldisc(int option
)
5619 if (option
== LD_ECHO
)
5621 if (option
== LD_EDIT
)
5626 static int ssh_return_exitcode(void)
5628 return ssh_exitcode
;
5631 Backend ssh_backend
= {
5638 ssh_return_exitcode
,