17 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
18 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
19 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
20 #define SSH1_CMSG_USER 4 /* 0x4 */
21 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
22 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
23 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
24 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
25 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
26 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
27 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
28 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
29 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
30 #define SSH1_SMSG_FAILURE 15 /* 0xf */
31 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
32 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
33 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
34 #define SSH1_CMSG_EOF 19 /* 0x13 */
35 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
36 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
37 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
38 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
39 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
40 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
41 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
42 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
43 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
44 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
45 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
46 #define SSH1_MSG_IGNORE 32 /* 0x20 */
47 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
48 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
49 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
50 #define SSH1_MSG_DEBUG 36 /* 0x24 */
51 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
52 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
53 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
54 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
55 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
56 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
57 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
59 #define SSH1_AUTH_TIS 5 /* 0x5 */
60 #define SSH1_AUTH_CCARD 16 /* 0x10 */
62 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
63 /* Mask for protoflags we will echo back to server if seen */
64 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
66 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
67 #define SSH2_MSG_IGNORE 2 /* 0x2 */
68 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
69 #define SSH2_MSG_DEBUG 4 /* 0x4 */
70 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
71 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
72 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
73 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
74 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
75 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
76 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
77 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
78 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
79 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
80 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
81 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
82 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
83 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
84 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
85 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
86 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
87 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
88 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
89 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
90 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
91 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
92 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
93 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
94 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
95 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
96 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
97 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
98 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
99 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
100 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
101 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
104 * Packet type contexts, so that ssh2_pkt_type can correctly decode
105 * the ambiguous type numbers back into the correct type strings.
107 #define SSH2_PKTCTX_DHGROUP1 0x0001
108 #define SSH2_PKTCTX_DHGEX 0x0002
109 #define SSH2_PKTCTX_PUBLICKEY 0x0010
110 #define SSH2_PKTCTX_PASSWORD 0x0020
111 #define SSH2_PKTCTX_KBDINTER 0x0040
112 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
114 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
115 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
116 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
117 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
118 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
119 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
120 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
121 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
122 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
123 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
124 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
125 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
126 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
127 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
128 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
130 static const char *const ssh2_disconnect_reasons
[] = {
132 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
133 "SSH_DISCONNECT_PROTOCOL_ERROR",
134 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
135 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
136 "SSH_DISCONNECT_MAC_ERROR",
137 "SSH_DISCONNECT_COMPRESSION_ERROR",
138 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
139 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
140 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
141 "SSH_DISCONNECT_CONNECTION_LOST",
142 "SSH_DISCONNECT_BY_APPLICATION",
143 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
144 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
145 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
146 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
149 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
150 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
151 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
152 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
154 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
157 * Various remote-bug flags.
159 #define BUG_CHOKES_ON_SSH1_IGNORE 1
160 #define BUG_SSH2_HMAC 2
161 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
162 #define BUG_CHOKES_ON_RSA 8
163 #define BUG_SSH2_RSA_PADDING 16
164 #define BUG_SSH2_DERIVEKEY 32
165 #define BUG_SSH2_DH_GEX 64
166 #define BUG_SSH2_PK_SESSIONID 128
168 #define translate(x) if (type == x) return #x
169 #define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
170 static char *ssh1_pkt_type(int type
)
172 translate(SSH1_MSG_DISCONNECT
);
173 translate(SSH1_SMSG_PUBLIC_KEY
);
174 translate(SSH1_CMSG_SESSION_KEY
);
175 translate(SSH1_CMSG_USER
);
176 translate(SSH1_CMSG_AUTH_RSA
);
177 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE
);
178 translate(SSH1_CMSG_AUTH_RSA_RESPONSE
);
179 translate(SSH1_CMSG_AUTH_PASSWORD
);
180 translate(SSH1_CMSG_REQUEST_PTY
);
181 translate(SSH1_CMSG_WINDOW_SIZE
);
182 translate(SSH1_CMSG_EXEC_SHELL
);
183 translate(SSH1_CMSG_EXEC_CMD
);
184 translate(SSH1_SMSG_SUCCESS
);
185 translate(SSH1_SMSG_FAILURE
);
186 translate(SSH1_CMSG_STDIN_DATA
);
187 translate(SSH1_SMSG_STDOUT_DATA
);
188 translate(SSH1_SMSG_STDERR_DATA
);
189 translate(SSH1_CMSG_EOF
);
190 translate(SSH1_SMSG_EXIT_STATUS
);
191 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
);
192 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE
);
193 translate(SSH1_MSG_CHANNEL_DATA
);
194 translate(SSH1_MSG_CHANNEL_CLOSE
);
195 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
);
196 translate(SSH1_SMSG_X11_OPEN
);
197 translate(SSH1_CMSG_PORT_FORWARD_REQUEST
);
198 translate(SSH1_MSG_PORT_OPEN
);
199 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING
);
200 translate(SSH1_SMSG_AGENT_OPEN
);
201 translate(SSH1_MSG_IGNORE
);
202 translate(SSH1_CMSG_EXIT_CONFIRMATION
);
203 translate(SSH1_CMSG_X11_REQUEST_FORWARDING
);
204 translate(SSH1_CMSG_AUTH_RHOSTS_RSA
);
205 translate(SSH1_MSG_DEBUG
);
206 translate(SSH1_CMSG_REQUEST_COMPRESSION
);
207 translate(SSH1_CMSG_AUTH_TIS
);
208 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE
);
209 translate(SSH1_CMSG_AUTH_TIS_RESPONSE
);
210 translate(SSH1_CMSG_AUTH_CCARD
);
211 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE
);
212 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE
);
215 static char *ssh2_pkt_type(int pkt_ctx
, int type
)
217 translate(SSH2_MSG_DISCONNECT
);
218 translate(SSH2_MSG_IGNORE
);
219 translate(SSH2_MSG_UNIMPLEMENTED
);
220 translate(SSH2_MSG_DEBUG
);
221 translate(SSH2_MSG_SERVICE_REQUEST
);
222 translate(SSH2_MSG_SERVICE_ACCEPT
);
223 translate(SSH2_MSG_KEXINIT
);
224 translate(SSH2_MSG_NEWKEYS
);
225 translatec(SSH2_MSG_KEXDH_INIT
, SSH2_PKTCTX_DHGROUP1
);
226 translatec(SSH2_MSG_KEXDH_REPLY
, SSH2_PKTCTX_DHGROUP1
);
227 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST
, SSH2_PKTCTX_DHGEX
);
228 translatec(SSH2_MSG_KEX_DH_GEX_GROUP
, SSH2_PKTCTX_DHGEX
);
229 translatec(SSH2_MSG_KEX_DH_GEX_INIT
, SSH2_PKTCTX_DHGEX
);
230 translatec(SSH2_MSG_KEX_DH_GEX_REPLY
, SSH2_PKTCTX_DHGEX
);
231 translate(SSH2_MSG_USERAUTH_REQUEST
);
232 translate(SSH2_MSG_USERAUTH_FAILURE
);
233 translate(SSH2_MSG_USERAUTH_SUCCESS
);
234 translate(SSH2_MSG_USERAUTH_BANNER
);
235 translatec(SSH2_MSG_USERAUTH_PK_OK
, SSH2_PKTCTX_PUBLICKEY
);
236 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ
, SSH2_PKTCTX_PASSWORD
);
237 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST
, SSH2_PKTCTX_KBDINTER
);
238 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE
, SSH2_PKTCTX_KBDINTER
);
239 translate(SSH2_MSG_GLOBAL_REQUEST
);
240 translate(SSH2_MSG_REQUEST_SUCCESS
);
241 translate(SSH2_MSG_REQUEST_FAILURE
);
242 translate(SSH2_MSG_CHANNEL_OPEN
);
243 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
244 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
245 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
246 translate(SSH2_MSG_CHANNEL_DATA
);
247 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA
);
248 translate(SSH2_MSG_CHANNEL_EOF
);
249 translate(SSH2_MSG_CHANNEL_CLOSE
);
250 translate(SSH2_MSG_CHANNEL_REQUEST
);
251 translate(SSH2_MSG_CHANNEL_SUCCESS
);
252 translate(SSH2_MSG_CHANNEL_FAILURE
);
258 #define GET_32BIT(cp) \
259 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
260 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
261 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
262 ((unsigned long)(unsigned char)(cp)[3]))
264 #define PUT_32BIT(cp, value) { \
265 (cp)[0] = (unsigned char)((value) >> 24); \
266 (cp)[1] = (unsigned char)((value) >> 16); \
267 (cp)[2] = (unsigned char)((value) >> 8); \
268 (cp)[3] = (unsigned char)(value); }
270 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
273 * Coroutine mechanics for the sillier bits of the code. If these
274 * macros look impenetrable to you, you might find it helpful to
277 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
279 * which explains the theory behind these macros.
281 * In particular, if you are getting `case expression not constant'
282 * errors when building with MS Visual Studio, this is because MS's
283 * Edit and Continue debugging feature causes their compiler to
284 * violate ANSI C. To disable Edit and Continue debugging:
286 * - right-click ssh.c in the FileView
288 * - select the C/C++ tab and the General category
289 * - under `Debug info:', select anything _other_ than `Program
290 * Database for Edit and Continue'.
292 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
295 if (!ssh->t) ssh->t = smalloc(sizeof(struct t)); \
297 #define crFinish(z) } *crLine = 0; return (z); }
298 #define crFinishV } *crLine = 0; return; }
299 #define crReturn(z) \
301 *crLine =__LINE__; return (z); case __LINE__:;\
305 *crLine=__LINE__; return; case __LINE__:;\
307 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
308 #define crStopV do{ *crLine = 0; return; }while(0)
309 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
310 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
312 typedef struct ssh_tag
*Ssh
;
314 static void ssh2_pkt_init(Ssh
, int pkt_type
);
315 static void ssh2_pkt_addbool(Ssh
, unsigned char value
);
316 static void ssh2_pkt_adduint32(Ssh
, unsigned long value
);
317 static void ssh2_pkt_addstring_start(Ssh
);
318 static void ssh2_pkt_addstring_str(Ssh
, char *data
);
319 static void ssh2_pkt_addstring_data(Ssh
, char *data
, int len
);
320 static void ssh2_pkt_addstring(Ssh
, char *data
);
321 static unsigned char *ssh2_mpint_fmt(Bignum b
, int *len
);
322 static void ssh2_pkt_addmp(Ssh
, Bignum b
);
323 static int ssh2_pkt_construct(Ssh
);
324 static void ssh2_pkt_send(Ssh
);
327 * Buffer management constants. There are several of these for
328 * various different purposes:
330 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
331 * on a local data stream before we throttle the whole SSH
332 * connection (in SSH1 only). Throttling the whole connection is
333 * pretty drastic so we set this high in the hope it won't
336 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
337 * on the SSH connection itself before we defensively throttle
338 * _all_ local data streams. This is pretty drastic too (though
339 * thankfully unlikely in SSH2 since the window mechanism should
340 * ensure that the server never has any need to throttle its end
341 * of the connection), so we set this high as well.
343 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
347 #define SSH1_BUFFER_LIMIT 32768
348 #define SSH_MAX_BACKLOG 32768
349 #define OUR_V2_WINSIZE 16384
351 const static struct ssh_kex
*kex_algs
[] = {
352 &ssh_diffiehellman_gex
,
356 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
358 static void *nullmac_make_context(void)
362 static void nullmac_free_context(void *handle
)
365 static void nullmac_key(void *handle
, unsigned char *key
)
368 static void nullmac_generate(void *handle
, unsigned char *blk
, int len
,
372 static int nullmac_verify(void *handle
, unsigned char *blk
, int len
,
377 const static struct ssh_mac ssh_mac_none
= {
378 nullmac_make_context
, nullmac_free_context
, nullmac_key
,
379 nullmac_generate
, nullmac_verify
, "none", 0
381 const static struct ssh_mac
*macs
[] = {
382 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
384 const static struct ssh_mac
*buggymacs
[] = {
385 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
388 static void *ssh_comp_none_init(void)
392 static void ssh_comp_none_cleanup(void *handle
)
395 static int ssh_comp_none_block(void *handle
, unsigned char *block
, int len
,
396 unsigned char **outblock
, int *outlen
)
400 static int ssh_comp_none_disable(void *handle
)
404 const static struct ssh_compress ssh_comp_none
= {
406 ssh_comp_none_init
, ssh_comp_none_cleanup
, ssh_comp_none_block
,
407 ssh_comp_none_init
, ssh_comp_none_cleanup
, ssh_comp_none_block
,
408 ssh_comp_none_disable
, NULL
410 extern const struct ssh_compress ssh_zlib
;
411 const static struct ssh_compress
*compressions
[] = {
412 &ssh_zlib
, &ssh_comp_none
415 enum { /* channel types */
420 CHAN_SOCKDATA_DORMANT
/* one the remote hasn't confirmed */
424 * 2-3-4 tree storing channels.
427 Ssh ssh
; /* pointer back to main context */
428 unsigned remoteid
, localid
;
431 * In SSH1, this value contains four bits:
433 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
434 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
435 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
436 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
438 * A channel is completely finished with when all four bits are set.
442 struct ssh1_data_channel
{
445 struct ssh2_data_channel
{
447 unsigned remwindow
, remmaxpkt
;
452 struct ssh_agent_channel
{
453 unsigned char *message
;
454 unsigned char msglen
[4];
455 int lensofar
, totallen
;
457 struct ssh_x11_channel
{
460 struct ssh_pfd_channel
{
467 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
468 * 2 use this structure in different ways, reflecting SSH 2's
469 * altogether saner approach to port forwarding.
471 * In SSH 1, you arrange a remote forwarding by sending the server
472 * the remote port number, and the local destination host:port.
473 * When a connection comes in, the server sends you back that
474 * host:port pair, and you connect to it. This is a ready-made
475 * security hole if you're not on the ball: a malicious server
476 * could send you back _any_ host:port pair, so if you trustingly
477 * connect to the address it gives you then you've just opened the
478 * entire inside of your corporate network just by connecting
479 * through it to a dodgy SSH server. Hence, we must store a list of
480 * host:port pairs we _are_ trying to forward to, and reject a
481 * connection request from the server if it's not in the list.
483 * In SSH 2, each side of the connection minds its own business and
484 * doesn't send unnecessary information to the other. You arrange a
485 * remote forwarding by sending the server just the remote port
486 * number. When a connection comes in, the server tells you which
487 * of its ports was connected to; and _you_ have to remember what
488 * local host:port pair went with that port number.
490 * Hence: in SSH 1 this structure stores host:port pairs we intend
491 * to allow connections to, and is indexed by those host:port
492 * pairs. In SSH 2 it stores a mapping from source port to
493 * destination host:port pair, and is indexed by source port.
495 struct ssh_rportfwd
{
496 unsigned sport
, dport
;
509 static void ssh1_protocol(Ssh ssh
, unsigned char *in
, int inlen
, int ispkt
);
510 static void ssh2_protocol(Ssh ssh
, unsigned char *in
, int inlen
, int ispkt
);
511 static void ssh_size(void *handle
, int width
, int height
);
512 static void ssh_special(void *handle
, Telnet_Special
);
513 static int ssh2_try_send(struct ssh_channel
*c
);
514 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
);
515 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
);
516 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
);
517 static int ssh_sendbuffer(void *handle
);
519 struct rdpkt1_state_tag
{
520 long len
, pad
, biglen
, to_read
;
521 unsigned long realcrc
, gotcrc
;
527 struct rdpkt2_state_tag
{
528 long len
, pad
, payload
, packetlen
, maclen
;
531 unsigned long incoming_sequence
;
535 const struct plug_function_table
*fn
;
536 /* the above field _must_ be first in the structure */
538 SHA_State exhash
, exhashbase
;
545 unsigned char session_key
[32];
547 int v1_remote_protoflags
;
548 int v1_local_protoflags
;
549 int agentfwd_enabled
;
552 const struct ssh_cipher
*cipher
;
555 const struct ssh2_cipher
*cscipher
, *sccipher
;
556 void *cs_cipher_ctx
, *sc_cipher_ctx
;
557 const struct ssh_mac
*csmac
, *scmac
;
558 void *cs_mac_ctx
, *sc_mac_ctx
;
559 const struct ssh_compress
*cscomp
, *sccomp
;
560 void *cs_comp_ctx
, *sc_comp_ctx
;
561 const struct ssh_kex
*kex
;
562 const struct ssh_signkey
*hostkey
;
563 unsigned char v2_session_id
[20];
569 int echoing
, editing
;
573 int term_width
, term_height
;
575 tree234
*channels
; /* indexed by local id */
576 struct ssh_channel
*mainchan
; /* primary session channel */
583 SSH_STATE_BEFORE_SIZE
,
589 int size_needed
, eof_needed
;
592 struct Packet pktout
;
593 unsigned char *deferred_send_data
;
594 int deferred_len
, deferred_size
;
597 * Gross hack: pscp will try to start SFTP but fall back to
598 * scp1 if that fails. This variable is the means by which
599 * scp.c can reach into the SSH code and find out which one it
605 * Used for username and password input.
607 char *userpass_input_buffer
;
608 int userpass_input_buflen
;
609 int userpass_input_bufpos
;
610 int userpass_input_echo
;
612 char *portfwd_strptr
;
618 int v1_throttle_count
;
621 int v1_stdout_throttling
;
622 int v2_outgoing_sequence
;
624 int ssh1_rdpkt_crstate
;
625 int ssh2_rdpkt_crstate
;
626 int do_ssh_init_crstate
;
627 int ssh_gotdata_crstate
;
628 int ssh1_protocol_crstate
;
629 int do_ssh1_login_crstate
;
630 int do_ssh2_transport_crstate
;
631 int do_ssh2_authconn_crstate
;
633 void *do_ssh_init_state
;
634 void *do_ssh1_login_state
;
635 void *do_ssh2_transport_state
;
636 void *do_ssh2_authconn_state
;
638 struct rdpkt1_state_tag rdpkt1_state
;
639 struct rdpkt2_state_tag rdpkt2_state
;
641 void (*protocol
) (Ssh ssh
, unsigned char *in
, int inlen
, int ispkt
);
642 int (*s_rdpkt
) (Ssh ssh
, unsigned char **data
, int *datalen
);
645 * We maintain a full _copy_ of a Config structure here, not
646 * merely a pointer to it. That way, when we're passed a new
647 * one for reconfiguration, we can check the differences and
648 * potentially reconfigure port forwardings etc in mid-session.
653 #define logevent(s) logevent(ssh->frontend, s)
655 /* logevent, only printf-formatted. */
656 static void logeventf(Ssh ssh
, char *fmt
, ...)
662 buf
= dupvprintf(fmt
, ap
);
668 #define bombout(msg) ( ssh->state = SSH_STATE_CLOSED, \
669 (ssh->s ? sk_close(ssh->s), ssh->s = NULL : 0), \
670 logeventf msg, connection_fatal msg )
672 static int ssh_channelcmp(void *av
, void *bv
)
674 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
675 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
676 if (a
->localid
< b
->localid
)
678 if (a
->localid
> b
->localid
)
682 static int ssh_channelfind(void *av
, void *bv
)
684 unsigned *a
= (unsigned *) av
;
685 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
693 static int ssh_rportcmp_ssh1(void *av
, void *bv
)
695 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
696 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
698 if ( (i
= strcmp(a
->dhost
, b
->dhost
)) != 0)
699 return i
< 0 ?
-1 : +1;
700 if (a
->dport
> b
->dport
)
702 if (a
->dport
< b
->dport
)
707 static int ssh_rportcmp_ssh2(void *av
, void *bv
)
709 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
710 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
712 if (a
->sport
> b
->sport
)
714 if (a
->sport
< b
->sport
)
719 static int alloc_channel_id(Ssh ssh
)
721 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
722 unsigned low
, high
, mid
;
724 struct ssh_channel
*c
;
727 * First-fit allocation of channel numbers: always pick the
728 * lowest unused one. To do this, binary-search using the
729 * counted B-tree to find the largest channel ID which is in a
730 * contiguous sequence from the beginning. (Precisely
731 * everything in that sequence must have ID equal to its tree
732 * index plus CHANNEL_NUMBER_OFFSET.)
734 tsize
= count234(ssh
->channels
);
738 while (high
- low
> 1) {
739 mid
= (high
+ low
) / 2;
740 c
= index234(ssh
->channels
, mid
);
741 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
742 low
= mid
; /* this one is fine */
744 high
= mid
; /* this one is past it */
747 * Now low points to either -1, or the tree index of the
748 * largest ID in the initial sequence.
751 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
752 assert(NULL
== find234(ssh
->channels
, &i
, ssh_channelfind
));
754 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
757 static void c_write(Ssh ssh
, const char *buf
, int len
)
759 if ((flags
& FLAG_STDERR
)) {
761 for (i
= 0; i
< len
; i
++)
763 fputc(buf
[i
], stderr
);
766 from_backend(ssh
->frontend
, 1, buf
, len
);
769 static void c_write_untrusted(Ssh ssh
, const char *buf
, int len
)
772 for (i
= 0; i
< len
; i
++) {
774 c_write(ssh
, "\r\n", 2);
775 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
776 c_write(ssh
, buf
+ i
, 1);
780 static void c_write_str(Ssh ssh
, const char *buf
)
782 c_write(ssh
, buf
, strlen(buf
));
786 * Collect incoming data in the incoming packet buffer.
787 * Decipher and verify the packet when it is completely read.
788 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
789 * Update the *data and *datalen variables.
790 * Return the additional nr of bytes needed, or 0 when
791 * a complete packet is available.
793 static int ssh1_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
795 struct rdpkt1_state_tag
*st
= &ssh
->rdpkt1_state
;
797 crBegin(ssh
->ssh1_rdpkt_crstate
);
802 ssh
->pktin
.length
= 0;
804 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
805 while ((*datalen
) == 0)
807 st
->len
= (st
->len
<< 8) + **data
;
808 (*data
)++, (*datalen
)--;
811 st
->pad
= 8 - (st
->len
% 8);
812 st
->biglen
= st
->len
+ st
->pad
;
813 ssh
->pktin
.length
= st
->len
- 5;
815 if (ssh
->pktin
.maxlen
< st
->biglen
) {
816 ssh
->pktin
.maxlen
= st
->biglen
;
817 ssh
->pktin
.data
= srealloc(ssh
->pktin
.data
, st
->biglen
+ APIEXTRA
);
820 st
->to_read
= st
->biglen
;
821 st
->p
= ssh
->pktin
.data
;
822 while (st
->to_read
> 0) {
823 st
->chunk
= st
->to_read
;
824 while ((*datalen
) == 0)
825 crReturn(st
->to_read
);
826 if (st
->chunk
> (*datalen
))
827 st
->chunk
= (*datalen
);
828 memcpy(st
->p
, *data
, st
->chunk
);
830 *datalen
-= st
->chunk
;
832 st
->to_read
-= st
->chunk
;
835 if (ssh
->cipher
&& detect_attack(ssh
->crcda_ctx
, ssh
->pktin
.data
,
837 bombout((ssh
,"Network attack (CRC compensation) detected!"));
842 ssh
->cipher
->decrypt(ssh
->v1_cipher_ctx
, ssh
->pktin
.data
, st
->biglen
);
844 st
->realcrc
= crc32(ssh
->pktin
.data
, st
->biglen
- 4);
845 st
->gotcrc
= GET_32BIT(ssh
->pktin
.data
+ st
->biglen
- 4);
846 if (st
->gotcrc
!= st
->realcrc
) {
847 bombout((ssh
,"Incorrect CRC received on packet"));
851 ssh
->pktin
.body
= ssh
->pktin
.data
+ st
->pad
+ 1;
853 if (ssh
->v1_compressing
) {
854 unsigned char *decompblk
;
856 zlib_decompress_block(ssh
->sc_comp_ctx
,
857 ssh
->pktin
.body
- 1, ssh
->pktin
.length
+ 1,
858 &decompblk
, &decomplen
);
860 if (ssh
->pktin
.maxlen
< st
->pad
+ decomplen
) {
861 ssh
->pktin
.maxlen
= st
->pad
+ decomplen
;
862 ssh
->pktin
.data
= srealloc(ssh
->pktin
.data
,
863 ssh
->pktin
.maxlen
+ APIEXTRA
);
864 ssh
->pktin
.body
= ssh
->pktin
.data
+ st
->pad
+ 1;
867 memcpy(ssh
->pktin
.body
- 1, decompblk
, decomplen
);
869 ssh
->pktin
.length
= decomplen
- 1;
872 ssh
->pktin
.type
= ssh
->pktin
.body
[-1];
875 log_packet(ssh
->logctx
,
876 PKT_INCOMING
, ssh
->pktin
.type
,
877 ssh1_pkt_type(ssh
->pktin
.type
),
878 ssh
->pktin
.body
, ssh
->pktin
.length
);
880 if (ssh
->pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
881 ssh
->pktin
.type
== SSH1_SMSG_STDERR_DATA
||
882 ssh
->pktin
.type
== SSH1_MSG_DEBUG
||
883 ssh
->pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
884 ssh
->pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
885 long stringlen
= GET_32BIT(ssh
->pktin
.body
);
886 if (stringlen
+ 4 != ssh
->pktin
.length
) {
887 bombout((ssh
,"Received data packet with bogus string length"));
892 if (ssh
->pktin
.type
== SSH1_MSG_DEBUG
) {
893 /* log debug message */
895 int stringlen
= GET_32BIT(ssh
->pktin
.body
);
896 strcpy(buf
, "Remote debug message: ");
899 memcpy(buf
+ 8, ssh
->pktin
.body
+ 4, stringlen
);
900 buf
[8 + stringlen
] = '\0';
903 } else if (ssh
->pktin
.type
== SSH1_MSG_IGNORE
) {
908 if (ssh
->pktin
.type
== SSH1_MSG_DISCONNECT
) {
909 /* log reason code in disconnect message */
911 unsigned msglen
= GET_32BIT(ssh
->pktin
.body
);
913 strcpy(buf
, "Remote sent disconnect: ");
914 nowlen
= strlen(buf
);
915 if (msglen
> sizeof(buf
) - nowlen
- 1)
916 msglen
= sizeof(buf
) - nowlen
- 1;
917 memcpy(buf
+ nowlen
, ssh
->pktin
.body
+ 4, msglen
);
918 buf
[nowlen
+ msglen
] = '\0';
919 /* logevent(buf); (this is now done within the bombout macro) */
920 bombout((ssh
,"Server sent disconnect message:\n\"%s\"", buf
+nowlen
));
927 static int ssh2_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
929 struct rdpkt2_state_tag
*st
= &ssh
->rdpkt2_state
;
931 crBegin(ssh
->ssh2_rdpkt_crstate
);
935 ssh
->pktin
.length
= 0;
937 st
->cipherblk
= ssh
->sccipher
->blksize
;
940 if (st
->cipherblk
< 8)
943 if (ssh
->pktin
.maxlen
< st
->cipherblk
) {
944 ssh
->pktin
.maxlen
= st
->cipherblk
;
945 ssh
->pktin
.data
= srealloc(ssh
->pktin
.data
, st
->cipherblk
+ APIEXTRA
);
949 * Acquire and decrypt the first block of the packet. This will
950 * contain the length and padding details.
952 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
953 while ((*datalen
) == 0)
954 crReturn(st
->cipherblk
- st
->i
);
955 ssh
->pktin
.data
[st
->i
] = *(*data
)++;
960 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
961 ssh
->pktin
.data
, st
->cipherblk
);
964 * Now get the length and padding figures.
966 st
->len
= GET_32BIT(ssh
->pktin
.data
);
967 st
->pad
= ssh
->pktin
.data
[4];
970 * _Completely_ silly lengths should be stomped on before they
971 * do us any more damage.
973 if (st
->len
< 0 || st
->pad
< 0 || st
->len
+ st
->pad
< 0) {
974 bombout((ssh
,"Incoming packet was garbled on decryption"));
979 * This enables us to deduce the payload length.
981 st
->payload
= st
->len
- st
->pad
- 1;
983 ssh
->pktin
.length
= st
->payload
+ 5;
986 * So now we can work out the total packet length.
988 st
->packetlen
= st
->len
+ 4;
989 st
->maclen
= ssh
->scmac ? ssh
->scmac
->len
: 0;
992 * Adjust memory allocation if packet is too big.
994 if (ssh
->pktin
.maxlen
< st
->packetlen
+ st
->maclen
) {
995 ssh
->pktin
.maxlen
= st
->packetlen
+ st
->maclen
;
996 ssh
->pktin
.data
= srealloc(ssh
->pktin
.data
,
997 ssh
->pktin
.maxlen
+ APIEXTRA
);
1001 * Read and decrypt the remainder of the packet.
1003 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
1005 while ((*datalen
) == 0)
1006 crReturn(st
->packetlen
+ st
->maclen
- st
->i
);
1007 ssh
->pktin
.data
[st
->i
] = *(*data
)++;
1010 /* Decrypt everything _except_ the MAC. */
1012 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
1013 ssh
->pktin
.data
+ st
->cipherblk
,
1014 st
->packetlen
- st
->cipherblk
);
1020 && !ssh
->scmac
->verify(ssh
->sc_mac_ctx
, ssh
->pktin
.data
, st
->len
+ 4,
1021 st
->incoming_sequence
)) {
1022 bombout((ssh
,"Incorrect MAC received on packet"));
1025 st
->incoming_sequence
++; /* whether or not we MACed */
1028 * Decompress packet payload.
1031 unsigned char *newpayload
;
1034 ssh
->sccomp
->decompress(ssh
->sc_comp_ctx
,
1035 ssh
->pktin
.data
+ 5, ssh
->pktin
.length
- 5,
1036 &newpayload
, &newlen
)) {
1037 if (ssh
->pktin
.maxlen
< newlen
+ 5) {
1038 ssh
->pktin
.maxlen
= newlen
+ 5;
1039 ssh
->pktin
.data
= srealloc(ssh
->pktin
.data
,
1040 ssh
->pktin
.maxlen
+ APIEXTRA
);
1042 ssh
->pktin
.length
= 5 + newlen
;
1043 memcpy(ssh
->pktin
.data
+ 5, newpayload
, newlen
);
1048 ssh
->pktin
.savedpos
= 6;
1049 ssh
->pktin
.type
= ssh
->pktin
.data
[5];
1052 log_packet(ssh
->logctx
, PKT_INCOMING
, ssh
->pktin
.type
,
1053 ssh2_pkt_type(ssh
->pkt_ctx
, ssh
->pktin
.type
),
1054 ssh
->pktin
.data
+6, ssh
->pktin
.length
-6);
1056 switch (ssh
->pktin
.type
) {
1058 * These packets we must handle instantly.
1060 case SSH2_MSG_DISCONNECT
:
1062 /* log reason code in disconnect message */
1065 int reason
= GET_32BIT(ssh
->pktin
.data
+ 6);
1066 unsigned msglen
= GET_32BIT(ssh
->pktin
.data
+ 10);
1068 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
1069 buf
= dupprintf("Received disconnect message (%s)",
1070 ssh2_disconnect_reasons
[reason
]);
1072 buf
= dupprintf("Received disconnect message (unknown"
1073 " type %d)", reason
);
1077 buf
= dupprintf("Disconnection message text: %n%.*s",
1078 &nowlen
, msglen
, ssh
->pktin
.data
+ 14);
1080 bombout((ssh
,"Server sent disconnect message\ntype %d (%s):\n\"%s\"",
1082 (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) ?
1083 ssh2_disconnect_reasons
[reason
] : "unknown",
1089 case SSH2_MSG_IGNORE
:
1091 case SSH2_MSG_DEBUG
:
1093 /* log the debug message */
1095 /* int display = ssh->pktin.body[6]; */
1096 int stringlen
= GET_32BIT(ssh
->pktin
.data
+7);
1098 strcpy(buf
, "Remote debug message: ");
1099 prefix
= strlen(buf
);
1100 if (stringlen
> (int)(sizeof(buf
)-prefix
-1))
1101 stringlen
= sizeof(buf
)-prefix
-1;
1102 memcpy(buf
+ prefix
, ssh
->pktin
.data
+ 11, stringlen
);
1103 buf
[prefix
+ stringlen
] = '\0';
1106 goto next_packet
; /* FIXME: print the debug message */
1109 * These packets we need do nothing about here.
1111 case SSH2_MSG_UNIMPLEMENTED
:
1112 case SSH2_MSG_SERVICE_REQUEST
:
1113 case SSH2_MSG_SERVICE_ACCEPT
:
1114 case SSH2_MSG_KEXINIT
:
1115 case SSH2_MSG_NEWKEYS
:
1116 case SSH2_MSG_KEXDH_INIT
:
1117 case SSH2_MSG_KEXDH_REPLY
:
1118 /* case SSH2_MSG_KEX_DH_GEX_REQUEST: duplicate case value */
1119 /* case SSH2_MSG_KEX_DH_GEX_GROUP: duplicate case value */
1120 case SSH2_MSG_KEX_DH_GEX_INIT
:
1121 case SSH2_MSG_KEX_DH_GEX_REPLY
:
1122 case SSH2_MSG_USERAUTH_REQUEST
:
1123 case SSH2_MSG_USERAUTH_FAILURE
:
1124 case SSH2_MSG_USERAUTH_SUCCESS
:
1125 case SSH2_MSG_USERAUTH_BANNER
:
1126 case SSH2_MSG_USERAUTH_PK_OK
:
1127 /* case SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: duplicate case value */
1128 /* case SSH2_MSG_USERAUTH_INFO_REQUEST: duplicate case value */
1129 case SSH2_MSG_USERAUTH_INFO_RESPONSE
:
1130 case SSH2_MSG_GLOBAL_REQUEST
:
1131 case SSH2_MSG_REQUEST_SUCCESS
:
1132 case SSH2_MSG_REQUEST_FAILURE
:
1133 case SSH2_MSG_CHANNEL_OPEN
:
1134 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
:
1135 case SSH2_MSG_CHANNEL_OPEN_FAILURE
:
1136 case SSH2_MSG_CHANNEL_WINDOW_ADJUST
:
1137 case SSH2_MSG_CHANNEL_DATA
:
1138 case SSH2_MSG_CHANNEL_EXTENDED_DATA
:
1139 case SSH2_MSG_CHANNEL_EOF
:
1140 case SSH2_MSG_CHANNEL_CLOSE
:
1141 case SSH2_MSG_CHANNEL_REQUEST
:
1142 case SSH2_MSG_CHANNEL_SUCCESS
:
1143 case SSH2_MSG_CHANNEL_FAILURE
:
1147 * For anything else we send SSH2_MSG_UNIMPLEMENTED.
1150 ssh2_pkt_init(ssh
, SSH2_MSG_UNIMPLEMENTED
);
1151 ssh2_pkt_adduint32(ssh
, st
->incoming_sequence
- 1);
1159 static void ssh1_pktout_size(Ssh ssh
, int len
)
1163 len
+= 5; /* type and CRC */
1164 pad
= 8 - (len
% 8);
1167 ssh
->pktout
.length
= len
- 5;
1168 if (ssh
->pktout
.maxlen
< biglen
) {
1169 ssh
->pktout
.maxlen
= biglen
;
1171 /* Allocate enough buffer space for extra block
1172 * for MS CryptEncrypt() */
1173 ssh
->pktout
.data
= srealloc(ssh
->pktout
.data
, biglen
+ 12);
1175 ssh
->pktout
.data
= srealloc(ssh
->pktout
.data
, biglen
+ 4);
1178 ssh
->pktout
.body
= ssh
->pktout
.data
+ 4 + pad
+ 1;
1181 static void s_wrpkt_start(Ssh ssh
, int type
, int len
)
1183 ssh1_pktout_size(ssh
, len
);
1184 ssh
->pktout
.type
= type
;
1187 static int s_wrpkt_prepare(Ssh ssh
)
1193 * XXX various versions of SC (including 8.8.4) screw up the
1194 * register allocation in this function and use the same register
1195 * (D6) for len and as a temporary, with predictable results. The
1196 * following sledgehammer prevents this.
1202 ssh
->pktout
.body
[-1] = ssh
->pktout
.type
;
1205 log_packet(ssh
->logctx
, PKT_OUTGOING
, ssh
->pktout
.type
,
1206 ssh1_pkt_type(ssh
->pktout
.type
),
1207 ssh
->pktout
.body
, ssh
->pktout
.length
);
1209 if (ssh
->v1_compressing
) {
1210 unsigned char *compblk
;
1212 zlib_compress_block(ssh
->cs_comp_ctx
,
1213 ssh
->pktout
.body
- 1, ssh
->pktout
.length
+ 1,
1214 &compblk
, &complen
);
1215 ssh1_pktout_size(ssh
, complen
- 1);
1216 memcpy(ssh
->pktout
.body
- 1, compblk
, complen
);
1220 len
= ssh
->pktout
.length
+ 5; /* type and CRC */
1221 pad
= 8 - (len
% 8);
1224 for (i
= 0; i
< pad
; i
++)
1225 ssh
->pktout
.data
[i
+ 4] = random_byte();
1226 crc
= crc32(ssh
->pktout
.data
+ 4, biglen
- 4);
1227 PUT_32BIT(ssh
->pktout
.data
+ biglen
, crc
);
1228 PUT_32BIT(ssh
->pktout
.data
, len
);
1231 ssh
->cipher
->encrypt(ssh
->v1_cipher_ctx
, ssh
->pktout
.data
+ 4, biglen
);
1236 static void s_wrpkt(Ssh ssh
)
1239 len
= s_wrpkt_prepare(ssh
);
1240 backlog
= sk_write(ssh
->s
, (char *)ssh
->pktout
.data
, len
);
1241 if (backlog
> SSH_MAX_BACKLOG
)
1242 ssh_throttle_all(ssh
, 1, backlog
);
1245 static void s_wrpkt_defer(Ssh ssh
)
1248 len
= s_wrpkt_prepare(ssh
);
1249 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
1250 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
1251 ssh
->deferred_send_data
= srealloc(ssh
->deferred_send_data
,
1252 ssh
->deferred_size
);
1254 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
, ssh
->pktout
.data
, len
);
1255 ssh
->deferred_len
+= len
;
1259 * Construct a packet with the specified contents.
1261 static void construct_packet(Ssh ssh
, int pkttype
, va_list ap1
, va_list ap2
)
1263 unsigned char *p
, *argp
, argchar
;
1264 unsigned long argint
;
1265 int pktlen
, argtype
, arglen
;
1269 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
1272 (void) va_arg(ap1
, int);
1276 (void) va_arg(ap1
, int);
1280 (void) va_arg(ap1
, unsigned char *);
1281 arglen
= va_arg(ap1
, int);
1285 argp
= va_arg(ap1
, unsigned char *);
1286 arglen
= strlen((char *)argp
);
1287 pktlen
+= 4 + arglen
;
1290 bn
= va_arg(ap1
, Bignum
);
1291 pktlen
+= ssh1_bignum_length(bn
);
1298 s_wrpkt_start(ssh
, pkttype
, pktlen
);
1299 p
= ssh
->pktout
.body
;
1301 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
1304 argint
= va_arg(ap2
, int);
1305 PUT_32BIT(p
, argint
);
1309 argchar
= (unsigned char) va_arg(ap2
, int);
1314 argp
= va_arg(ap2
, unsigned char *);
1315 arglen
= va_arg(ap2
, int);
1316 memcpy(p
, argp
, arglen
);
1320 argp
= va_arg(ap2
, unsigned char *);
1321 arglen
= strlen((char *)argp
);
1322 PUT_32BIT(p
, arglen
);
1323 memcpy(p
+ 4, argp
, arglen
);
1327 bn
= va_arg(ap2
, Bignum
);
1328 p
+= ssh1_write_bignum(p
, bn
);
1334 static void send_packet(Ssh ssh
, int pkttype
, ...)
1337 va_start(ap1
, pkttype
);
1338 va_start(ap2
, pkttype
);
1339 construct_packet(ssh
, pkttype
, ap1
, ap2
);
1343 static void defer_packet(Ssh ssh
, int pkttype
, ...)
1346 va_start(ap1
, pkttype
);
1347 va_start(ap2
, pkttype
);
1348 construct_packet(ssh
, pkttype
, ap1
, ap2
);
1352 static int ssh_versioncmp(char *a
, char *b
)
1355 unsigned long av
, bv
;
1357 av
= strtoul(a
, &ae
, 10);
1358 bv
= strtoul(b
, &be
, 10);
1360 return (av
< bv ?
-1 : +1);
1365 av
= strtoul(ae
, &ae
, 10);
1366 bv
= strtoul(be
, &be
, 10);
1368 return (av
< bv ?
-1 : +1);
1373 * Utility routines for putting an SSH-protocol `string' and
1374 * `uint32' into a SHA state.
1377 static void sha_string(SHA_State
* s
, void *str
, int len
)
1379 unsigned char lenblk
[4];
1380 PUT_32BIT(lenblk
, len
);
1381 SHA_Bytes(s
, lenblk
, 4);
1382 SHA_Bytes(s
, str
, len
);
1385 static void sha_uint32(SHA_State
* s
, unsigned i
)
1387 unsigned char intblk
[4];
1388 PUT_32BIT(intblk
, i
);
1389 SHA_Bytes(s
, intblk
, 4);
1393 * SSH2 packet construction functions.
1395 static void ssh2_pkt_ensure(Ssh ssh
, int length
)
1397 if (ssh
->pktout
.maxlen
< length
) {
1398 ssh
->pktout
.maxlen
= length
+ 256;
1399 ssh
->pktout
.data
= srealloc(ssh
->pktout
.data
,
1400 ssh
->pktout
.maxlen
+ APIEXTRA
);
1401 if (!ssh
->pktout
.data
)
1402 fatalbox("Out of memory");
1405 static void ssh2_pkt_adddata(Ssh ssh
, void *data
, int len
)
1407 ssh
->pktout
.length
+= len
;
1408 ssh2_pkt_ensure(ssh
, ssh
->pktout
.length
);
1409 memcpy(ssh
->pktout
.data
+ ssh
->pktout
.length
- len
, data
, len
);
1411 static void ssh2_pkt_addbyte(Ssh ssh
, unsigned char byte
)
1413 ssh2_pkt_adddata(ssh
, &byte
, 1);
1415 static void ssh2_pkt_init(Ssh ssh
, int pkt_type
)
1417 ssh
->pktout
.length
= 5;
1418 ssh2_pkt_addbyte(ssh
, (unsigned char) pkt_type
);
1420 static void ssh2_pkt_addbool(Ssh ssh
, unsigned char value
)
1422 ssh2_pkt_adddata(ssh
, &value
, 1);
1424 static void ssh2_pkt_adduint32(Ssh ssh
, unsigned long value
)
1427 PUT_32BIT(x
, value
);
1428 ssh2_pkt_adddata(ssh
, x
, 4);
1430 static void ssh2_pkt_addstring_start(Ssh ssh
)
1432 ssh2_pkt_adduint32(ssh
, 0);
1433 ssh
->pktout
.savedpos
= ssh
->pktout
.length
;
1435 static void ssh2_pkt_addstring_str(Ssh ssh
, char *data
)
1437 ssh2_pkt_adddata(ssh
, data
, strlen(data
));
1438 PUT_32BIT(ssh
->pktout
.data
+ ssh
->pktout
.savedpos
- 4,
1439 ssh
->pktout
.length
- ssh
->pktout
.savedpos
);
1441 static void ssh2_pkt_addstring_data(Ssh ssh
, char *data
, int len
)
1443 ssh2_pkt_adddata(ssh
, data
, len
);
1444 PUT_32BIT(ssh
->pktout
.data
+ ssh
->pktout
.savedpos
- 4,
1445 ssh
->pktout
.length
- ssh
->pktout
.savedpos
);
1447 static void ssh2_pkt_addstring(Ssh ssh
, char *data
)
1449 ssh2_pkt_addstring_start(ssh
);
1450 ssh2_pkt_addstring_str(ssh
, data
);
1452 static unsigned char *ssh2_mpint_fmt(Bignum b
, int *len
)
1455 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1458 fatalbox("out of memory");
1460 for (i
= 1; i
<= n
; i
++)
1461 p
[i
] = bignum_byte(b
, n
- i
);
1463 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1465 memmove(p
, p
+ i
, n
+ 1 - i
);
1469 static void ssh2_pkt_addmp(Ssh ssh
, Bignum b
)
1473 p
= ssh2_mpint_fmt(b
, &len
);
1474 ssh2_pkt_addstring_start(ssh
);
1475 ssh2_pkt_addstring_data(ssh
, (char *)p
, len
);
1480 * Construct an SSH2 final-form packet: compress it, encrypt it,
1481 * put the MAC on it. Final packet, ready to be sent, is stored in
1482 * ssh->pktout.data. Total length is returned.
1484 static int ssh2_pkt_construct(Ssh ssh
)
1486 int cipherblk
, maclen
, padding
, i
;
1489 log_packet(ssh
->logctx
, PKT_OUTGOING
, ssh
->pktout
.data
[5],
1490 ssh2_pkt_type(ssh
->pkt_ctx
, ssh
->pktout
.data
[5]),
1491 ssh
->pktout
.data
+ 6, ssh
->pktout
.length
- 6);
1494 * Compress packet payload.
1497 unsigned char *newpayload
;
1500 ssh
->cscomp
->compress(ssh
->cs_comp_ctx
, ssh
->pktout
.data
+ 5,
1501 ssh
->pktout
.length
- 5,
1502 &newpayload
, &newlen
)) {
1503 ssh
->pktout
.length
= 5;
1504 ssh2_pkt_adddata(ssh
, newpayload
, newlen
);
1510 * Add padding. At least four bytes, and must also bring total
1511 * length (minus MAC) up to a multiple of the block size.
1513 cipherblk
= ssh
->cscipher ? ssh
->cscipher
->blksize
: 8; /* block size */
1514 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1517 (cipherblk
- (ssh
->pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
1518 maclen
= ssh
->csmac ? ssh
->csmac
->len
: 0;
1519 ssh2_pkt_ensure(ssh
, ssh
->pktout
.length
+ padding
+ maclen
);
1520 ssh
->pktout
.data
[4] = padding
;
1521 for (i
= 0; i
< padding
; i
++)
1522 ssh
->pktout
.data
[ssh
->pktout
.length
+ i
] = random_byte();
1523 PUT_32BIT(ssh
->pktout
.data
, ssh
->pktout
.length
+ padding
- 4);
1525 ssh
->csmac
->generate(ssh
->cs_mac_ctx
, ssh
->pktout
.data
,
1526 ssh
->pktout
.length
+ padding
,
1527 ssh
->v2_outgoing_sequence
);
1528 ssh
->v2_outgoing_sequence
++; /* whether or not we MACed */
1531 ssh
->cscipher
->encrypt(ssh
->cs_cipher_ctx
,
1532 ssh
->pktout
.data
, ssh
->pktout
.length
+ padding
);
1534 /* Ready-to-send packet starts at ssh->pktout.data. We return length. */
1535 return ssh
->pktout
.length
+ padding
+ maclen
;
1539 * Construct and send an SSH2 packet immediately.
1541 static void ssh2_pkt_send(Ssh ssh
)
1545 len
= ssh2_pkt_construct(ssh
);
1546 backlog
= sk_write(ssh
->s
, (char *)ssh
->pktout
.data
, len
);
1547 if (backlog
> SSH_MAX_BACKLOG
)
1548 ssh_throttle_all(ssh
, 1, backlog
);
1552 * Construct an SSH2 packet and add it to a deferred data block.
1553 * Useful for sending multiple packets in a single sk_write() call,
1554 * to prevent a traffic-analysing listener from being able to work
1555 * out the length of any particular packet (such as the password
1558 * Note that because SSH2 sequence-numbers its packets, this can
1559 * NOT be used as an m4-style `defer' allowing packets to be
1560 * constructed in one order and sent in another.
1562 static void ssh2_pkt_defer(Ssh ssh
)
1564 int len
= ssh2_pkt_construct(ssh
);
1565 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
1566 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
1567 ssh
->deferred_send_data
= srealloc(ssh
->deferred_send_data
,
1568 ssh
->deferred_size
);
1570 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
, ssh
->pktout
.data
, len
);
1571 ssh
->deferred_len
+= len
;
1575 * Send the whole deferred data block constructed by
1576 * ssh2_pkt_defer() or SSH1's defer_packet().
1578 static void ssh_pkt_defersend(Ssh ssh
)
1581 backlog
= sk_write(ssh
->s
, (char *)ssh
->deferred_send_data
,
1583 ssh
->deferred_len
= ssh
->deferred_size
= 0;
1584 sfree(ssh
->deferred_send_data
);
1585 ssh
->deferred_send_data
= NULL
;
1586 if (backlog
> SSH_MAX_BACKLOG
)
1587 ssh_throttle_all(ssh
, 1, backlog
);
1591 void bndebug(char *string
, Bignum b
)
1595 p
= ssh2_mpint_fmt(b
, &len
);
1596 debug(("%s", string
));
1597 for (i
= 0; i
< len
; i
++)
1598 debug((" %02x", p
[i
]));
1604 static void sha_mpint(SHA_State
* s
, Bignum b
)
1608 p
= ssh2_mpint_fmt(b
, &len
);
1609 sha_string(s
, p
, len
);
1614 * SSH2 packet decode functions.
1616 static unsigned long ssh2_pkt_getuint32(Ssh ssh
)
1618 unsigned long value
;
1619 if (ssh
->pktin
.length
- ssh
->pktin
.savedpos
< 4)
1620 return 0; /* arrgh, no way to decline (FIXME?) */
1621 value
= GET_32BIT(ssh
->pktin
.data
+ ssh
->pktin
.savedpos
);
1622 ssh
->pktin
.savedpos
+= 4;
1625 static int ssh2_pkt_getbool(Ssh ssh
)
1627 unsigned long value
;
1628 if (ssh
->pktin
.length
- ssh
->pktin
.savedpos
< 1)
1629 return 0; /* arrgh, no way to decline (FIXME?) */
1630 value
= ssh
->pktin
.data
[ssh
->pktin
.savedpos
] != 0;
1631 ssh
->pktin
.savedpos
++;
1634 static void ssh2_pkt_getstring(Ssh ssh
, char **p
, int *length
)
1639 if (ssh
->pktin
.length
- ssh
->pktin
.savedpos
< 4)
1641 len
= GET_32BIT(ssh
->pktin
.data
+ ssh
->pktin
.savedpos
);
1645 ssh
->pktin
.savedpos
+= 4;
1646 if (ssh
->pktin
.length
- ssh
->pktin
.savedpos
< *length
)
1648 *p
= (char *)(ssh
->pktin
.data
+ ssh
->pktin
.savedpos
);
1649 ssh
->pktin
.savedpos
+= *length
;
1651 static Bignum
ssh2_pkt_getmp(Ssh ssh
)
1657 ssh2_pkt_getstring(ssh
, &p
, &length
);
1661 bombout((ssh
,"internal error: Can't handle negative mpints"));
1664 b
= bignum_from_bytes((unsigned char *)p
, length
);
1669 * Helper function to add an SSH2 signature blob to a packet.
1670 * Expects to be shown the public key blob as well as the signature
1671 * blob. Normally works just like ssh2_pkt_addstring, but will
1672 * fiddle with the signature packet if necessary for
1673 * BUG_SSH2_RSA_PADDING.
1675 static void ssh2_add_sigblob(Ssh ssh
, void *pkblob_v
, int pkblob_len
,
1676 void *sigblob_v
, int sigblob_len
)
1678 unsigned char *pkblob
= (unsigned char *)pkblob_v
;
1679 unsigned char *sigblob
= (unsigned char *)sigblob_v
;
1681 /* dmemdump(pkblob, pkblob_len); */
1682 /* dmemdump(sigblob, sigblob_len); */
1685 * See if this is in fact an ssh-rsa signature and a buggy
1686 * server; otherwise we can just do this the easy way.
1688 if ((ssh
->remote_bugs
& BUG_SSH2_RSA_PADDING
) &&
1689 (GET_32BIT(pkblob
) == 7 && !memcmp(pkblob
+4, "ssh-rsa", 7))) {
1690 int pos
, len
, siglen
;
1693 * Find the byte length of the modulus.
1696 pos
= 4+7; /* skip over "ssh-rsa" */
1697 pos
+= 4 + GET_32BIT(pkblob
+pos
); /* skip over exponent */
1698 len
= GET_32BIT(pkblob
+pos
); /* find length of modulus */
1699 pos
+= 4; /* find modulus itself */
1700 while (len
> 0 && pkblob
[pos
] == 0)
1702 /* debug(("modulus length is %d\n", len)); */
1705 * Now find the signature integer.
1707 pos
= 4+7; /* skip over "ssh-rsa" */
1708 siglen
= GET_32BIT(sigblob
+pos
);
1709 /* debug(("signature length is %d\n", siglen)); */
1711 if (len
!= siglen
) {
1712 unsigned char newlen
[4];
1713 ssh2_pkt_addstring_start(ssh
);
1714 ssh2_pkt_addstring_data(ssh
, (char *)sigblob
, pos
);
1715 /* dmemdump(sigblob, pos); */
1716 pos
+= 4; /* point to start of actual sig */
1717 PUT_32BIT(newlen
, len
);
1718 ssh2_pkt_addstring_data(ssh
, (char *)newlen
, 4);
1719 /* dmemdump(newlen, 4); */
1721 while (len
-- > siglen
) {
1722 ssh2_pkt_addstring_data(ssh
, (char *)newlen
, 1);
1723 /* dmemdump(newlen, 1); */
1725 ssh2_pkt_addstring_data(ssh
, (char *)(sigblob
+pos
), siglen
);
1726 /* dmemdump(sigblob+pos, siglen); */
1730 /* Otherwise fall through and do it the easy way. */
1733 ssh2_pkt_addstring_start(ssh
);
1734 ssh2_pkt_addstring_data(ssh
, (char *)sigblob
, sigblob_len
);
1738 * Examine the remote side's version string and compare it against
1739 * a list of known buggy implementations.
1741 static void ssh_detect_bugs(Ssh ssh
, char *vstring
)
1743 char *imp
; /* pointer to implementation part */
1745 imp
+= strcspn(imp
, "-");
1747 imp
+= strcspn(imp
, "-");
1750 ssh
->remote_bugs
= 0;
1752 if (ssh
->cfg
.sshbug_ignore1
== FORCE_ON
||
1753 (ssh
->cfg
.sshbug_ignore1
== AUTO
&&
1754 (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
1755 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
1756 !strcmp(imp
, "1.2.22") || !strcmp(imp
, "Cisco-1.25")))) {
1758 * These versions don't support SSH1_MSG_IGNORE, so we have
1759 * to use a different defence against password length
1762 ssh
->remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
1763 logevent("We believe remote version has SSH1 ignore bug");
1766 if (ssh
->cfg
.sshbug_plainpw1
== FORCE_ON
||
1767 (ssh
->cfg
.sshbug_plainpw1
== AUTO
&&
1768 (!strcmp(imp
, "Cisco-1.25")))) {
1770 * These versions need a plain password sent; they can't
1771 * handle having a null and a random length of data after
1774 ssh
->remote_bugs
|= BUG_NEEDS_SSH1_PLAIN_PASSWORD
;
1775 logevent("We believe remote version needs a plain SSH1 password");
1778 if (ssh
->cfg
.sshbug_rsa1
== FORCE_ON
||
1779 (ssh
->cfg
.sshbug_rsa1
== AUTO
&&
1780 (!strcmp(imp
, "Cisco-1.25")))) {
1782 * These versions apparently have no clue whatever about
1783 * RSA authentication and will panic and die if they see
1784 * an AUTH_RSA message.
1786 ssh
->remote_bugs
|= BUG_CHOKES_ON_RSA
;
1787 logevent("We believe remote version can't handle RSA authentication");
1790 if (ssh
->cfg
.sshbug_hmac2
== FORCE_ON
||
1791 (ssh
->cfg
.sshbug_hmac2
== AUTO
&&
1792 (wc_match("2.1.0*", imp
) || wc_match("2.0.*", imp
) ||
1793 wc_match("2.2.0*", imp
) || wc_match("2.3.0*", imp
) ||
1794 wc_match("2.1 *", imp
)))) {
1796 * These versions have the HMAC bug.
1798 ssh
->remote_bugs
|= BUG_SSH2_HMAC
;
1799 logevent("We believe remote version has SSH2 HMAC bug");
1802 if (ssh
->cfg
.sshbug_derivekey2
== FORCE_ON
||
1803 (ssh
->cfg
.sshbug_derivekey2
== AUTO
&&
1804 (wc_match("2.0.0*", imp
) || wc_match("2.0.10*", imp
) ))) {
1806 * These versions have the key-derivation bug (failing to
1807 * include the literal shared secret in the hashes that
1808 * generate the keys).
1810 ssh
->remote_bugs
|= BUG_SSH2_DERIVEKEY
;
1811 logevent("We believe remote version has SSH2 key-derivation bug");
1814 if (ssh
->cfg
.sshbug_rsapad2
== FORCE_ON
||
1815 (ssh
->cfg
.sshbug_rsapad2
== AUTO
&&
1816 (wc_match("OpenSSH_2.[5-9]*", imp
) ||
1817 wc_match("OpenSSH_3.[0-2]*", imp
)))) {
1819 * These versions have the SSH2 RSA padding bug.
1821 ssh
->remote_bugs
|= BUG_SSH2_RSA_PADDING
;
1822 logevent("We believe remote version has SSH2 RSA padding bug");
1825 if (ssh
->cfg
.sshbug_pksessid2
== FORCE_ON
||
1826 (ssh
->cfg
.sshbug_pksessid2
== AUTO
&&
1827 wc_match("OpenSSH_2.[0-2]*", imp
))) {
1829 * These versions have the SSH2 session-ID bug in
1830 * public-key authentication.
1832 ssh
->remote_bugs
|= BUG_SSH2_PK_SESSIONID
;
1833 logevent("We believe remote version has SSH2 public-key-session-ID bug");
1836 if (ssh
->cfg
.sshbug_dhgex2
== FORCE_ON
) {
1838 * User specified the SSH2 DH GEX bug.
1840 ssh
->remote_bugs
|= BUG_SSH2_DH_GEX
;
1841 logevent("We believe remote version has SSH2 DH group exchange bug");
1845 static int do_ssh_init(Ssh ssh
, unsigned char c
)
1847 struct do_ssh_init_state
{
1855 crState(do_ssh_init_state
);
1857 crBegin(ssh
->do_ssh_init_crstate
);
1859 /* Search for the string "SSH-" in the input. */
1862 static const int transS
[] = { 1, 2, 2, 1 };
1863 static const int transH
[] = { 0, 0, 3, 0 };
1864 static const int transminus
[] = { 0, 0, 0, -1 };
1866 s
->i
= transS
[s
->i
];
1868 s
->i
= transH
[s
->i
];
1870 s
->i
= transminus
[s
->i
];
1875 crReturn(1); /* get another character */
1879 s
->vstring
= smalloc(s
->vstrsize
);
1880 strcpy(s
->vstring
, "SSH-");
1884 crReturn(1); /* get another char */
1885 if (s
->vslen
>= s
->vstrsize
- 1) {
1887 s
->vstring
= srealloc(s
->vstring
, s
->vstrsize
);
1889 s
->vstring
[s
->vslen
++] = c
;
1892 s
->version
[s
->i
] = '\0';
1894 } else if (s
->i
< sizeof(s
->version
) - 1)
1895 s
->version
[s
->i
++] = c
;
1896 } else if (c
== '\012')
1900 ssh
->agentfwd_enabled
= FALSE
;
1901 ssh
->rdpkt2_state
.incoming_sequence
= 0;
1903 s
->vstring
[s
->vslen
] = 0;
1904 s
->vstring
[strcspn(s
->vstring
, "\r\n")] = '\0';/* remove EOL chars */
1907 vlog
= smalloc(20 + s
->vslen
);
1908 sprintf(vlog
, "Server version: %s", s
->vstring
);
1912 ssh_detect_bugs(ssh
, s
->vstring
);
1915 * Decide which SSH protocol version to support.
1918 /* Anything strictly below "2.0" means protocol 1 is supported. */
1919 s
->proto1
= ssh_versioncmp(s
->version
, "2.0") < 0;
1920 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
1921 s
->proto2
= ssh_versioncmp(s
->version
, "1.99") >= 0;
1923 if (ssh
->cfg
.sshprot
== 0 && !s
->proto1
) {
1924 bombout((ssh
,"SSH protocol version 1 required by user but not provided by server"));
1927 if (ssh
->cfg
.sshprot
== 3 && !s
->proto2
) {
1928 bombout((ssh
,"SSH protocol version 2 required by user but not provided by server"));
1932 if (s
->proto2
&& (ssh
->cfg
.sshprot
>= 2 || !s
->proto1
)) {
1936 char verstring
[80], vlog
[100];
1937 sprintf(verstring
, "SSH-2.0-%s", sshver
);
1938 SHA_Init(&ssh
->exhashbase
);
1940 * Hash our version string and their version string.
1942 sha_string(&ssh
->exhashbase
, verstring
, strlen(verstring
));
1943 sha_string(&ssh
->exhashbase
, s
->vstring
, strcspn(s
->vstring
, "\r\n"));
1944 sprintf(vlog
, "We claim version: %s", verstring
);
1946 strcat(verstring
, "\012");
1947 logevent("Using SSH protocol version 2");
1948 sk_write(ssh
->s
, verstring
, strlen(verstring
));
1949 ssh
->protocol
= ssh2_protocol
;
1951 ssh
->s_rdpkt
= ssh2_rdpkt
;
1956 char verstring
[80], vlog
[100];
1957 sprintf(verstring
, "SSH-%s-%s",
1958 (ssh_versioncmp(s
->version
, "1.5") <= 0 ? s
->version
: "1.5"),
1960 sprintf(vlog
, "We claim version: %s", verstring
);
1962 strcat(verstring
, "\012");
1964 logevent("Using SSH protocol version 1");
1965 sk_write(ssh
->s
, verstring
, strlen(verstring
));
1966 ssh
->protocol
= ssh1_protocol
;
1968 ssh
->s_rdpkt
= ssh1_rdpkt
;
1970 ssh
->state
= SSH_STATE_BEFORE_SIZE
;
1977 static void ssh_gotdata(Ssh ssh
, unsigned char *data
, int datalen
)
1979 crBegin(ssh
->ssh_gotdata_crstate
);
1982 * To begin with, feed the characters one by one to the
1983 * protocol initialisation / selection function do_ssh_init().
1984 * When that returns 0, we're done with the initial greeting
1985 * exchange and can move on to packet discipline.
1988 int ret
; /* need not be kept across crReturn */
1990 crReturnV
; /* more data please */
1991 ret
= do_ssh_init(ssh
, *data
);
1999 * We emerge from that loop when the initial negotiation is
2000 * over and we have selected an s_rdpkt function. Now pass
2001 * everything to s_rdpkt, and then pass the resulting packets
2002 * to the proper protocol handler.
2007 while (datalen
> 0) {
2008 if (ssh
->s_rdpkt(ssh
, &data
, &datalen
) == 0) {
2009 if (ssh
->state
== SSH_STATE_CLOSED
) {
2012 ssh
->protocol(ssh
, NULL
, 0, 1);
2013 if (ssh
->state
== SSH_STATE_CLOSED
) {
2023 static int ssh_closing(Plug plug
, char *error_msg
, int error_code
,
2026 Ssh ssh
= (Ssh
) plug
;
2027 ssh
->state
= SSH_STATE_CLOSED
;
2033 /* A socket error has occurred. */
2034 logevent(error_msg
);
2035 connection_fatal(ssh
->frontend
, error_msg
);
2037 /* Otherwise, the remote side closed the connection normally. */
2042 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
2044 Ssh ssh
= (Ssh
) plug
;
2045 ssh_gotdata(ssh
, (unsigned char *)data
, len
);
2046 if (ssh
->state
== SSH_STATE_CLOSED
) {
2056 static void ssh_sent(Plug plug
, int bufsize
)
2058 Ssh ssh
= (Ssh
) plug
;
2060 * If the send backlog on the SSH socket itself clears, we
2061 * should unthrottle the whole world if it was throttled.
2063 if (bufsize
< SSH_MAX_BACKLOG
)
2064 ssh_throttle_all(ssh
, 0, bufsize
);
2068 * Connect to specified host and port.
2069 * Returns an error message, or NULL on success.
2070 * Also places the canonical host name into `realhost'. It must be
2071 * freed by the caller.
2073 static char *connect_to_host(Ssh ssh
, char *host
, int port
,
2074 char **realhost
, int nodelay
)
2076 static const struct plug_function_table fn_table
= {
2086 ssh
->savedhost
= smalloc(1 + strlen(host
));
2087 if (!ssh
->savedhost
)
2088 fatalbox("Out of memory");
2089 strcpy(ssh
->savedhost
, host
);
2092 port
= 22; /* default ssh port */
2093 ssh
->savedport
= port
;
2098 logeventf(ssh
, "Looking up host \"%s\"", host
);
2099 addr
= name_lookup(host
, port
, realhost
, &ssh
->cfg
);
2100 if ((err
= sk_addr_error(addr
)) != NULL
)
2108 sk_getaddr(addr
, addrbuf
, 100);
2109 logeventf(ssh
, "Connecting to %s port %d", addrbuf
, port
);
2111 ssh
->fn
= &fn_table
;
2112 ssh
->s
= new_connection(addr
, *realhost
, port
,
2113 0, 1, nodelay
, (Plug
) ssh
, &ssh
->cfg
);
2114 if ((err
= sk_socket_error(ssh
->s
)) != NULL
) {
2123 * Throttle or unthrottle the SSH connection.
2125 static void ssh1_throttle(Ssh ssh
, int adjust
)
2127 int old_count
= ssh
->v1_throttle_count
;
2128 ssh
->v1_throttle_count
+= adjust
;
2129 assert(ssh
->v1_throttle_count
>= 0);
2130 if (ssh
->v1_throttle_count
&& !old_count
) {
2131 sk_set_frozen(ssh
->s
, 1);
2132 } else if (!ssh
->v1_throttle_count
&& old_count
) {
2133 sk_set_frozen(ssh
->s
, 0);
2138 * Throttle or unthrottle _all_ local data streams (for when sends
2139 * on the SSH connection itself back up).
2141 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
)
2144 struct ssh_channel
*c
;
2146 if (enable
== ssh
->throttled_all
)
2148 ssh
->throttled_all
= enable
;
2149 ssh
->overall_bufsize
= bufsize
;
2152 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++) {
2154 case CHAN_MAINSESSION
:
2156 * This is treated separately, outside the switch.
2160 x11_override_throttle(c
->u
.x11
.s
, enable
);
2163 /* Agent channels require no buffer management. */
2166 pfd_override_throttle(c
->u
.x11
.s
, enable
);
2173 * Username and password input, abstracted off into routines
2174 * reusable in several places - even between SSH1 and SSH2.
2177 /* Set up a username or password input loop on a given buffer. */
2178 static void setup_userpass_input(Ssh ssh
, char *buffer
, int buflen
, int echo
)
2180 ssh
->userpass_input_buffer
= buffer
;
2181 ssh
->userpass_input_buflen
= buflen
;
2182 ssh
->userpass_input_bufpos
= 0;
2183 ssh
->userpass_input_echo
= echo
;
2187 * Process some terminal data in the course of username/password
2188 * input. Returns >0 for success (line of input returned in
2189 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2190 * for inconclusive (keep waiting for more input please).
2192 static int process_userpass_input(Ssh ssh
, unsigned char *in
, int inlen
)
2197 switch (c
= *in
++) {
2200 ssh
->userpass_input_buffer
[ssh
->userpass_input_bufpos
] = 0;
2201 ssh
->userpass_input_buffer
[ssh
->userpass_input_buflen
-1] = 0;
2206 if (ssh
->userpass_input_bufpos
> 0) {
2207 if (ssh
->userpass_input_echo
)
2208 c_write_str(ssh
, "\b \b");
2209 ssh
->userpass_input_bufpos
--;
2214 while (ssh
->userpass_input_bufpos
> 0) {
2215 if (ssh
->userpass_input_echo
)
2216 c_write_str(ssh
, "\b \b");
2217 ssh
->userpass_input_bufpos
--;
2226 * This simplistic check for printability is disabled
2227 * when we're doing password input, because some people
2228 * have control characters in their passwords.o
2230 if ((!ssh
->userpass_input_echo
||
2231 (c
>= ' ' && c
<= '~') ||
2232 ((unsigned char) c
>= 160))
2233 && ssh
->userpass_input_bufpos
< ssh
->userpass_input_buflen
-1) {
2234 ssh
->userpass_input_buffer
[ssh
->userpass_input_bufpos
++] = c
;
2235 if (ssh
->userpass_input_echo
)
2236 c_write(ssh
, &c
, 1);
2245 * Handle the key exchange and user authentication phases.
2247 static int do_ssh1_login(Ssh ssh
, unsigned char *in
, int inlen
, int ispkt
)
2250 unsigned char cookie
[8];
2251 struct RSAKey servkey
, hostkey
;
2252 struct MD5Context md5c
;
2253 struct do_ssh1_login_state
{
2255 unsigned char *rsabuf
, *keystr1
, *keystr2
;
2256 unsigned long supported_ciphers_mask
, supported_auths_mask
;
2257 int tried_publickey
, tried_agent
;
2258 int tis_auth_refused
, ccard_auth_refused
;
2259 unsigned char session_id
[16];
2262 void *publickey_blob
;
2263 int publickey_bloblen
;
2269 unsigned char request
[5], *response
, *p
;
2278 crState(do_ssh1_login_state
);
2280 crBegin(ssh
->do_ssh1_login_crstate
);
2285 if (ssh
->pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
2286 bombout((ssh
,"Public key packet not received"));
2290 logevent("Received public keys");
2292 memcpy(cookie
, ssh
->pktin
.body
, 8);
2294 i
= makekey(ssh
->pktin
.body
+ 8, &servkey
, &s
->keystr1
, 0);
2295 j
= makekey(ssh
->pktin
.body
+ 8 + i
, &hostkey
, &s
->keystr2
, 0);
2298 * Log the host key fingerprint.
2302 logevent("Host key fingerprint is:");
2303 strcpy(logmsg
, " ");
2304 hostkey
.comment
= NULL
;
2305 rsa_fingerprint(logmsg
+ strlen(logmsg
),
2306 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
2310 ssh
->v1_remote_protoflags
= GET_32BIT(ssh
->pktin
.body
+ 8 + i
+ j
);
2311 s
->supported_ciphers_mask
= GET_32BIT(ssh
->pktin
.body
+ 12 + i
+ j
);
2312 s
->supported_auths_mask
= GET_32BIT(ssh
->pktin
.body
+ 16 + i
+ j
);
2314 ssh
->v1_local_protoflags
=
2315 ssh
->v1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
2316 ssh
->v1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
2319 MD5Update(&md5c
, s
->keystr2
, hostkey
.bytes
);
2320 MD5Update(&md5c
, s
->keystr1
, servkey
.bytes
);
2321 MD5Update(&md5c
, ssh
->pktin
.body
, 8);
2322 MD5Final(s
->session_id
, &md5c
);
2324 for (i
= 0; i
< 32; i
++)
2325 ssh
->session_key
[i
] = random_byte();
2327 s
->len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
2329 s
->rsabuf
= smalloc(s
->len
);
2331 fatalbox("Out of memory");
2334 * Verify the host key.
2338 * First format the key into a string.
2340 int len
= rsastr_len(&hostkey
);
2341 char fingerprint
[100];
2342 char *keystr
= smalloc(len
);
2344 fatalbox("Out of memory");
2345 rsastr_fmt(keystr
, &hostkey
);
2346 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
2347 verify_ssh_host_key(ssh
->frontend
,
2348 ssh
->savedhost
, ssh
->savedport
, "rsa", keystr
,
2353 for (i
= 0; i
< 32; i
++) {
2354 s
->rsabuf
[i
] = ssh
->session_key
[i
];
2356 s
->rsabuf
[i
] ^= s
->session_id
[i
];
2359 if (hostkey
.bytes
> servkey
.bytes
) {
2360 rsaencrypt(s
->rsabuf
, 32, &servkey
);
2361 rsaencrypt(s
->rsabuf
, servkey
.bytes
, &hostkey
);
2363 rsaencrypt(s
->rsabuf
, 32, &hostkey
);
2364 rsaencrypt(s
->rsabuf
, hostkey
.bytes
, &servkey
);
2367 logevent("Encrypted session key");
2370 int cipher_chosen
= 0, warn
= 0;
2371 char *cipher_string
= NULL
;
2373 for (i
= 0; !cipher_chosen
&& i
< CIPHER_MAX
; i
++) {
2374 int next_cipher
= ssh
->cfg
.ssh_cipherlist
[i
];
2375 if (next_cipher
== CIPHER_WARN
) {
2376 /* If/when we choose a cipher, warn about it */
2378 } else if (next_cipher
== CIPHER_AES
) {
2379 /* XXX Probably don't need to mention this. */
2380 logevent("AES not supported in SSH1, skipping");
2382 switch (next_cipher
) {
2383 case CIPHER_3DES
: s
->cipher_type
= SSH_CIPHER_3DES
;
2384 cipher_string
= "3DES"; break;
2385 case CIPHER_BLOWFISH
: s
->cipher_type
= SSH_CIPHER_BLOWFISH
;
2386 cipher_string
= "Blowfish"; break;
2387 case CIPHER_DES
: s
->cipher_type
= SSH_CIPHER_DES
;
2388 cipher_string
= "single-DES"; break;
2390 if (s
->supported_ciphers_mask
& (1 << s
->cipher_type
))
2394 if (!cipher_chosen
) {
2395 if ((s
->supported_ciphers_mask
& (1 << SSH_CIPHER_3DES
)) == 0)
2396 bombout((ssh
,"Server violates SSH 1 protocol by not "
2397 "supporting 3DES encryption"));
2399 /* shouldn't happen */
2400 bombout((ssh
,"No supported ciphers found"));
2404 /* Warn about chosen cipher if necessary. */
2406 askcipher(ssh
->frontend
, cipher_string
, 0);
2409 switch (s
->cipher_type
) {
2410 case SSH_CIPHER_3DES
:
2411 logevent("Using 3DES encryption");
2413 case SSH_CIPHER_DES
:
2414 logevent("Using single-DES encryption");
2416 case SSH_CIPHER_BLOWFISH
:
2417 logevent("Using Blowfish encryption");
2421 send_packet(ssh
, SSH1_CMSG_SESSION_KEY
,
2422 PKT_CHAR
, s
->cipher_type
,
2423 PKT_DATA
, cookie
, 8,
2424 PKT_CHAR
, (s
->len
* 8) >> 8, PKT_CHAR
, (s
->len
* 8) & 0xFF,
2425 PKT_DATA
, s
->rsabuf
, s
->len
,
2426 PKT_INT
, ssh
->v1_local_protoflags
, PKT_END
);
2428 logevent("Trying to enable encryption...");
2432 ssh
->cipher
= (s
->cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
2433 s
->cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
2435 ssh
->v1_cipher_ctx
= ssh
->cipher
->make_context();
2436 ssh
->cipher
->sesskey(ssh
->v1_cipher_ctx
, ssh
->session_key
);
2437 logeventf(ssh
, "Initialised %s encryption", ssh
->cipher
->text_name
);
2439 ssh
->crcda_ctx
= crcda_make_context();
2440 logevent("Installing CRC compensation attack detector");
2444 if (ssh
->pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2445 bombout((ssh
,"Encryption not successfully enabled"));
2449 logevent("Successfully started encryption");
2453 if ((flags
& FLAG_INTERACTIVE
) && !*ssh
->cfg
.username
) {
2454 if (ssh_get_line
&& !ssh_getline_pw_only
) {
2455 if (!ssh_get_line("login as: ",
2456 s
->username
, sizeof(s
->username
), FALSE
)) {
2458 * get_line failed to get a username.
2461 logevent("No username provided. Abandoning session.");
2462 ssh
->state
= SSH_STATE_CLOSED
;
2466 int ret
; /* need not be kept over crReturn */
2467 c_write_str(ssh
, "login as: ");
2470 setup_userpass_input(ssh
, s
->username
, sizeof(s
->username
), 1);
2472 crWaitUntil(!ispkt
);
2473 ret
= process_userpass_input(ssh
, in
, inlen
);
2477 c_write_str(ssh
, "\r\n");
2480 strncpy(s
->username
, ssh
->cfg
.username
, sizeof(s
->username
));
2481 s
->username
[sizeof(s
->username
)-1] = '\0';
2484 send_packet(ssh
, SSH1_CMSG_USER
, PKT_STR
, s
->username
, PKT_END
);
2486 char userlog
[22 + sizeof(s
->username
)];
2487 sprintf(userlog
, "Sent username \"%s\"", s
->username
);
2489 if (flags
& FLAG_INTERACTIVE
&&
2490 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
2491 strcat(userlog
, "\r\n");
2492 c_write_str(ssh
, userlog
);
2499 if ((ssh
->remote_bugs
& BUG_CHOKES_ON_RSA
)) {
2500 /* We must not attempt PK auth. Pretend we've already tried it. */
2501 s
->tried_publickey
= s
->tried_agent
= 1;
2503 s
->tried_publickey
= s
->tried_agent
= 0;
2505 s
->tis_auth_refused
= s
->ccard_auth_refused
= 0;
2506 /* Load the public half of ssh->cfg.keyfile so we notice if it's in Pageant */
2507 if (!filename_is_null(ssh
->cfg
.keyfile
)) {
2508 if (!rsakey_pubblob(&ssh
->cfg
.keyfile
,
2509 &s
->publickey_blob
, &s
->publickey_bloblen
))
2510 s
->publickey_blob
= NULL
;
2512 s
->publickey_blob
= NULL
;
2514 while (ssh
->pktin
.type
== SSH1_SMSG_FAILURE
) {
2515 s
->pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
2517 if (agent_exists() && !s
->tried_agent
) {
2519 * Attempt RSA authentication using Pageant.
2525 logevent("Pageant is running. Requesting keys.");
2527 /* Request the keys held by the agent. */
2528 PUT_32BIT(s
->request
, 1);
2529 s
->request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
2530 agent_query(s
->request
, 5, &r
, &s
->responselen
);
2531 s
->response
= (unsigned char *) r
;
2532 if (s
->response
&& s
->responselen
>= 5 &&
2533 s
->response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
2534 s
->p
= s
->response
+ 5;
2535 s
->nkeys
= GET_32BIT(s
->p
);
2539 sprintf(buf
, "Pageant has %d SSH1 keys", s
->nkeys
);
2542 for (s
->keyi
= 0; s
->keyi
< s
->nkeys
; s
->keyi
++) {
2545 sprintf(buf
, "Trying Pageant key #%d", s
->keyi
);
2548 if (s
->publickey_blob
&&
2549 !memcmp(s
->p
, s
->publickey_blob
,
2550 s
->publickey_bloblen
)) {
2551 logevent("This key matches configured key file");
2552 s
->tried_publickey
= 1;
2555 s
->p
+= ssh1_read_bignum(s
->p
, &s
->key
.exponent
);
2556 s
->p
+= ssh1_read_bignum(s
->p
, &s
->key
.modulus
);
2557 s
->commentlen
= GET_32BIT(s
->p
);
2559 s
->commentp
= (char *)s
->p
;
2560 s
->p
+= s
->commentlen
;
2561 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
2562 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
2564 if (ssh
->pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2565 logevent("Key refused");
2568 logevent("Received RSA challenge");
2569 ssh1_read_bignum(ssh
->pktin
.body
, &s
->challenge
);
2571 char *agentreq
, *q
, *ret
;
2574 len
= 1 + 4; /* message type, bit count */
2575 len
+= ssh1_bignum_length(s
->key
.exponent
);
2576 len
+= ssh1_bignum_length(s
->key
.modulus
);
2577 len
+= ssh1_bignum_length(s
->challenge
);
2578 len
+= 16; /* session id */
2579 len
+= 4; /* response format */
2580 agentreq
= smalloc(4 + len
);
2581 PUT_32BIT(agentreq
, len
);
2583 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
2584 PUT_32BIT(q
, bignum_bitcount(s
->key
.modulus
));
2586 q
+= ssh1_write_bignum(q
, s
->key
.exponent
);
2587 q
+= ssh1_write_bignum(q
, s
->key
.modulus
);
2588 q
+= ssh1_write_bignum(q
, s
->challenge
);
2589 memcpy(q
, s
->session_id
, 16);
2591 PUT_32BIT(q
, 1); /* response format */
2592 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
2596 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
2597 logevent("Sending Pageant's response");
2598 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
2599 PKT_DATA
, ret
+ 5, 16,
2603 if (ssh
->pktin
.type
== SSH1_SMSG_SUCCESS
) {
2605 ("Pageant's response accepted");
2606 if (flags
& FLAG_VERBOSE
) {
2607 c_write_str(ssh
, "Authenticated using"
2609 c_write(ssh
, s
->commentp
,
2611 c_write_str(ssh
, "\" from agent\r\n");
2616 ("Pageant's response not accepted");
2619 ("Pageant failed to answer challenge");
2623 logevent("No reply received from Pageant");
2626 freebn(s
->key
.exponent
);
2627 freebn(s
->key
.modulus
);
2628 freebn(s
->challenge
);
2636 if (!filename_is_null(ssh
->cfg
.keyfile
) && !s
->tried_publickey
)
2637 s
->pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
2639 if (ssh
->cfg
.try_tis_auth
&&
2640 (s
->supported_auths_mask
& (1 << SSH1_AUTH_TIS
)) &&
2641 !s
->tis_auth_refused
) {
2642 s
->pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
2643 logevent("Requested TIS authentication");
2644 send_packet(ssh
, SSH1_CMSG_AUTH_TIS
, PKT_END
);
2646 if (ssh
->pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
2647 logevent("TIS authentication declined");
2648 if (flags
& FLAG_INTERACTIVE
)
2649 c_write_str(ssh
, "TIS authentication refused.\r\n");
2650 s
->tis_auth_refused
= 1;
2653 int challengelen
= GET_32BIT(ssh
->pktin
.body
);
2654 logevent("Received TIS challenge");
2655 if (challengelen
> sizeof(s
->prompt
) - 1)
2656 challengelen
= sizeof(s
->prompt
) - 1;/* prevent overrun */
2657 memcpy(s
->prompt
, ssh
->pktin
.body
+ 4, challengelen
);
2658 /* Prompt heuristic comes from OpenSSH */
2659 strncpy(s
->prompt
+ challengelen
,
2660 memchr(s
->prompt
, '\n', challengelen
) ?
2661 "": "\r\nResponse: ",
2662 (sizeof s
->prompt
) - challengelen
);
2663 s
->prompt
[(sizeof s
->prompt
) - 1] = '\0';
2666 if (ssh
->cfg
.try_tis_auth
&&
2667 (s
->supported_auths_mask
& (1 << SSH1_AUTH_CCARD
)) &&
2668 !s
->ccard_auth_refused
) {
2669 s
->pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
2670 logevent("Requested CryptoCard authentication");
2671 send_packet(ssh
, SSH1_CMSG_AUTH_CCARD
, PKT_END
);
2673 if (ssh
->pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
2674 logevent("CryptoCard authentication declined");
2675 c_write_str(ssh
, "CryptoCard authentication refused.\r\n");
2676 s
->ccard_auth_refused
= 1;
2679 int challengelen
= GET_32BIT(ssh
->pktin
.body
);
2680 logevent("Received CryptoCard challenge");
2681 if (challengelen
> sizeof(s
->prompt
) - 1)
2682 challengelen
= sizeof(s
->prompt
) - 1;/* prevent overrun */
2683 memcpy(s
->prompt
, ssh
->pktin
.body
+ 4, challengelen
);
2684 strncpy(s
->prompt
+ challengelen
,
2685 memchr(s
->prompt
, '\n', challengelen
) ?
2686 "" : "\r\nResponse: ",
2687 sizeof(s
->prompt
) - challengelen
);
2688 s
->prompt
[sizeof(s
->prompt
) - 1] = '\0';
2691 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2692 sprintf(s
->prompt
, "%.90s@%.90s's password: ",
2693 s
->username
, ssh
->savedhost
);
2695 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2696 char *comment
= NULL
;
2699 if (flags
& FLAG_VERBOSE
)
2700 c_write_str(ssh
, "Trying public key authentication.\r\n");
2701 logeventf(ssh
, "Trying public key \"%s\"",
2702 filename_to_str(&ssh
->cfg
.keyfile
));
2703 type
= key_type(&ssh
->cfg
.keyfile
);
2704 if (type
!= SSH_KEYTYPE_SSH1
) {
2705 sprintf(msgbuf
, "Key is of wrong type (%s)",
2706 key_type_to_str(type
));
2708 c_write_str(ssh
, msgbuf
);
2709 c_write_str(ssh
, "\r\n");
2710 s
->tried_publickey
= 1;
2713 if (!rsakey_encrypted(&ssh
->cfg
.keyfile
, &comment
)) {
2714 if (flags
& FLAG_VERBOSE
)
2715 c_write_str(ssh
, "No passphrase required.\r\n");
2718 sprintf(s
->prompt
, "Passphrase for key \"%.100s\": ", comment
);
2723 * Show password prompt, having first obtained it via a TIS
2724 * or CryptoCard exchange if we're doing TIS or CryptoCard
2728 if (!ssh_get_line(s
->prompt
, s
->password
,
2729 sizeof(s
->password
), TRUE
)) {
2731 * get_line failed to get a password (for example
2732 * because one was supplied on the command line
2733 * which has already failed to work). Terminate.
2735 send_packet(ssh
, SSH1_MSG_DISCONNECT
,
2736 PKT_STR
, "No more passwords available to try",
2738 logevent("Unable to authenticate");
2739 connection_fatal(ssh
->frontend
, "Unable to authenticate");
2740 ssh
->state
= SSH_STATE_CLOSED
;
2744 /* Prompt may have come from server. We've munged it a bit, so
2745 * we know it to be zero-terminated at least once. */
2746 int ret
; /* need not be saved over crReturn */
2747 c_write_untrusted(ssh
, s
->prompt
, strlen(s
->prompt
));
2750 setup_userpass_input(ssh
, s
->password
, sizeof(s
->password
), 0);
2752 crWaitUntil(!ispkt
);
2753 ret
= process_userpass_input(ssh
, in
, inlen
);
2757 c_write_str(ssh
, "\r\n");
2761 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2763 * Try public key authentication with the specified
2766 s
->tried_publickey
= 1;
2769 int ret
= loadrsakey(&ssh
->cfg
.keyfile
, &s
->key
, s
->password
);
2771 c_write_str(ssh
, "Couldn't load private key from ");
2772 c_write_str(ssh
, filename_to_str(&ssh
->cfg
.keyfile
));
2773 c_write_str(ssh
, ".\r\n");
2774 continue; /* go and try password */
2777 c_write_str(ssh
, "Wrong passphrase.\r\n");
2778 s
->tried_publickey
= 0;
2779 continue; /* try again */
2784 * Send a public key attempt.
2786 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
2787 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
2790 if (ssh
->pktin
.type
== SSH1_SMSG_FAILURE
) {
2791 c_write_str(ssh
, "Server refused our public key.\r\n");
2792 continue; /* go and try password */
2794 if (ssh
->pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2795 bombout((ssh
,"Bizarre response to offer of public key"));
2801 unsigned char buffer
[32];
2802 Bignum challenge
, response
;
2804 ssh1_read_bignum(ssh
->pktin
.body
, &challenge
);
2805 response
= rsadecrypt(challenge
, &s
->key
);
2806 freebn(s
->key
.private_exponent
);/* burn the evidence */
2808 for (i
= 0; i
< 32; i
++) {
2809 buffer
[i
] = bignum_byte(response
, 31 - i
);
2813 MD5Update(&md5c
, buffer
, 32);
2814 MD5Update(&md5c
, s
->session_id
, 16);
2815 MD5Final(buffer
, &md5c
);
2817 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
2818 PKT_DATA
, buffer
, 16, PKT_END
);
2825 if (ssh
->pktin
.type
== SSH1_SMSG_FAILURE
) {
2826 if (flags
& FLAG_VERBOSE
)
2827 c_write_str(ssh
, "Failed to authenticate with"
2828 " our public key.\r\n");
2829 continue; /* go and try password */
2830 } else if (ssh
->pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2831 bombout((ssh
,"Bizarre response to RSA authentication response"));
2835 break; /* we're through! */
2837 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2839 * Defence against traffic analysis: we send a
2840 * whole bunch of packets containing strings of
2841 * different lengths. One of these strings is the
2842 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2843 * The others are all random data in
2844 * SSH1_MSG_IGNORE packets. This way a passive
2845 * listener can't tell which is the password, and
2846 * hence can't deduce the password length.
2848 * Anybody with a password length greater than 16
2849 * bytes is going to have enough entropy in their
2850 * password that a listener won't find it _that_
2851 * much help to know how long it is. So what we'll
2854 * - if password length < 16, we send 15 packets
2855 * containing string lengths 1 through 15
2857 * - otherwise, we let N be the nearest multiple
2858 * of 8 below the password length, and send 8
2859 * packets containing string lengths N through
2860 * N+7. This won't obscure the order of
2861 * magnitude of the password length, but it will
2862 * introduce a bit of extra uncertainty.
2864 * A few servers (the old 1.2.18 through 1.2.22)
2865 * can't deal with SSH1_MSG_IGNORE. For these
2866 * servers, we need an alternative defence. We make
2867 * use of the fact that the password is interpreted
2868 * as a C string: so we can append a NUL, then some
2871 * One server (a Cisco one) can deal with neither
2872 * SSH1_MSG_IGNORE _nor_ a padded password string.
2873 * For this server we are left with no defences
2874 * against password length sniffing.
2876 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
)) {
2878 * The server can deal with SSH1_MSG_IGNORE, so
2879 * we can use the primary defence.
2881 int bottom
, top
, pwlen
, i
;
2884 pwlen
= strlen(s
->password
);
2886 bottom
= 0; /* zero length passwords are OK! :-) */
2889 bottom
= pwlen
& ~7;
2893 assert(pwlen
>= bottom
&& pwlen
<= top
);
2895 randomstr
= smalloc(top
+ 1);
2897 for (i
= bottom
; i
<= top
; i
++) {
2899 defer_packet(ssh
, s
->pwpkt_type
,
2900 PKT_STR
, s
->password
, PKT_END
);
2902 for (j
= 0; j
< i
; j
++) {
2904 randomstr
[j
] = random_byte();
2905 } while (randomstr
[j
] == '\0');
2907 randomstr
[i
] = '\0';
2908 defer_packet(ssh
, SSH1_MSG_IGNORE
,
2909 PKT_STR
, randomstr
, PKT_END
);
2912 logevent("Sending password with camouflage packets");
2913 ssh_pkt_defersend(ssh
);
2915 else if (!(ssh
->remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
2917 * The server can't deal with SSH1_MSG_IGNORE
2918 * but can deal with padded passwords, so we
2919 * can use the secondary defence.
2925 len
= strlen(s
->password
);
2926 if (len
< sizeof(string
)) {
2928 strcpy(string
, s
->password
);
2929 len
++; /* cover the zero byte */
2930 while (len
< sizeof(string
)) {
2931 string
[len
++] = (char) random_byte();
2936 logevent("Sending length-padded password");
2937 send_packet(ssh
, s
->pwpkt_type
, PKT_INT
, len
,
2938 PKT_DATA
, ss
, len
, PKT_END
);
2941 * The server has _both_
2942 * BUG_CHOKES_ON_SSH1_IGNORE and
2943 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2944 * therefore nothing we can do.
2947 len
= strlen(s
->password
);
2948 logevent("Sending unpadded password");
2949 send_packet(ssh
, s
->pwpkt_type
, PKT_INT
, len
,
2950 PKT_DATA
, s
->password
, len
, PKT_END
);
2953 send_packet(ssh
, s
->pwpkt_type
, PKT_STR
, s
->password
, PKT_END
);
2956 logevent("Sent password");
2957 memset(s
->password
, 0, strlen(s
->password
));
2959 if (ssh
->pktin
.type
== SSH1_SMSG_FAILURE
) {
2960 if (flags
& FLAG_VERBOSE
)
2961 c_write_str(ssh
, "Access denied\r\n");
2962 logevent("Authentication refused");
2963 } else if (ssh
->pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2964 bombout((ssh
,"Strange packet received, type %d", ssh
->pktin
.type
));
2969 logevent("Authentication successful");
2974 void sshfwd_close(struct ssh_channel
*c
)
2978 if (c
&& !c
->closes
) {
2980 * If the channel's remoteid is -1, we have sent
2981 * CHANNEL_OPEN for this channel, but it hasn't even been
2982 * acknowledged by the server. So we must set a close flag
2983 * on it now, and then when the server acks the channel
2984 * open, we can close it then.
2986 if (((int)c
->remoteid
) != -1) {
2987 if (ssh
->version
== 1) {
2988 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
2991 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_CLOSE
);
2992 ssh2_pkt_adduint32(ssh
, c
->remoteid
);
2996 c
->closes
= 1; /* sent MSG_CLOSE */
2997 if (c
->type
== CHAN_X11
) {
2999 logevent("Forwarded X11 connection terminated");
3000 } else if (c
->type
== CHAN_SOCKDATA
||
3001 c
->type
== CHAN_SOCKDATA_DORMANT
) {
3003 logevent("Forwarded port closed");
3008 int sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
3012 if (ssh
->version
== 1) {
3013 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
3014 PKT_INT
, c
->remoteid
,
3015 PKT_INT
, len
, PKT_DATA
, buf
, len
, PKT_END
);
3017 * In SSH1 we can return 0 here - implying that forwarded
3018 * connections are never individually throttled - because
3019 * the only circumstance that can cause throttling will be
3020 * the whole SSH connection backing up, in which case
3021 * _everything_ will be throttled as a whole.
3025 ssh2_add_channel_data(c
, buf
, len
);
3026 return ssh2_try_send(c
);
3030 void sshfwd_unthrottle(struct ssh_channel
*c
, int bufsize
)
3034 if (ssh
->version
== 1) {
3035 if (c
->v
.v1
.throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
3036 c
->v
.v1
.throttling
= 0;
3037 ssh1_throttle(ssh
, -1);
3040 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
3044 static void ssh1_protocol(Ssh ssh
, unsigned char *in
, int inlen
, int ispkt
)
3046 crBegin(ssh
->ssh1_protocol_crstate
);
3050 while (!do_ssh1_login(ssh
, in
, inlen
, ispkt
)) {
3053 if (ssh
->state
== SSH_STATE_CLOSED
)
3056 if (ssh
->cfg
.agentfwd
&& agent_exists()) {
3057 logevent("Requesting agent forwarding");
3058 send_packet(ssh
, SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
3062 if (ssh
->pktin
.type
!= SSH1_SMSG_SUCCESS
3063 && ssh
->pktin
.type
!= SSH1_SMSG_FAILURE
) {
3064 bombout((ssh
,"Protocol confusion"));
3066 } else if (ssh
->pktin
.type
== SSH1_SMSG_FAILURE
) {
3067 logevent("Agent forwarding refused");
3069 logevent("Agent forwarding enabled");
3070 ssh
->agentfwd_enabled
= TRUE
;
3074 if (ssh
->cfg
.x11_forward
) {
3075 char proto
[20], data
[64];
3076 logevent("Requesting X11 forwarding");
3077 ssh
->x11auth
= x11_invent_auth(proto
, sizeof(proto
),
3078 data
, sizeof(data
), ssh
->cfg
.x11_auth
);
3079 x11_get_real_auth(ssh
->x11auth
, ssh
->cfg
.x11_display
);
3080 if (ssh
->v1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
3081 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
3082 PKT_STR
, proto
, PKT_STR
, data
,
3083 PKT_INT
, x11_get_screen_number(ssh
->cfg
.x11_display
),
3086 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
3087 PKT_STR
, proto
, PKT_STR
, data
, PKT_END
);
3092 if (ssh
->pktin
.type
!= SSH1_SMSG_SUCCESS
3093 && ssh
->pktin
.type
!= SSH1_SMSG_FAILURE
) {
3094 bombout((ssh
,"Protocol confusion"));
3096 } else if (ssh
->pktin
.type
== SSH1_SMSG_FAILURE
) {
3097 logevent("X11 forwarding refused");
3099 logevent("X11 forwarding enabled");
3100 ssh
->X11_fwd_enabled
= TRUE
;
3107 int sport
,dport
,sserv
,dserv
;
3108 char sports
[256], dports
[256], saddr
[256], host
[256];
3110 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh1
);
3111 /* Add port forwardings. */
3112 ssh
->portfwd_strptr
= ssh
->cfg
.portfwd
;
3113 while (*ssh
->portfwd_strptr
) {
3114 type
= *ssh
->portfwd_strptr
++;
3117 while (*ssh
->portfwd_strptr
&& *ssh
->portfwd_strptr
!= '\t') {
3118 if (*ssh
->portfwd_strptr
== ':') {
3120 * We've seen a colon in the middle of the
3121 * source port number. This means that
3122 * everything we've seen until now is the
3123 * source _address_, so we'll move it into
3124 * saddr and start sports from the beginning
3127 ssh
->portfwd_strptr
++;
3129 strcpy(saddr
, sports
);
3132 if (n
< 255) sports
[n
++] = *ssh
->portfwd_strptr
++;
3135 if (*ssh
->portfwd_strptr
== '\t')
3136 ssh
->portfwd_strptr
++;
3138 while (*ssh
->portfwd_strptr
&& *ssh
->portfwd_strptr
!= ':') {
3139 if (n
< 255) host
[n
++] = *ssh
->portfwd_strptr
++;
3142 if (*ssh
->portfwd_strptr
== ':')
3143 ssh
->portfwd_strptr
++;
3145 while (*ssh
->portfwd_strptr
) {
3146 if (n
< 255) dports
[n
++] = *ssh
->portfwd_strptr
++;
3149 ssh
->portfwd_strptr
++;
3150 dport
= atoi(dports
);
3154 dport
= net_service_lookup(dports
);
3156 logeventf(ssh
, "Service lookup failed for"
3157 " destination port \"%s\"", dports
);
3160 sport
= atoi(sports
);
3164 sport
= net_service_lookup(sports
);
3166 logeventf(ssh
, "Service lookup failed for source"
3167 " port \"%s\"", sports
);
3170 if (sport
&& dport
) {
3172 pfd_addforward(host
, dport
, *saddr ? saddr
: NULL
,
3173 sport
, ssh
, &ssh
->cfg
);
3174 logeventf(ssh
, "Local port %.*s%.*s%.*s%.*s%d%.*s"
3175 " forwarding to %s:%.*s%.*s%d%.*s",
3176 (int)(*saddr?
strlen(saddr
):0), *saddr?saddr
:NULL
,
3177 (int)(*saddr?
1:0), ":",
3178 (int)(sserv ?
strlen(sports
) : 0), sports
,
3179 sserv
, "(", sport
, sserv
, ")",
3181 (int)(dserv ?
strlen(dports
) : 0), dports
,
3182 dserv
, "(", dport
, dserv
, ")");
3184 struct ssh_rportfwd
*pf
;
3185 pf
= smalloc(sizeof(*pf
));
3186 strcpy(pf
->dhost
, host
);
3190 "SSH1 cannot handle source address spec \"%s:%d\"; ignoring",
3193 if (add234(ssh
->rportfwds
, pf
) != pf
) {
3195 "Duplicate remote port forwarding to %s:%d",
3199 logeventf(ssh
, "Requesting remote port %.*s%.*s%d%.*s"
3200 " forward to %s:%.*s%.*s%d%.*s",
3201 (int)(sserv ?
strlen(sports
) : 0), sports
,
3202 sserv
, "(", sport
, sserv
, ")",
3204 (int)(dserv ?
strlen(dports
) : 0), dports
,
3205 dserv
, "(", dport
, dserv
, ")");
3206 send_packet(ssh
, SSH1_CMSG_PORT_FORWARD_REQUEST
,
3214 if (ssh
->pktin
.type
!= SSH1_SMSG_SUCCESS
3215 && ssh
->pktin
.type
!= SSH1_SMSG_FAILURE
) {
3216 bombout((ssh
,"Protocol confusion"));
3218 } else if (ssh
->pktin
.type
== SSH1_SMSG_FAILURE
) {
3219 c_write_str(ssh
, "Server refused port"
3222 logevent("Remote port forwarding enabled");
3229 if (!ssh
->cfg
.nopty
) {
3230 send_packet(ssh
, SSH1_CMSG_REQUEST_PTY
,
3231 PKT_STR
, ssh
->cfg
.termtype
,
3232 PKT_INT
, ssh
->term_height
,
3233 PKT_INT
, ssh
->term_width
,
3234 PKT_INT
, 0, PKT_INT
, 0, PKT_CHAR
, 0, PKT_END
);
3235 ssh
->state
= SSH_STATE_INTERMED
;
3239 if (ssh
->pktin
.type
!= SSH1_SMSG_SUCCESS
3240 && ssh
->pktin
.type
!= SSH1_SMSG_FAILURE
) {
3241 bombout((ssh
,"Protocol confusion"));
3243 } else if (ssh
->pktin
.type
== SSH1_SMSG_FAILURE
) {
3244 c_write_str(ssh
, "Server refused to allocate pty\r\n");
3245 ssh
->editing
= ssh
->echoing
= 1;
3247 logevent("Allocated pty");
3249 ssh
->editing
= ssh
->echoing
= 1;
3252 if (ssh
->cfg
.compression
) {
3253 send_packet(ssh
, SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
3257 if (ssh
->pktin
.type
!= SSH1_SMSG_SUCCESS
3258 && ssh
->pktin
.type
!= SSH1_SMSG_FAILURE
) {
3259 bombout((ssh
,"Protocol confusion"));
3261 } else if (ssh
->pktin
.type
== SSH1_SMSG_FAILURE
) {
3262 c_write_str(ssh
, "Server refused to compress\r\n");
3264 logevent("Started compression");
3265 ssh
->v1_compressing
= TRUE
;
3266 ssh
->cs_comp_ctx
= zlib_compress_init();
3267 logevent("Initialised zlib (RFC1950) compression");
3268 ssh
->sc_comp_ctx
= zlib_decompress_init();
3269 logevent("Initialised zlib (RFC1950) decompression");
3273 * Start the shell or command.
3275 * Special case: if the first-choice command is an SSH2
3276 * subsystem (hence not usable here) and the second choice
3277 * exists, we fall straight back to that.
3280 char *cmd
= ssh
->cfg
.remote_cmd_ptr
;
3282 if (ssh
->cfg
.ssh_subsys
&& ssh
->cfg
.remote_cmd_ptr2
) {
3283 cmd
= ssh
->cfg
.remote_cmd_ptr2
;
3284 ssh
->fallback_cmd
= TRUE
;
3287 send_packet(ssh
, SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
3289 send_packet(ssh
, SSH1_CMSG_EXEC_SHELL
, PKT_END
);
3290 logevent("Started session");
3293 ssh
->state
= SSH_STATE_SESSION
;
3294 if (ssh
->size_needed
)
3295 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
3296 if (ssh
->eof_needed
)
3297 ssh_special(ssh
, TS_EOF
);
3300 ldisc_send(ssh
->ldisc
, NULL
, 0, 0);/* cause ldisc to notice changes */
3302 ssh
->channels
= newtree234(ssh_channelcmp
);
3306 if (ssh
->pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
3307 ssh
->pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
3308 long len
= GET_32BIT(ssh
->pktin
.body
);
3310 from_backend(ssh
->frontend
,
3311 ssh
->pktin
.type
== SSH1_SMSG_STDERR_DATA
,
3312 (char *)(ssh
->pktin
.body
) + 4, len
);
3313 if (!ssh
->v1_stdout_throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
3314 ssh
->v1_stdout_throttling
= 1;
3315 ssh1_throttle(ssh
, +1);
3317 } else if (ssh
->pktin
.type
== SSH1_MSG_DISCONNECT
) {
3318 ssh
->state
= SSH_STATE_CLOSED
;
3319 logevent("Received disconnect request");
3321 } else if (ssh
->pktin
.type
== SSH1_SMSG_X11_OPEN
) {
3322 /* Remote side is trying to open a channel to talk to our
3323 * X-Server. Give them back a local channel number. */
3324 struct ssh_channel
*c
;
3326 logevent("Received X11 connect request");
3327 /* Refuse if X11 forwarding is disabled. */
3328 if (!ssh
->X11_fwd_enabled
) {
3329 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3330 PKT_INT
, GET_32BIT(ssh
->pktin
.body
), PKT_END
);
3331 logevent("Rejected X11 connect request");
3333 c
= smalloc(sizeof(struct ssh_channel
));
3336 if (x11_init(&c
->u
.x11
.s
, ssh
->cfg
.x11_display
, c
,
3337 ssh
->x11auth
, NULL
, -1, &ssh
->cfg
) != NULL
) {
3338 logevent("opening X11 forward connection failed");
3340 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3341 PKT_INT
, GET_32BIT(ssh
->pktin
.body
),
3345 ("opening X11 forward connection succeeded");
3346 c
->remoteid
= GET_32BIT(ssh
->pktin
.body
);
3347 c
->localid
= alloc_channel_id(ssh
);
3349 c
->v
.v1
.throttling
= 0;
3350 c
->type
= CHAN_X11
; /* identify channel type */
3351 add234(ssh
->channels
, c
);
3352 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
3353 PKT_INT
, c
->remoteid
, PKT_INT
,
3354 c
->localid
, PKT_END
);
3355 logevent("Opened X11 forward channel");
3358 } else if (ssh
->pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
3359 /* Remote side is trying to open a channel to talk to our
3360 * agent. Give them back a local channel number. */
3361 struct ssh_channel
*c
;
3363 /* Refuse if agent forwarding is disabled. */
3364 if (!ssh
->agentfwd_enabled
) {
3365 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3366 PKT_INT
, GET_32BIT(ssh
->pktin
.body
), PKT_END
);
3368 c
= smalloc(sizeof(struct ssh_channel
));
3370 c
->remoteid
= GET_32BIT(ssh
->pktin
.body
);
3371 c
->localid
= alloc_channel_id(ssh
);
3373 c
->v
.v1
.throttling
= 0;
3374 c
->type
= CHAN_AGENT
; /* identify channel type */
3375 c
->u
.a
.lensofar
= 0;
3376 add234(ssh
->channels
, c
);
3377 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
3378 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
3381 } else if (ssh
->pktin
.type
== SSH1_MSG_PORT_OPEN
) {
3382 /* Remote side is trying to open a channel to talk to a
3383 * forwarded port. Give them back a local channel number. */
3384 struct ssh_channel
*c
;
3385 struct ssh_rportfwd pf
;
3387 char host
[256], buf
[1024];
3389 c
= smalloc(sizeof(struct ssh_channel
));
3392 hostsize
= GET_32BIT(ssh
->pktin
.body
+4);
3393 for (h
= host
, p
= (char *)(ssh
->pktin
.body
+8);
3394 hostsize
!= 0; hostsize
--) {
3395 if (h
+1 < host
+sizeof(host
))
3400 port
= GET_32BIT(p
);
3402 strcpy(pf
.dhost
, host
);
3405 if (find234(ssh
->rportfwds
, &pf
, NULL
) == NULL
) {
3406 sprintf(buf
, "Rejected remote port open request for %s:%d",
3409 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3410 PKT_INT
, GET_32BIT(ssh
->pktin
.body
), PKT_END
);
3412 sprintf(buf
, "Received remote port open request for %s:%d",
3415 e
= pfd_newconnect(&c
->u
.pfd
.s
, host
, port
, c
, &ssh
->cfg
);
3418 sprintf(buf
, "Port open failed: %s", e
);
3421 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3422 PKT_INT
, GET_32BIT(ssh
->pktin
.body
),
3425 c
->remoteid
= GET_32BIT(ssh
->pktin
.body
);
3426 c
->localid
= alloc_channel_id(ssh
);
3428 c
->v
.v1
.throttling
= 0;
3429 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
3430 add234(ssh
->channels
, c
);
3431 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
3432 PKT_INT
, c
->remoteid
, PKT_INT
,
3433 c
->localid
, PKT_END
);
3434 logevent("Forwarded port opened successfully");
3438 } else if (ssh
->pktin
.type
== SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
) {
3439 unsigned int remoteid
= GET_32BIT(ssh
->pktin
.body
);
3440 unsigned int localid
= GET_32BIT(ssh
->pktin
.body
+4);
3441 struct ssh_channel
*c
;
3443 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
3444 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
3445 c
->remoteid
= localid
;
3446 c
->type
= CHAN_SOCKDATA
;
3447 c
->v
.v1
.throttling
= 0;
3448 pfd_confirm(c
->u
.pfd
.s
);
3451 if (c
&& c
->closes
) {
3453 * We have a pending close on this channel,
3454 * which we decided on before the server acked
3455 * the channel open. So now we know the
3456 * remoteid, we can close it again.
3458 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
,
3459 PKT_INT
, c
->remoteid
, PKT_END
);
3462 } else if (ssh
->pktin
.type
== SSH1_MSG_CHANNEL_OPEN_FAILURE
) {
3463 unsigned int remoteid
= GET_32BIT(ssh
->pktin
.body
);
3464 struct ssh_channel
*c
;
3466 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
3467 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
3468 logevent("Forwarded connection refused by server");
3469 pfd_close(c
->u
.pfd
.s
);
3470 del234(ssh
->channels
, c
);
3474 } else if (ssh
->pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
3475 ssh
->pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
3476 /* Remote side closes a channel. */
3477 unsigned i
= GET_32BIT(ssh
->pktin
.body
);
3478 struct ssh_channel
*c
;
3479 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
3480 if (c
&& ((int)c
->remoteid
) != -1) {
3483 (ssh
->pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
3485 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
3486 logevent("Forwarded X11 connection terminated");
3487 assert(c
->u
.x11
.s
!= NULL
);
3488 x11_close(c
->u
.x11
.s
);
3491 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
3492 logevent("Forwarded port closed");
3493 assert(c
->u
.pfd
.s
!= NULL
);
3494 pfd_close(c
->u
.pfd
.s
);
3498 c
->closes
|= (closetype
<< 2); /* seen this message */
3499 if (!(c
->closes
& closetype
)) {
3500 send_packet(ssh
, ssh
->pktin
.type
, PKT_INT
, c
->remoteid
,
3502 c
->closes
|= closetype
; /* sent it too */
3505 if (c
->closes
== 15) {
3506 del234(ssh
->channels
, c
);
3510 bombout((ssh
,"Received CHANNEL_CLOSE%s for %s channel %d\n",
3511 ssh
->pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
"" :
3512 "_CONFIRMATION", c ?
"half-open" : "nonexistent",
3515 } else if (ssh
->pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
3516 /* Data sent down one of our channels. */
3517 int i
= GET_32BIT(ssh
->pktin
.body
);
3518 int len
= GET_32BIT(ssh
->pktin
.body
+ 4);
3519 unsigned char *p
= ssh
->pktin
.body
+ 8;
3520 struct ssh_channel
*c
;
3521 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
3526 bufsize
= x11_send(c
->u
.x11
.s
, (char *)p
, len
);
3529 bufsize
= pfd_send(c
->u
.pfd
.s
, (char *)p
, len
);
3532 /* Data for an agent message. Buffer it. */
3534 if (c
->u
.a
.lensofar
< 4) {
3535 int l
= min(4 - c
->u
.a
.lensofar
, len
);
3536 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
3540 c
->u
.a
.lensofar
+= l
;
3542 if (c
->u
.a
.lensofar
== 4) {
3544 4 + GET_32BIT(c
->u
.a
.msglen
);
3545 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
3546 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
3548 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
3550 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
3552 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
3556 c
->u
.a
.lensofar
+= l
;
3558 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
3559 void *reply
, *sentreply
;
3561 agent_query(c
->u
.a
.message
,
3562 c
->u
.a
.totallen
, &reply
,
3567 /* Fake SSH_AGENT_FAILURE. */
3568 sentreply
= "\0\0\0\1\5";
3571 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
3572 PKT_INT
, c
->remoteid
,
3574 PKT_DATA
, sentreply
, replylen
,
3578 sfree(c
->u
.a
.message
);
3579 c
->u
.a
.lensofar
= 0;
3582 bufsize
= 0; /* agent channels never back up */
3585 if (!c
->v
.v1
.throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
3586 c
->v
.v1
.throttling
= 1;
3587 ssh1_throttle(ssh
, +1);
3590 } else if (ssh
->pktin
.type
== SSH1_SMSG_SUCCESS
) {
3591 /* may be from EXEC_SHELL on some servers */
3592 } else if (ssh
->pktin
.type
== SSH1_SMSG_FAILURE
) {
3593 /* may be from EXEC_SHELL on some servers
3594 * if no pty is available or in other odd cases. Ignore */
3595 } else if (ssh
->pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
3597 ssh
->exitcode
= GET_32BIT(ssh
->pktin
.body
);
3598 sprintf(buf
, "Server sent command exit status %d",
3601 send_packet(ssh
, SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
3603 * In case `helpful' firewalls or proxies tack
3604 * extra human-readable text on the end of the
3605 * session which we might mistake for another
3606 * encrypted packet, we close the session once
3607 * we've sent EXIT_CONFIRMATION.
3609 ssh
->state
= SSH_STATE_CLOSED
;
3612 bombout((ssh
,"Strange packet received: type %d", ssh
->pktin
.type
));
3617 int len
= min(inlen
, 512);
3618 send_packet(ssh
, SSH1_CMSG_STDIN_DATA
,
3619 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
3630 * Utility routine for decoding comma-separated strings in KEXINIT.
3632 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
3635 if (!needle
|| !haystack
) /* protect against null pointers */
3637 needlen
= strlen(needle
);
3640 * Is it at the start of the string?
3642 if (haylen
>= needlen
&& /* haystack is long enough */
3643 !memcmp(needle
, haystack
, needlen
) && /* initial match */
3644 (haylen
== needlen
|| haystack
[needlen
] == ',')
3645 /* either , or EOS follows */
3649 * If not, search for the next comma and resume after that.
3650 * If no comma found, terminate.
3652 while (haylen
> 0 && *haystack
!= ',')
3653 haylen
--, haystack
++;
3656 haylen
--, haystack
++; /* skip over comma itself */
3661 * SSH2 key creation method.
3663 static void ssh2_mkkey(Ssh ssh
, Bignum K
, unsigned char *H
,
3664 unsigned char *sessid
, char chr
,
3665 unsigned char *keyspace
)
3668 /* First 20 bytes. */
3670 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
3672 SHA_Bytes(&s
, H
, 20);
3673 SHA_Bytes(&s
, &chr
, 1);
3674 SHA_Bytes(&s
, sessid
, 20);
3675 SHA_Final(&s
, keyspace
);
3676 /* Next 20 bytes. */
3678 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
3680 SHA_Bytes(&s
, H
, 20);
3681 SHA_Bytes(&s
, keyspace
, 20);
3682 SHA_Final(&s
, keyspace
+ 20);
3686 * Handle the SSH2 transport layer.
3688 static int do_ssh2_transport(Ssh ssh
, unsigned char *in
, int inlen
, int ispkt
)
3690 struct do_ssh2_transport_state
{
3691 int nbits
, pbits
, warn
;
3692 Bignum p
, g
, e
, f
, K
;
3693 int kex_init_value
, kex_reply_value
;
3694 const struct ssh_mac
**maclist
;
3696 const struct ssh2_cipher
*cscipher_tobe
;
3697 const struct ssh2_cipher
*sccipher_tobe
;
3698 const struct ssh_mac
*csmac_tobe
;
3699 const struct ssh_mac
*scmac_tobe
;
3700 const struct ssh_compress
*cscomp_tobe
;
3701 const struct ssh_compress
*sccomp_tobe
;
3702 char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
3703 int hostkeylen
, siglen
;
3704 void *hkey
; /* actual host key */
3705 unsigned char exchange_hash
[20];
3706 int n_preferred_ciphers
;
3707 const struct ssh2_ciphers
*preferred_ciphers
[CIPHER_MAX
];
3708 const struct ssh_compress
*preferred_comp
;
3711 crState(do_ssh2_transport_state
);
3713 crBegin(ssh
->do_ssh2_transport_crstate
);
3715 s
->cscipher_tobe
= s
->sccipher_tobe
= NULL
;
3716 s
->csmac_tobe
= s
->scmac_tobe
= NULL
;
3717 s
->cscomp_tobe
= s
->sccomp_tobe
= NULL
;
3725 * Set up the preferred ciphers. (NULL => warn below here)
3727 s
->n_preferred_ciphers
= 0;
3728 for (i
= 0; i
< CIPHER_MAX
; i
++) {
3729 switch (ssh
->cfg
.ssh_cipherlist
[i
]) {
3730 case CIPHER_BLOWFISH
:
3731 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_blowfish
;
3734 if (ssh
->cfg
.ssh2_des_cbc
) {
3735 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_des
;
3739 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_3des
;
3742 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_aes
;
3745 /* Flag for later. Don't bother if it's the last in
3747 if (i
< CIPHER_MAX
- 1) {
3748 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = NULL
;
3756 * Set up preferred compression.
3758 if (ssh
->cfg
.compression
)
3759 s
->preferred_comp
= &ssh_zlib
;
3761 s
->preferred_comp
= &ssh_comp_none
;
3764 * Be prepared to work around the buggy MAC problem.
3766 if (ssh
->remote_bugs
& BUG_SSH2_HMAC
)
3767 s
->maclist
= buggymacs
, s
->nmacs
= lenof(buggymacs
);
3769 s
->maclist
= macs
, s
->nmacs
= lenof(macs
);
3773 int i
, j
, cipherstr_started
;
3776 * Construct and send our key exchange packet.
3778 ssh2_pkt_init(ssh
, SSH2_MSG_KEXINIT
);
3779 for (i
= 0; i
< 16; i
++)
3780 ssh2_pkt_addbyte(ssh
, (unsigned char) random_byte());
3781 /* List key exchange algorithms. */
3782 ssh2_pkt_addstring_start(ssh
);
3783 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3784 if (kex_algs
[i
] == &ssh_diffiehellman_gex
&&
3785 (ssh
->remote_bugs
& BUG_SSH2_DH_GEX
))
3787 ssh2_pkt_addstring_str(ssh
, kex_algs
[i
]->name
);
3788 if (i
< lenof(kex_algs
) - 1)
3789 ssh2_pkt_addstring_str(ssh
, ",");
3791 /* List server host key algorithms. */
3792 ssh2_pkt_addstring_start(ssh
);
3793 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3794 ssh2_pkt_addstring_str(ssh
, hostkey_algs
[i
]->name
);
3795 if (i
< lenof(hostkey_algs
) - 1)
3796 ssh2_pkt_addstring_str(ssh
, ",");
3798 /* List client->server encryption algorithms. */
3799 ssh2_pkt_addstring_start(ssh
);
3800 cipherstr_started
= 0;
3801 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
3802 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
3803 if (!c
) continue; /* warning flag */
3804 for (j
= 0; j
< c
->nciphers
; j
++) {
3805 if (cipherstr_started
)
3806 ssh2_pkt_addstring_str(ssh
, ",");
3807 ssh2_pkt_addstring_str(ssh
, c
->list
[j
]->name
);
3808 cipherstr_started
= 1;
3811 /* List server->client encryption algorithms. */
3812 ssh2_pkt_addstring_start(ssh
);
3813 cipherstr_started
= 0;
3814 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
3815 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
3816 if (!c
) continue; /* warning flag */
3817 for (j
= 0; j
< c
->nciphers
; j
++) {
3818 if (cipherstr_started
)
3819 ssh2_pkt_addstring_str(ssh
, ",");
3820 ssh2_pkt_addstring_str(ssh
, c
->list
[j
]->name
);
3821 cipherstr_started
= 1;
3824 /* List client->server MAC algorithms. */
3825 ssh2_pkt_addstring_start(ssh
);
3826 for (i
= 0; i
< s
->nmacs
; i
++) {
3827 ssh2_pkt_addstring_str(ssh
, s
->maclist
[i
]->name
);
3828 if (i
< s
->nmacs
- 1)
3829 ssh2_pkt_addstring_str(ssh
, ",");
3831 /* List server->client MAC algorithms. */
3832 ssh2_pkt_addstring_start(ssh
);
3833 for (i
= 0; i
< s
->nmacs
; i
++) {
3834 ssh2_pkt_addstring_str(ssh
, s
->maclist
[i
]->name
);
3835 if (i
< s
->nmacs
- 1)
3836 ssh2_pkt_addstring_str(ssh
, ",");
3838 /* List client->server compression algorithms. */
3839 ssh2_pkt_addstring_start(ssh
);
3840 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3841 const struct ssh_compress
*c
=
3842 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
3843 ssh2_pkt_addstring_str(ssh
, c
->name
);
3844 if (i
< lenof(compressions
))
3845 ssh2_pkt_addstring_str(ssh
, ",");
3847 /* List server->client compression algorithms. */
3848 ssh2_pkt_addstring_start(ssh
);
3849 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3850 const struct ssh_compress
*c
=
3851 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
3852 ssh2_pkt_addstring_str(ssh
, c
->name
);
3853 if (i
< lenof(compressions
))
3854 ssh2_pkt_addstring_str(ssh
, ",");
3856 /* List client->server languages. Empty list. */
3857 ssh2_pkt_addstring_start(ssh
);
3858 /* List server->client languages. Empty list. */
3859 ssh2_pkt_addstring_start(ssh
);
3860 /* First KEX packet does _not_ follow, because we're not that brave. */
3861 ssh2_pkt_addbool(ssh
, FALSE
);
3863 ssh2_pkt_adduint32(ssh
, 0);
3866 ssh
->exhash
= ssh
->exhashbase
;
3867 sha_string(&ssh
->exhash
, ssh
->pktout
.data
+ 5, ssh
->pktout
.length
- 5);
3873 if (ssh
->pktin
.length
> 5)
3874 sha_string(&ssh
->exhash
, ssh
->pktin
.data
+ 5, ssh
->pktin
.length
- 5);
3877 * Now examine the other side's KEXINIT to see what we're up
3884 if (ssh
->pktin
.type
!= SSH2_MSG_KEXINIT
) {
3885 bombout((ssh
,"expected key exchange packet from server"));
3889 ssh
->hostkey
= NULL
;
3890 s
->cscipher_tobe
= NULL
;
3891 s
->sccipher_tobe
= NULL
;
3892 s
->csmac_tobe
= NULL
;
3893 s
->scmac_tobe
= NULL
;
3894 s
->cscomp_tobe
= NULL
;
3895 s
->sccomp_tobe
= NULL
;
3896 ssh
->pktin
.savedpos
+= 16; /* skip garbage cookie */
3897 ssh2_pkt_getstring(ssh
, &str
, &len
); /* key exchange algorithms */
3898 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3899 if (kex_algs
[i
] == &ssh_diffiehellman_gex
&&
3900 (ssh
->remote_bugs
& BUG_SSH2_DH_GEX
))
3902 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
3903 ssh
->kex
= kex_algs
[i
];
3907 ssh2_pkt_getstring(ssh
, &str
, &len
); /* host key algorithms */
3908 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3909 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
3910 ssh
->hostkey
= hostkey_algs
[i
];
3914 ssh2_pkt_getstring(ssh
, &str
, &len
); /* client->server cipher */
3916 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
3917 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
3921 for (j
= 0; j
< c
->nciphers
; j
++) {
3922 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3923 s
->cscipher_tobe
= c
->list
[j
];
3928 if (s
->cscipher_tobe
) {
3930 askcipher(ssh
->frontend
, s
->cscipher_tobe
->name
, 1);
3934 if (!s
->cscipher_tobe
) {
3935 bombout((ssh
,"Couldn't agree a client-to-server cipher (available: %s)",
3936 str ? str
: "(null)"));
3940 ssh2_pkt_getstring(ssh
, &str
, &len
); /* server->client cipher */
3942 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
3943 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
3947 for (j
= 0; j
< c
->nciphers
; j
++) {
3948 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3949 s
->sccipher_tobe
= c
->list
[j
];
3954 if (s
->sccipher_tobe
) {
3956 askcipher(ssh
->frontend
, s
->sccipher_tobe
->name
, 2);
3960 if (!s
->sccipher_tobe
) {
3961 bombout((ssh
,"Couldn't agree a server-to-client cipher (available: %s)",
3962 str ? str
: "(null)"));
3966 ssh2_pkt_getstring(ssh
, &str
, &len
); /* client->server mac */
3967 for (i
= 0; i
< s
->nmacs
; i
++) {
3968 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
3969 s
->csmac_tobe
= s
->maclist
[i
];
3973 ssh2_pkt_getstring(ssh
, &str
, &len
); /* server->client mac */
3974 for (i
= 0; i
< s
->nmacs
; i
++) {
3975 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
3976 s
->scmac_tobe
= s
->maclist
[i
];
3980 ssh2_pkt_getstring(ssh
, &str
, &len
); /* client->server compression */
3981 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3982 const struct ssh_compress
*c
=
3983 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
3984 if (in_commasep_string(c
->name
, str
, len
)) {
3989 ssh2_pkt_getstring(ssh
, &str
, &len
); /* server->client compression */
3990 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3991 const struct ssh_compress
*c
=
3992 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
3993 if (in_commasep_string(c
->name
, str
, len
)) {
4001 * Work out the number of bits of key we will need from the key
4002 * exchange. We start with the maximum key length of either
4008 csbits
= s
->cscipher_tobe
->keylen
;
4009 scbits
= s
->sccipher_tobe
->keylen
;
4010 s
->nbits
= (csbits
> scbits ? csbits
: scbits
);
4012 /* The keys only have 160-bit entropy, since they're based on
4013 * a SHA-1 hash. So cap the key size at 160 bits. */
4018 * If we're doing Diffie-Hellman group exchange, start by
4019 * requesting a group.
4021 if (ssh
->kex
== &ssh_diffiehellman_gex
) {
4022 logevent("Doing Diffie-Hellman group exchange");
4023 ssh
->pkt_ctx
|= SSH2_PKTCTX_DHGEX
;
4025 * Work out how big a DH group we will need to allow that
4028 s
->pbits
= 512 << ((s
->nbits
- 1) / 64);
4029 ssh2_pkt_init(ssh
, SSH2_MSG_KEX_DH_GEX_REQUEST
);
4030 ssh2_pkt_adduint32(ssh
, s
->pbits
);
4034 if (ssh
->pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
4035 bombout((ssh
,"expected key exchange group packet from server"));
4038 s
->p
= ssh2_pkt_getmp(ssh
);
4039 s
->g
= ssh2_pkt_getmp(ssh
);
4040 ssh
->kex_ctx
= dh_setup_group(s
->p
, s
->g
);
4041 s
->kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
4042 s
->kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
4044 ssh
->pkt_ctx
|= SSH2_PKTCTX_DHGROUP1
;
4045 ssh
->kex_ctx
= dh_setup_group1();
4046 s
->kex_init_value
= SSH2_MSG_KEXDH_INIT
;
4047 s
->kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
4050 logevent("Doing Diffie-Hellman key exchange");
4052 * Now generate and send e for Diffie-Hellman.
4054 s
->e
= dh_create_e(ssh
->kex_ctx
, s
->nbits
* 2);
4055 ssh2_pkt_init(ssh
, s
->kex_init_value
);
4056 ssh2_pkt_addmp(ssh
, s
->e
);
4060 if (ssh
->pktin
.type
!= s
->kex_reply_value
) {
4061 bombout((ssh
,"expected key exchange reply packet from server"));
4064 ssh2_pkt_getstring(ssh
, &s
->hostkeydata
, &s
->hostkeylen
);
4065 s
->f
= ssh2_pkt_getmp(ssh
);
4066 ssh2_pkt_getstring(ssh
, &s
->sigdata
, &s
->siglen
);
4068 s
->K
= dh_find_K(ssh
->kex_ctx
, s
->f
);
4070 sha_string(&ssh
->exhash
, s
->hostkeydata
, s
->hostkeylen
);
4071 if (ssh
->kex
== &ssh_diffiehellman_gex
) {
4072 sha_uint32(&ssh
->exhash
, s
->pbits
);
4073 sha_mpint(&ssh
->exhash
, s
->p
);
4074 sha_mpint(&ssh
->exhash
, s
->g
);
4076 sha_mpint(&ssh
->exhash
, s
->e
);
4077 sha_mpint(&ssh
->exhash
, s
->f
);
4078 sha_mpint(&ssh
->exhash
, s
->K
);
4079 SHA_Final(&ssh
->exhash
, s
->exchange_hash
);
4081 dh_cleanup(ssh
->kex_ctx
);
4082 ssh
->kex_ctx
= NULL
;
4085 debug(("Exchange hash is:\n"));
4086 dmemdump(s
->exchange_hash
, 20);
4089 s
->hkey
= ssh
->hostkey
->newkey(s
->hostkeydata
, s
->hostkeylen
);
4091 !ssh
->hostkey
->verifysig(s
->hkey
, s
->sigdata
, s
->siglen
,
4092 (char *)s
->exchange_hash
, 20)) {
4093 bombout((ssh
,"Server's host key did not match the signature supplied"));
4098 * Authenticate remote host: verify host key. (We've already
4099 * checked the signature of the exchange hash.)
4101 s
->keystr
= ssh
->hostkey
->fmtkey(s
->hkey
);
4102 s
->fingerprint
= ssh
->hostkey
->fingerprint(s
->hkey
);
4103 verify_ssh_host_key(ssh
->frontend
,
4104 ssh
->savedhost
, ssh
->savedport
, ssh
->hostkey
->keytype
,
4105 s
->keystr
, s
->fingerprint
);
4106 if (s
->first_kex
) { /* don't bother logging this in rekeys */
4107 logevent("Host key fingerprint is:");
4108 logevent(s
->fingerprint
);
4110 sfree(s
->fingerprint
);
4112 ssh
->hostkey
->freekey(s
->hkey
);
4115 * Send SSH2_MSG_NEWKEYS.
4117 ssh2_pkt_init(ssh
, SSH2_MSG_NEWKEYS
);
4121 * Expect SSH2_MSG_NEWKEYS from server.
4124 if (ssh
->pktin
.type
!= SSH2_MSG_NEWKEYS
) {
4125 bombout((ssh
,"expected new-keys packet from server"));
4130 * Create and initialise session keys.
4132 if (ssh
->cs_cipher_ctx
)
4133 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
4134 ssh
->cscipher
= s
->cscipher_tobe
;
4135 ssh
->cs_cipher_ctx
= ssh
->cscipher
->make_context();
4137 if (ssh
->sc_cipher_ctx
)
4138 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
4139 ssh
->sccipher
= s
->sccipher_tobe
;
4140 ssh
->sc_cipher_ctx
= ssh
->sccipher
->make_context();
4142 if (ssh
->cs_mac_ctx
)
4143 ssh
->csmac
->free_context(ssh
->cs_mac_ctx
);
4144 ssh
->csmac
= s
->csmac_tobe
;
4145 ssh
->cs_mac_ctx
= ssh
->csmac
->make_context();
4147 if (ssh
->sc_mac_ctx
)
4148 ssh
->scmac
->free_context(ssh
->sc_mac_ctx
);
4149 ssh
->scmac
= s
->scmac_tobe
;
4150 ssh
->sc_mac_ctx
= ssh
->scmac
->make_context();
4152 if (ssh
->cs_comp_ctx
)
4153 ssh
->cscomp
->compress_cleanup(ssh
->cs_comp_ctx
);
4154 ssh
->cscomp
= s
->cscomp_tobe
;
4155 ssh
->cs_comp_ctx
= ssh
->cscomp
->compress_init();
4157 if (ssh
->sc_comp_ctx
)
4158 ssh
->sccomp
->decompress_cleanup(ssh
->sc_comp_ctx
);
4159 ssh
->sccomp
= s
->sccomp_tobe
;
4160 ssh
->sc_comp_ctx
= ssh
->sccomp
->decompress_init();
4163 * Set IVs after keys. Here we use the exchange hash from the
4164 * _first_ key exchange.
4167 unsigned char keyspace
[40];
4169 memcpy(ssh
->v2_session_id
, s
->exchange_hash
,
4170 sizeof(s
->exchange_hash
));
4171 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'C',keyspace
);
4172 ssh
->cscipher
->setkey(ssh
->cs_cipher_ctx
, keyspace
);
4173 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'D',keyspace
);
4174 ssh
->sccipher
->setkey(ssh
->sc_cipher_ctx
, keyspace
);
4175 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'A',keyspace
);
4176 ssh
->cscipher
->setiv(ssh
->cs_cipher_ctx
, keyspace
);
4177 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'B',keyspace
);
4178 ssh
->sccipher
->setiv(ssh
->sc_cipher_ctx
, keyspace
);
4179 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'E',keyspace
);
4180 ssh
->csmac
->setkey(ssh
->cs_mac_ctx
, keyspace
);
4181 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'F',keyspace
);
4182 ssh
->scmac
->setkey(ssh
->sc_mac_ctx
, keyspace
);
4184 logeventf(ssh
, "Initialised %.200s client->server encryption",
4185 ssh
->cscipher
->text_name
);
4186 logeventf(ssh
, "Initialised %.200s server->client encryption",
4187 ssh
->sccipher
->text_name
);
4188 if (ssh
->cscomp
->text_name
)
4189 logeventf(ssh
, "Initialised %s compression",
4190 ssh
->cscomp
->text_name
);
4191 if (ssh
->sccomp
->text_name
)
4192 logeventf(ssh
, "Initialised %s decompression",
4193 ssh
->sccomp
->text_name
);
4196 * If this is the first key exchange phase, we must pass the
4197 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
4198 * wants to see it but because it will need time to initialise
4199 * itself before it sees an actual packet. In subsequent key
4200 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
4201 * it would only confuse the layer above.
4203 if (!s
->first_kex
) {
4209 * Now we're encrypting. Begin returning 1 to the protocol main
4210 * function so that other things can run on top of the
4211 * transport. If we ever see a KEXINIT, we must go back to the
4214 while (!(ispkt
&& ssh
->pktin
.type
== SSH2_MSG_KEXINIT
)) {
4217 logevent("Server initiated key re-exchange");
4218 goto begin_key_exchange
;
4224 * Add data to an SSH2 channel output buffer.
4226 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
4229 bufchain_add(&c
->v
.v2
.outbuffer
, buf
, len
);
4233 * Attempt to send data on an SSH2 channel.
4235 static int ssh2_try_send(struct ssh_channel
*c
)
4239 while (c
->v
.v2
.remwindow
> 0 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0) {
4242 bufchain_prefix(&c
->v
.v2
.outbuffer
, &data
, &len
);
4243 if ((unsigned)len
> c
->v
.v2
.remwindow
)
4244 len
= c
->v
.v2
.remwindow
;
4245 if ((unsigned)len
> c
->v
.v2
.remmaxpkt
)
4246 len
= c
->v
.v2
.remmaxpkt
;
4247 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_DATA
);
4248 ssh2_pkt_adduint32(ssh
, c
->remoteid
);
4249 ssh2_pkt_addstring_start(ssh
);
4250 ssh2_pkt_addstring_data(ssh
, data
, len
);
4252 bufchain_consume(&c
->v
.v2
.outbuffer
, len
);
4253 c
->v
.v2
.remwindow
-= len
;
4257 * After having sent as much data as we can, return the amount
4260 return bufchain_size(&c
->v
.v2
.outbuffer
);
4264 * Potentially enlarge the window on an SSH2 channel.
4266 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
)
4271 * Never send WINDOW_ADJUST for a channel that the remote side
4272 * already thinks it's closed; there's no point, since it won't
4273 * be sending any more data anyway.
4278 if (newwin
> c
->v
.v2
.locwindow
) {
4279 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4280 ssh2_pkt_adduint32(ssh
, c
->remoteid
);
4281 ssh2_pkt_adduint32(ssh
, newwin
- c
->v
.v2
.locwindow
);
4283 c
->v
.v2
.locwindow
= newwin
;
4288 * Handle the SSH2 userauth and connection layers.
4290 static void do_ssh2_authconn(Ssh ssh
, unsigned char *in
, int inlen
, int ispkt
)
4292 struct do_ssh2_authconn_state
{
4294 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
,
4296 AUTH_KEYBOARD_INTERACTIVE
4300 AUTH_TYPE_PUBLICKEY
,
4301 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
4302 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
4304 AUTH_TYPE_KEYBOARD_INTERACTIVE
,
4305 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
4307 int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
4308 int tried_pubkey_config
, tried_agent
, tried_keyb_inter
;
4309 int kbd_inter_running
;
4311 int num_prompts
, curr_prompt
, echo
;
4316 void *publickey_blob
;
4317 int publickey_bloblen
;
4318 unsigned char request
[5], *response
, *p
;
4322 char *pkblob
, *alg
, *commentp
;
4323 int pklen
, alglen
, commentlen
;
4324 int siglen
, retlen
, len
;
4325 char *q
, *agentreq
, *ret
;
4328 crState(do_ssh2_authconn_state
);
4330 crBegin(ssh
->do_ssh2_authconn_crstate
);
4333 * Request userauth protocol, and await a response to it.
4335 ssh2_pkt_init(ssh
, SSH2_MSG_SERVICE_REQUEST
);
4336 ssh2_pkt_addstring(ssh
, "ssh-userauth");
4338 crWaitUntilV(ispkt
);
4339 if (ssh
->pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
4340 bombout((ssh
,"Server refused user authentication protocol"));
4345 * We repeat this whole loop, including the username prompt,
4346 * until we manage a successful authentication. If the user
4347 * types the wrong _password_, they can be sent back to the
4348 * beginning to try another username, if this is configured on.
4349 * (If they specify a username in the config, they are never
4350 * asked, even if they do give a wrong password.)
4352 * I think this best serves the needs of
4354 * - the people who have no configuration, no keys, and just
4355 * want to try repeated (username,password) pairs until they
4356 * type both correctly
4358 * - people who have keys and configuration but occasionally
4359 * need to fall back to passwords
4361 * - people with a key held in Pageant, who might not have
4362 * logged in to a particular machine before; so they want to
4363 * type a username, and then _either_ their key will be
4364 * accepted, _or_ they will type a password. If they mistype
4365 * the username they will want to be able to get back and
4368 s
->username
[0] = '\0';
4369 s
->got_username
= FALSE
;
4374 if (s
->got_username
&& !ssh
->cfg
.change_username
) {
4376 * We got a username last time round this loop, and
4377 * with change_username turned off we don't try to get
4380 } else if ((flags
& FLAG_INTERACTIVE
) && !*ssh
->cfg
.username
) {
4381 if (ssh_get_line
&& !ssh_getline_pw_only
) {
4382 if (!ssh_get_line("login as: ",
4383 s
->username
, sizeof(s
->username
), FALSE
)) {
4385 * get_line failed to get a username.
4388 logevent("No username provided. Abandoning session.");
4389 ssh
->state
= SSH_STATE_CLOSED
;
4393 int ret
; /* need not be saved across crReturn */
4394 c_write_str(ssh
, "login as: ");
4396 setup_userpass_input(ssh
, s
->username
, sizeof(s
->username
), 1);
4398 crWaitUntilV(!ispkt
);
4399 ret
= process_userpass_input(ssh
, in
, inlen
);
4403 c_write_str(ssh
, "\r\n");
4405 s
->username
[strcspn(s
->username
, "\n\r")] = '\0';
4408 strncpy(s
->username
, ssh
->cfg
.username
, sizeof(s
->username
));
4409 s
->username
[sizeof(s
->username
)-1] = '\0';
4410 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
4411 stuff
= dupprintf("Using username \"%s\".\r\n", s
->username
);
4412 c_write_str(ssh
, stuff
);
4416 s
->got_username
= TRUE
;
4419 * Send an authentication request using method "none": (a)
4420 * just in case it succeeds, and (b) so that we know what
4421 * authentication methods we can usefully try next.
4423 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4425 ssh2_pkt_init(ssh
, SSH2_MSG_USERAUTH_REQUEST
);
4426 ssh2_pkt_addstring(ssh
, s
->username
);
4427 ssh2_pkt_addstring(ssh
, "ssh-connection");/* service requested */
4428 ssh2_pkt_addstring(ssh
, "none"); /* method */
4430 s
->type
= AUTH_TYPE_NONE
;
4432 s
->we_are_in
= FALSE
;
4434 s
->tried_pubkey_config
= FALSE
;
4435 s
->tried_agent
= FALSE
;
4436 s
->tried_keyb_inter
= FALSE
;
4437 s
->kbd_inter_running
= FALSE
;
4438 /* Load the pub half of ssh->cfg.keyfile so we notice if it's in Pageant */
4439 if (!filename_is_null(ssh
->cfg
.keyfile
)) {
4441 logeventf(ssh
, "Reading private key file \"%.150s\"",
4442 filename_to_str(&ssh
->cfg
.keyfile
));
4443 keytype
= key_type(&ssh
->cfg
.keyfile
);
4444 if (keytype
== SSH_KEYTYPE_SSH2
) {
4446 ssh2_userkey_loadpub(&ssh
->cfg
.keyfile
, NULL
,
4447 &s
->publickey_bloblen
);
4450 logeventf(ssh
, "Unable to use this key file (%s)",
4451 key_type_to_str(keytype
));
4452 msgbuf
= dupprintf("Unable to use key file \"%.150s\""
4454 filename_to_str(&ssh
->cfg
.keyfile
),
4455 key_type_to_str(keytype
));
4456 c_write_str(ssh
, msgbuf
);
4458 s
->publickey_blob
= NULL
;
4461 s
->publickey_blob
= NULL
;
4465 * Wait for the result of the last authentication request.
4468 crWaitUntilV(ispkt
);
4469 while (ssh
->pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
4473 * Don't show the banner if we're operating in
4474 * non-verbose non-interactive mode. (It's probably
4475 * a script, which means nobody will read the
4476 * banner _anyway_, and moreover the printing of
4477 * the banner will screw up processing on the
4478 * output of (say) plink.)
4480 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
4481 ssh2_pkt_getstring(ssh
, &banner
, &size
);
4483 c_write_untrusted(ssh
, banner
, size
);
4485 crWaitUntilV(ispkt
);
4487 if (ssh
->pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
4488 logevent("Access granted");
4489 s
->we_are_in
= TRUE
;
4493 if (s
->kbd_inter_running
&&
4494 ssh
->pktin
.type
== SSH2_MSG_USERAUTH_INFO_REQUEST
) {
4496 * This is either a further set-of-prompts packet
4497 * in keyboard-interactive authentication, or it's
4498 * the same one and we came back here with `gotit'
4499 * set. In the former case, we must reset the
4500 * curr_prompt variable.
4504 } else if (ssh
->pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
4505 bombout((ssh
,"Strange packet received during authentication: type %d",
4513 * OK, we're now sitting on a USERAUTH_FAILURE message, so
4514 * we can look at the string in it and know what we can
4515 * helpfully try next.
4517 if (ssh
->pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
) {
4520 ssh2_pkt_getstring(ssh
, &methods
, &methlen
);
4521 s
->kbd_inter_running
= FALSE
;
4522 if (!ssh2_pkt_getbool(ssh
)) {
4524 * We have received an unequivocal Access
4525 * Denied. This can translate to a variety of
4528 * - if we'd just tried "none" authentication,
4529 * it's not worth printing anything at all
4531 * - if we'd just tried a public key _offer_,
4532 * the message should be "Server refused our
4533 * key" (or no message at all if the key
4534 * came from Pageant)
4536 * - if we'd just tried anything else, the
4537 * message really should be "Access denied".
4539 * Additionally, if we'd just tried password
4540 * authentication, we should break out of this
4541 * whole loop so as to go back to the username
4544 if (s
->type
== AUTH_TYPE_NONE
) {
4546 } else if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
4547 s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
4548 if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
4549 c_write_str(ssh
, "Server refused our key\r\n");
4550 logevent("Server refused public key");
4551 } else if (s
->type
==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
) {
4552 /* server declined keyboard-interactive; ignore */
4554 c_write_str(ssh
, "Access denied\r\n");
4555 logevent("Access denied");
4556 if (s
->type
== AUTH_TYPE_PASSWORD
) {
4557 s
->we_are_in
= FALSE
;
4562 c_write_str(ssh
, "Further authentication required\r\n");
4563 logevent("Further authentication required");
4567 in_commasep_string("publickey", methods
, methlen
);
4569 in_commasep_string("password", methods
, methlen
);
4570 s
->can_keyb_inter
= ssh
->cfg
.try_ki_auth
&&
4571 in_commasep_string("keyboard-interactive", methods
, methlen
);
4575 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4578 * Most password/passphrase prompts will be
4579 * non-echoing, so we set this to 0 by default.
4580 * Exception is that some keyboard-interactive prompts
4581 * can be echoing, in which case we'll set this to 1.
4585 if (!s
->method
&& s
->can_pubkey
&&
4586 agent_exists() && !s
->tried_agent
) {
4588 * Attempt public-key authentication using Pageant.
4593 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4594 ssh
->pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
4596 s
->tried_agent
= TRUE
;
4598 logevent("Pageant is running. Requesting keys.");
4600 /* Request the keys held by the agent. */
4601 PUT_32BIT(s
->request
, 1);
4602 s
->request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
4603 agent_query(s
->request
, 5, &r
, &s
->responselen
);
4604 s
->response
= (unsigned char *) r
;
4605 if (s
->response
&& s
->responselen
>= 5 &&
4606 s
->response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
4607 s
->p
= s
->response
+ 5;
4608 s
->nkeys
= GET_32BIT(s
->p
);
4612 sprintf(buf
, "Pageant has %d SSH2 keys", s
->nkeys
);
4615 for (s
->keyi
= 0; s
->keyi
< s
->nkeys
; s
->keyi
++) {
4620 sprintf(buf
, "Trying Pageant key #%d", s
->keyi
);
4623 s
->pklen
= GET_32BIT(s
->p
);
4625 if (s
->publickey_blob
&&
4626 s
->pklen
== s
->publickey_bloblen
&&
4627 !memcmp(s
->p
, s
->publickey_blob
,
4628 s
->publickey_bloblen
)) {
4629 logevent("This key matches configured key file");
4630 s
->tried_pubkey_config
= 1;
4632 s
->pkblob
= (char *)s
->p
;
4634 s
->alglen
= GET_32BIT(s
->pkblob
);
4635 s
->alg
= s
->pkblob
+ 4;
4636 s
->commentlen
= GET_32BIT(s
->p
);
4638 s
->commentp
= (char *)s
->p
;
4639 s
->p
+= s
->commentlen
;
4640 ssh2_pkt_init(ssh
, SSH2_MSG_USERAUTH_REQUEST
);
4641 ssh2_pkt_addstring(ssh
, s
->username
);
4642 ssh2_pkt_addstring(ssh
, "ssh-connection"); /* service requested */
4643 ssh2_pkt_addstring(ssh
, "publickey"); /* method */
4644 ssh2_pkt_addbool(ssh
, FALSE
); /* no signature included */
4645 ssh2_pkt_addstring_start(ssh
);
4646 ssh2_pkt_addstring_data(ssh
, s
->alg
, s
->alglen
);
4647 ssh2_pkt_addstring_start(ssh
);
4648 ssh2_pkt_addstring_data(ssh
, s
->pkblob
, s
->pklen
);
4651 crWaitUntilV(ispkt
);
4652 if (ssh
->pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
4653 logevent("Key refused");
4657 if (flags
& FLAG_VERBOSE
) {
4658 c_write_str(ssh
, "Authenticating with "
4660 c_write(ssh
, s
->commentp
, s
->commentlen
);
4661 c_write_str(ssh
, "\" from agent\r\n");
4665 * Server is willing to accept the key.
4666 * Construct a SIGN_REQUEST.
4668 ssh2_pkt_init(ssh
, SSH2_MSG_USERAUTH_REQUEST
);
4669 ssh2_pkt_addstring(ssh
, s
->username
);
4670 ssh2_pkt_addstring(ssh
, "ssh-connection"); /* service requested */
4671 ssh2_pkt_addstring(ssh
, "publickey"); /* method */
4672 ssh2_pkt_addbool(ssh
, TRUE
);
4673 ssh2_pkt_addstring_start(ssh
);
4674 ssh2_pkt_addstring_data(ssh
, s
->alg
, s
->alglen
);
4675 ssh2_pkt_addstring_start(ssh
);
4676 ssh2_pkt_addstring_data(ssh
, s
->pkblob
, s
->pklen
);
4678 s
->siglen
= ssh
->pktout
.length
- 5 + 4 + 20;
4679 if (ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)
4681 s
->len
= 1; /* message type */
4682 s
->len
+= 4 + s
->pklen
; /* key blob */
4683 s
->len
+= 4 + s
->siglen
; /* data to sign */
4684 s
->len
+= 4; /* flags */
4685 s
->agentreq
= smalloc(4 + s
->len
);
4686 PUT_32BIT(s
->agentreq
, s
->len
);
4687 s
->q
= s
->agentreq
+ 4;
4688 *s
->q
++ = SSH2_AGENTC_SIGN_REQUEST
;
4689 PUT_32BIT(s
->q
, s
->pklen
);
4691 memcpy(s
->q
, s
->pkblob
, s
->pklen
);
4693 PUT_32BIT(s
->q
, s
->siglen
);
4695 /* Now the data to be signed... */
4696 if (!(ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)) {
4697 PUT_32BIT(s
->q
, 20);
4700 memcpy(s
->q
, ssh
->v2_session_id
, 20);
4702 memcpy(s
->q
, ssh
->pktout
.data
+ 5,
4703 ssh
->pktout
.length
- 5);
4704 s
->q
+= ssh
->pktout
.length
- 5;
4705 /* And finally the (zero) flags word. */
4707 agent_query(s
->agentreq
, s
->len
+ 4, &vret
, &s
->retlen
);
4711 if (s
->ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
4712 logevent("Sending Pageant's response");
4713 ssh2_add_sigblob(ssh
, s
->pkblob
, s
->pklen
,
4715 GET_32BIT(s
->ret
+ 5));
4721 ("Pageant failed to answer challenge");
4731 if (!s
->method
&& s
->can_pubkey
&& s
->publickey_blob
4732 && !s
->tried_pubkey_config
) {
4733 unsigned char *pub_blob
;
4734 char *algorithm
, *comment
;
4737 s
->tried_pubkey_config
= TRUE
;
4739 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4740 ssh
->pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
4743 * Try the public key supplied in the configuration.
4745 * First, offer the public blob to see if the server is
4746 * willing to accept it.
4749 (unsigned char *)ssh2_userkey_loadpub(&ssh
->cfg
.keyfile
,
4753 ssh2_pkt_init(ssh
, SSH2_MSG_USERAUTH_REQUEST
);
4754 ssh2_pkt_addstring(ssh
, s
->username
);
4755 ssh2_pkt_addstring(ssh
, "ssh-connection"); /* service requested */
4756 ssh2_pkt_addstring(ssh
, "publickey"); /* method */
4757 ssh2_pkt_addbool(ssh
, FALSE
); /* no signature included */
4758 ssh2_pkt_addstring(ssh
, algorithm
);
4759 ssh2_pkt_addstring_start(ssh
);
4760 ssh2_pkt_addstring_data(ssh
, (char *)pub_blob
,
4763 logevent("Offered public key"); /* FIXME */
4765 crWaitUntilV(ispkt
);
4766 if (ssh
->pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
4768 s
->type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
4769 continue; /* key refused; give up on it */
4772 logevent("Offer of public key accepted");
4774 * Actually attempt a serious authentication using
4777 if (ssh2_userkey_encrypted(&ssh
->cfg
.keyfile
, &comment
)) {
4778 sprintf(s
->pwprompt
,
4779 "Passphrase for key \"%.100s\": ",
4785 c_write_str(ssh
, "Authenticating with public key \"");
4786 c_write_str(ssh
, comment
);
4787 c_write_str(ssh
, "\"\r\n");
4788 s
->method
= AUTH_PUBLICKEY_FILE
;
4792 if (!s
->method
&& s
->can_keyb_inter
&& !s
->tried_keyb_inter
) {
4793 s
->method
= AUTH_KEYBOARD_INTERACTIVE
;
4794 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4795 s
->tried_keyb_inter
= TRUE
;
4797 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4798 ssh
->pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
4800 ssh2_pkt_init(ssh
, SSH2_MSG_USERAUTH_REQUEST
);
4801 ssh2_pkt_addstring(ssh
, s
->username
);
4802 ssh2_pkt_addstring(ssh
, "ssh-connection"); /* service requested */
4803 ssh2_pkt_addstring(ssh
, "keyboard-interactive"); /* method */
4804 ssh2_pkt_addstring(ssh
, ""); /* lang */
4805 ssh2_pkt_addstring(ssh
, "");
4808 crWaitUntilV(ispkt
);
4809 if (ssh
->pktin
.type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
4810 if (ssh
->pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
)
4812 logevent("Keyboard-interactive authentication refused");
4813 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
;
4817 s
->kbd_inter_running
= TRUE
;
4821 if (s
->kbd_inter_running
) {
4822 s
->method
= AUTH_KEYBOARD_INTERACTIVE
;
4823 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4824 s
->tried_keyb_inter
= TRUE
;
4826 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4827 ssh
->pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
4829 if (s
->curr_prompt
== 0) {
4831 * We've got a fresh USERAUTH_INFO_REQUEST.
4832 * Display header data, and start going through
4835 char *name
, *inst
, *lang
;
4836 int name_len
, inst_len
, lang_len
;
4838 ssh2_pkt_getstring(ssh
, &name
, &name_len
);
4839 ssh2_pkt_getstring(ssh
, &inst
, &inst_len
);
4840 ssh2_pkt_getstring(ssh
, &lang
, &lang_len
);
4842 c_write_untrusted(ssh
, name
, name_len
);
4843 c_write_str(ssh
, "\r\n");
4846 c_write_untrusted(ssh
, inst
, inst_len
);
4847 c_write_str(ssh
, "\r\n");
4849 s
->num_prompts
= ssh2_pkt_getuint32(ssh
);
4853 * If there are prompts remaining in the packet,
4854 * display one and get a response.
4856 if (s
->curr_prompt
< s
->num_prompts
) {
4860 ssh2_pkt_getstring(ssh
, &prompt
, &prompt_len
);
4861 if (prompt_len
> 0) {
4862 strncpy(s
->pwprompt
, prompt
, sizeof(s
->pwprompt
));
4863 s
->pwprompt
[prompt_len
< sizeof(s
->pwprompt
) ?
4864 prompt_len
: sizeof(s
->pwprompt
)-1] = '\0';
4867 "<server failed to send prompt>: ");
4869 s
->echo
= ssh2_pkt_getbool(ssh
);
4875 if (!s
->method
&& s
->can_passwd
) {
4876 s
->method
= AUTH_PASSWORD
;
4877 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4878 ssh
->pkt_ctx
|= SSH2_PKTCTX_PASSWORD
;
4879 sprintf(s
->pwprompt
, "%.90s@%.90s's password: ", s
->username
,
4886 if (!ssh_get_line(s
->pwprompt
, s
->password
,
4887 sizeof(s
->password
), TRUE
)) {
4889 * get_line failed to get a password (for
4890 * example because one was supplied on the
4891 * command line which has already failed to
4894 ssh2_pkt_init(ssh
, SSH2_MSG_DISCONNECT
);
4895 ssh2_pkt_adduint32(ssh
,SSH2_DISCONNECT_BY_APPLICATION
);
4896 ssh2_pkt_addstring(ssh
, "No more passwords available"
4898 ssh2_pkt_addstring(ssh
, "en"); /* language tag */
4900 logevent("Unable to authenticate");
4901 connection_fatal(ssh
->frontend
,
4902 "Unable to authenticate");
4903 ssh
->state
= SSH_STATE_CLOSED
;
4907 int ret
; /* need not be saved across crReturn */
4908 c_write_untrusted(ssh
, s
->pwprompt
, strlen(s
->pwprompt
));
4911 setup_userpass_input(ssh
, s
->password
,
4912 sizeof(s
->password
), s
->echo
);
4914 crWaitUntilV(!ispkt
);
4915 ret
= process_userpass_input(ssh
, in
, inlen
);
4919 c_write_str(ssh
, "\r\n");
4923 if (s
->method
== AUTH_PUBLICKEY_FILE
) {
4925 * We have our passphrase. Now try the actual authentication.
4927 struct ssh2_userkey
*key
;
4929 key
= ssh2_load_userkey(&ssh
->cfg
.keyfile
, s
->password
);
4930 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
4931 if (key
== SSH2_WRONG_PASSPHRASE
) {
4932 c_write_str(ssh
, "Wrong passphrase\r\n");
4933 s
->tried_pubkey_config
= FALSE
;
4935 c_write_str(ssh
, "Unable to load private key\r\n");
4936 s
->tried_pubkey_config
= TRUE
;
4938 /* Send a spurious AUTH_NONE to return to the top. */
4939 ssh2_pkt_init(ssh
, SSH2_MSG_USERAUTH_REQUEST
);
4940 ssh2_pkt_addstring(ssh
, s
->username
);
4941 ssh2_pkt_addstring(ssh
, "ssh-connection"); /* service requested */
4942 ssh2_pkt_addstring(ssh
, "none"); /* method */
4944 s
->type
= AUTH_TYPE_NONE
;
4946 unsigned char *pkblob
, *sigblob
, *sigdata
;
4947 int pkblob_len
, sigblob_len
, sigdata_len
;
4951 * We have loaded the private key and the server
4952 * has announced that it's willing to accept it.
4953 * Hallelujah. Generate a signature and send it.
4955 ssh2_pkt_init(ssh
, SSH2_MSG_USERAUTH_REQUEST
);
4956 ssh2_pkt_addstring(ssh
, s
->username
);
4957 ssh2_pkt_addstring(ssh
, "ssh-connection"); /* service requested */
4958 ssh2_pkt_addstring(ssh
, "publickey"); /* method */
4959 ssh2_pkt_addbool(ssh
, TRUE
);
4960 ssh2_pkt_addstring(ssh
, key
->alg
->name
);
4961 pkblob
= key
->alg
->public_blob(key
->data
, &pkblob_len
);
4962 ssh2_pkt_addstring_start(ssh
);
4963 ssh2_pkt_addstring_data(ssh
, (char *)pkblob
, pkblob_len
);
4966 * The data to be signed is:
4970 * followed by everything so far placed in the
4973 sigdata_len
= ssh
->pktout
.length
- 5 + 4 + 20;
4974 if (ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)
4976 sigdata
= smalloc(sigdata_len
);
4978 if (!(ssh
->remote_bugs
& BUG_SSH2_PK_SESSIONID
)) {
4979 PUT_32BIT(sigdata
+p
, 20);
4982 memcpy(sigdata
+p
, ssh
->v2_session_id
, 20); p
+= 20;
4983 memcpy(sigdata
+p
, ssh
->pktout
.data
+ 5,
4984 ssh
->pktout
.length
- 5);
4985 p
+= ssh
->pktout
.length
- 5;
4986 assert(p
== sigdata_len
);
4987 sigblob
= key
->alg
->sign(key
->data
, (char *)sigdata
,
4988 sigdata_len
, &sigblob_len
);
4989 ssh2_add_sigblob(ssh
, pkblob
, pkblob_len
,
4990 sigblob
, sigblob_len
);
4996 s
->type
= AUTH_TYPE_PUBLICKEY
;
4998 } else if (s
->method
== AUTH_PASSWORD
) {
5000 * We send the password packet lumped tightly together with
5001 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
5002 * string long enough to make the total length of the two
5003 * packets constant. This should ensure that a passive
5004 * listener doing traffic analyis can't work out the length
5007 * For this to work, we need an assumption about the
5008 * maximum length of the password packet. I think 256 is
5009 * pretty conservative. Anyone using a password longer than
5010 * that probably doesn't have much to worry about from
5011 * people who find out how long their password is!
5013 ssh2_pkt_init(ssh
, SSH2_MSG_USERAUTH_REQUEST
);
5014 ssh2_pkt_addstring(ssh
, s
->username
);
5015 ssh2_pkt_addstring(ssh
, "ssh-connection"); /* service requested */
5016 ssh2_pkt_addstring(ssh
, "password");
5017 ssh2_pkt_addbool(ssh
, FALSE
);
5018 ssh2_pkt_addstring(ssh
, s
->password
);
5019 memset(s
->password
, 0, sizeof(s
->password
));
5020 ssh2_pkt_defer(ssh
);
5022 * We'll include a string that's an exact multiple of the
5023 * cipher block size. If the cipher is NULL for some
5024 * reason, we don't do this trick at all because we gain
5027 if (ssh
->cscipher
) {
5030 stringlen
= (256 - ssh
->deferred_len
);
5031 stringlen
+= ssh
->cscipher
->blksize
- 1;
5032 stringlen
-= (stringlen
% ssh
->cscipher
->blksize
);
5035 * Temporarily disable actual compression,
5036 * so we can guarantee to get this string
5037 * exactly the length we want it. The
5038 * compression-disabling routine should
5039 * return an integer indicating how many
5040 * bytes we should adjust our string length
5044 ssh
->cscomp
->disable_compression(ssh
->cs_comp_ctx
);
5046 ssh2_pkt_init(ssh
, SSH2_MSG_IGNORE
);
5047 ssh2_pkt_addstring_start(ssh
);
5048 for (i
= 0; i
< stringlen
; i
++) {
5049 char c
= (char) random_byte();
5050 ssh2_pkt_addstring_data(ssh
, &c
, 1);
5052 ssh2_pkt_defer(ssh
);
5054 ssh_pkt_defersend(ssh
);
5055 logevent("Sent password");
5056 s
->type
= AUTH_TYPE_PASSWORD
;
5057 } else if (s
->method
== AUTH_KEYBOARD_INTERACTIVE
) {
5058 if (s
->curr_prompt
== 0) {
5059 ssh2_pkt_init(ssh
, SSH2_MSG_USERAUTH_INFO_RESPONSE
);
5060 ssh2_pkt_adduint32(ssh
, s
->num_prompts
);
5062 if (s
->need_pw
) { /* only add pw if we just got one! */
5063 ssh2_pkt_addstring(ssh
, s
->password
);
5064 memset(s
->password
, 0, sizeof(s
->password
));
5067 if (s
->curr_prompt
>= s
->num_prompts
) {
5071 * If there are prompts remaining, we set
5072 * `gotit' so that we won't attempt to get
5073 * another packet. Then we go back round the
5074 * loop and will end up retrieving another
5075 * prompt out of the existing packet. Funky or
5080 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
5082 c_write_str(ssh
, "No supported authentication methods"
5083 " left to try!\r\n");
5084 logevent("No supported authentications offered."
5086 ssh2_pkt_init(ssh
, SSH2_MSG_DISCONNECT
);
5087 ssh2_pkt_adduint32(ssh
, SSH2_DISCONNECT_BY_APPLICATION
);
5088 ssh2_pkt_addstring(ssh
, "No supported authentication"
5089 " methods available");
5090 ssh2_pkt_addstring(ssh
, "en"); /* language tag */
5092 ssh
->state
= SSH_STATE_CLOSED
;
5096 } while (!s
->we_are_in
);
5099 * Now we're authenticated for the connection protocol. The
5100 * connection protocol will automatically have started at this
5101 * point; there's no need to send SERVICE_REQUEST.
5105 * So now create a channel with a session in it.
5107 ssh
->channels
= newtree234(ssh_channelcmp
);
5108 ssh
->mainchan
= smalloc(sizeof(struct ssh_channel
));
5109 ssh
->mainchan
->ssh
= ssh
;
5110 ssh
->mainchan
->localid
= alloc_channel_id(ssh
);
5111 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_OPEN
);
5112 ssh2_pkt_addstring(ssh
, "session");
5113 ssh2_pkt_adduint32(ssh
, ssh
->mainchan
->localid
);
5114 ssh
->mainchan
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
5115 ssh2_pkt_adduint32(ssh
, ssh
->mainchan
->v
.v2
.locwindow
);/* our window size */
5116 ssh2_pkt_adduint32(ssh
, 0x4000UL
); /* our max pkt size */
5118 crWaitUntilV(ispkt
);
5119 if (ssh
->pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
5120 bombout((ssh
,"Server refused to open a session"));
5122 /* FIXME: error data comes back in FAILURE packet */
5124 if (ssh2_pkt_getuint32(ssh
) != ssh
->mainchan
->localid
) {
5125 bombout((ssh
,"Server's channel confirmation cited wrong channel"));
5128 ssh
->mainchan
->remoteid
= ssh2_pkt_getuint32(ssh
);
5129 ssh
->mainchan
->type
= CHAN_MAINSESSION
;
5130 ssh
->mainchan
->closes
= 0;
5131 ssh
->mainchan
->v
.v2
.remwindow
= ssh2_pkt_getuint32(ssh
);
5132 ssh
->mainchan
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32(ssh
);
5133 bufchain_init(&ssh
->mainchan
->v
.v2
.outbuffer
);
5134 add234(ssh
->channels
, ssh
->mainchan
);
5135 logevent("Opened channel for session");
5138 * Potentially enable X11 forwarding.
5140 if (ssh
->cfg
.x11_forward
) {
5141 char proto
[20], data
[64];
5142 logevent("Requesting X11 forwarding");
5143 ssh
->x11auth
= x11_invent_auth(proto
, sizeof(proto
),
5144 data
, sizeof(data
), ssh
->cfg
.x11_auth
);
5145 x11_get_real_auth(ssh
->x11auth
, ssh
->cfg
.x11_display
);
5146 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_REQUEST
);
5147 ssh2_pkt_adduint32(ssh
, ssh
->mainchan
->remoteid
);
5148 ssh2_pkt_addstring(ssh
, "x11-req");
5149 ssh2_pkt_addbool(ssh
, 1); /* want reply */
5150 ssh2_pkt_addbool(ssh
, 0); /* many connections */
5151 ssh2_pkt_addstring(ssh
, proto
);
5152 ssh2_pkt_addstring(ssh
, data
);
5153 ssh2_pkt_adduint32(ssh
, x11_get_screen_number(ssh
->cfg
.x11_display
));
5157 crWaitUntilV(ispkt
);
5158 if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
5159 unsigned i
= ssh2_pkt_getuint32(ssh
);
5160 struct ssh_channel
*c
;
5161 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5163 continue; /* nonexistent channel */
5164 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32(ssh
);
5166 } while (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
5168 if (ssh
->pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
5169 if (ssh
->pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
5170 bombout((ssh
,"Unexpected response to X11 forwarding request:"
5171 " packet type %d", ssh
->pktin
.type
));
5174 logevent("X11 forwarding refused");
5176 logevent("X11 forwarding enabled");
5177 ssh
->X11_fwd_enabled
= TRUE
;
5182 * Enable port forwardings.
5187 int sport
,dport
,sserv
,dserv
;
5188 char sports
[256], dports
[256], saddr
[256], host
[256];
5190 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh2
);
5191 /* Add port forwardings. */
5192 ssh
->portfwd_strptr
= ssh
->cfg
.portfwd
;
5193 while (*ssh
->portfwd_strptr
) {
5194 type
= *ssh
->portfwd_strptr
++;
5197 while (*ssh
->portfwd_strptr
&& *ssh
->portfwd_strptr
!= '\t') {
5198 if (*ssh
->portfwd_strptr
== ':') {
5200 * We've seen a colon in the middle of the
5201 * source port number. This means that
5202 * everything we've seen until now is the
5203 * source _address_, so we'll move it into
5204 * saddr and start sports from the beginning
5207 ssh
->portfwd_strptr
++;
5209 strcpy(saddr
, sports
);
5212 if (n
< 255) sports
[n
++] = *ssh
->portfwd_strptr
++;
5215 if (*ssh
->portfwd_strptr
== '\t')
5216 ssh
->portfwd_strptr
++;
5218 while (*ssh
->portfwd_strptr
&& *ssh
->portfwd_strptr
!= ':') {
5219 if (n
< 255) host
[n
++] = *ssh
->portfwd_strptr
++;
5222 if (*ssh
->portfwd_strptr
== ':')
5223 ssh
->portfwd_strptr
++;
5225 while (*ssh
->portfwd_strptr
) {
5226 if (n
< 255) dports
[n
++] = *ssh
->portfwd_strptr
++;
5229 ssh
->portfwd_strptr
++;
5230 dport
= atoi(dports
);
5234 dport
= net_service_lookup(dports
);
5236 logeventf(ssh
, "Service lookup failed for destination"
5237 " port \"%s\"", dports
);
5240 sport
= atoi(sports
);
5244 sport
= net_service_lookup(sports
);
5246 logeventf(ssh
, "Service lookup failed for source"
5247 " port \"%s\"", sports
);
5250 if (sport
&& dport
) {
5252 pfd_addforward(host
, dport
, *saddr ? saddr
: NULL
,
5253 sport
, ssh
, &ssh
->cfg
);
5254 logeventf(ssh
, "Local port %.*s%.*s%.*s%.*s%d%.*s"
5255 " forwarding to %s:%.*s%.*s%d%.*s",
5256 (int)(*saddr?
strlen(saddr
):0), *saddr?saddr
:NULL
,
5257 (int)(*saddr?
1:0), ":",
5258 (int)(sserv ?
strlen(sports
) : 0), sports
,
5259 sserv
, "(", sport
, sserv
, ")",
5261 (int)(dserv ?
strlen(dports
) : 0), dports
,
5262 dserv
, "(", dport
, dserv
, ")");
5264 struct ssh_rportfwd
*pf
;
5265 pf
= smalloc(sizeof(*pf
));
5266 strcpy(pf
->dhost
, host
);
5269 if (add234(ssh
->rportfwds
, pf
) != pf
) {
5270 logeventf(ssh
, "Duplicate remote port forwarding"
5271 " to %s:%d", host
, dport
);
5274 logeventf(ssh
, "Requesting remote port "
5275 "%.*s%.*s%.*s%.*s%d%.*s"
5276 " forward to %s:%.*s%.*s%d%.*s",
5277 (int)(*saddr?
strlen(saddr
):0),
5279 (int)(*saddr?
1:0), ":",
5280 (int)(sserv ?
strlen(sports
) : 0), sports
,
5281 sserv
, "(", sport
, sserv
, ")",
5283 (int)(dserv ?
strlen(dports
) : 0), dports
,
5284 dserv
, "(", dport
, dserv
, ")");
5285 ssh2_pkt_init(ssh
, SSH2_MSG_GLOBAL_REQUEST
);
5286 ssh2_pkt_addstring(ssh
, "tcpip-forward");
5287 ssh2_pkt_addbool(ssh
, 1);/* want reply */
5289 ssh2_pkt_addstring(ssh
, saddr
);
5290 if (ssh
->cfg
.rport_acceptall
)
5291 ssh2_pkt_addstring(ssh
, "0.0.0.0");
5293 ssh2_pkt_addstring(ssh
, "127.0.0.1");
5294 ssh2_pkt_adduint32(ssh
, sport
);
5298 crWaitUntilV(ispkt
);
5299 if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
5300 unsigned i
= ssh2_pkt_getuint32(ssh
);
5301 struct ssh_channel
*c
;
5302 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5304 continue;/* nonexistent channel */
5305 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32(ssh
);
5307 } while (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
5309 if (ssh
->pktin
.type
!= SSH2_MSG_REQUEST_SUCCESS
) {
5310 if (ssh
->pktin
.type
!= SSH2_MSG_REQUEST_FAILURE
) {
5311 bombout((ssh
,"Unexpected response to port "
5312 "forwarding request: packet type %d",
5316 logevent("Server refused this port forwarding");
5318 logevent("Remote port forwarding enabled");
5327 * Potentially enable agent forwarding.
5329 if (ssh
->cfg
.agentfwd
&& agent_exists()) {
5330 logevent("Requesting OpenSSH-style agent forwarding");
5331 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_REQUEST
);
5332 ssh2_pkt_adduint32(ssh
, ssh
->mainchan
->remoteid
);
5333 ssh2_pkt_addstring(ssh
, "auth-agent-req@openssh.com");
5334 ssh2_pkt_addbool(ssh
, 1); /* want reply */
5338 crWaitUntilV(ispkt
);
5339 if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
5340 unsigned i
= ssh2_pkt_getuint32(ssh
);
5341 struct ssh_channel
*c
;
5342 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5344 continue; /* nonexistent channel */
5345 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32(ssh
);
5347 } while (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
5349 if (ssh
->pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
5350 if (ssh
->pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
5351 bombout((ssh
,"Unexpected response to agent forwarding request:"
5352 " packet type %d", ssh
->pktin
.type
));
5355 logevent("Agent forwarding refused");
5357 logevent("Agent forwarding enabled");
5358 ssh
->agentfwd_enabled
= TRUE
;
5363 * Now allocate a pty for the session.
5365 if (!ssh
->cfg
.nopty
) {
5366 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_REQUEST
);
5367 ssh2_pkt_adduint32(ssh
, ssh
->mainchan
->remoteid
); /* recipient channel */
5368 ssh2_pkt_addstring(ssh
, "pty-req");
5369 ssh2_pkt_addbool(ssh
, 1); /* want reply */
5370 ssh2_pkt_addstring(ssh
, ssh
->cfg
.termtype
);
5371 ssh2_pkt_adduint32(ssh
, ssh
->term_width
);
5372 ssh2_pkt_adduint32(ssh
, ssh
->term_height
);
5373 ssh2_pkt_adduint32(ssh
, 0); /* pixel width */
5374 ssh2_pkt_adduint32(ssh
, 0); /* pixel height */
5375 ssh2_pkt_addstring_start(ssh
);
5376 ssh2_pkt_addstring_data(ssh
, "\0", 1); /* TTY_OP_END, no special options */
5378 ssh
->state
= SSH_STATE_INTERMED
;
5381 crWaitUntilV(ispkt
);
5382 if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
5383 unsigned i
= ssh2_pkt_getuint32(ssh
);
5384 struct ssh_channel
*c
;
5385 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5387 continue; /* nonexistent channel */
5388 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32(ssh
);
5390 } while (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
5392 if (ssh
->pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
5393 if (ssh
->pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
5394 bombout((ssh
,"Unexpected response to pty request:"
5395 " packet type %d", ssh
->pktin
.type
));
5398 c_write_str(ssh
, "Server refused to allocate pty\r\n");
5399 ssh
->editing
= ssh
->echoing
= 1;
5401 logevent("Allocated pty");
5404 ssh
->editing
= ssh
->echoing
= 1;
5408 * Start a shell or a remote command. We may have to attempt
5409 * this twice if the config data has provided a second choice
5416 if (ssh
->fallback_cmd
) {
5417 subsys
= ssh
->cfg
.ssh_subsys2
;
5418 cmd
= ssh
->cfg
.remote_cmd_ptr2
;
5420 subsys
= ssh
->cfg
.ssh_subsys
;
5421 cmd
= ssh
->cfg
.remote_cmd_ptr
;
5424 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_REQUEST
);
5425 ssh2_pkt_adduint32(ssh
, ssh
->mainchan
->remoteid
); /* recipient channel */
5427 ssh2_pkt_addstring(ssh
, "subsystem");
5428 ssh2_pkt_addbool(ssh
, 1); /* want reply */
5429 ssh2_pkt_addstring(ssh
, cmd
);
5431 ssh2_pkt_addstring(ssh
, "exec");
5432 ssh2_pkt_addbool(ssh
, 1); /* want reply */
5433 ssh2_pkt_addstring(ssh
, cmd
);
5435 ssh2_pkt_addstring(ssh
, "shell");
5436 ssh2_pkt_addbool(ssh
, 1); /* want reply */
5440 crWaitUntilV(ispkt
);
5441 if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
5442 unsigned i
= ssh2_pkt_getuint32(ssh
);
5443 struct ssh_channel
*c
;
5444 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5446 continue; /* nonexistent channel */
5447 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32(ssh
);
5449 } while (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
5450 if (ssh
->pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
5451 if (ssh
->pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
5452 bombout((ssh
,"Unexpected response to shell/command request:"
5453 " packet type %d", ssh
->pktin
.type
));
5457 * We failed to start the command. If this is the
5458 * fallback command, we really are finished; if it's
5459 * not, and if the fallback command exists, try falling
5460 * back to it before complaining.
5462 if (!ssh
->fallback_cmd
&& ssh
->cfg
.remote_cmd_ptr2
!= NULL
) {
5463 logevent("Primary command failed; attempting fallback");
5464 ssh
->fallback_cmd
= TRUE
;
5467 bombout((ssh
,"Server refused to start a shell/command"));
5470 logevent("Started a shell/command");
5475 ssh
->state
= SSH_STATE_SESSION
;
5476 if (ssh
->size_needed
)
5477 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
5478 if (ssh
->eof_needed
)
5479 ssh_special(ssh
, TS_EOF
);
5485 ldisc_send(ssh
->ldisc
, NULL
, 0, 0);/* cause ldisc to notice changes */
5489 s
->try_send
= FALSE
;
5491 if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
5492 ssh
->pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
5495 unsigned i
= ssh2_pkt_getuint32(ssh
);
5496 struct ssh_channel
*c
;
5497 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5499 continue; /* nonexistent channel */
5500 if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
5501 ssh2_pkt_getuint32(ssh
) != SSH2_EXTENDED_DATA_STDERR
)
5502 continue; /* extended but not stderr */
5503 ssh2_pkt_getstring(ssh
, &data
, &length
);
5506 c
->v
.v2
.locwindow
-= length
;
5508 case CHAN_MAINSESSION
:
5510 from_backend(ssh
->frontend
, ssh
->pktin
.type
==
5511 SSH2_MSG_CHANNEL_EXTENDED_DATA
,
5515 bufsize
= x11_send(c
->u
.x11
.s
, data
, length
);
5518 bufsize
= pfd_send(c
->u
.pfd
.s
, data
, length
);
5521 while (length
> 0) {
5522 if (c
->u
.a
.lensofar
< 4) {
5523 int l
= min(4 - c
->u
.a
.lensofar
, length
);
5524 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
5528 c
->u
.a
.lensofar
+= l
;
5530 if (c
->u
.a
.lensofar
== 4) {
5532 4 + GET_32BIT(c
->u
.a
.msglen
);
5533 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
5534 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
5536 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
5538 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
5540 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
5544 c
->u
.a
.lensofar
+= l
;
5546 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
5547 void *reply
, *sentreply
;
5549 agent_query(c
->u
.a
.message
,
5550 c
->u
.a
.totallen
, &reply
,
5555 /* Fake SSH_AGENT_FAILURE. */
5556 sentreply
= "\0\0\0\1\5";
5559 ssh2_add_channel_data(c
, sentreply
, replylen
);
5563 sfree(c
->u
.a
.message
);
5564 c
->u
.a
.lensofar
= 0;
5571 * If we are not buffering too much data,
5572 * enlarge the window again at the remote side.
5574 if (bufsize
< OUR_V2_WINSIZE
)
5575 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
5577 } else if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
5578 unsigned i
= ssh2_pkt_getuint32(ssh
);
5579 struct ssh_channel
*c
;
5581 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5583 continue; /* nonexistent channel */
5585 if (c
->type
== CHAN_X11
) {
5587 * Remote EOF on an X11 channel means we should
5588 * wrap up and close the channel ourselves.
5590 x11_close(c
->u
.x11
.s
);
5592 } else if (c
->type
== CHAN_AGENT
) {
5594 } else if (c
->type
== CHAN_SOCKDATA
) {
5595 pfd_close(c
->u
.pfd
.s
);
5598 } else if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
5599 unsigned i
= ssh2_pkt_getuint32(ssh
);
5600 struct ssh_channel
*c
;
5602 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5603 if (!c
|| ((int)c
->remoteid
) == -1) {
5604 bombout((ssh
,"Received CHANNEL_CLOSE for %s channel %d\n",
5605 c ?
"half-open" : "nonexistent", i
));
5607 /* Do pre-close processing on the channel. */
5609 case CHAN_MAINSESSION
:
5610 break; /* nothing to see here, move along */
5612 if (c
->u
.x11
.s
!= NULL
)
5613 x11_close(c
->u
.x11
.s
);
5620 if (c
->u
.pfd
.s
!= NULL
)
5621 pfd_close(c
->u
.pfd
.s
);
5625 if (c
->closes
== 0) {
5626 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_CLOSE
);
5627 ssh2_pkt_adduint32(ssh
, c
->remoteid
);
5630 del234(ssh
->channels
, c
);
5631 bufchain_clear(&c
->v
.v2
.outbuffer
);
5635 * See if that was the last channel left open.
5637 if (count234(ssh
->channels
) == 0) {
5640 * We used to send SSH_MSG_DISCONNECT here,
5641 * because I'd believed that _every_ conforming
5642 * SSH2 connection had to end with a disconnect
5643 * being sent by at least one side; apparently
5644 * I was wrong and it's perfectly OK to
5645 * unceremoniously slam the connection shut
5646 * when you're done, and indeed OpenSSH feels
5647 * this is more polite than sending a
5648 * DISCONNECT. So now we don't.
5650 logevent("All channels closed. Disconnecting");
5651 ssh2_pkt_init(ssh
, SSH2_MSG_DISCONNECT
);
5652 ssh2_pkt_adduint32(ssh
, SSH2_DISCONNECT_BY_APPLICATION
);
5653 ssh2_pkt_addstring(ssh
, "All open channels closed");
5654 ssh2_pkt_addstring(ssh
, "en"); /* language tag */
5657 ssh
->state
= SSH_STATE_CLOSED
;
5660 continue; /* remote sends close; ignore (FIXME) */
5661 } else if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
5662 unsigned i
= ssh2_pkt_getuint32(ssh
);
5663 struct ssh_channel
*c
;
5664 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5665 if (!c
|| c
->closes
)
5666 continue; /* nonexistent or closing channel */
5667 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32(ssh
);
5669 } else if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
5670 unsigned i
= ssh2_pkt_getuint32(ssh
);
5671 struct ssh_channel
*c
;
5672 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5674 continue; /* nonexistent channel */
5675 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
5676 continue; /* dunno why they're confirming this */
5677 c
->remoteid
= ssh2_pkt_getuint32(ssh
);
5678 c
->type
= CHAN_SOCKDATA
;
5679 c
->v
.v2
.remwindow
= ssh2_pkt_getuint32(ssh
);
5680 c
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32(ssh
);
5682 pfd_confirm(c
->u
.pfd
.s
);
5685 * We have a pending close on this channel,
5686 * which we decided on before the server acked
5687 * the channel open. So now we know the
5688 * remoteid, we can close it again.
5690 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_CLOSE
);
5691 ssh2_pkt_adduint32(ssh
, c
->remoteid
);
5694 } else if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_OPEN_FAILURE
) {
5695 unsigned i
= ssh2_pkt_getuint32(ssh
);
5696 struct ssh_channel
*c
;
5697 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5699 continue; /* nonexistent channel */
5700 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
5701 continue; /* dunno why they're failing this */
5703 logevent("Forwarded connection refused by server");
5705 pfd_close(c
->u
.pfd
.s
);
5707 del234(ssh
->channels
, c
);
5709 } else if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
5712 int typelen
, want_reply
;
5713 struct ssh_channel
*c
;
5715 localid
= ssh2_pkt_getuint32(ssh
);
5716 ssh2_pkt_getstring(ssh
, &type
, &typelen
);
5717 want_reply
= ssh2_pkt_getbool(ssh
);
5720 * First, check that the channel exists. Otherwise,
5721 * we can instantly disconnect with a rude message.
5723 c
= find234(ssh
->channels
, &localid
, ssh_channelfind
);
5726 sprintf(buf
, "Received channel request for nonexistent"
5727 " channel %d", localid
);
5729 ssh2_pkt_init(ssh
, SSH2_MSG_DISCONNECT
);
5730 ssh2_pkt_adduint32(ssh
, SSH2_DISCONNECT_BY_APPLICATION
);
5731 ssh2_pkt_addstring(ssh
, buf
);
5732 ssh2_pkt_addstring(ssh
, "en"); /* language tag */
5734 connection_fatal("%s", buf
);
5735 ssh
->state
= SSH_STATE_CLOSED
;
5740 * Having got the channel number, we now look at
5741 * the request type string to see if it's something
5744 if (typelen
== 11 && !memcmp(type
, "exit-status", 11) &&
5745 c
== ssh
->mainchan
) {
5746 /* We recognise "exit-status" on the primary channel. */
5748 ssh
->exitcode
= ssh2_pkt_getuint32(ssh
);
5749 sprintf(buf
, "Server sent command exit status %d",
5753 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_SUCCESS
);
5754 ssh2_pkt_adduint32(ssh
, c
->remoteid
);
5759 * This is a channel request we don't know
5760 * about, so we now either ignore the request
5761 * or respond with CHANNEL_FAILURE, depending
5765 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_FAILURE
);
5766 ssh2_pkt_adduint32(ssh
, c
->remoteid
);
5770 } else if (ssh
->pktin
.type
== SSH2_MSG_GLOBAL_REQUEST
) {
5772 int typelen
, want_reply
;
5774 ssh2_pkt_getstring(ssh
, &type
, &typelen
);
5775 want_reply
= ssh2_pkt_getbool(ssh
);
5778 * We currently don't support any global requests
5779 * at all, so we either ignore the request or
5780 * respond with REQUEST_FAILURE, depending on
5784 ssh2_pkt_init(ssh
, SSH2_MSG_REQUEST_FAILURE
);
5787 } else if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
5794 struct ssh_channel
*c
;
5795 unsigned remid
, winsize
, pktsize
;
5796 ssh2_pkt_getstring(ssh
, &type
, &typelen
);
5797 c
= smalloc(sizeof(struct ssh_channel
));
5800 remid
= ssh2_pkt_getuint32(ssh
);
5801 winsize
= ssh2_pkt_getuint32(ssh
);
5802 pktsize
= ssh2_pkt_getuint32(ssh
);
5803 ssh2_pkt_getstring(ssh
, &peeraddr
, &peeraddrlen
);
5804 port
= ssh2_pkt_getuint32(ssh
);
5806 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
5807 char *addrstr
= smalloc(peeraddrlen
+1);
5808 memcpy(addrstr
, peeraddr
, peeraddrlen
);
5809 peeraddr
[peeraddrlen
] = '\0';
5811 if (!ssh
->X11_fwd_enabled
)
5812 error
= "X11 forwarding is not enabled";
5813 else if (x11_init(&c
->u
.x11
.s
, ssh
->cfg
.x11_display
, c
,
5814 ssh
->x11auth
, addrstr
, port
,
5815 &ssh
->cfg
) != NULL
) {
5816 error
= "Unable to open an X11 connection";
5822 } else if (typelen
== 15 &&
5823 !memcmp(type
, "forwarded-tcpip", 15)) {
5824 struct ssh_rportfwd pf
, *realpf
;
5827 ssh2_pkt_getstring(ssh
, &dummy
, &dummylen
);/* skip address */
5828 pf
.sport
= ssh2_pkt_getuint32(ssh
);
5829 realpf
= find234(ssh
->rportfwds
, &pf
, NULL
);
5830 if (realpf
== NULL
) {
5831 error
= "Remote port is not recognised";
5833 char *e
= pfd_newconnect(&c
->u
.pfd
.s
, realpf
->dhost
,
5834 realpf
->dport
, c
, &ssh
->cfg
);
5835 logeventf(ssh
, "Received remote port open request"
5836 " for %s:%d", realpf
->dhost
, realpf
->dport
);
5838 logeventf(ssh
, "Port open failed: %s", e
);
5839 error
= "Port open failed";
5841 logevent("Forwarded port opened successfully");
5842 c
->type
= CHAN_SOCKDATA
;
5845 } else if (typelen
== 22 &&
5846 !memcmp(type
, "auth-agent@openssh.com", 3)) {
5847 if (!ssh
->agentfwd_enabled
)
5848 error
= "Agent forwarding is not enabled";
5850 c
->type
= CHAN_AGENT
; /* identify channel type */
5851 c
->u
.a
.lensofar
= 0;
5854 error
= "Unsupported channel type requested";
5857 c
->remoteid
= remid
;
5859 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_OPEN_FAILURE
);
5860 ssh2_pkt_adduint32(ssh
, c
->remoteid
);
5861 ssh2_pkt_adduint32(ssh
, SSH2_OPEN_CONNECT_FAILED
);
5862 ssh2_pkt_addstring(ssh
, error
);
5863 ssh2_pkt_addstring(ssh
, "en"); /* language tag */
5867 c
->localid
= alloc_channel_id(ssh
);
5869 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
5870 c
->v
.v2
.remwindow
= winsize
;
5871 c
->v
.v2
.remmaxpkt
= pktsize
;
5872 bufchain_init(&c
->v
.v2
.outbuffer
);
5873 add234(ssh
->channels
, c
);
5874 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
5875 ssh2_pkt_adduint32(ssh
, c
->remoteid
);
5876 ssh2_pkt_adduint32(ssh
, c
->localid
);
5877 ssh2_pkt_adduint32(ssh
, c
->v
.v2
.locwindow
);
5878 ssh2_pkt_adduint32(ssh
, 0x4000UL
); /* our max pkt size */
5882 bombout((ssh
,"Strange packet received: type %d", ssh
->pktin
.type
));
5887 * We have spare data. Add it to the channel buffer.
5889 ssh2_add_channel_data(ssh
->mainchan
, (char *)in
, inlen
);
5894 struct ssh_channel
*c
;
5896 * Try to send data on all channels if we can.
5898 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++) {
5901 continue; /* don't send on closing channels */
5902 bufsize
= ssh2_try_send(c
);
5905 case CHAN_MAINSESSION
:
5906 /* stdin need not receive an unthrottle
5907 * notification since it will be polled */
5910 x11_unthrottle(c
->u
.x11
.s
);
5913 /* agent sockets are request/response and need no
5914 * buffer management */
5917 pfd_unthrottle(c
->u
.pfd
.s
);
5929 * Handle the top-level SSH2 protocol.
5931 static void ssh2_protocol(Ssh ssh
, unsigned char *in
, int inlen
, int ispkt
)
5933 if (do_ssh2_transport(ssh
, in
, inlen
, ispkt
) == 0)
5935 do_ssh2_authconn(ssh
, in
, inlen
, ispkt
);
5939 * Called to set up the connection.
5941 * Returns an error message, or NULL on success.
5943 static char *ssh_init(void *frontend_handle
, void **backend_handle
,
5945 char *host
, int port
, char **realhost
, int nodelay
)
5950 ssh
= smalloc(sizeof(*ssh
));
5951 ssh
->cfg
= *cfg
; /* STRUCTURE COPY */
5954 ssh
->v1_cipher_ctx
= NULL
;
5955 ssh
->crcda_ctx
= NULL
;
5956 ssh
->cscipher
= NULL
;
5957 ssh
->cs_cipher_ctx
= NULL
;
5958 ssh
->sccipher
= NULL
;
5959 ssh
->sc_cipher_ctx
= NULL
;
5961 ssh
->cs_mac_ctx
= NULL
;
5963 ssh
->sc_mac_ctx
= NULL
;
5965 ssh
->cs_comp_ctx
= NULL
;
5967 ssh
->sc_comp_ctx
= NULL
;
5969 ssh
->kex_ctx
= NULL
;
5970 ssh
->hostkey
= NULL
;
5972 ssh
->state
= SSH_STATE_PREPACKET
;
5973 ssh
->size_needed
= FALSE
;
5974 ssh
->eof_needed
= FALSE
;
5978 static const struct Packet empty
= { 0, 0, NULL
, NULL
, 0 };
5979 ssh
->pktin
= ssh
->pktout
= empty
;
5981 ssh
->deferred_send_data
= NULL
;
5982 ssh
->deferred_len
= 0;
5983 ssh
->deferred_size
= 0;
5984 ssh
->fallback_cmd
= 0;
5986 ssh
->x11auth
= NULL
;
5987 ssh
->v1_compressing
= FALSE
;
5988 ssh
->v2_outgoing_sequence
= 0;
5989 ssh
->ssh1_rdpkt_crstate
= 0;
5990 ssh
->ssh2_rdpkt_crstate
= 0;
5991 ssh
->do_ssh_init_crstate
= 0;
5992 ssh
->ssh_gotdata_crstate
= 0;
5993 ssh
->ssh1_protocol_crstate
= 0;
5994 ssh
->do_ssh1_login_crstate
= 0;
5995 ssh
->do_ssh2_transport_crstate
= 0;
5996 ssh
->do_ssh2_authconn_crstate
= 0;
5997 ssh
->do_ssh_init_state
= NULL
;
5998 ssh
->do_ssh1_login_state
= NULL
;
5999 ssh
->do_ssh2_transport_state
= NULL
;
6000 ssh
->do_ssh2_authconn_state
= NULL
;
6001 ssh
->mainchan
= NULL
;
6002 ssh
->throttled_all
= 0;
6003 ssh
->v1_stdout_throttling
= 0;
6005 *backend_handle
= ssh
;
6008 if (crypto_startup() == 0)
6009 return "Microsoft high encryption pack not installed!";
6012 ssh
->frontend
= frontend_handle
;
6013 ssh
->term_width
= ssh
->cfg
.width
;
6014 ssh
->term_height
= ssh
->cfg
.height
;
6016 ssh
->channels
= NULL
;
6017 ssh
->rportfwds
= NULL
;
6022 ssh
->v1_throttle_count
= 0;
6023 ssh
->overall_bufsize
= 0;
6024 ssh
->fallback_cmd
= 0;
6026 ssh
->protocol
= NULL
;
6028 p
= connect_to_host(ssh
, host
, port
, realhost
, nodelay
);
6035 static void ssh_free(void *handle
)
6037 Ssh ssh
= (Ssh
) handle
;
6038 struct ssh_channel
*c
;
6039 struct ssh_rportfwd
*pf
;
6041 if (ssh
->v1_cipher_ctx
)
6042 ssh
->cipher
->free_context(ssh
->v1_cipher_ctx
);
6043 if (ssh
->cs_cipher_ctx
)
6044 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
6045 if (ssh
->sc_cipher_ctx
)
6046 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
6047 if (ssh
->cs_mac_ctx
)
6048 ssh
->csmac
->free_context(ssh
->cs_mac_ctx
);
6049 if (ssh
->sc_mac_ctx
)
6050 ssh
->scmac
->free_context(ssh
->sc_mac_ctx
);
6051 if (ssh
->cs_comp_ctx
)
6052 ssh
->cscomp
->compress_cleanup(ssh
->cs_comp_ctx
);
6053 if (ssh
->sc_comp_ctx
)
6054 ssh
->sccomp
->compress_cleanup(ssh
->sc_comp_ctx
);
6056 dh_cleanup(ssh
->kex_ctx
);
6057 sfree(ssh
->savedhost
);
6059 if (ssh
->channels
) {
6060 while ((c
= delpos234(ssh
->channels
, 0)) != NULL
) {
6063 if (c
->u
.x11
.s
!= NULL
)
6064 x11_close(c
->u
.x11
.s
);
6067 if (c
->u
.pfd
.s
!= NULL
)
6068 pfd_close(c
->u
.pfd
.s
);
6073 freetree234(ssh
->channels
);
6076 if (ssh
->rportfwds
) {
6077 while ((pf
= delpos234(ssh
->rportfwds
, 0)) != NULL
)
6079 freetree234(ssh
->rportfwds
);
6081 sfree(ssh
->deferred_send_data
);
6083 x11_free_auth(ssh
->x11auth
);
6084 sfree(ssh
->do_ssh_init_state
);
6085 sfree(ssh
->do_ssh1_login_state
);
6086 sfree(ssh
->do_ssh2_transport_state
);
6087 sfree(ssh
->do_ssh2_authconn_state
);
6095 * Reconfigure the SSH backend.
6097 * Currently, this function does nothing very useful. In future,
6098 * however, we could do some handy things with it. For example, we
6099 * could make the port forwarding configurer active in the Change
6100 * Settings box, and this routine could close down existing
6101 * forwardings and open up new ones in response to changes.
6103 static void ssh_reconfig(void *handle
, Config
*cfg
)
6105 Ssh ssh
= (Ssh
) handle
;
6106 ssh
->cfg
= *cfg
; /* STRUCTURE COPY */
6110 * Called to send data down the Telnet connection.
6112 static int ssh_send(void *handle
, char *buf
, int len
)
6114 Ssh ssh
= (Ssh
) handle
;
6116 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
6119 ssh
->protocol(ssh
, (unsigned char *)buf
, len
, 0);
6121 return ssh_sendbuffer(ssh
);
6125 * Called to query the current amount of buffered stdin data.
6127 static int ssh_sendbuffer(void *handle
)
6129 Ssh ssh
= (Ssh
) handle
;
6132 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
6136 * If the SSH socket itself has backed up, add the total backup
6137 * size on that to any individual buffer on the stdin channel.
6140 if (ssh
->throttled_all
)
6141 override_value
= ssh
->overall_bufsize
;
6143 if (ssh
->version
== 1) {
6144 return override_value
;
6145 } else if (ssh
->version
== 2) {
6146 if (!ssh
->mainchan
|| ssh
->mainchan
->closes
> 0)
6147 return override_value
;
6149 return (override_value
+
6150 bufchain_size(&ssh
->mainchan
->v
.v2
.outbuffer
));
6157 * Called to set the size of the window from SSH's POV.
6159 static void ssh_size(void *handle
, int width
, int height
)
6161 Ssh ssh
= (Ssh
) handle
;
6163 ssh
->term_width
= width
;
6164 ssh
->term_height
= height
;
6166 switch (ssh
->state
) {
6167 case SSH_STATE_BEFORE_SIZE
:
6168 case SSH_STATE_PREPACKET
:
6169 case SSH_STATE_CLOSED
:
6170 break; /* do nothing */
6171 case SSH_STATE_INTERMED
:
6172 ssh
->size_needed
= TRUE
; /* buffer for later */
6174 case SSH_STATE_SESSION
:
6175 if (!ssh
->cfg
.nopty
) {
6176 if (ssh
->version
== 1) {
6177 send_packet(ssh
, SSH1_CMSG_WINDOW_SIZE
,
6178 PKT_INT
, ssh
->term_height
,
6179 PKT_INT
, ssh
->term_width
,
6180 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
6182 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_REQUEST
);
6183 ssh2_pkt_adduint32(ssh
, ssh
->mainchan
->remoteid
);
6184 ssh2_pkt_addstring(ssh
, "window-change");
6185 ssh2_pkt_addbool(ssh
, 0);
6186 ssh2_pkt_adduint32(ssh
, ssh
->term_width
);
6187 ssh2_pkt_adduint32(ssh
, ssh
->term_height
);
6188 ssh2_pkt_adduint32(ssh
, 0);
6189 ssh2_pkt_adduint32(ssh
, 0);
6198 * Send Telnet special codes. TS_EOF is useful for `plink', so you
6199 * can send an EOF and collect resulting output (e.g. `plink
6202 static void ssh_special(void *handle
, Telnet_Special code
)
6204 Ssh ssh
= (Ssh
) handle
;
6206 if (code
== TS_EOF
) {
6207 if (ssh
->state
!= SSH_STATE_SESSION
) {
6209 * Buffer the EOF in case we are pre-SESSION, so we can
6210 * send it as soon as we reach SESSION.
6213 ssh
->eof_needed
= TRUE
;
6216 if (ssh
->version
== 1) {
6217 send_packet(ssh
, SSH1_CMSG_EOF
, PKT_END
);
6219 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_EOF
);
6220 ssh2_pkt_adduint32(ssh
, ssh
->mainchan
->remoteid
);
6223 logevent("Sent EOF message");
6224 } else if (code
== TS_PING
) {
6225 if (ssh
->state
== SSH_STATE_CLOSED
6226 || ssh
->state
== SSH_STATE_PREPACKET
) return;
6227 if (ssh
->version
== 1) {
6228 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
6229 send_packet(ssh
, SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
6231 ssh2_pkt_init(ssh
, SSH2_MSG_IGNORE
);
6232 ssh2_pkt_addstring_start(ssh
);
6240 void *new_sock_channel(void *handle
, Socket s
)
6242 Ssh ssh
= (Ssh
) handle
;
6243 struct ssh_channel
*c
;
6244 c
= smalloc(sizeof(struct ssh_channel
));
6248 c
->remoteid
= -1; /* to be set when open confirmed */
6249 c
->localid
= alloc_channel_id(ssh
);
6251 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
6253 bufchain_init(&c
->v
.v2
.outbuffer
);
6254 add234(ssh
->channels
, c
);
6260 * This is called when stdout/stderr (the entity to which
6261 * from_backend sends data) manages to clear some backlog.
6263 static void ssh_unthrottle(void *handle
, int bufsize
)
6265 Ssh ssh
= (Ssh
) handle
;
6266 if (ssh
->version
== 1) {
6267 if (ssh
->v1_stdout_throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
6268 ssh
->v1_stdout_throttling
= 0;
6269 ssh1_throttle(ssh
, -1);
6272 if (ssh
->mainchan
&& ssh
->mainchan
->closes
== 0)
6273 ssh2_set_window(ssh
->mainchan
, OUR_V2_WINSIZE
- bufsize
);
6277 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
6279 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
6282 logeventf(ssh
, "Opening forwarded connection to %s:%d", hostname
, port
);
6284 if (ssh
->version
== 1) {
6285 send_packet(ssh
, SSH1_MSG_PORT_OPEN
,
6286 PKT_INT
, c
->localid
,
6289 //PKT_STR, <org:orgport>,
6292 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_OPEN
);
6293 ssh2_pkt_addstring(ssh
, "direct-tcpip");
6294 ssh2_pkt_adduint32(ssh
, c
->localid
);
6295 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
6296 ssh2_pkt_adduint32(ssh
, c
->v
.v2
.locwindow
);/* our window size */
6297 ssh2_pkt_adduint32(ssh
, 0x4000UL
); /* our max pkt size */
6298 ssh2_pkt_addstring(ssh
, hostname
);
6299 ssh2_pkt_adduint32(ssh
, port
);
6301 * We make up values for the originator data; partly it's
6302 * too much hassle to keep track, and partly I'm not
6303 * convinced the server should be told details like that
6304 * about my local network configuration.
6306 ssh2_pkt_addstring(ssh
, "client-side-connection");
6307 ssh2_pkt_adduint32(ssh
, 0);
6313 static Socket
ssh_socket(void *handle
)
6315 Ssh ssh
= (Ssh
) handle
;
6319 static int ssh_sendok(void *handle
)
6321 Ssh ssh
= (Ssh
) handle
;
6322 return ssh
->send_ok
;
6325 static int ssh_ldisc(void *handle
, int option
)
6327 Ssh ssh
= (Ssh
) handle
;
6328 if (option
== LD_ECHO
)
6329 return ssh
->echoing
;
6330 if (option
== LD_EDIT
)
6331 return ssh
->editing
;
6335 static void ssh_provide_ldisc(void *handle
, void *ldisc
)
6337 Ssh ssh
= (Ssh
) handle
;
6341 static void ssh_provide_logctx(void *handle
, void *logctx
)
6343 Ssh ssh
= (Ssh
) handle
;
6344 ssh
->logctx
= logctx
;
6347 static int ssh_return_exitcode(void *handle
)
6349 Ssh ssh
= (Ssh
) handle
;
6350 return ssh
->exitcode
;
6354 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
6355 * that fails. This variable is the means by which scp.c can reach
6356 * into the SSH code and find out which one it got.
6358 extern int ssh_fallback_cmd(void *handle
)
6360 Ssh ssh
= (Ssh
) handle
;
6361 return ssh
->fallback_cmd
;
6364 Backend ssh_backend
= {
6373 ssh_return_exitcode
,