18 #define logevent(s) { logevent(s); \
19 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
20 { fprintf(stderr, "%s\n", s); fflush(stderr); } }
22 /* logevent, only printf-formatted. */
23 void logeventf(char *fmt
, ...)
29 vsprintf(stuff
, fmt
, ap
);
34 #define bombout(msg) ( ssh->state = SSH_STATE_CLOSED, \
35 (ssh->s ? sk_close(ssh->s), ssh->s = NULL : 0), \
36 logeventf msg, connection_fatal msg )
38 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
39 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
40 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
41 #define SSH1_CMSG_USER 4 /* 0x4 */
42 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
43 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
44 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
45 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
46 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
47 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
48 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
49 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
50 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
51 #define SSH1_SMSG_FAILURE 15 /* 0xf */
52 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
53 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
54 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
55 #define SSH1_CMSG_EOF 19 /* 0x13 */
56 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
57 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
58 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
59 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
60 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
61 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
62 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
63 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
64 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
65 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
66 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
67 #define SSH1_MSG_IGNORE 32 /* 0x20 */
68 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
69 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
70 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
71 #define SSH1_MSG_DEBUG 36 /* 0x24 */
72 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
73 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
74 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
75 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
76 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
77 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
78 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
80 #define SSH1_AUTH_TIS 5 /* 0x5 */
81 #define SSH1_AUTH_CCARD 16 /* 0x10 */
83 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
84 /* Mask for protoflags we will echo back to server if seen */
85 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
87 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
88 #define SSH2_MSG_IGNORE 2 /* 0x2 */
89 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
90 #define SSH2_MSG_DEBUG 4 /* 0x4 */
91 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
92 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
93 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
94 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
95 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
96 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
97 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
98 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
99 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
100 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
101 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
102 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
103 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
104 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
105 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
106 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
107 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
108 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
109 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
110 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
111 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
112 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
113 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
114 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
115 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
116 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
117 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
118 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
119 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
120 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
121 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
122 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
125 * Packet type contexts, so that ssh2_pkt_type can correctly decode
126 * the ambiguous type numbers back into the correct type strings.
128 #define SSH2_PKTCTX_DHGROUP1 0x0001
129 #define SSH2_PKTCTX_DHGEX 0x0002
130 #define SSH2_PKTCTX_PUBLICKEY 0x0010
131 #define SSH2_PKTCTX_PASSWORD 0x0020
132 #define SSH2_PKTCTX_KBDINTER 0x0040
133 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
135 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
136 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
137 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
138 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
139 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
140 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
141 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
142 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
143 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
144 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
145 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
146 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
147 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
148 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
149 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
151 static const char *const ssh2_disconnect_reasons
[] = {
153 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
154 "SSH_DISCONNECT_PROTOCOL_ERROR",
155 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
156 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
157 "SSH_DISCONNECT_MAC_ERROR",
158 "SSH_DISCONNECT_COMPRESSION_ERROR",
159 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
160 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
161 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
162 "SSH_DISCONNECT_CONNECTION_LOST",
163 "SSH_DISCONNECT_BY_APPLICATION",
164 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
165 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
166 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
167 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
170 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
171 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
172 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
173 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
175 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
178 * Various remote-bug flags.
180 #define BUG_CHOKES_ON_SSH1_IGNORE 1
181 #define BUG_SSH2_HMAC 2
182 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
183 #define BUG_CHOKES_ON_RSA 8
184 #define BUG_SSH2_RSA_PADDING 16
185 #define BUG_SSH2_DERIVEKEY 32
186 #define BUG_SSH2_DH_GEX 64
188 #define translate(x) if (type == x) return #x
189 #define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
190 char *ssh1_pkt_type(int type
)
192 translate(SSH1_MSG_DISCONNECT
);
193 translate(SSH1_SMSG_PUBLIC_KEY
);
194 translate(SSH1_CMSG_SESSION_KEY
);
195 translate(SSH1_CMSG_USER
);
196 translate(SSH1_CMSG_AUTH_RSA
);
197 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE
);
198 translate(SSH1_CMSG_AUTH_RSA_RESPONSE
);
199 translate(SSH1_CMSG_AUTH_PASSWORD
);
200 translate(SSH1_CMSG_REQUEST_PTY
);
201 translate(SSH1_CMSG_WINDOW_SIZE
);
202 translate(SSH1_CMSG_EXEC_SHELL
);
203 translate(SSH1_CMSG_EXEC_CMD
);
204 translate(SSH1_SMSG_SUCCESS
);
205 translate(SSH1_SMSG_FAILURE
);
206 translate(SSH1_CMSG_STDIN_DATA
);
207 translate(SSH1_SMSG_STDOUT_DATA
);
208 translate(SSH1_SMSG_STDERR_DATA
);
209 translate(SSH1_CMSG_EOF
);
210 translate(SSH1_SMSG_EXIT_STATUS
);
211 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
);
212 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE
);
213 translate(SSH1_MSG_CHANNEL_DATA
);
214 translate(SSH1_MSG_CHANNEL_CLOSE
);
215 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
);
216 translate(SSH1_SMSG_X11_OPEN
);
217 translate(SSH1_CMSG_PORT_FORWARD_REQUEST
);
218 translate(SSH1_MSG_PORT_OPEN
);
219 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING
);
220 translate(SSH1_SMSG_AGENT_OPEN
);
221 translate(SSH1_MSG_IGNORE
);
222 translate(SSH1_CMSG_EXIT_CONFIRMATION
);
223 translate(SSH1_CMSG_X11_REQUEST_FORWARDING
);
224 translate(SSH1_CMSG_AUTH_RHOSTS_RSA
);
225 translate(SSH1_MSG_DEBUG
);
226 translate(SSH1_CMSG_REQUEST_COMPRESSION
);
227 translate(SSH1_CMSG_AUTH_TIS
);
228 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE
);
229 translate(SSH1_CMSG_AUTH_TIS_RESPONSE
);
230 translate(SSH1_CMSG_AUTH_CCARD
);
231 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE
);
232 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE
);
235 char *ssh2_pkt_type(int pkt_ctx
, int type
)
237 translate(SSH2_MSG_DISCONNECT
);
238 translate(SSH2_MSG_IGNORE
);
239 translate(SSH2_MSG_UNIMPLEMENTED
);
240 translate(SSH2_MSG_DEBUG
);
241 translate(SSH2_MSG_SERVICE_REQUEST
);
242 translate(SSH2_MSG_SERVICE_ACCEPT
);
243 translate(SSH2_MSG_KEXINIT
);
244 translate(SSH2_MSG_NEWKEYS
);
245 translatec(SSH2_MSG_KEXDH_INIT
, SSH2_PKTCTX_DHGROUP1
);
246 translatec(SSH2_MSG_KEXDH_REPLY
, SSH2_PKTCTX_DHGROUP1
);
247 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST
, SSH2_PKTCTX_DHGEX
);
248 translatec(SSH2_MSG_KEX_DH_GEX_GROUP
, SSH2_PKTCTX_DHGEX
);
249 translatec(SSH2_MSG_KEX_DH_GEX_INIT
, SSH2_PKTCTX_DHGEX
);
250 translatec(SSH2_MSG_KEX_DH_GEX_REPLY
, SSH2_PKTCTX_DHGEX
);
251 translate(SSH2_MSG_USERAUTH_REQUEST
);
252 translate(SSH2_MSG_USERAUTH_FAILURE
);
253 translate(SSH2_MSG_USERAUTH_SUCCESS
);
254 translate(SSH2_MSG_USERAUTH_BANNER
);
255 translatec(SSH2_MSG_USERAUTH_PK_OK
, SSH2_PKTCTX_PUBLICKEY
);
256 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ
, SSH2_PKTCTX_PASSWORD
);
257 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST
, SSH2_PKTCTX_KBDINTER
);
258 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE
, SSH2_PKTCTX_KBDINTER
);
259 translate(SSH2_MSG_GLOBAL_REQUEST
);
260 translate(SSH2_MSG_REQUEST_SUCCESS
);
261 translate(SSH2_MSG_REQUEST_FAILURE
);
262 translate(SSH2_MSG_CHANNEL_OPEN
);
263 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
264 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
265 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
266 translate(SSH2_MSG_CHANNEL_DATA
);
267 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA
);
268 translate(SSH2_MSG_CHANNEL_EOF
);
269 translate(SSH2_MSG_CHANNEL_CLOSE
);
270 translate(SSH2_MSG_CHANNEL_REQUEST
);
271 translate(SSH2_MSG_CHANNEL_SUCCESS
);
272 translate(SSH2_MSG_CHANNEL_FAILURE
);
278 #define GET_32BIT(cp) \
279 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
280 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
281 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
282 ((unsigned long)(unsigned char)(cp)[3]))
284 #define PUT_32BIT(cp, value) { \
285 (cp)[0] = (unsigned char)((value) >> 24); \
286 (cp)[1] = (unsigned char)((value) >> 16); \
287 (cp)[2] = (unsigned char)((value) >> 8); \
288 (cp)[3] = (unsigned char)(value); }
290 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
292 /* Coroutine mechanics for the sillier bits of the code */
293 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
296 if (!ssh->t) ssh->t = smalloc(sizeof(struct t)); \
298 #define crFinish(z) } *crLine = 0; return (z); }
299 #define crFinishV } *crLine = 0; return; }
300 #define crReturn(z) \
302 *crLine =__LINE__; return (z); case __LINE__:;\
306 *crLine=__LINE__; return; case __LINE__:;\
308 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
309 #define crStopV do{ *crLine = 0; return; }while(0)
310 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
311 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
313 typedef struct ssh_tag
*Ssh
;
315 extern char *x11_init(Socket
*, char *, void *);
316 extern void x11_close(Socket
);
317 extern int x11_send(Socket
, char *, int);
318 extern void x11_invent_auth(char *, int, char *, int);
319 extern void x11_unthrottle(Socket s
);
320 extern void x11_override_throttle(Socket s
, int enable
);
322 extern char *pfd_newconnect(Socket
* s
, char *hostname
, int port
, void *c
);
323 extern char *pfd_addforward(char *desthost
, int destport
, int port
);
324 extern void pfd_close(Socket s
);
325 extern int pfd_send(Socket s
, char *data
, int len
);
326 extern void pfd_confirm(Socket s
);
327 extern void pfd_unthrottle(Socket s
);
328 extern void pfd_override_throttle(Socket s
, int enable
);
330 static void ssh2_pkt_init(Ssh
, int pkt_type
);
331 static void ssh2_pkt_addbool(Ssh
, unsigned char value
);
332 static void ssh2_pkt_adduint32(Ssh
, unsigned long value
);
333 static void ssh2_pkt_addstring_start(Ssh
);
334 static void ssh2_pkt_addstring_str(Ssh
, char *data
);
335 static void ssh2_pkt_addstring_data(Ssh
, char *data
, int len
);
336 static void ssh2_pkt_addstring(Ssh
, char *data
);
337 static char *ssh2_mpint_fmt(Bignum b
, int *len
);
338 static void ssh2_pkt_addmp(Ssh
, Bignum b
);
339 static int ssh2_pkt_construct(Ssh
);
340 static void ssh2_pkt_send(Ssh
);
343 * Buffer management constants. There are several of these for
344 * various different purposes:
346 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
347 * on a local data stream before we throttle the whole SSH
348 * connection (in SSH1 only). Throttling the whole connection is
349 * pretty drastic so we set this high in the hope it won't
352 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
353 * on the SSH connection itself before we defensively throttle
354 * _all_ local data streams. This is pretty drastic too (though
355 * thankfully unlikely in SSH2 since the window mechanism should
356 * ensure that the server never has any need to throttle its end
357 * of the connection), so we set this high as well.
359 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
363 #define SSH1_BUFFER_LIMIT 32768
364 #define SSH_MAX_BACKLOG 32768
365 #define OUR_V2_WINSIZE 16384
367 const static struct ssh_kex
*kex_algs
[] = {
368 &ssh_diffiehellman_gex
,
372 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
374 static void nullmac_key(unsigned char *key
)
377 static void nullmac_generate(unsigned char *blk
, int len
,
381 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
)
385 const static struct ssh_mac ssh_mac_none
= {
386 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
388 const static struct ssh_mac
*macs
[] = {
389 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
391 const static struct ssh_mac
*buggymacs
[] = {
392 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
395 static void ssh_comp_none_init(void)
398 static int ssh_comp_none_block(unsigned char *block
, int len
,
399 unsigned char **outblock
, int *outlen
)
403 static int ssh_comp_none_disable(void)
407 const static struct ssh_compress ssh_comp_none
= {
409 ssh_comp_none_init
, ssh_comp_none_block
,
410 ssh_comp_none_init
, ssh_comp_none_block
,
411 ssh_comp_none_disable
413 extern const struct ssh_compress ssh_zlib
;
414 const static struct ssh_compress
*compressions
[] = {
415 &ssh_zlib
, &ssh_comp_none
418 enum { /* channel types */
423 CHAN_SOCKDATA_DORMANT
/* one the remote hasn't confirmed */
427 * 2-3-4 tree storing channels.
430 Ssh ssh
; /* pointer back to main context */
431 unsigned remoteid
, localid
;
434 * In SSH1, this value contains four bits:
436 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
437 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
438 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
439 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
441 * A channel is completely finished with when all four bits are set.
445 struct ssh1_data_channel
{
448 struct ssh2_data_channel
{
450 unsigned remwindow
, remmaxpkt
;
455 struct ssh_agent_channel
{
456 unsigned char *message
;
457 unsigned char msglen
[4];
458 int lensofar
, totallen
;
460 struct ssh_x11_channel
{
463 struct ssh_pfd_channel
{
470 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
471 * 2 use this structure in different ways, reflecting SSH 2's
472 * altogether saner approach to port forwarding.
474 * In SSH 1, you arrange a remote forwarding by sending the server
475 * the remote port number, and the local destination host:port.
476 * When a connection comes in, the server sends you back that
477 * host:port pair, and you connect to it. This is a ready-made
478 * security hole if you're not on the ball: a malicious server
479 * could send you back _any_ host:port pair, so if you trustingly
480 * connect to the address it gives you then you've just opened the
481 * entire inside of your corporate network just by connecting
482 * through it to a dodgy SSH server. Hence, we must store a list of
483 * host:port pairs we _are_ trying to forward to, and reject a
484 * connection request from the server if it's not in the list.
486 * In SSH 2, each side of the connection minds its own business and
487 * doesn't send unnecessary information to the other. You arrange a
488 * remote forwarding by sending the server just the remote port
489 * number. When a connection comes in, the server tells you which
490 * of its ports was connected to; and _you_ have to remember what
491 * local host:port pair went with that port number.
493 * Hence: in SSH 1 this structure stores host:port pairs we intend
494 * to allow connections to, and is indexed by those host:port
495 * pairs. In SSH 2 it stores a mapping from source port to
496 * destination host:port pair, and is indexed by source port.
498 struct ssh_rportfwd
{
499 unsigned sport
, dport
;
512 static void ssh1_protocol(Ssh ssh
, unsigned char *in
, int inlen
, int ispkt
);
513 static void ssh2_protocol(Ssh ssh
, unsigned char *in
, int inlen
, int ispkt
);
514 static void ssh_size(void *handle
, int width
, int height
);
515 static void ssh_special(void *handle
, Telnet_Special
);
516 static int ssh2_try_send(struct ssh_channel
*c
);
517 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
);
518 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
);
519 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
);
520 static int ssh_sendbuffer(void *handle
);
522 struct rdpkt1_state_tag
{
523 long len
, pad
, biglen
, to_read
;
524 unsigned long realcrc
, gotcrc
;
530 struct rdpkt2_state_tag
{
531 long len
, pad
, payload
, packetlen
, maclen
;
534 unsigned long incoming_sequence
;
538 const struct plug_function_table
*fn
;
539 /* the above field _must_ be first in the structure */
541 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
;
554 const struct ssh2_cipher
*cscipher
, *sccipher
;
555 void *cs_cipher_ctx
, *sc_cipher_ctx
;
556 const struct ssh_mac
*csmac
, *scmac
;
557 const struct ssh_compress
*cscomp
, *sccomp
;
558 const struct ssh_kex
*kex
;
559 const struct ssh_signkey
*hostkey
;
560 unsigned char v2_session_id
[20];
565 int echoing
, editing
;
569 int term_width
, term_height
;
571 tree234
*channels
; /* indexed by local id */
572 struct ssh_channel
*mainchan
; /* primary session channel */
579 SSH_STATE_BEFORE_SIZE
,
585 int size_needed
, eof_needed
;
588 struct Packet pktout
;
589 unsigned char *deferred_send_data
;
590 int deferred_len
, deferred_size
;
593 * Gross hack: pscp will try to start SFTP but fall back to
594 * scp1 if that fails. This variable is the means by which
595 * scp.c can reach into the SSH code and find out which one it
601 * Used for username and password input.
603 char *userpass_input_buffer
;
604 int userpass_input_buflen
;
605 int userpass_input_bufpos
;
606 int userpass_input_echo
;
608 char *portfwd_strptr
;
612 int v1_throttle_count
;
615 int v1_stdout_throttling
;
616 int v2_outgoing_sequence
;
618 int ssh1_rdpkt_crstate
;
619 int ssh2_rdpkt_crstate
;
620 int do_ssh_init_crstate
;
621 int ssh_gotdata_crstate
;
622 int ssh1_protocol_crstate
;
623 int do_ssh1_login_crstate
;
624 int do_ssh2_transport_crstate
;
625 int do_ssh2_authconn_crstate
;
627 void *do_ssh_init_state
;
628 void *do_ssh1_login_state
;
629 void *do_ssh2_transport_state
;
630 void *do_ssh2_authconn_state
;
632 struct rdpkt1_state_tag rdpkt1_state
;
633 struct rdpkt2_state_tag rdpkt2_state
;
635 void (*protocol
) (Ssh ssh
, unsigned char *in
, int inlen
, int ispkt
);
636 int (*s_rdpkt
) (Ssh ssh
, unsigned char **data
, int *datalen
);
639 static int ssh_channelcmp(void *av
, void *bv
)
641 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
642 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
643 if (a
->localid
< b
->localid
)
645 if (a
->localid
> b
->localid
)
649 static int ssh_channelfind(void *av
, void *bv
)
651 unsigned *a
= (unsigned *) av
;
652 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
660 static int ssh_rportcmp_ssh1(void *av
, void *bv
)
662 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
663 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
665 if ( (i
= strcmp(a
->dhost
, b
->dhost
)) != 0)
666 return i
< 0 ?
-1 : +1;
667 if (a
->dport
> b
->dport
)
669 if (a
->dport
< b
->dport
)
674 static int ssh_rportcmp_ssh2(void *av
, void *bv
)
676 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
677 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
679 if (a
->sport
> b
->sport
)
681 if (a
->sport
< b
->sport
)
686 static int alloc_channel_id(Ssh ssh
)
688 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
689 unsigned low
, high
, mid
;
691 struct ssh_channel
*c
;
694 * First-fit allocation of channel numbers: always pick the
695 * lowest unused one. To do this, binary-search using the
696 * counted B-tree to find the largest channel ID which is in a
697 * contiguous sequence from the beginning. (Precisely
698 * everything in that sequence must have ID equal to its tree
699 * index plus CHANNEL_NUMBER_OFFSET.)
701 tsize
= count234(ssh
->channels
);
705 while (high
- low
> 1) {
706 mid
= (high
+ low
) / 2;
707 c
= index234(ssh
->channels
, mid
);
708 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
709 low
= mid
; /* this one is fine */
711 high
= mid
; /* this one is past it */
714 * Now low points to either -1, or the tree index of the
715 * largest ID in the initial sequence.
718 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
719 assert(NULL
== find234(ssh
->channels
, &i
, ssh_channelfind
));
721 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
724 static void c_write(Ssh ssh
, char *buf
, int len
)
726 if ((flags
& FLAG_STDERR
)) {
728 for (i
= 0; i
< len
; i
++)
730 fputc(buf
[i
], stderr
);
733 from_backend(ssh
->frontend
, 1, buf
, len
);
736 static void c_write_untrusted(Ssh ssh
, char *buf
, int len
)
739 for (i
= 0; i
< len
; i
++) {
741 c_write(ssh
, "\r\n", 2);
742 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
743 c_write(ssh
, buf
+ i
, 1);
747 static void c_write_str(Ssh ssh
, char *buf
)
749 c_write(ssh
, buf
, strlen(buf
));
753 * Collect incoming data in the incoming packet buffer.
754 * Decipher and verify the packet when it is completely read.
755 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
756 * Update the *data and *datalen variables.
757 * Return the additional nr of bytes needed, or 0 when
758 * a complete packet is available.
760 static int ssh1_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
762 struct rdpkt1_state_tag
*st
= &ssh
->rdpkt1_state
;
764 crBegin(ssh
->ssh1_rdpkt_crstate
);
769 ssh
->pktin
.length
= 0;
771 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
772 while ((*datalen
) == 0)
774 st
->len
= (st
->len
<< 8) + **data
;
775 (*data
)++, (*datalen
)--;
778 st
->pad
= 8 - (st
->len
% 8);
779 st
->biglen
= st
->len
+ st
->pad
;
780 ssh
->pktin
.length
= st
->len
- 5;
782 if (ssh
->pktin
.maxlen
< st
->biglen
) {
783 ssh
->pktin
.maxlen
= st
->biglen
;
784 ssh
->pktin
.data
= srealloc(ssh
->pktin
.data
, st
->biglen
+ APIEXTRA
);
787 st
->to_read
= st
->biglen
;
788 st
->p
= ssh
->pktin
.data
;
789 while (st
->to_read
> 0) {
790 st
->chunk
= st
->to_read
;
791 while ((*datalen
) == 0)
792 crReturn(st
->to_read
);
793 if (st
->chunk
> (*datalen
))
794 st
->chunk
= (*datalen
);
795 memcpy(st
->p
, *data
, st
->chunk
);
797 *datalen
-= st
->chunk
;
799 st
->to_read
-= st
->chunk
;
802 if (ssh
->cipher
&& detect_attack(ssh
->pktin
.data
, st
->biglen
, NULL
)) {
803 bombout(("Network attack (CRC compensation) detected!"));
808 ssh
->cipher
->decrypt(ssh
->v1_cipher_ctx
, ssh
->pktin
.data
, st
->biglen
);
810 st
->realcrc
= crc32(ssh
->pktin
.data
, st
->biglen
- 4);
811 st
->gotcrc
= GET_32BIT(ssh
->pktin
.data
+ st
->biglen
- 4);
812 if (st
->gotcrc
!= st
->realcrc
) {
813 bombout(("Incorrect CRC received on packet"));
817 ssh
->pktin
.body
= ssh
->pktin
.data
+ st
->pad
+ 1;
819 if (ssh
->v1_compressing
) {
820 unsigned char *decompblk
;
822 zlib_decompress_block(ssh
->pktin
.body
- 1, ssh
->pktin
.length
+ 1,
823 &decompblk
, &decomplen
);
825 if (ssh
->pktin
.maxlen
< st
->pad
+ decomplen
) {
826 ssh
->pktin
.maxlen
= st
->pad
+ decomplen
;
827 ssh
->pktin
.data
= srealloc(ssh
->pktin
.data
,
828 ssh
->pktin
.maxlen
+ APIEXTRA
);
829 ssh
->pktin
.body
= ssh
->pktin
.data
+ st
->pad
+ 1;
832 memcpy(ssh
->pktin
.body
- 1, decompblk
, decomplen
);
834 ssh
->pktin
.length
= decomplen
- 1;
837 ssh
->pktin
.type
= ssh
->pktin
.body
[-1];
839 log_packet(PKT_INCOMING
, ssh
->pktin
.type
, ssh1_pkt_type(ssh
->pktin
.type
),
840 ssh
->pktin
.body
, ssh
->pktin
.length
);
842 if (ssh
->pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
843 ssh
->pktin
.type
== SSH1_SMSG_STDERR_DATA
||
844 ssh
->pktin
.type
== SSH1_MSG_DEBUG
||
845 ssh
->pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
846 ssh
->pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
847 long stringlen
= GET_32BIT(ssh
->pktin
.body
);
848 if (stringlen
+ 4 != ssh
->pktin
.length
) {
849 bombout(("Received data packet with bogus string length"));
854 if (ssh
->pktin
.type
== SSH1_MSG_DEBUG
) {
855 /* log debug message */
857 int stringlen
= GET_32BIT(ssh
->pktin
.body
);
858 strcpy(buf
, "Remote debug message: ");
861 memcpy(buf
+ 8, ssh
->pktin
.body
+ 4, stringlen
);
862 buf
[8 + stringlen
] = '\0';
865 } else if (ssh
->pktin
.type
== SSH1_MSG_IGNORE
) {
870 if (ssh
->pktin
.type
== SSH1_MSG_DISCONNECT
) {
871 /* log reason code in disconnect message */
873 unsigned msglen
= GET_32BIT(ssh
->pktin
.body
);
875 strcpy(buf
, "Remote sent disconnect: ");
876 nowlen
= strlen(buf
);
877 if (msglen
> sizeof(buf
) - nowlen
- 1)
878 msglen
= sizeof(buf
) - nowlen
- 1;
879 memcpy(buf
+ nowlen
, ssh
->pktin
.body
+ 4, msglen
);
880 buf
[nowlen
+ msglen
] = '\0';
881 /* logevent(buf); (this is now done within the bombout macro) */
882 bombout(("Server sent disconnect message:\n\"%s\"", buf
+nowlen
));
889 static int ssh2_rdpkt(Ssh ssh
, unsigned char **data
, int *datalen
)
891 struct rdpkt2_state_tag
*st
= &ssh
->rdpkt2_state
;
893 crBegin(ssh
->ssh2_rdpkt_crstate
);
897 ssh
->pktin
.length
= 0;
899 st
->cipherblk
= ssh
->sccipher
->blksize
;
902 if (st
->cipherblk
< 8)
905 if (ssh
->pktin
.maxlen
< st
->cipherblk
) {
906 ssh
->pktin
.maxlen
= st
->cipherblk
;
907 ssh
->pktin
.data
= srealloc(ssh
->pktin
.data
, st
->cipherblk
+ APIEXTRA
);
911 * Acquire and decrypt the first block of the packet. This will
912 * contain the length and padding details.
914 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
915 while ((*datalen
) == 0)
916 crReturn(st
->cipherblk
- st
->i
);
917 ssh
->pktin
.data
[st
->i
] = *(*data
)++;
922 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
923 ssh
->pktin
.data
, st
->cipherblk
);
926 * Now get the length and padding figures.
928 st
->len
= GET_32BIT(ssh
->pktin
.data
);
929 st
->pad
= ssh
->pktin
.data
[4];
932 * _Completely_ silly lengths should be stomped on before they
933 * do us any more damage.
935 if (st
->len
< 0 || st
->pad
< 0 || st
->len
+ st
->pad
< 0) {
936 bombout(("Incoming packet was garbled on decryption"));
941 * This enables us to deduce the payload length.
943 st
->payload
= st
->len
- st
->pad
- 1;
945 ssh
->pktin
.length
= st
->payload
+ 5;
948 * So now we can work out the total packet length.
950 st
->packetlen
= st
->len
+ 4;
951 st
->maclen
= ssh
->scmac ? ssh
->scmac
->len
: 0;
954 * Adjust memory allocation if packet is too big.
956 if (ssh
->pktin
.maxlen
< st
->packetlen
+ st
->maclen
) {
957 ssh
->pktin
.maxlen
= st
->packetlen
+ st
->maclen
;
958 ssh
->pktin
.data
= srealloc(ssh
->pktin
.data
,
959 ssh
->pktin
.maxlen
+ APIEXTRA
);
963 * Read and decrypt the remainder of the packet.
965 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
967 while ((*datalen
) == 0)
968 crReturn(st
->packetlen
+ st
->maclen
- st
->i
);
969 ssh
->pktin
.data
[st
->i
] = *(*data
)++;
972 /* Decrypt everything _except_ the MAC. */
974 ssh
->sccipher
->decrypt(ssh
->sc_cipher_ctx
,
975 ssh
->pktin
.data
+ st
->cipherblk
,
976 st
->packetlen
- st
->cipherblk
);
982 && !ssh
->scmac
->verify(ssh
->pktin
.data
, st
->len
+ 4,
983 st
->incoming_sequence
)) {
984 bombout(("Incorrect MAC received on packet"));
987 st
->incoming_sequence
++; /* whether or not we MACed */
990 * Decompress packet payload.
993 unsigned char *newpayload
;
996 ssh
->sccomp
->decompress(ssh
->pktin
.data
+ 5, ssh
->pktin
.length
- 5,
997 &newpayload
, &newlen
)) {
998 if (ssh
->pktin
.maxlen
< newlen
+ 5) {
999 ssh
->pktin
.maxlen
= newlen
+ 5;
1000 ssh
->pktin
.data
= srealloc(ssh
->pktin
.data
,
1001 ssh
->pktin
.maxlen
+ APIEXTRA
);
1003 ssh
->pktin
.length
= 5 + newlen
;
1004 memcpy(ssh
->pktin
.data
+ 5, newpayload
, newlen
);
1009 ssh
->pktin
.savedpos
= 6;
1010 ssh
->pktin
.type
= ssh
->pktin
.data
[5];
1012 log_packet(PKT_INCOMING
, ssh
->pktin
.type
,
1013 ssh2_pkt_type(ssh
->pkt_ctx
, ssh
->pktin
.type
),
1014 ssh
->pktin
.data
+6, ssh
->pktin
.length
-6);
1016 switch (ssh
->pktin
.type
) {
1018 * These packets we must handle instantly.
1020 case SSH2_MSG_DISCONNECT
:
1022 /* log reason code in disconnect message */
1024 int reason
= GET_32BIT(ssh
->pktin
.data
+ 6);
1025 unsigned msglen
= GET_32BIT(ssh
->pktin
.data
+ 10);
1027 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
1028 sprintf(buf
, "Received disconnect message (%s)",
1029 ssh2_disconnect_reasons
[reason
]);
1031 sprintf(buf
, "Received disconnect message (unknown type %d)",
1035 strcpy(buf
, "Disconnection message text: ");
1036 nowlen
= strlen(buf
);
1037 if (msglen
> sizeof(buf
) - nowlen
- 1)
1038 msglen
= sizeof(buf
) - nowlen
- 1;
1039 memcpy(buf
+ nowlen
, ssh
->pktin
.data
+ 14, msglen
);
1040 buf
[nowlen
+ msglen
] = '\0';
1042 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
1044 (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) ?
1045 ssh2_disconnect_reasons
[reason
] : "unknown",
1050 case SSH2_MSG_IGNORE
:
1052 case SSH2_MSG_DEBUG
:
1054 /* log the debug message */
1056 /* int display = ssh->pktin.body[6]; */
1057 int stringlen
= GET_32BIT(ssh
->pktin
.data
+7);
1059 strcpy(buf
, "Remote debug message: ");
1060 prefix
= strlen(buf
);
1061 if (stringlen
> (int)(sizeof(buf
)-prefix
-1))
1062 stringlen
= sizeof(buf
)-prefix
-1;
1063 memcpy(buf
+ prefix
, ssh
->pktin
.data
+ 11, stringlen
);
1064 buf
[prefix
+ stringlen
] = '\0';
1067 goto next_packet
; /* FIXME: print the debug message */
1070 * These packets we need do nothing about here.
1072 case SSH2_MSG_UNIMPLEMENTED
:
1073 case SSH2_MSG_SERVICE_REQUEST
:
1074 case SSH2_MSG_SERVICE_ACCEPT
:
1075 case SSH2_MSG_KEXINIT
:
1076 case SSH2_MSG_NEWKEYS
:
1077 case SSH2_MSG_KEXDH_INIT
:
1078 case SSH2_MSG_KEXDH_REPLY
:
1079 /* case SSH2_MSG_KEX_DH_GEX_REQUEST: duplicate case value */
1080 /* case SSH2_MSG_KEX_DH_GEX_GROUP: duplicate case value */
1081 case SSH2_MSG_KEX_DH_GEX_INIT
:
1082 case SSH2_MSG_KEX_DH_GEX_REPLY
:
1083 case SSH2_MSG_USERAUTH_REQUEST
:
1084 case SSH2_MSG_USERAUTH_FAILURE
:
1085 case SSH2_MSG_USERAUTH_SUCCESS
:
1086 case SSH2_MSG_USERAUTH_BANNER
:
1087 case SSH2_MSG_USERAUTH_PK_OK
:
1088 /* case SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: duplicate case value */
1089 /* case SSH2_MSG_USERAUTH_INFO_REQUEST: duplicate case value */
1090 case SSH2_MSG_USERAUTH_INFO_RESPONSE
:
1091 case SSH2_MSG_GLOBAL_REQUEST
:
1092 case SSH2_MSG_REQUEST_SUCCESS
:
1093 case SSH2_MSG_REQUEST_FAILURE
:
1094 case SSH2_MSG_CHANNEL_OPEN
:
1095 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
:
1096 case SSH2_MSG_CHANNEL_OPEN_FAILURE
:
1097 case SSH2_MSG_CHANNEL_WINDOW_ADJUST
:
1098 case SSH2_MSG_CHANNEL_DATA
:
1099 case SSH2_MSG_CHANNEL_EXTENDED_DATA
:
1100 case SSH2_MSG_CHANNEL_EOF
:
1101 case SSH2_MSG_CHANNEL_CLOSE
:
1102 case SSH2_MSG_CHANNEL_REQUEST
:
1103 case SSH2_MSG_CHANNEL_SUCCESS
:
1104 case SSH2_MSG_CHANNEL_FAILURE
:
1108 * For anything else we send SSH2_MSG_UNIMPLEMENTED.
1111 ssh2_pkt_init(ssh
, SSH2_MSG_UNIMPLEMENTED
);
1112 ssh2_pkt_adduint32(ssh
, st
->incoming_sequence
- 1);
1120 static void ssh1_pktout_size(Ssh ssh
, int len
)
1124 len
+= 5; /* type and CRC */
1125 pad
= 8 - (len
% 8);
1128 ssh
->pktout
.length
= len
- 5;
1129 if (ssh
->pktout
.maxlen
< biglen
) {
1130 ssh
->pktout
.maxlen
= biglen
;
1132 /* Allocate enough buffer space for extra block
1133 * for MS CryptEncrypt() */
1134 ssh
->pktout
.data
= srealloc(ssh
->pktout
.data
, biglen
+ 12);
1136 ssh
->pktout
.data
= srealloc(ssh
->pktout
.data
, biglen
+ 4);
1139 ssh
->pktout
.body
= ssh
->pktout
.data
+ 4 + pad
+ 1;
1142 static void s_wrpkt_start(Ssh ssh
, int type
, int len
)
1144 ssh1_pktout_size(ssh
, len
);
1145 ssh
->pktout
.type
= type
;
1148 static int s_wrpkt_prepare(Ssh ssh
)
1150 int pad
, len
, biglen
, i
;
1153 ssh
->pktout
.body
[-1] = ssh
->pktout
.type
;
1155 log_packet(PKT_OUTGOING
, ssh
->pktout
.type
, ssh1_pkt_type(ssh
->pktout
.type
),
1156 ssh
->pktout
.body
, ssh
->pktout
.length
);
1158 if (ssh
->v1_compressing
) {
1159 unsigned char *compblk
;
1161 zlib_compress_block(ssh
->pktout
.body
- 1, ssh
->pktout
.length
+ 1,
1162 &compblk
, &complen
);
1163 ssh1_pktout_size(ssh
, complen
- 1);
1164 memcpy(ssh
->pktout
.body
- 1, compblk
, complen
);
1168 len
= ssh
->pktout
.length
+ 5; /* type and CRC */
1169 pad
= 8 - (len
% 8);
1172 for (i
= 0; i
< pad
; i
++)
1173 ssh
->pktout
.data
[i
+ 4] = random_byte();
1174 crc
= crc32(ssh
->pktout
.data
+ 4, biglen
- 4);
1175 PUT_32BIT(ssh
->pktout
.data
+ biglen
, crc
);
1176 PUT_32BIT(ssh
->pktout
.data
, len
);
1179 ssh
->cipher
->encrypt(ssh
->v1_cipher_ctx
, ssh
->pktout
.data
+ 4, biglen
);
1184 static void s_wrpkt(Ssh ssh
)
1187 len
= s_wrpkt_prepare(ssh
);
1188 backlog
= sk_write(ssh
->s
, ssh
->pktout
.data
, len
);
1189 if (backlog
> SSH_MAX_BACKLOG
)
1190 ssh_throttle_all(ssh
, 1, backlog
);
1193 static void s_wrpkt_defer(Ssh ssh
)
1196 len
= s_wrpkt_prepare(ssh
);
1197 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
1198 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
1199 ssh
->deferred_send_data
= srealloc(ssh
->deferred_send_data
,
1200 ssh
->deferred_size
);
1202 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
, ssh
->pktout
.data
, len
);
1203 ssh
->deferred_len
+= len
;
1207 * Construct a packet with the specified contents.
1209 static void construct_packet(Ssh ssh
, int pkttype
, va_list ap1
, va_list ap2
)
1211 unsigned char *p
, *argp
, argchar
;
1212 unsigned long argint
;
1213 int pktlen
, argtype
, arglen
;
1217 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
1220 (void) va_arg(ap1
, int);
1224 (void) va_arg(ap1
, char);
1228 (void) va_arg(ap1
, unsigned char *);
1229 arglen
= va_arg(ap1
, int);
1233 argp
= va_arg(ap1
, unsigned char *);
1234 arglen
= strlen(argp
);
1235 pktlen
+= 4 + arglen
;
1238 bn
= va_arg(ap1
, Bignum
);
1239 pktlen
+= ssh1_bignum_length(bn
);
1246 s_wrpkt_start(ssh
, pkttype
, pktlen
);
1247 p
= ssh
->pktout
.body
;
1249 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
1252 argint
= va_arg(ap2
, int);
1253 PUT_32BIT(p
, argint
);
1257 argchar
= va_arg(ap2
, unsigned char);
1262 argp
= va_arg(ap2
, unsigned char *);
1263 arglen
= va_arg(ap2
, int);
1264 memcpy(p
, argp
, arglen
);
1268 argp
= va_arg(ap2
, unsigned char *);
1269 arglen
= strlen(argp
);
1270 PUT_32BIT(p
, arglen
);
1271 memcpy(p
+ 4, argp
, arglen
);
1275 bn
= va_arg(ap2
, Bignum
);
1276 p
+= ssh1_write_bignum(p
, bn
);
1282 static void send_packet(Ssh ssh
, int pkttype
, ...)
1285 va_start(ap1
, pkttype
);
1286 va_start(ap2
, pkttype
);
1287 construct_packet(ssh
, pkttype
, ap1
, ap2
);
1291 static void defer_packet(Ssh ssh
, int pkttype
, ...)
1294 va_start(ap1
, pkttype
);
1295 va_start(ap2
, pkttype
);
1296 construct_packet(ssh
, pkttype
, ap1
, ap2
);
1300 static int ssh_versioncmp(char *a
, char *b
)
1303 unsigned long av
, bv
;
1305 av
= strtoul(a
, &ae
, 10);
1306 bv
= strtoul(b
, &be
, 10);
1308 return (av
< bv ?
-1 : +1);
1313 av
= strtoul(ae
, &ae
, 10);
1314 bv
= strtoul(be
, &be
, 10);
1316 return (av
< bv ?
-1 : +1);
1321 * Utility routines for putting an SSH-protocol `string' and
1322 * `uint32' into a SHA state.
1325 static void sha_string(SHA_State
* s
, void *str
, int len
)
1327 unsigned char lenblk
[4];
1328 PUT_32BIT(lenblk
, len
);
1329 SHA_Bytes(s
, lenblk
, 4);
1330 SHA_Bytes(s
, str
, len
);
1333 static void sha_uint32(SHA_State
* s
, unsigned i
)
1335 unsigned char intblk
[4];
1336 PUT_32BIT(intblk
, i
);
1337 SHA_Bytes(s
, intblk
, 4);
1341 * SSH2 packet construction functions.
1343 static void ssh2_pkt_ensure(Ssh ssh
, int length
)
1345 if (ssh
->pktout
.maxlen
< length
) {
1346 ssh
->pktout
.maxlen
= length
+ 256;
1347 ssh
->pktout
.data
= srealloc(ssh
->pktout
.data
,
1348 ssh
->pktout
.maxlen
+ APIEXTRA
);
1349 if (!ssh
->pktout
.data
)
1350 fatalbox("Out of memory");
1353 static void ssh2_pkt_adddata(Ssh ssh
, void *data
, int len
)
1355 ssh
->pktout
.length
+= len
;
1356 ssh2_pkt_ensure(ssh
, ssh
->pktout
.length
);
1357 memcpy(ssh
->pktout
.data
+ ssh
->pktout
.length
- len
, data
, len
);
1359 static void ssh2_pkt_addbyte(Ssh ssh
, unsigned char byte
)
1361 ssh2_pkt_adddata(ssh
, &byte
, 1);
1363 static void ssh2_pkt_init(Ssh ssh
, int pkt_type
)
1365 ssh
->pktout
.length
= 5;
1366 ssh2_pkt_addbyte(ssh
, (unsigned char) pkt_type
);
1368 static void ssh2_pkt_addbool(Ssh ssh
, unsigned char value
)
1370 ssh2_pkt_adddata(ssh
, &value
, 1);
1372 static void ssh2_pkt_adduint32(Ssh ssh
, unsigned long value
)
1375 PUT_32BIT(x
, value
);
1376 ssh2_pkt_adddata(ssh
, x
, 4);
1378 static void ssh2_pkt_addstring_start(Ssh ssh
)
1380 ssh2_pkt_adduint32(ssh
, 0);
1381 ssh
->pktout
.savedpos
= ssh
->pktout
.length
;
1383 static void ssh2_pkt_addstring_str(Ssh ssh
, char *data
)
1385 ssh2_pkt_adddata(ssh
, data
, strlen(data
));
1386 PUT_32BIT(ssh
->pktout
.data
+ ssh
->pktout
.savedpos
- 4,
1387 ssh
->pktout
.length
- ssh
->pktout
.savedpos
);
1389 static void ssh2_pkt_addstring_data(Ssh ssh
, char *data
, int len
)
1391 ssh2_pkt_adddata(ssh
, data
, len
);
1392 PUT_32BIT(ssh
->pktout
.data
+ ssh
->pktout
.savedpos
- 4,
1393 ssh
->pktout
.length
- ssh
->pktout
.savedpos
);
1395 static void ssh2_pkt_addstring(Ssh ssh
, char *data
)
1397 ssh2_pkt_addstring_start(ssh
);
1398 ssh2_pkt_addstring_str(ssh
, data
);
1400 static char *ssh2_mpint_fmt(Bignum b
, int *len
)
1403 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1406 fatalbox("out of memory");
1408 for (i
= 1; i
<= n
; i
++)
1409 p
[i
] = bignum_byte(b
, n
- i
);
1411 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1413 memmove(p
, p
+ i
, n
+ 1 - i
);
1417 static void ssh2_pkt_addmp(Ssh ssh
, Bignum b
)
1421 p
= ssh2_mpint_fmt(b
, &len
);
1422 ssh2_pkt_addstring_start(ssh
);
1423 ssh2_pkt_addstring_data(ssh
, p
, len
);
1428 * Construct an SSH2 final-form packet: compress it, encrypt it,
1429 * put the MAC on it. Final packet, ready to be sent, is stored in
1430 * ssh->pktout.data. Total length is returned.
1432 static int ssh2_pkt_construct(Ssh ssh
)
1434 int cipherblk
, maclen
, padding
, i
;
1436 log_packet(PKT_OUTGOING
, ssh
->pktout
.data
[5],
1437 ssh2_pkt_type(ssh
->pkt_ctx
, ssh
->pktout
.data
[5]),
1438 ssh
->pktout
.data
+ 6, ssh
->pktout
.length
- 6);
1441 * Compress packet payload.
1444 unsigned char *newpayload
;
1447 ssh
->cscomp
->compress(ssh
->pktout
.data
+ 5, ssh
->pktout
.length
- 5,
1448 &newpayload
, &newlen
)) {
1449 ssh
->pktout
.length
= 5;
1450 ssh2_pkt_adddata(ssh
, newpayload
, newlen
);
1456 * Add padding. At least four bytes, and must also bring total
1457 * length (minus MAC) up to a multiple of the block size.
1459 cipherblk
= ssh
->cscipher ? ssh
->cscipher
->blksize
: 8; /* block size */
1460 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1463 (cipherblk
- (ssh
->pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
1464 maclen
= ssh
->csmac ? ssh
->csmac
->len
: 0;
1465 ssh2_pkt_ensure(ssh
, ssh
->pktout
.length
+ padding
+ maclen
);
1466 ssh
->pktout
.data
[4] = padding
;
1467 for (i
= 0; i
< padding
; i
++)
1468 ssh
->pktout
.data
[ssh
->pktout
.length
+ i
] = random_byte();
1469 PUT_32BIT(ssh
->pktout
.data
, ssh
->pktout
.length
+ padding
- 4);
1471 ssh
->csmac
->generate(ssh
->pktout
.data
, ssh
->pktout
.length
+ padding
,
1472 ssh
->v2_outgoing_sequence
);
1473 ssh
->v2_outgoing_sequence
++; /* whether or not we MACed */
1476 ssh
->cscipher
->encrypt(ssh
->cs_cipher_ctx
,
1477 ssh
->pktout
.data
, ssh
->pktout
.length
+ padding
);
1479 /* Ready-to-send packet starts at ssh->pktout.data. We return length. */
1480 return ssh
->pktout
.length
+ padding
+ maclen
;
1484 * Construct and send an SSH2 packet immediately.
1486 static void ssh2_pkt_send(Ssh ssh
)
1490 len
= ssh2_pkt_construct(ssh
);
1491 backlog
= sk_write(ssh
->s
, ssh
->pktout
.data
, len
);
1492 if (backlog
> SSH_MAX_BACKLOG
)
1493 ssh_throttle_all(ssh
, 1, backlog
);
1497 * Construct an SSH2 packet and add it to a deferred data block.
1498 * Useful for sending multiple packets in a single sk_write() call,
1499 * to prevent a traffic-analysing listener from being able to work
1500 * out the length of any particular packet (such as the password
1503 * Note that because SSH2 sequence-numbers its packets, this can
1504 * NOT be used as an m4-style `defer' allowing packets to be
1505 * constructed in one order and sent in another.
1507 static void ssh2_pkt_defer(Ssh ssh
)
1509 int len
= ssh2_pkt_construct(ssh
);
1510 if (ssh
->deferred_len
+ len
> ssh
->deferred_size
) {
1511 ssh
->deferred_size
= ssh
->deferred_len
+ len
+ 128;
1512 ssh
->deferred_send_data
= srealloc(ssh
->deferred_send_data
,
1513 ssh
->deferred_size
);
1515 memcpy(ssh
->deferred_send_data
+ ssh
->deferred_len
, ssh
->pktout
.data
, len
);
1516 ssh
->deferred_len
+= len
;
1520 * Send the whole deferred data block constructed by
1521 * ssh2_pkt_defer() or SSH1's defer_packet().
1523 static void ssh_pkt_defersend(Ssh ssh
)
1526 backlog
= sk_write(ssh
->s
, ssh
->deferred_send_data
, ssh
->deferred_len
);
1527 ssh
->deferred_len
= ssh
->deferred_size
= 0;
1528 sfree(ssh
->deferred_send_data
);
1529 ssh
->deferred_send_data
= NULL
;
1530 if (backlog
> SSH_MAX_BACKLOG
)
1531 ssh_throttle_all(ssh
, 1, backlog
);
1535 void bndebug(char *string
, Bignum b
)
1539 p
= ssh2_mpint_fmt(b
, &len
);
1540 debug(("%s", string
));
1541 for (i
= 0; i
< len
; i
++)
1542 debug((" %02x", p
[i
]));
1548 static void sha_mpint(SHA_State
* s
, Bignum b
)
1552 p
= ssh2_mpint_fmt(b
, &len
);
1553 sha_string(s
, p
, len
);
1558 * SSH2 packet decode functions.
1560 static unsigned long ssh2_pkt_getuint32(Ssh ssh
)
1562 unsigned long value
;
1563 if (ssh
->pktin
.length
- ssh
->pktin
.savedpos
< 4)
1564 return 0; /* arrgh, no way to decline (FIXME?) */
1565 value
= GET_32BIT(ssh
->pktin
.data
+ ssh
->pktin
.savedpos
);
1566 ssh
->pktin
.savedpos
+= 4;
1569 static int ssh2_pkt_getbool(Ssh ssh
)
1571 unsigned long value
;
1572 if (ssh
->pktin
.length
- ssh
->pktin
.savedpos
< 1)
1573 return 0; /* arrgh, no way to decline (FIXME?) */
1574 value
= ssh
->pktin
.data
[ssh
->pktin
.savedpos
] != 0;
1575 ssh
->pktin
.savedpos
++;
1578 static void ssh2_pkt_getstring(Ssh ssh
, char **p
, int *length
)
1582 if (ssh
->pktin
.length
- ssh
->pktin
.savedpos
< 4)
1584 *length
= GET_32BIT(ssh
->pktin
.data
+ ssh
->pktin
.savedpos
);
1585 ssh
->pktin
.savedpos
+= 4;
1586 if (ssh
->pktin
.length
- ssh
->pktin
.savedpos
< *length
)
1588 *p
= ssh
->pktin
.data
+ ssh
->pktin
.savedpos
;
1589 ssh
->pktin
.savedpos
+= *length
;
1591 static Bignum
ssh2_pkt_getmp(Ssh ssh
)
1597 ssh2_pkt_getstring(ssh
, &p
, &length
);
1601 bombout(("internal error: Can't handle negative mpints"));
1604 b
= bignum_from_bytes(p
, length
);
1609 * Helper function to add an SSH2 signature blob to a packet.
1610 * Expects to be shown the public key blob as well as the signature
1611 * blob. Normally works just like ssh2_pkt_addstring, but will
1612 * fiddle with the signature packet if necessary for
1613 * BUG_SSH2_RSA_PADDING.
1615 static void ssh2_add_sigblob(Ssh ssh
, void *pkblob_v
, int pkblob_len
,
1616 void *sigblob_v
, int sigblob_len
)
1618 unsigned char *pkblob
= (unsigned char *)pkblob_v
;
1619 unsigned char *sigblob
= (unsigned char *)sigblob_v
;
1621 /* dmemdump(pkblob, pkblob_len); */
1622 /* dmemdump(sigblob, sigblob_len); */
1625 * See if this is in fact an ssh-rsa signature and a buggy
1626 * server; otherwise we can just do this the easy way.
1628 if ((ssh
->remote_bugs
& BUG_SSH2_RSA_PADDING
) &&
1629 (GET_32BIT(pkblob
) == 7 && !memcmp(pkblob
+4, "ssh-rsa", 7))) {
1630 int pos
, len
, siglen
;
1633 * Find the byte length of the modulus.
1636 pos
= 4+7; /* skip over "ssh-rsa" */
1637 pos
+= 4 + GET_32BIT(pkblob
+pos
); /* skip over exponent */
1638 len
= GET_32BIT(pkblob
+pos
); /* find length of modulus */
1639 pos
+= 4; /* find modulus itself */
1640 while (len
> 0 && pkblob
[pos
] == 0)
1642 /* debug(("modulus length is %d\n", len)); */
1645 * Now find the signature integer.
1647 pos
= 4+7; /* skip over "ssh-rsa" */
1648 siglen
= GET_32BIT(sigblob
+pos
);
1649 /* debug(("signature length is %d\n", siglen)); */
1651 if (len
!= siglen
) {
1652 unsigned char newlen
[4];
1653 ssh2_pkt_addstring_start(ssh
);
1654 ssh2_pkt_addstring_data(ssh
, sigblob
, pos
);
1655 /* dmemdump(sigblob, pos); */
1656 pos
+= 4; /* point to start of actual sig */
1657 PUT_32BIT(newlen
, len
);
1658 ssh2_pkt_addstring_data(ssh
, newlen
, 4);
1659 /* dmemdump(newlen, 4); */
1661 while (len
-- > siglen
) {
1662 ssh2_pkt_addstring_data(ssh
, newlen
, 1);
1663 /* dmemdump(newlen, 1); */
1665 ssh2_pkt_addstring_data(ssh
, sigblob
+pos
, siglen
);
1666 /* dmemdump(sigblob+pos, siglen); */
1670 /* Otherwise fall through and do it the easy way. */
1673 ssh2_pkt_addstring_start(ssh
);
1674 ssh2_pkt_addstring_data(ssh
, sigblob
, sigblob_len
);
1678 * Examine the remote side's version string and compare it against
1679 * a list of known buggy implementations.
1681 static void ssh_detect_bugs(Ssh ssh
, char *vstring
)
1683 char *imp
; /* pointer to implementation part */
1685 imp
+= strcspn(imp
, "-");
1687 imp
+= strcspn(imp
, "-");
1690 ssh
->remote_bugs
= 0;
1692 if (cfg
.sshbug_ignore1
== BUG_ON
||
1693 (cfg
.sshbug_ignore1
== BUG_AUTO
&&
1694 (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
1695 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
1696 !strcmp(imp
, "1.2.22") || !strcmp(imp
, "Cisco-1.25")))) {
1698 * These versions don't support SSH1_MSG_IGNORE, so we have
1699 * to use a different defence against password length
1702 ssh
->remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
1703 logevent("We believe remote version has SSH1 ignore bug");
1706 if (cfg
.sshbug_plainpw1
== BUG_ON
||
1707 (cfg
.sshbug_plainpw1
== BUG_AUTO
&&
1708 (!strcmp(imp
, "Cisco-1.25")))) {
1710 * These versions need a plain password sent; they can't
1711 * handle having a null and a random length of data after
1714 ssh
->remote_bugs
|= BUG_NEEDS_SSH1_PLAIN_PASSWORD
;
1715 logevent("We believe remote version needs a plain SSH1 password");
1718 if (cfg
.sshbug_rsa1
== BUG_ON
||
1719 (cfg
.sshbug_rsa1
== BUG_AUTO
&&
1720 (!strcmp(imp
, "Cisco-1.25")))) {
1722 * These versions apparently have no clue whatever about
1723 * RSA authentication and will panic and die if they see
1724 * an AUTH_RSA message.
1726 ssh
->remote_bugs
|= BUG_CHOKES_ON_RSA
;
1727 logevent("We believe remote version can't handle RSA authentication");
1730 if (cfg
.sshbug_hmac2
== BUG_ON
||
1731 (cfg
.sshbug_hmac2
== BUG_AUTO
&&
1732 (!strncmp(imp
, "2.1.0", 5) || !strncmp(imp
, "2.0.", 4) ||
1733 !strncmp(imp
, "2.2.0", 5) || !strncmp(imp
, "2.3.0", 5) ||
1734 !strncmp(imp
, "2.1 ", 4)))) {
1736 * These versions have the HMAC bug.
1738 ssh
->remote_bugs
|= BUG_SSH2_HMAC
;
1739 logevent("We believe remote version has SSH2 HMAC bug");
1742 if (cfg
.sshbug_derivekey2
== BUG_ON
||
1743 (cfg
.sshbug_derivekey2
== BUG_AUTO
&&
1744 (!strncmp(imp
, "2.0.", 4)))) {
1746 * These versions have the key-derivation bug (failing to
1747 * include the literal shared secret in the hashes that
1748 * generate the keys).
1750 ssh
->remote_bugs
|= BUG_SSH2_DERIVEKEY
;
1751 logevent("We believe remote version has SSH2 key-derivation bug");
1754 if (cfg
.sshbug_rsapad2
== BUG_ON
||
1755 (cfg
.sshbug_rsapad2
== BUG_AUTO
&&
1756 ((!strncmp(imp
, "OpenSSH_2.", 10) && imp
[10]>='5' && imp
[10]<='9') ||
1757 (!strncmp(imp
, "OpenSSH_3.", 10) && imp
[10]>='0' && imp
[10]<='2')))){
1759 * These versions have the SSH2 RSA padding bug.
1761 ssh
->remote_bugs
|= BUG_SSH2_RSA_PADDING
;
1762 logevent("We believe remote version has SSH2 RSA padding bug");
1765 if (cfg
.sshbug_dhgex2
== BUG_ON
) {
1767 * These versions have the SSH2 DH GEX bug.
1769 ssh
->remote_bugs
|= BUG_SSH2_DH_GEX
;
1770 logevent("We believe remote version has SSH2 DH group exchange bug");
1774 static int do_ssh_init(Ssh ssh
, unsigned char c
)
1776 struct do_ssh_init_state
{
1784 crState(do_ssh_init_state
);
1786 crBegin(ssh
->do_ssh_init_crstate
);
1788 /* Search for the string "SSH-" in the input. */
1791 static const int transS
[] = { 1, 2, 2, 1 };
1792 static const int transH
[] = { 0, 0, 3, 0 };
1793 static const int transminus
[] = { 0, 0, 0, -1 };
1795 s
->i
= transS
[s
->i
];
1797 s
->i
= transH
[s
->i
];
1799 s
->i
= transminus
[s
->i
];
1804 crReturn(1); /* get another character */
1808 s
->vstring
= smalloc(s
->vstrsize
);
1809 strcpy(s
->vstring
, "SSH-");
1813 crReturn(1); /* get another char */
1814 if (s
->vslen
>= s
->vstrsize
- 1) {
1816 s
->vstring
= srealloc(s
->vstring
, s
->vstrsize
);
1818 s
->vstring
[s
->vslen
++] = c
;
1821 s
->version
[s
->i
] = '\0';
1823 } else if (s
->i
< sizeof(s
->version
) - 1)
1824 s
->version
[s
->i
++] = c
;
1825 } else if (c
== '\n')
1829 ssh
->agentfwd_enabled
= FALSE
;
1830 ssh
->rdpkt2_state
.incoming_sequence
= 0;
1832 s
->vstring
[s
->vslen
] = 0;
1833 s
->vstring
[strcspn(s
->vstring
, "\r\n")] = '\0';/* remove EOL chars */
1836 vlog
= smalloc(20 + s
->vslen
);
1837 sprintf(vlog
, "Server version: %s", s
->vstring
);
1841 ssh_detect_bugs(ssh
, s
->vstring
);
1844 * Decide which SSH protocol version to support.
1847 /* Anything strictly below "2.0" means protocol 1 is supported. */
1848 s
->proto1
= ssh_versioncmp(s
->version
, "2.0") < 0;
1849 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
1850 s
->proto2
= ssh_versioncmp(s
->version
, "1.99") >= 0;
1852 if (cfg
.sshprot
== 0 && !s
->proto1
) {
1853 bombout(("SSH protocol version 1 required by user but not provided by server"));
1856 if (cfg
.sshprot
== 3 && !s
->proto2
) {
1857 bombout(("SSH protocol version 2 required by user but not provided by server"));
1861 if (s
->proto2
&& (cfg
.sshprot
>= 2 || !s
->proto1
)) {
1865 char verstring
[80], vlog
[100];
1866 sprintf(verstring
, "SSH-2.0-%s", sshver
);
1867 SHA_Init(&ssh
->exhashbase
);
1869 * Hash our version string and their version string.
1871 sha_string(&ssh
->exhashbase
, verstring
, strlen(verstring
));
1872 sha_string(&ssh
->exhashbase
, s
->vstring
, strcspn(s
->vstring
, "\r\n"));
1873 sprintf(vlog
, "We claim version: %s", verstring
);
1875 strcat(verstring
, "\n");
1876 logevent("Using SSH protocol version 2");
1877 sk_write(ssh
->s
, verstring
, strlen(verstring
));
1878 ssh
->protocol
= ssh2_protocol
;
1880 ssh
->s_rdpkt
= ssh2_rdpkt
;
1885 char verstring
[80], vlog
[100];
1886 sprintf(verstring
, "SSH-%s-%s",
1887 (ssh_versioncmp(s
->version
, "1.5") <= 0 ? s
->version
: "1.5"),
1889 sprintf(vlog
, "We claim version: %s", verstring
);
1891 strcat(verstring
, "\n");
1893 logevent("Using SSH protocol version 1");
1894 sk_write(ssh
->s
, verstring
, strlen(verstring
));
1895 ssh
->protocol
= ssh1_protocol
;
1897 ssh
->s_rdpkt
= ssh1_rdpkt
;
1899 ssh
->state
= SSH_STATE_BEFORE_SIZE
;
1906 static void ssh_gotdata(Ssh ssh
, unsigned char *data
, int datalen
)
1908 crBegin(ssh
->ssh_gotdata_crstate
);
1911 * To begin with, feed the characters one by one to the
1912 * protocol initialisation / selection function do_ssh_init().
1913 * When that returns 0, we're done with the initial greeting
1914 * exchange and can move on to packet discipline.
1917 int ret
; /* need not be kept across crReturn */
1919 crReturnV
; /* more data please */
1920 ret
= do_ssh_init(ssh
, *data
);
1928 * We emerge from that loop when the initial negotiation is
1929 * over and we have selected an s_rdpkt function. Now pass
1930 * everything to s_rdpkt, and then pass the resulting packets
1931 * to the proper protocol handler.
1936 while (datalen
> 0) {
1937 if (ssh
->s_rdpkt(ssh
, &data
, &datalen
) == 0) {
1938 if (ssh
->state
== SSH_STATE_CLOSED
) {
1941 ssh
->protocol(ssh
, NULL
, 0, 1);
1942 if (ssh
->state
== SSH_STATE_CLOSED
) {
1952 static int ssh_closing(Plug plug
, char *error_msg
, int error_code
,
1955 Ssh ssh
= (Ssh
) plug
;
1956 ssh
->state
= SSH_STATE_CLOSED
;
1962 /* A socket error has occurred. */
1963 logevent(error_msg
);
1964 connection_fatal(error_msg
);
1966 /* Otherwise, the remote side closed the connection normally. */
1971 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
1973 Ssh ssh
= (Ssh
) plug
;
1974 ssh_gotdata(ssh
, data
, len
);
1975 if (ssh
->state
== SSH_STATE_CLOSED
) {
1985 static void ssh_sent(Plug plug
, int bufsize
)
1987 Ssh ssh
= (Ssh
) plug
;
1989 * If the send backlog on the SSH socket itself clears, we
1990 * should unthrottle the whole world if it was throttled.
1992 if (bufsize
< SSH_MAX_BACKLOG
)
1993 ssh_throttle_all(ssh
, 0, bufsize
);
1997 * Connect to specified host and port.
1998 * Returns an error message, or NULL on success.
1999 * Also places the canonical host name into `realhost'. It must be
2000 * freed by the caller.
2002 static char *connect_to_host(Ssh ssh
, char *host
, int port
,
2003 char **realhost
, int nodelay
)
2005 static const struct plug_function_table fn_table
= {
2015 ssh
->savedhost
= smalloc(1 + strlen(host
));
2016 if (!ssh
->savedhost
)
2017 fatalbox("Out of memory");
2018 strcpy(ssh
->savedhost
, host
);
2021 port
= 22; /* default ssh port */
2022 ssh
->savedport
= port
;
2029 sprintf(buf
, "Looking up host \"%.170s\"", host
);
2032 addr
= sk_namelookup(host
, realhost
);
2033 if ((err
= sk_addr_error(addr
)))
2040 char buf
[200], addrbuf
[100];
2041 sk_getaddr(addr
, addrbuf
, 100);
2042 sprintf(buf
, "Connecting to %.100s port %d", addrbuf
, port
);
2045 ssh
->fn
= &fn_table
;
2046 ssh
->s
= new_connection(addr
, *realhost
, port
, 0, 1, nodelay
, (Plug
) ssh
);
2047 if ((err
= sk_socket_error(ssh
->s
))) {
2056 * Throttle or unthrottle the SSH connection.
2058 static void ssh1_throttle(Ssh ssh
, int adjust
)
2060 int old_count
= ssh
->v1_throttle_count
;
2061 ssh
->v1_throttle_count
+= adjust
;
2062 assert(ssh
->v1_throttle_count
>= 0);
2063 if (ssh
->v1_throttle_count
&& !old_count
) {
2064 sk_set_frozen(ssh
->s
, 1);
2065 } else if (!ssh
->v1_throttle_count
&& old_count
) {
2066 sk_set_frozen(ssh
->s
, 0);
2071 * Throttle or unthrottle _all_ local data streams (for when sends
2072 * on the SSH connection itself back up).
2074 static void ssh_throttle_all(Ssh ssh
, int enable
, int bufsize
)
2077 struct ssh_channel
*c
;
2079 if (enable
== ssh
->throttled_all
)
2081 ssh
->throttled_all
= enable
;
2082 ssh
->overall_bufsize
= bufsize
;
2085 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++) {
2087 case CHAN_MAINSESSION
:
2089 * This is treated separately, outside the switch.
2093 x11_override_throttle(c
->u
.x11
.s
, enable
);
2096 /* Agent channels require no buffer management. */
2099 pfd_override_throttle(c
->u
.x11
.s
, enable
);
2106 * Username and password input, abstracted off into routines
2107 * reusable in several places - even between SSH1 and SSH2.
2110 /* Set up a username or password input loop on a given buffer. */
2111 void setup_userpass_input(Ssh ssh
, char *buffer
, int buflen
, int echo
)
2113 ssh
->userpass_input_buffer
= buffer
;
2114 ssh
->userpass_input_buflen
= buflen
;
2115 ssh
->userpass_input_bufpos
= 0;
2116 ssh
->userpass_input_echo
= echo
;
2120 * Process some terminal data in the course of username/password
2121 * input. Returns >0 for success (line of input returned in
2122 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2123 * for inconclusive (keep waiting for more input please).
2125 int process_userpass_input(Ssh ssh
, unsigned char *in
, int inlen
)
2130 switch (c
= *in
++) {
2133 ssh
->userpass_input_buffer
[ssh
->userpass_input_bufpos
] = 0;
2134 ssh
->userpass_input_buffer
[ssh
->userpass_input_buflen
-1] = 0;
2139 if (ssh
->userpass_input_bufpos
> 0) {
2140 if (ssh
->userpass_input_echo
)
2141 c_write_str(ssh
, "\b \b");
2142 ssh
->userpass_input_bufpos
--;
2147 while (ssh
->userpass_input_bufpos
> 0) {
2148 if (ssh
->userpass_input_echo
)
2149 c_write_str(ssh
, "\b \b");
2150 ssh
->userpass_input_bufpos
--;
2158 if (((c
>= ' ' && c
<= '~') ||
2159 ((unsigned char) c
>= 160))
2160 && ssh
->userpass_input_bufpos
< ssh
->userpass_input_buflen
-1) {
2161 ssh
->userpass_input_buffer
[ssh
->userpass_input_bufpos
++] = c
;
2162 if (ssh
->userpass_input_echo
)
2163 c_write(ssh
, &c
, 1);
2172 * Handle the key exchange and user authentication phases.
2174 static int do_ssh1_login(Ssh ssh
, unsigned char *in
, int inlen
, int ispkt
)
2177 unsigned char cookie
[8];
2178 struct RSAKey servkey
, hostkey
;
2179 struct MD5Context md5c
;
2180 struct do_ssh1_login_state
{
2182 unsigned char *rsabuf
, *keystr1
, *keystr2
;
2183 unsigned long supported_ciphers_mask
, supported_auths_mask
;
2184 int tried_publickey
, tried_agent
;
2185 int tis_auth_refused
, ccard_auth_refused
;
2186 unsigned char session_id
[16];
2189 void *publickey_blob
;
2190 int publickey_bloblen
;
2196 unsigned char request
[5], *response
, *p
;
2205 crState(do_ssh1_login_state
);
2207 crBegin(ssh
->do_ssh1_login_crstate
);
2212 if (ssh
->pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
2213 bombout(("Public key packet not received"));
2217 logevent("Received public keys");
2219 memcpy(cookie
, ssh
->pktin
.body
, 8);
2221 i
= makekey(ssh
->pktin
.body
+ 8, &servkey
, &s
->keystr1
, 0);
2222 j
= makekey(ssh
->pktin
.body
+ 8 + i
, &hostkey
, &s
->keystr2
, 0);
2225 * Log the host key fingerprint.
2229 logevent("Host key fingerprint is:");
2230 strcpy(logmsg
, " ");
2231 hostkey
.comment
= NULL
;
2232 rsa_fingerprint(logmsg
+ strlen(logmsg
),
2233 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
2237 ssh
->v1_remote_protoflags
= GET_32BIT(ssh
->pktin
.body
+ 8 + i
+ j
);
2238 s
->supported_ciphers_mask
= GET_32BIT(ssh
->pktin
.body
+ 12 + i
+ j
);
2239 s
->supported_auths_mask
= GET_32BIT(ssh
->pktin
.body
+ 16 + i
+ j
);
2241 ssh
->v1_local_protoflags
=
2242 ssh
->v1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
2243 ssh
->v1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
2246 MD5Update(&md5c
, s
->keystr2
, hostkey
.bytes
);
2247 MD5Update(&md5c
, s
->keystr1
, servkey
.bytes
);
2248 MD5Update(&md5c
, ssh
->pktin
.body
, 8);
2249 MD5Final(s
->session_id
, &md5c
);
2251 for (i
= 0; i
< 32; i
++)
2252 ssh
->session_key
[i
] = random_byte();
2254 s
->len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
2256 s
->rsabuf
= smalloc(s
->len
);
2258 fatalbox("Out of memory");
2261 * Verify the host key.
2265 * First format the key into a string.
2267 int len
= rsastr_len(&hostkey
);
2268 char fingerprint
[100];
2269 char *keystr
= smalloc(len
);
2271 fatalbox("Out of memory");
2272 rsastr_fmt(keystr
, &hostkey
);
2273 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
2274 verify_ssh_host_key(ssh
->savedhost
, ssh
->savedport
, "rsa", keystr
,
2279 for (i
= 0; i
< 32; i
++) {
2280 s
->rsabuf
[i
] = ssh
->session_key
[i
];
2282 s
->rsabuf
[i
] ^= s
->session_id
[i
];
2285 if (hostkey
.bytes
> servkey
.bytes
) {
2286 rsaencrypt(s
->rsabuf
, 32, &servkey
);
2287 rsaencrypt(s
->rsabuf
, servkey
.bytes
, &hostkey
);
2289 rsaencrypt(s
->rsabuf
, 32, &hostkey
);
2290 rsaencrypt(s
->rsabuf
, hostkey
.bytes
, &servkey
);
2293 logevent("Encrypted session key");
2296 int cipher_chosen
= 0, warn
= 0;
2297 char *cipher_string
= NULL
;
2299 for (i
= 0; !cipher_chosen
&& i
< CIPHER_MAX
; i
++) {
2300 int next_cipher
= cfg
.ssh_cipherlist
[i
];
2301 if (next_cipher
== CIPHER_WARN
) {
2302 /* If/when we choose a cipher, warn about it */
2304 } else if (next_cipher
== CIPHER_AES
) {
2305 /* XXX Probably don't need to mention this. */
2306 logevent("AES not supported in SSH1, skipping");
2308 switch (next_cipher
) {
2309 case CIPHER_3DES
: s
->cipher_type
= SSH_CIPHER_3DES
;
2310 cipher_string
= "3DES"; break;
2311 case CIPHER_BLOWFISH
: s
->cipher_type
= SSH_CIPHER_BLOWFISH
;
2312 cipher_string
= "Blowfish"; break;
2313 case CIPHER_DES
: s
->cipher_type
= SSH_CIPHER_DES
;
2314 cipher_string
= "single-DES"; break;
2316 if (s
->supported_ciphers_mask
& (1 << s
->cipher_type
))
2320 if (!cipher_chosen
) {
2321 if ((s
->supported_ciphers_mask
& (1 << SSH_CIPHER_3DES
)) == 0)
2322 bombout(("Server violates SSH 1 protocol by not "
2323 "supporting 3DES encryption"));
2325 /* shouldn't happen */
2326 bombout(("No supported ciphers found"));
2330 /* Warn about chosen cipher if necessary. */
2332 askcipher(cipher_string
, 0);
2335 switch (s
->cipher_type
) {
2336 case SSH_CIPHER_3DES
:
2337 logevent("Using 3DES encryption");
2339 case SSH_CIPHER_DES
:
2340 logevent("Using single-DES encryption");
2342 case SSH_CIPHER_BLOWFISH
:
2343 logevent("Using Blowfish encryption");
2347 send_packet(ssh
, SSH1_CMSG_SESSION_KEY
,
2348 PKT_CHAR
, s
->cipher_type
,
2349 PKT_DATA
, cookie
, 8,
2350 PKT_CHAR
, (s
->len
* 8) >> 8, PKT_CHAR
, (s
->len
* 8) & 0xFF,
2351 PKT_DATA
, s
->rsabuf
, s
->len
,
2352 PKT_INT
, ssh
->v1_local_protoflags
, PKT_END
);
2354 logevent("Trying to enable encryption...");
2358 ssh
->cipher
= (s
->cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
2359 s
->cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
2361 ssh
->v1_cipher_ctx
= ssh
->cipher
->make_context();
2362 ssh
->cipher
->sesskey(ssh
->v1_cipher_ctx
, ssh
->session_key
);
2365 sprintf(buf
, "Initialised %.200s encryption", ssh
->cipher
->text_name
);
2371 if (ssh
->pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2372 bombout(("Encryption not successfully enabled"));
2376 logevent("Successfully started encryption");
2380 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
2381 if (ssh_get_line
&& !ssh_getline_pw_only
) {
2382 if (!ssh_get_line("login as: ",
2383 s
->username
, sizeof(s
->username
), FALSE
)) {
2385 * get_line failed to get a username.
2388 logevent("No username provided. Abandoning session.");
2389 ssh
->state
= SSH_STATE_CLOSED
;
2393 int ret
; /* need not be kept over crReturn */
2394 c_write_str(ssh
, "login as: ");
2397 setup_userpass_input(ssh
, s
->username
, sizeof(s
->username
), 1);
2399 crWaitUntil(!ispkt
);
2400 ret
= process_userpass_input(ssh
, in
, inlen
);
2404 c_write_str(ssh
, "\r\n");
2407 strncpy(s
->username
, cfg
.username
, sizeof(s
->username
));
2408 s
->username
[sizeof(s
->username
)-1] = '\0';
2411 send_packet(ssh
, SSH1_CMSG_USER
, PKT_STR
, s
->username
, PKT_END
);
2413 char userlog
[22 + sizeof(s
->username
)];
2414 sprintf(userlog
, "Sent username \"%s\"", s
->username
);
2416 if (flags
& FLAG_INTERACTIVE
&&
2417 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
2418 strcat(userlog
, "\r\n");
2419 c_write_str(ssh
, userlog
);
2426 if ((ssh
->remote_bugs
& BUG_CHOKES_ON_RSA
)) {
2427 /* We must not attempt PK auth. Pretend we've already tried it. */
2428 s
->tried_publickey
= s
->tried_agent
= 1;
2430 s
->tried_publickey
= s
->tried_agent
= 0;
2432 s
->tis_auth_refused
= s
->ccard_auth_refused
= 0;
2433 /* Load the public half of cfg.keyfile so we notice if it's in Pageant */
2435 if (!rsakey_pubblob(cfg
.keyfile
,
2436 &s
->publickey_blob
, &s
->publickey_bloblen
))
2437 s
->publickey_blob
= NULL
;
2439 s
->publickey_blob
= NULL
;
2441 while (ssh
->pktin
.type
== SSH1_SMSG_FAILURE
) {
2442 s
->pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
2444 if (agent_exists() && !s
->tried_agent
) {
2446 * Attempt RSA authentication using Pageant.
2452 logevent("Pageant is running. Requesting keys.");
2454 /* Request the keys held by the agent. */
2455 PUT_32BIT(s
->request
, 1);
2456 s
->request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
2457 agent_query(s
->request
, 5, &r
, &s
->responselen
);
2458 s
->response
= (unsigned char *) r
;
2459 if (s
->response
&& s
->responselen
>= 5 &&
2460 s
->response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
2461 s
->p
= s
->response
+ 5;
2462 s
->nkeys
= GET_32BIT(s
->p
);
2466 sprintf(buf
, "Pageant has %d SSH1 keys", s
->nkeys
);
2469 for (s
->keyi
= 0; s
->keyi
< s
->nkeys
; s
->keyi
++) {
2472 sprintf(buf
, "Trying Pageant key #%d", s
->keyi
);
2475 if (s
->publickey_blob
&&
2476 !memcmp(s
->p
, s
->publickey_blob
,
2477 s
->publickey_bloblen
)) {
2478 logevent("This key matches configured key file");
2479 s
->tried_publickey
= 1;
2482 s
->p
+= ssh1_read_bignum(s
->p
, &s
->key
.exponent
);
2483 s
->p
+= ssh1_read_bignum(s
->p
, &s
->key
.modulus
);
2484 s
->commentlen
= GET_32BIT(s
->p
);
2487 s
->p
+= s
->commentlen
;
2488 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
2489 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
2491 if (ssh
->pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2492 logevent("Key refused");
2495 logevent("Received RSA challenge");
2496 ssh1_read_bignum(ssh
->pktin
.body
, &s
->challenge
);
2498 char *agentreq
, *q
, *ret
;
2501 len
= 1 + 4; /* message type, bit count */
2502 len
+= ssh1_bignum_length(s
->key
.exponent
);
2503 len
+= ssh1_bignum_length(s
->key
.modulus
);
2504 len
+= ssh1_bignum_length(s
->challenge
);
2505 len
+= 16; /* session id */
2506 len
+= 4; /* response format */
2507 agentreq
= smalloc(4 + len
);
2508 PUT_32BIT(agentreq
, len
);
2510 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
2511 PUT_32BIT(q
, bignum_bitcount(s
->key
.modulus
));
2513 q
+= ssh1_write_bignum(q
, s
->key
.exponent
);
2514 q
+= ssh1_write_bignum(q
, s
->key
.modulus
);
2515 q
+= ssh1_write_bignum(q
, s
->challenge
);
2516 memcpy(q
, s
->session_id
, 16);
2518 PUT_32BIT(q
, 1); /* response format */
2519 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
2523 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
2524 logevent("Sending Pageant's response");
2525 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
2526 PKT_DATA
, ret
+ 5, 16,
2530 if (ssh
->pktin
.type
== SSH1_SMSG_SUCCESS
) {
2532 ("Pageant's response accepted");
2533 if (flags
& FLAG_VERBOSE
) {
2534 c_write_str(ssh
, "Authenticated using"
2536 c_write(ssh
, s
->commentp
,
2538 c_write_str(ssh
, "\" from agent\r\n");
2543 ("Pageant's response not accepted");
2546 ("Pageant failed to answer challenge");
2550 logevent("No reply received from Pageant");
2553 freebn(s
->key
.exponent
);
2554 freebn(s
->key
.modulus
);
2555 freebn(s
->challenge
);
2563 if (*cfg
.keyfile
&& !s
->tried_publickey
)
2564 s
->pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
2566 if (cfg
.try_tis_auth
&&
2567 (s
->supported_auths_mask
& (1 << SSH1_AUTH_TIS
)) &&
2568 !s
->tis_auth_refused
) {
2569 s
->pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
2570 logevent("Requested TIS authentication");
2571 send_packet(ssh
, SSH1_CMSG_AUTH_TIS
, PKT_END
);
2573 if (ssh
->pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
2574 logevent("TIS authentication declined");
2575 if (flags
& FLAG_INTERACTIVE
)
2576 c_write_str(ssh
, "TIS authentication refused.\r\n");
2577 s
->tis_auth_refused
= 1;
2580 int challengelen
= GET_32BIT(ssh
->pktin
.body
);
2581 logevent("Received TIS challenge");
2582 if (challengelen
> sizeof(s
->prompt
) - 1)
2583 challengelen
= sizeof(s
->prompt
) - 1;/* prevent overrun */
2584 memcpy(s
->prompt
, ssh
->pktin
.body
+ 4, challengelen
);
2585 /* Prompt heuristic comes from OpenSSH */
2586 strncpy(s
->prompt
+ challengelen
,
2587 memchr(s
->prompt
, '\n', challengelen
) ?
2588 "": "\r\nResponse: ",
2589 (sizeof s
->prompt
) - challengelen
);
2590 s
->prompt
[(sizeof s
->prompt
) - 1] = '\0';
2593 if (cfg
.try_tis_auth
&&
2594 (s
->supported_auths_mask
& (1 << SSH1_AUTH_CCARD
)) &&
2595 !s
->ccard_auth_refused
) {
2596 s
->pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
2597 logevent("Requested CryptoCard authentication");
2598 send_packet(ssh
, SSH1_CMSG_AUTH_CCARD
, PKT_END
);
2600 if (ssh
->pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
2601 logevent("CryptoCard authentication declined");
2602 c_write_str(ssh
, "CryptoCard authentication refused.\r\n");
2603 s
->ccard_auth_refused
= 1;
2606 int challengelen
= GET_32BIT(ssh
->pktin
.body
);
2607 logevent("Received CryptoCard challenge");
2608 if (challengelen
> sizeof(s
->prompt
) - 1)
2609 challengelen
= sizeof(s
->prompt
) - 1;/* prevent overrun */
2610 memcpy(s
->prompt
, ssh
->pktin
.body
+ 4, challengelen
);
2611 strncpy(s
->prompt
+ challengelen
,
2612 memchr(s
->prompt
, '\n', challengelen
) ?
2613 "" : "\r\nResponse: ",
2614 sizeof(s
->prompt
) - challengelen
);
2615 s
->prompt
[sizeof(s
->prompt
) - 1] = '\0';
2618 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2619 sprintf(s
->prompt
, "%.90s@%.90s's password: ",
2620 s
->username
, ssh
->savedhost
);
2622 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2623 char *comment
= NULL
;
2626 if (flags
& FLAG_VERBOSE
)
2627 c_write_str(ssh
, "Trying public key authentication.\r\n");
2628 sprintf(msgbuf
, "Trying public key \"%.200s\"", cfg
.keyfile
);
2630 type
= key_type(cfg
.keyfile
);
2631 if (type
!= SSH_KEYTYPE_SSH1
) {
2632 sprintf(msgbuf
, "Key is of wrong type (%s)",
2633 key_type_to_str(type
));
2635 c_write_str(ssh
, msgbuf
);
2636 c_write_str(ssh
, "\r\n");
2637 s
->tried_publickey
= 1;
2640 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
2641 if (flags
& FLAG_VERBOSE
)
2642 c_write_str(ssh
, "No passphrase required.\r\n");
2645 sprintf(s
->prompt
, "Passphrase for key \"%.100s\": ", comment
);
2650 * Show password prompt, having first obtained it via a TIS
2651 * or CryptoCard exchange if we're doing TIS or CryptoCard
2655 if (!ssh_get_line(s
->prompt
, s
->password
,
2656 sizeof(s
->password
), TRUE
)) {
2658 * get_line failed to get a password (for example
2659 * because one was supplied on the command line
2660 * which has already failed to work). Terminate.
2662 send_packet(ssh
, SSH1_MSG_DISCONNECT
,
2663 PKT_STR
, "No more passwords available to try",
2665 logevent("Unable to authenticate");
2666 connection_fatal("Unable to authenticate");
2667 ssh
->state
= SSH_STATE_CLOSED
;
2671 /* Prompt may have come from server. We've munged it a bit, so
2672 * we know it to be zero-terminated at least once. */
2673 int ret
; /* need not be saved over crReturn */
2674 c_write_untrusted(ssh
, s
->prompt
, strlen(s
->prompt
));
2677 setup_userpass_input(ssh
, s
->password
, sizeof(s
->password
), 0);
2679 crWaitUntil(!ispkt
);
2680 ret
= process_userpass_input(ssh
, in
, inlen
);
2684 c_write_str(ssh
, "\r\n");
2688 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2690 * Try public key authentication with the specified
2693 s
->tried_publickey
= 1;
2696 int ret
= loadrsakey(cfg
.keyfile
, &s
->key
, s
->password
);
2698 c_write_str(ssh
, "Couldn't load private key from ");
2699 c_write_str(ssh
, cfg
.keyfile
);
2700 c_write_str(ssh
, ".\r\n");
2701 continue; /* go and try password */
2704 c_write_str(ssh
, "Wrong passphrase.\r\n");
2705 s
->tried_publickey
= 0;
2706 continue; /* try again */
2711 * Send a public key attempt.
2713 send_packet(ssh
, SSH1_CMSG_AUTH_RSA
,
2714 PKT_BIGNUM
, s
->key
.modulus
, PKT_END
);
2717 if (ssh
->pktin
.type
== SSH1_SMSG_FAILURE
) {
2718 c_write_str(ssh
, "Server refused our public key.\r\n");
2719 continue; /* go and try password */
2721 if (ssh
->pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2722 bombout(("Bizarre response to offer of public key"));
2728 unsigned char buffer
[32];
2729 Bignum challenge
, response
;
2731 ssh1_read_bignum(ssh
->pktin
.body
, &challenge
);
2732 response
= rsadecrypt(challenge
, &s
->key
);
2733 freebn(s
->key
.private_exponent
);/* burn the evidence */
2735 for (i
= 0; i
< 32; i
++) {
2736 buffer
[i
] = bignum_byte(response
, 31 - i
);
2740 MD5Update(&md5c
, buffer
, 32);
2741 MD5Update(&md5c
, s
->session_id
, 16);
2742 MD5Final(buffer
, &md5c
);
2744 send_packet(ssh
, SSH1_CMSG_AUTH_RSA_RESPONSE
,
2745 PKT_DATA
, buffer
, 16, PKT_END
);
2752 if (ssh
->pktin
.type
== SSH1_SMSG_FAILURE
) {
2753 if (flags
& FLAG_VERBOSE
)
2754 c_write_str(ssh
, "Failed to authenticate with"
2755 " our public key.\r\n");
2756 continue; /* go and try password */
2757 } else if (ssh
->pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2758 bombout(("Bizarre response to RSA authentication response"));
2762 break; /* we're through! */
2764 if (s
->pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2766 * Defence against traffic analysis: we send a
2767 * whole bunch of packets containing strings of
2768 * different lengths. One of these strings is the
2769 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2770 * The others are all random data in
2771 * SSH1_MSG_IGNORE packets. This way a passive
2772 * listener can't tell which is the password, and
2773 * hence can't deduce the password length.
2775 * Anybody with a password length greater than 16
2776 * bytes is going to have enough entropy in their
2777 * password that a listener won't find it _that_
2778 * much help to know how long it is. So what we'll
2781 * - if password length < 16, we send 15 packets
2782 * containing string lengths 1 through 15
2784 * - otherwise, we let N be the nearest multiple
2785 * of 8 below the password length, and send 8
2786 * packets containing string lengths N through
2787 * N+7. This won't obscure the order of
2788 * magnitude of the password length, but it will
2789 * introduce a bit of extra uncertainty.
2791 * A few servers (the old 1.2.18 through 1.2.22)
2792 * can't deal with SSH1_MSG_IGNORE. For these
2793 * servers, we need an alternative defence. We make
2794 * use of the fact that the password is interpreted
2795 * as a C string: so we can append a NUL, then some
2798 * One server (a Cisco one) can deal with neither
2799 * SSH1_MSG_IGNORE _nor_ a padded password string.
2800 * For this server we are left with no defences
2801 * against password length sniffing.
2803 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
)) {
2805 * The server can deal with SSH1_MSG_IGNORE, so
2806 * we can use the primary defence.
2808 int bottom
, top
, pwlen
, i
;
2811 pwlen
= strlen(s
->password
);
2813 bottom
= 0; /* zero length passwords are OK! :-) */
2816 bottom
= pwlen
& ~7;
2820 assert(pwlen
>= bottom
&& pwlen
<= top
);
2822 randomstr
= smalloc(top
+ 1);
2824 for (i
= bottom
; i
<= top
; i
++) {
2826 defer_packet(ssh
, s
->pwpkt_type
,
2827 PKT_STR
, s
->password
, PKT_END
);
2829 for (j
= 0; j
< i
; j
++) {
2831 randomstr
[j
] = random_byte();
2832 } while (randomstr
[j
] == '\0');
2834 randomstr
[i
] = '\0';
2835 defer_packet(ssh
, SSH1_MSG_IGNORE
,
2836 PKT_STR
, randomstr
, PKT_END
);
2839 logevent("Sending password with camouflage packets");
2840 ssh_pkt_defersend(ssh
);
2842 else if (!(ssh
->remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
2844 * The server can't deal with SSH1_MSG_IGNORE
2845 * but can deal with padded passwords, so we
2846 * can use the secondary defence.
2852 len
= strlen(s
->password
);
2853 if (len
< sizeof(string
)) {
2855 strcpy(string
, s
->password
);
2856 len
++; /* cover the zero byte */
2857 while (len
< sizeof(string
)) {
2858 string
[len
++] = (char) random_byte();
2863 logevent("Sending length-padded password");
2864 send_packet(ssh
, s
->pwpkt_type
, PKT_INT
, len
,
2865 PKT_DATA
, ss
, len
, PKT_END
);
2868 * The server has _both_
2869 * BUG_CHOKES_ON_SSH1_IGNORE and
2870 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2871 * therefore nothing we can do.
2874 len
= strlen(s
->password
);
2875 logevent("Sending unpadded password");
2876 send_packet(ssh
, s
->pwpkt_type
, PKT_INT
, len
,
2877 PKT_DATA
, s
->password
, len
, PKT_END
);
2880 send_packet(ssh
, s
->pwpkt_type
, PKT_STR
, s
->password
, PKT_END
);
2883 logevent("Sent password");
2884 memset(s
->password
, 0, strlen(s
->password
));
2886 if (ssh
->pktin
.type
== SSH1_SMSG_FAILURE
) {
2887 if (flags
& FLAG_VERBOSE
)
2888 c_write_str(ssh
, "Access denied\r\n");
2889 logevent("Authentication refused");
2890 } else if (ssh
->pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2891 bombout(("Strange packet received, type %d", ssh
->pktin
.type
));
2896 logevent("Authentication successful");
2901 void sshfwd_close(struct ssh_channel
*c
)
2905 if (c
&& !c
->closes
) {
2907 * If the channel's remoteid is -1, we have sent
2908 * CHANNEL_OPEN for this channel, but it hasn't even been
2909 * acknowledged by the server. So we must set a close flag
2910 * on it now, and then when the server acks the channel
2911 * open, we can close it then.
2913 if (((int)c
->remoteid
) != -1) {
2914 if (ssh
->version
== 1) {
2915 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
2918 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_CLOSE
);
2919 ssh2_pkt_adduint32(ssh
, c
->remoteid
);
2923 c
->closes
= 1; /* sent MSG_CLOSE */
2924 if (c
->type
== CHAN_X11
) {
2926 logevent("Forwarded X11 connection terminated");
2927 } else if (c
->type
== CHAN_SOCKDATA
||
2928 c
->type
== CHAN_SOCKDATA_DORMANT
) {
2930 logevent("Forwarded port closed");
2935 int sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
2939 if (ssh
->version
== 1) {
2940 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
2941 PKT_INT
, c
->remoteid
,
2942 PKT_INT
, len
, PKT_DATA
, buf
, len
, PKT_END
);
2944 * In SSH1 we can return 0 here - implying that forwarded
2945 * connections are never individually throttled - because
2946 * the only circumstance that can cause throttling will be
2947 * the whole SSH connection backing up, in which case
2948 * _everything_ will be throttled as a whole.
2952 ssh2_add_channel_data(c
, buf
, len
);
2953 return ssh2_try_send(c
);
2957 void sshfwd_unthrottle(struct ssh_channel
*c
, int bufsize
)
2961 if (ssh
->version
== 1) {
2962 if (c
->v
.v1
.throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
2963 c
->v
.v1
.throttling
= 0;
2964 ssh1_throttle(ssh
, -1);
2967 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
2971 static void ssh1_protocol(Ssh ssh
, unsigned char *in
, int inlen
, int ispkt
)
2973 crBegin(ssh
->ssh1_protocol_crstate
);
2977 while (!do_ssh1_login(ssh
, in
, inlen
, ispkt
)) {
2980 if (ssh
->state
== SSH_STATE_CLOSED
)
2983 if (cfg
.agentfwd
&& agent_exists()) {
2984 logevent("Requesting agent forwarding");
2985 send_packet(ssh
, SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
2989 if (ssh
->pktin
.type
!= SSH1_SMSG_SUCCESS
2990 && ssh
->pktin
.type
!= SSH1_SMSG_FAILURE
) {
2991 bombout(("Protocol confusion"));
2993 } else if (ssh
->pktin
.type
== SSH1_SMSG_FAILURE
) {
2994 logevent("Agent forwarding refused");
2996 logevent("Agent forwarding enabled");
2997 ssh
->agentfwd_enabled
= TRUE
;
3001 if (cfg
.x11_forward
) {
3002 char proto
[20], data
[64];
3003 logevent("Requesting X11 forwarding");
3004 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
3005 if (ssh
->v1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
3006 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
3007 PKT_STR
, proto
, PKT_STR
, data
,
3008 PKT_INT
, 0, PKT_END
);
3010 send_packet(ssh
, SSH1_CMSG_X11_REQUEST_FORWARDING
,
3011 PKT_STR
, proto
, PKT_STR
, data
, PKT_END
);
3016 if (ssh
->pktin
.type
!= SSH1_SMSG_SUCCESS
3017 && ssh
->pktin
.type
!= SSH1_SMSG_FAILURE
) {
3018 bombout(("Protocol confusion"));
3020 } else if (ssh
->pktin
.type
== SSH1_SMSG_FAILURE
) {
3021 logevent("X11 forwarding refused");
3023 logevent("X11 forwarding enabled");
3024 ssh
->X11_fwd_enabled
= TRUE
;
3031 int sport
,dport
,sserv
,dserv
;
3032 char sports
[256], dports
[256], host
[256];
3036 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh1
);
3037 /* Add port forwardings. */
3038 ssh
->portfwd_strptr
= cfg
.portfwd
;
3039 while (*ssh
->portfwd_strptr
) {
3040 type
= *ssh
->portfwd_strptr
++;
3042 while (*ssh
->portfwd_strptr
&& *ssh
->portfwd_strptr
!= '\t')
3043 sports
[n
++] = *ssh
->portfwd_strptr
++;
3045 if (*ssh
->portfwd_strptr
== '\t')
3046 ssh
->portfwd_strptr
++;
3048 while (*ssh
->portfwd_strptr
&& *ssh
->portfwd_strptr
!= ':')
3049 host
[n
++] = *ssh
->portfwd_strptr
++;
3051 if (*ssh
->portfwd_strptr
== ':')
3052 ssh
->portfwd_strptr
++;
3054 while (*ssh
->portfwd_strptr
)
3055 dports
[n
++] = *ssh
->portfwd_strptr
++;
3057 ssh
->portfwd_strptr
++;
3058 dport
= atoi(dports
);
3062 se
= getservbyname(dports
, NULL
);
3064 dport
= ntohs(se
->s_port
);
3067 "Service lookup failed for destination port \"%s\"",
3072 sport
= atoi(sports
);
3076 se
= getservbyname(sports
, NULL
);
3078 sport
= ntohs(se
->s_port
);
3081 "Service lookup failed for source port \"%s\"",
3086 if (sport
&& dport
) {
3088 pfd_addforward(host
, dport
, sport
);
3089 sprintf(buf
, "Local port %.*s%.*s%d%.*s forwarding to"
3090 " %s:%.*s%.*s%d%.*s",
3091 sserv ?
strlen(sports
) : 0, sports
,
3092 sserv
, "(", sport
, sserv
, ")",
3094 dserv ?
strlen(dports
) : 0, dports
,
3095 dserv
, "(", dport
, dserv
, ")");
3098 struct ssh_rportfwd
*pf
;
3099 pf
= smalloc(sizeof(*pf
));
3100 strcpy(pf
->dhost
, host
);
3102 if (add234(ssh
->rportfwds
, pf
) != pf
) {
3104 "Duplicate remote port forwarding to %s:%d",
3109 sprintf(buf
, "Requesting remote port %.*s%.*s%d%.*s"
3110 " forward to %s:%.*s%.*s%d%.*s",
3111 sserv ?
strlen(sports
) : 0, sports
,
3112 sserv
, "(", sport
, sserv
, ")",
3114 dserv ?
strlen(dports
) : 0, dports
,
3115 dserv
, "(", dport
, dserv
, ")");
3117 send_packet(ssh
, SSH1_CMSG_PORT_FORWARD_REQUEST
,
3125 if (ssh
->pktin
.type
!= SSH1_SMSG_SUCCESS
3126 && ssh
->pktin
.type
!= SSH1_SMSG_FAILURE
) {
3127 bombout(("Protocol confusion"));
3129 } else if (ssh
->pktin
.type
== SSH1_SMSG_FAILURE
) {
3130 c_write_str(ssh
, "Server refused port"
3133 logevent("Remote port forwarding enabled");
3141 send_packet(ssh
, SSH1_CMSG_REQUEST_PTY
,
3142 PKT_STR
, cfg
.termtype
,
3143 PKT_INT
, ssh
->term_height
,
3144 PKT_INT
, ssh
->term_width
,
3145 PKT_INT
, 0, PKT_INT
, 0, PKT_CHAR
, 0, PKT_END
);
3146 ssh
->state
= SSH_STATE_INTERMED
;
3150 if (ssh
->pktin
.type
!= SSH1_SMSG_SUCCESS
3151 && ssh
->pktin
.type
!= SSH1_SMSG_FAILURE
) {
3152 bombout(("Protocol confusion"));
3154 } else if (ssh
->pktin
.type
== SSH1_SMSG_FAILURE
) {
3155 c_write_str(ssh
, "Server refused to allocate pty\r\n");
3156 ssh
->editing
= ssh
->echoing
= 1;
3158 logevent("Allocated pty");
3160 ssh
->editing
= ssh
->echoing
= 1;
3163 if (cfg
.compression
) {
3164 send_packet(ssh
, SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
3168 if (ssh
->pktin
.type
!= SSH1_SMSG_SUCCESS
3169 && ssh
->pktin
.type
!= SSH1_SMSG_FAILURE
) {
3170 bombout(("Protocol confusion"));
3172 } else if (ssh
->pktin
.type
== SSH1_SMSG_FAILURE
) {
3173 c_write_str(ssh
, "Server refused to compress\r\n");
3175 logevent("Started compression");
3176 ssh
->v1_compressing
= TRUE
;
3177 zlib_compress_init();
3178 zlib_decompress_init();
3182 * Start the shell or command.
3184 * Special case: if the first-choice command is an SSH2
3185 * subsystem (hence not usable here) and the second choice
3186 * exists, we fall straight back to that.
3189 char *cmd
= cfg
.remote_cmd_ptr
;
3191 if (cfg
.ssh_subsys
&& cfg
.remote_cmd_ptr2
) {
3192 cmd
= cfg
.remote_cmd_ptr2
;
3193 ssh
->fallback_cmd
= TRUE
;
3196 send_packet(ssh
, SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
3198 send_packet(ssh
, SSH1_CMSG_EXEC_SHELL
, PKT_END
);
3199 logevent("Started session");
3202 ssh
->state
= SSH_STATE_SESSION
;
3203 if (ssh
->size_needed
)
3204 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
3205 if (ssh
->eof_needed
)
3206 ssh_special(ssh
, TS_EOF
);
3208 ldisc_send(NULL
, 0, 0); /* cause ldisc to notice changes */
3210 ssh
->channels
= newtree234(ssh_channelcmp
);
3214 if (ssh
->pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
3215 ssh
->pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
3216 long len
= GET_32BIT(ssh
->pktin
.body
);
3218 from_backend(ssh
->frontend
,
3219 ssh
->pktin
.type
== SSH1_SMSG_STDERR_DATA
,
3220 ssh
->pktin
.body
+ 4, len
);
3221 if (!ssh
->v1_stdout_throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
3222 ssh
->v1_stdout_throttling
= 1;
3223 ssh1_throttle(ssh
, +1);
3225 } else if (ssh
->pktin
.type
== SSH1_MSG_DISCONNECT
) {
3226 ssh
->state
= SSH_STATE_CLOSED
;
3227 logevent("Received disconnect request");
3229 } else if (ssh
->pktin
.type
== SSH1_SMSG_X11_OPEN
) {
3230 /* Remote side is trying to open a channel to talk to our
3231 * X-Server. Give them back a local channel number. */
3232 struct ssh_channel
*c
;
3234 logevent("Received X11 connect request");
3235 /* Refuse if X11 forwarding is disabled. */
3236 if (!ssh
->X11_fwd_enabled
) {
3237 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3238 PKT_INT
, GET_32BIT(ssh
->pktin
.body
), PKT_END
);
3239 logevent("Rejected X11 connect request");
3241 c
= smalloc(sizeof(struct ssh_channel
));
3244 if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
3245 logevent("opening X11 forward connection failed");
3247 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3248 PKT_INT
, GET_32BIT(ssh
->pktin
.body
),
3252 ("opening X11 forward connection succeeded");
3253 c
->remoteid
= GET_32BIT(ssh
->pktin
.body
);
3254 c
->localid
= alloc_channel_id(ssh
);
3256 c
->v
.v1
.throttling
= 0;
3257 c
->type
= CHAN_X11
; /* identify channel type */
3258 add234(ssh
->channels
, c
);
3259 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
3260 PKT_INT
, c
->remoteid
, PKT_INT
,
3261 c
->localid
, PKT_END
);
3262 logevent("Opened X11 forward channel");
3265 } else if (ssh
->pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
3266 /* Remote side is trying to open a channel to talk to our
3267 * agent. Give them back a local channel number. */
3268 struct ssh_channel
*c
;
3270 /* Refuse if agent forwarding is disabled. */
3271 if (!ssh
->agentfwd_enabled
) {
3272 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3273 PKT_INT
, GET_32BIT(ssh
->pktin
.body
), PKT_END
);
3275 c
= smalloc(sizeof(struct ssh_channel
));
3277 c
->remoteid
= GET_32BIT(ssh
->pktin
.body
);
3278 c
->localid
= alloc_channel_id(ssh
);
3280 c
->v
.v1
.throttling
= 0;
3281 c
->type
= CHAN_AGENT
; /* identify channel type */
3282 c
->u
.a
.lensofar
= 0;
3283 add234(ssh
->channels
, c
);
3284 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
3285 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
3288 } else if (ssh
->pktin
.type
== SSH1_MSG_PORT_OPEN
) {
3289 /* Remote side is trying to open a channel to talk to a
3290 * forwarded port. Give them back a local channel number. */
3291 struct ssh_channel
*c
;
3292 struct ssh_rportfwd pf
;
3294 char host
[256], buf
[1024];
3296 c
= smalloc(sizeof(struct ssh_channel
));
3299 hostsize
= GET_32BIT(ssh
->pktin
.body
+4);
3300 for(h
= host
, p
= ssh
->pktin
.body
+8; hostsize
!= 0; hostsize
--) {
3301 if (h
+1 < host
+sizeof(host
))
3306 port
= GET_32BIT(p
);
3308 strcpy(pf
.dhost
, host
);
3311 if (find234(ssh
->rportfwds
, &pf
, NULL
) == NULL
) {
3312 sprintf(buf
, "Rejected remote port open request for %s:%d",
3315 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3316 PKT_INT
, GET_32BIT(ssh
->pktin
.body
), PKT_END
);
3318 sprintf(buf
, "Received remote port open request for %s:%d",
3321 e
= pfd_newconnect(&c
->u
.pfd
.s
, host
, port
, c
);
3324 sprintf(buf
, "Port open failed: %s", e
);
3327 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3328 PKT_INT
, GET_32BIT(ssh
->pktin
.body
),
3331 c
->remoteid
= GET_32BIT(ssh
->pktin
.body
);
3332 c
->localid
= alloc_channel_id(ssh
);
3334 c
->v
.v1
.throttling
= 0;
3335 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
3336 add234(ssh
->channels
, c
);
3337 send_packet(ssh
, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
3338 PKT_INT
, c
->remoteid
, PKT_INT
,
3339 c
->localid
, PKT_END
);
3340 logevent("Forwarded port opened successfully");
3344 } else if (ssh
->pktin
.type
== SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
) {
3345 unsigned int remoteid
= GET_32BIT(ssh
->pktin
.body
);
3346 unsigned int localid
= GET_32BIT(ssh
->pktin
.body
+4);
3347 struct ssh_channel
*c
;
3349 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
3350 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
3351 c
->remoteid
= localid
;
3352 c
->type
= CHAN_SOCKDATA
;
3353 c
->v
.v1
.throttling
= 0;
3354 pfd_confirm(c
->u
.pfd
.s
);
3357 if (c
&& c
->closes
) {
3359 * We have a pending close on this channel,
3360 * which we decided on before the server acked
3361 * the channel open. So now we know the
3362 * remoteid, we can close it again.
3364 send_packet(ssh
, SSH1_MSG_CHANNEL_CLOSE
,
3365 PKT_INT
, c
->remoteid
, PKT_END
);
3368 } else if (ssh
->pktin
.type
== SSH1_MSG_CHANNEL_OPEN_FAILURE
) {
3369 unsigned int remoteid
= GET_32BIT(ssh
->pktin
.body
);
3370 unsigned int localid
= GET_32BIT(ssh
->pktin
.body
+4);
3371 struct ssh_channel
*c
;
3373 c
= find234(ssh
->channels
, &remoteid
, ssh_channelfind
);
3374 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
3375 logevent("Forwarded connection refused by server");
3376 pfd_close(c
->u
.pfd
.s
);
3377 del234(ssh
->channels
, c
);
3381 } else if (ssh
->pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
3382 ssh
->pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
3383 /* Remote side closes a channel. */
3384 unsigned i
= GET_32BIT(ssh
->pktin
.body
);
3385 struct ssh_channel
*c
;
3386 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
3387 if (c
&& ((int)c
->remoteid
) != -1) {
3390 (ssh
->pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
3392 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
3393 logevent("Forwarded X11 connection terminated");
3394 assert(c
->u
.x11
.s
!= NULL
);
3395 x11_close(c
->u
.x11
.s
);
3398 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
3399 logevent("Forwarded port closed");
3400 assert(c
->u
.pfd
.s
!= NULL
);
3401 pfd_close(c
->u
.pfd
.s
);
3405 c
->closes
|= (closetype
<< 2); /* seen this message */
3406 if (!(c
->closes
& closetype
)) {
3407 send_packet(ssh
, ssh
->pktin
.type
, PKT_INT
, c
->remoteid
,
3409 c
->closes
|= closetype
; /* sent it too */
3412 if (c
->closes
== 15) {
3413 del234(ssh
->channels
, c
);
3417 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
3418 ssh
->pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
"" :
3419 "_CONFIRMATION", c ?
"half-open" : "nonexistent",
3422 } else if (ssh
->pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
3423 /* Data sent down one of our channels. */
3424 int i
= GET_32BIT(ssh
->pktin
.body
);
3425 int len
= GET_32BIT(ssh
->pktin
.body
+ 4);
3426 unsigned char *p
= ssh
->pktin
.body
+ 8;
3427 struct ssh_channel
*c
;
3428 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
3433 bufsize
= x11_send(c
->u
.x11
.s
, p
, len
);
3436 bufsize
= pfd_send(c
->u
.pfd
.s
, p
, len
);
3439 /* Data for an agent message. Buffer it. */
3441 if (c
->u
.a
.lensofar
< 4) {
3442 int l
= min(4 - c
->u
.a
.lensofar
, len
);
3443 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
3447 c
->u
.a
.lensofar
+= l
;
3449 if (c
->u
.a
.lensofar
== 4) {
3451 4 + GET_32BIT(c
->u
.a
.msglen
);
3452 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
3453 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
3455 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
3457 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
3459 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
3463 c
->u
.a
.lensofar
+= l
;
3465 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
3466 void *reply
, *sentreply
;
3468 agent_query(c
->u
.a
.message
,
3469 c
->u
.a
.totallen
, &reply
,
3474 /* Fake SSH_AGENT_FAILURE. */
3475 sentreply
= "\0\0\0\1\5";
3478 send_packet(ssh
, SSH1_MSG_CHANNEL_DATA
,
3479 PKT_INT
, c
->remoteid
,
3481 PKT_DATA
, sentreply
, replylen
,
3485 sfree(c
->u
.a
.message
);
3486 c
->u
.a
.lensofar
= 0;
3489 bufsize
= 0; /* agent channels never back up */
3492 if (!c
->v
.v1
.throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
3493 c
->v
.v1
.throttling
= 1;
3494 ssh1_throttle(ssh
, +1);
3497 } else if (ssh
->pktin
.type
== SSH1_SMSG_SUCCESS
) {
3498 /* may be from EXEC_SHELL on some servers */
3499 } else if (ssh
->pktin
.type
== SSH1_SMSG_FAILURE
) {
3500 /* may be from EXEC_SHELL on some servers
3501 * if no pty is available or in other odd cases. Ignore */
3502 } else if (ssh
->pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
3504 ssh
->exitcode
= GET_32BIT(ssh
->pktin
.body
);
3505 sprintf(buf
, "Server sent command exit status %d",
3508 send_packet(ssh
, SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
3510 * In case `helpful' firewalls or proxies tack
3511 * extra human-readable text on the end of the
3512 * session which we might mistake for another
3513 * encrypted packet, we close the session once
3514 * we've sent EXIT_CONFIRMATION.
3516 ssh
->state
= SSH_STATE_CLOSED
;
3519 bombout(("Strange packet received: type %d", ssh
->pktin
.type
));
3524 int len
= min(inlen
, 512);
3525 send_packet(ssh
, SSH1_CMSG_STDIN_DATA
,
3526 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
3537 * Utility routine for decoding comma-separated strings in KEXINIT.
3539 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
3541 int needlen
= strlen(needle
);
3544 * Is it at the start of the string?
3546 if (haylen
>= needlen
&& /* haystack is long enough */
3547 !memcmp(needle
, haystack
, needlen
) && /* initial match */
3548 (haylen
== needlen
|| haystack
[needlen
] == ',')
3549 /* either , or EOS follows */
3553 * If not, search for the next comma and resume after that.
3554 * If no comma found, terminate.
3556 while (haylen
> 0 && *haystack
!= ',')
3557 haylen
--, haystack
++;
3560 haylen
--, haystack
++; /* skip over comma itself */
3565 * SSH2 key creation method.
3567 static void ssh2_mkkey(Ssh ssh
, Bignum K
, char *H
, char *sessid
, char chr
,
3571 /* First 20 bytes. */
3573 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
3575 SHA_Bytes(&s
, H
, 20);
3576 SHA_Bytes(&s
, &chr
, 1);
3577 SHA_Bytes(&s
, sessid
, 20);
3578 SHA_Final(&s
, keyspace
);
3579 /* Next 20 bytes. */
3581 if (!(ssh
->remote_bugs
& BUG_SSH2_DERIVEKEY
))
3583 SHA_Bytes(&s
, H
, 20);
3584 SHA_Bytes(&s
, keyspace
, 20);
3585 SHA_Final(&s
, keyspace
+ 20);
3589 * Handle the SSH2 transport layer.
3591 static int do_ssh2_transport(Ssh ssh
, unsigned char *in
, int inlen
, int ispkt
)
3593 struct do_ssh2_transport_state
{
3594 int nbits
, pbits
, warn
;
3595 Bignum p
, g
, e
, f
, K
;
3596 int kex_init_value
, kex_reply_value
;
3597 const struct ssh_mac
**maclist
;
3599 const struct ssh2_cipher
*cscipher_tobe
;
3600 const struct ssh2_cipher
*sccipher_tobe
;
3601 const struct ssh_mac
*csmac_tobe
;
3602 const struct ssh_mac
*scmac_tobe
;
3603 const struct ssh_compress
*cscomp_tobe
;
3604 const struct ssh_compress
*sccomp_tobe
;
3605 char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
3606 int hostkeylen
, siglen
;
3607 void *hkey
; /* actual host key */
3608 unsigned char exchange_hash
[20];
3609 int n_preferred_ciphers
;
3610 const struct ssh2_ciphers
*preferred_ciphers
[CIPHER_MAX
];
3611 const struct ssh_compress
*preferred_comp
;
3614 crState(do_ssh2_transport_state
);
3616 crBegin(ssh
->do_ssh2_transport_crstate
);
3618 s
->cscipher_tobe
= s
->sccipher_tobe
= NULL
;
3619 s
->csmac_tobe
= s
->scmac_tobe
= NULL
;
3620 s
->cscomp_tobe
= s
->sccomp_tobe
= NULL
;
3628 * Set up the preferred ciphers. (NULL => warn below here)
3630 s
->n_preferred_ciphers
= 0;
3631 for (i
= 0; i
< CIPHER_MAX
; i
++) {
3632 switch (cfg
.ssh_cipherlist
[i
]) {
3633 case CIPHER_BLOWFISH
:
3634 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_blowfish
;
3637 if (cfg
.ssh2_des_cbc
) {
3638 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_des
;
3642 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_3des
;
3645 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = &ssh2_aes
;
3648 /* Flag for later. Don't bother if it's the last in
3650 if (i
< CIPHER_MAX
- 1) {
3651 s
->preferred_ciphers
[s
->n_preferred_ciphers
++] = NULL
;
3659 * Set up preferred compression.
3661 if (cfg
.compression
)
3662 s
->preferred_comp
= &ssh_zlib
;
3664 s
->preferred_comp
= &ssh_comp_none
;
3667 * Be prepared to work around the buggy MAC problem.
3669 if (ssh
->remote_bugs
& BUG_SSH2_HMAC
)
3670 s
->maclist
= buggymacs
, s
->nmacs
= lenof(buggymacs
);
3672 s
->maclist
= macs
, s
->nmacs
= lenof(macs
);
3676 int i
, j
, cipherstr_started
;
3679 * Construct and send our key exchange packet.
3681 ssh2_pkt_init(ssh
, SSH2_MSG_KEXINIT
);
3682 for (i
= 0; i
< 16; i
++)
3683 ssh2_pkt_addbyte(ssh
, (unsigned char) random_byte());
3684 /* List key exchange algorithms. */
3685 ssh2_pkt_addstring_start(ssh
);
3686 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3687 if (kex_algs
[i
] == &ssh_diffiehellman_gex
&&
3688 (ssh
->remote_bugs
& BUG_SSH2_DH_GEX
))
3690 ssh2_pkt_addstring_str(ssh
, kex_algs
[i
]->name
);
3691 if (i
< lenof(kex_algs
) - 1)
3692 ssh2_pkt_addstring_str(ssh
, ",");
3694 /* List server host key algorithms. */
3695 ssh2_pkt_addstring_start(ssh
);
3696 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3697 ssh2_pkt_addstring_str(ssh
, hostkey_algs
[i
]->name
);
3698 if (i
< lenof(hostkey_algs
) - 1)
3699 ssh2_pkt_addstring_str(ssh
, ",");
3701 /* List client->server encryption algorithms. */
3702 ssh2_pkt_addstring_start(ssh
);
3703 cipherstr_started
= 0;
3704 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
3705 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
3706 if (!c
) continue; /* warning flag */
3707 for (j
= 0; j
< c
->nciphers
; j
++) {
3708 if (cipherstr_started
)
3709 ssh2_pkt_addstring_str(ssh
, ",");
3710 ssh2_pkt_addstring_str(ssh
, c
->list
[j
]->name
);
3711 cipherstr_started
= 1;
3714 /* List server->client encryption algorithms. */
3715 ssh2_pkt_addstring_start(ssh
);
3716 cipherstr_started
= 0;
3717 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
3718 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
3719 if (!c
) continue; /* warning flag */
3720 for (j
= 0; j
< c
->nciphers
; j
++) {
3721 if (cipherstr_started
)
3722 ssh2_pkt_addstring_str(ssh
, ",");
3723 ssh2_pkt_addstring_str(ssh
, c
->list
[j
]->name
);
3724 cipherstr_started
= 1;
3727 /* List client->server MAC algorithms. */
3728 ssh2_pkt_addstring_start(ssh
);
3729 for (i
= 0; i
< s
->nmacs
; i
++) {
3730 ssh2_pkt_addstring_str(ssh
, s
->maclist
[i
]->name
);
3731 if (i
< s
->nmacs
- 1)
3732 ssh2_pkt_addstring_str(ssh
, ",");
3734 /* List server->client MAC algorithms. */
3735 ssh2_pkt_addstring_start(ssh
);
3736 for (i
= 0; i
< s
->nmacs
; i
++) {
3737 ssh2_pkt_addstring_str(ssh
, s
->maclist
[i
]->name
);
3738 if (i
< s
->nmacs
- 1)
3739 ssh2_pkt_addstring_str(ssh
, ",");
3741 /* List client->server compression algorithms. */
3742 ssh2_pkt_addstring_start(ssh
);
3743 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3744 const struct ssh_compress
*c
=
3745 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
3746 ssh2_pkt_addstring_str(ssh
, c
->name
);
3747 if (i
< lenof(compressions
))
3748 ssh2_pkt_addstring_str(ssh
, ",");
3750 /* List server->client compression algorithms. */
3751 ssh2_pkt_addstring_start(ssh
);
3752 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3753 const struct ssh_compress
*c
=
3754 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
3755 ssh2_pkt_addstring_str(ssh
, c
->name
);
3756 if (i
< lenof(compressions
))
3757 ssh2_pkt_addstring_str(ssh
, ",");
3759 /* List client->server languages. Empty list. */
3760 ssh2_pkt_addstring_start(ssh
);
3761 /* List server->client languages. Empty list. */
3762 ssh2_pkt_addstring_start(ssh
);
3763 /* First KEX packet does _not_ follow, because we're not that brave. */
3764 ssh2_pkt_addbool(ssh
, FALSE
);
3766 ssh2_pkt_adduint32(ssh
, 0);
3769 ssh
->exhash
= ssh
->exhashbase
;
3770 sha_string(&ssh
->exhash
, ssh
->pktout
.data
+ 5, ssh
->pktout
.length
- 5);
3776 sha_string(&ssh
->exhash
, ssh
->pktin
.data
+ 5, ssh
->pktin
.length
- 5);
3779 * Now examine the other side's KEXINIT to see what we're up
3786 if (ssh
->pktin
.type
!= SSH2_MSG_KEXINIT
) {
3787 bombout(("expected key exchange packet from server"));
3791 ssh
->hostkey
= NULL
;
3792 s
->cscipher_tobe
= NULL
;
3793 s
->sccipher_tobe
= NULL
;
3794 s
->csmac_tobe
= NULL
;
3795 s
->scmac_tobe
= NULL
;
3796 s
->cscomp_tobe
= NULL
;
3797 s
->sccomp_tobe
= NULL
;
3798 ssh
->pktin
.savedpos
+= 16; /* skip garbage cookie */
3799 ssh2_pkt_getstring(ssh
, &str
, &len
); /* key exchange algorithms */
3800 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3801 if (kex_algs
[i
] == &ssh_diffiehellman_gex
&&
3802 (ssh
->remote_bugs
& BUG_SSH2_DH_GEX
))
3804 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
3805 ssh
->kex
= kex_algs
[i
];
3809 ssh2_pkt_getstring(ssh
, &str
, &len
); /* host key algorithms */
3810 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3811 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
3812 ssh
->hostkey
= hostkey_algs
[i
];
3816 ssh2_pkt_getstring(ssh
, &str
, &len
); /* client->server cipher */
3818 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
3819 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
3823 for (j
= 0; j
< c
->nciphers
; j
++) {
3824 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3825 s
->cscipher_tobe
= c
->list
[j
];
3830 if (s
->cscipher_tobe
) {
3832 askcipher(s
->cscipher_tobe
->name
, 1);
3836 if (!s
->cscipher_tobe
) {
3837 bombout(("Couldn't agree a client-to-server cipher (available: %s)", str
));
3841 ssh2_pkt_getstring(ssh
, &str
, &len
); /* server->client cipher */
3843 for (i
= 0; i
< s
->n_preferred_ciphers
; i
++) {
3844 const struct ssh2_ciphers
*c
= s
->preferred_ciphers
[i
];
3848 for (j
= 0; j
< c
->nciphers
; j
++) {
3849 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3850 s
->sccipher_tobe
= c
->list
[j
];
3855 if (s
->sccipher_tobe
) {
3857 askcipher(s
->sccipher_tobe
->name
, 2);
3861 if (!s
->sccipher_tobe
) {
3862 bombout(("Couldn't agree a server-to-client cipher (available: %s)", str
));
3866 ssh2_pkt_getstring(ssh
, &str
, &len
); /* client->server mac */
3867 for (i
= 0; i
< s
->nmacs
; i
++) {
3868 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
3869 s
->csmac_tobe
= s
->maclist
[i
];
3873 ssh2_pkt_getstring(ssh
, &str
, &len
); /* server->client mac */
3874 for (i
= 0; i
< s
->nmacs
; i
++) {
3875 if (in_commasep_string(s
->maclist
[i
]->name
, str
, len
)) {
3876 s
->scmac_tobe
= s
->maclist
[i
];
3880 ssh2_pkt_getstring(ssh
, &str
, &len
); /* client->server compression */
3881 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3882 const struct ssh_compress
*c
=
3883 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
3884 if (in_commasep_string(c
->name
, str
, len
)) {
3889 ssh2_pkt_getstring(ssh
, &str
, &len
); /* server->client compression */
3890 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3891 const struct ssh_compress
*c
=
3892 i
== 0 ? s
->preferred_comp
: compressions
[i
- 1];
3893 if (in_commasep_string(c
->name
, str
, len
)) {
3901 * Work out the number of bits of key we will need from the key
3902 * exchange. We start with the maximum key length of either
3908 csbits
= s
->cscipher_tobe
->keylen
;
3909 scbits
= s
->sccipher_tobe
->keylen
;
3910 s
->nbits
= (csbits
> scbits ? csbits
: scbits
);
3912 /* The keys only have 160-bit entropy, since they're based on
3913 * a SHA-1 hash. So cap the key size at 160 bits. */
3918 * If we're doing Diffie-Hellman group exchange, start by
3919 * requesting a group.
3921 if (ssh
->kex
== &ssh_diffiehellman_gex
) {
3922 logevent("Doing Diffie-Hellman group exchange");
3923 ssh
->pkt_ctx
|= SSH2_PKTCTX_DHGEX
;
3925 * Work out how big a DH group we will need to allow that
3928 s
->pbits
= 512 << ((s
->nbits
- 1) / 64);
3929 ssh2_pkt_init(ssh
, SSH2_MSG_KEX_DH_GEX_REQUEST
);
3930 ssh2_pkt_adduint32(ssh
, s
->pbits
);
3934 if (ssh
->pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
3935 bombout(("expected key exchange group packet from server"));
3938 s
->p
= ssh2_pkt_getmp(ssh
);
3939 s
->g
= ssh2_pkt_getmp(ssh
);
3940 dh_setup_group(s
->p
, s
->g
);
3941 s
->kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
3942 s
->kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
3944 ssh
->pkt_ctx
|= SSH2_PKTCTX_DHGROUP1
;
3946 s
->kex_init_value
= SSH2_MSG_KEXDH_INIT
;
3947 s
->kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
3950 logevent("Doing Diffie-Hellman key exchange");
3952 * Now generate and send e for Diffie-Hellman.
3954 s
->e
= dh_create_e(s
->nbits
* 2);
3955 ssh2_pkt_init(ssh
, s
->kex_init_value
);
3956 ssh2_pkt_addmp(ssh
, s
->e
);
3960 if (ssh
->pktin
.type
!= s
->kex_reply_value
) {
3961 bombout(("expected key exchange reply packet from server"));
3964 ssh2_pkt_getstring(ssh
, &s
->hostkeydata
, &s
->hostkeylen
);
3965 s
->f
= ssh2_pkt_getmp(ssh
);
3966 ssh2_pkt_getstring(ssh
, &s
->sigdata
, &s
->siglen
);
3968 s
->K
= dh_find_K(s
->f
);
3970 sha_string(&ssh
->exhash
, s
->hostkeydata
, s
->hostkeylen
);
3971 if (ssh
->kex
== &ssh_diffiehellman_gex
) {
3972 sha_uint32(&ssh
->exhash
, s
->pbits
);
3973 sha_mpint(&ssh
->exhash
, s
->p
);
3974 sha_mpint(&ssh
->exhash
, s
->g
);
3976 sha_mpint(&ssh
->exhash
, s
->e
);
3977 sha_mpint(&ssh
->exhash
, s
->f
);
3978 sha_mpint(&ssh
->exhash
, s
->K
);
3979 SHA_Final(&ssh
->exhash
, s
->exchange_hash
);
3984 debug(("Exchange hash is:\n"));
3985 dmemdump(s
->exchange_hash
, 20);
3988 s
->hkey
= ssh
->hostkey
->newkey(s
->hostkeydata
, s
->hostkeylen
);
3990 !ssh
->hostkey
->verifysig(s
->hkey
, s
->sigdata
, s
->siglen
,
3991 s
->exchange_hash
, 20)) {
3992 bombout(("Server's host key did not match the signature supplied"));
3997 * Authenticate remote host: verify host key. (We've already
3998 * checked the signature of the exchange hash.)
4000 s
->keystr
= ssh
->hostkey
->fmtkey(s
->hkey
);
4001 s
->fingerprint
= ssh
->hostkey
->fingerprint(s
->hkey
);
4002 verify_ssh_host_key(ssh
->savedhost
, ssh
->savedport
, ssh
->hostkey
->keytype
,
4003 s
->keystr
, s
->fingerprint
);
4004 if (s
->first_kex
) { /* don't bother logging this in rekeys */
4005 logevent("Host key fingerprint is:");
4006 logevent(s
->fingerprint
);
4008 sfree(s
->fingerprint
);
4010 ssh
->hostkey
->freekey(s
->hkey
);
4013 * Send SSH2_MSG_NEWKEYS.
4015 ssh2_pkt_init(ssh
, SSH2_MSG_NEWKEYS
);
4019 * Expect SSH2_MSG_NEWKEYS from server.
4022 if (ssh
->pktin
.type
!= SSH2_MSG_NEWKEYS
) {
4023 bombout(("expected new-keys packet from server"));
4028 * Create and initialise session keys.
4030 if (ssh
->cs_cipher_ctx
)
4031 ssh
->cscipher
->free_context(ssh
->cs_cipher_ctx
);
4032 ssh
->cscipher
= s
->cscipher_tobe
;
4033 ssh
->cs_cipher_ctx
= ssh
->cscipher
->make_context();
4034 if (ssh
->sc_cipher_ctx
)
4035 ssh
->sccipher
->free_context(ssh
->sc_cipher_ctx
);
4036 ssh
->sccipher
= s
->sccipher_tobe
;
4037 ssh
->sc_cipher_ctx
= ssh
->sccipher
->make_context();
4038 ssh
->csmac
= s
->csmac_tobe
;
4039 ssh
->scmac
= s
->scmac_tobe
;
4040 ssh
->cscomp
= s
->cscomp_tobe
;
4041 ssh
->sccomp
= s
->sccomp_tobe
;
4042 ssh
->cscomp
->compress_init();
4043 ssh
->sccomp
->decompress_init();
4045 * Set IVs after keys. Here we use the exchange hash from the
4046 * _first_ key exchange.
4049 unsigned char keyspace
[40];
4051 memcpy(ssh
->v2_session_id
, s
->exchange_hash
,
4052 sizeof(s
->exchange_hash
));
4053 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'C',keyspace
);
4054 ssh
->cscipher
->setkey(ssh
->cs_cipher_ctx
, keyspace
);
4055 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'D',keyspace
);
4056 ssh
->sccipher
->setkey(ssh
->sc_cipher_ctx
, keyspace
);
4057 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'A',keyspace
);
4058 ssh
->cscipher
->setiv(ssh
->cs_cipher_ctx
, keyspace
);
4059 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'B',keyspace
);
4060 ssh
->sccipher
->setiv(ssh
->sc_cipher_ctx
, keyspace
);
4061 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'E',keyspace
);
4062 ssh
->csmac
->setcskey(keyspace
);
4063 ssh2_mkkey(ssh
,s
->K
,s
->exchange_hash
,ssh
->v2_session_id
,'F',keyspace
);
4064 ssh
->scmac
->setsckey(keyspace
);
4068 sprintf(buf
, "Initialised %.200s client->server encryption",
4069 ssh
->cscipher
->text_name
);
4071 sprintf(buf
, "Initialised %.200s server->client encryption",
4072 ssh
->sccipher
->text_name
);
4078 * If this is the first key exchange phase, we must pass the
4079 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
4080 * wants to see it but because it will need time to initialise
4081 * itself before it sees an actual packet. In subsequent key
4082 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
4083 * it would only confuse the layer above.
4085 if (!s
->first_kex
) {
4091 * Now we're encrypting. Begin returning 1 to the protocol main
4092 * function so that other things can run on top of the
4093 * transport. If we ever see a KEXINIT, we must go back to the
4096 while (!(ispkt
&& ssh
->pktin
.type
== SSH2_MSG_KEXINIT
)) {
4099 logevent("Server initiated key re-exchange");
4100 goto begin_key_exchange
;
4106 * Add data to an SSH2 channel output buffer.
4108 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
4111 bufchain_add(&c
->v
.v2
.outbuffer
, buf
, len
);
4115 * Attempt to send data on an SSH2 channel.
4117 static int ssh2_try_send(struct ssh_channel
*c
)
4121 while (c
->v
.v2
.remwindow
> 0 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0) {
4124 bufchain_prefix(&c
->v
.v2
.outbuffer
, &data
, &len
);
4125 if ((unsigned)len
> c
->v
.v2
.remwindow
)
4126 len
= c
->v
.v2
.remwindow
;
4127 if ((unsigned)len
> c
->v
.v2
.remmaxpkt
)
4128 len
= c
->v
.v2
.remmaxpkt
;
4129 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_DATA
);
4130 ssh2_pkt_adduint32(ssh
, c
->remoteid
);
4131 ssh2_pkt_addstring_start(ssh
);
4132 ssh2_pkt_addstring_data(ssh
, data
, len
);
4134 bufchain_consume(&c
->v
.v2
.outbuffer
, len
);
4135 c
->v
.v2
.remwindow
-= len
;
4139 * After having sent as much data as we can, return the amount
4142 return bufchain_size(&c
->v
.v2
.outbuffer
);
4146 * Potentially enlarge the window on an SSH2 channel.
4148 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
)
4153 * Never send WINDOW_ADJUST for a channel that the remote side
4154 * already thinks it's closed; there's no point, since it won't
4155 * be sending any more data anyway.
4160 if (newwin
> c
->v
.v2
.locwindow
) {
4161 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4162 ssh2_pkt_adduint32(ssh
, c
->remoteid
);
4163 ssh2_pkt_adduint32(ssh
, newwin
- c
->v
.v2
.locwindow
);
4165 c
->v
.v2
.locwindow
= newwin
;
4170 * Handle the SSH2 userauth and connection layers.
4172 static void do_ssh2_authconn(Ssh ssh
, unsigned char *in
, int inlen
, int ispkt
)
4174 struct do_ssh2_authconn_state
{
4176 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
,
4178 AUTH_KEYBOARD_INTERACTIVE
4182 AUTH_TYPE_PUBLICKEY
,
4183 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
4184 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
4186 AUTH_TYPE_KEYBOARD_INTERACTIVE
,
4187 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
4189 int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
4190 int tried_pubkey_config
, tried_agent
, tried_keyb_inter
;
4191 int kbd_inter_running
;
4193 int num_prompts
, curr_prompt
, echo
;
4198 void *publickey_blob
;
4199 int publickey_bloblen
;
4200 unsigned char request
[5], *response
, *p
;
4204 char *pkblob
, *alg
, *commentp
;
4205 int pklen
, alglen
, commentlen
;
4206 int siglen
, retlen
, len
;
4207 char *q
, *agentreq
, *ret
;
4210 crState(do_ssh2_authconn_state
);
4212 crBegin(ssh
->do_ssh2_authconn_crstate
);
4215 * Request userauth protocol, and await a response to it.
4217 ssh2_pkt_init(ssh
, SSH2_MSG_SERVICE_REQUEST
);
4218 ssh2_pkt_addstring(ssh
, "ssh-userauth");
4220 crWaitUntilV(ispkt
);
4221 if (ssh
->pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
4222 bombout(("Server refused user authentication protocol"));
4227 * We repeat this whole loop, including the username prompt,
4228 * until we manage a successful authentication. If the user
4229 * types the wrong _password_, they can be sent back to the
4230 * beginning to try another username, if this is configured on.
4231 * (If they specify a username in the config, they are never
4232 * asked, even if they do give a wrong password.)
4234 * I think this best serves the needs of
4236 * - the people who have no configuration, no keys, and just
4237 * want to try repeated (username,password) pairs until they
4238 * type both correctly
4240 * - people who have keys and configuration but occasionally
4241 * need to fall back to passwords
4243 * - people with a key held in Pageant, who might not have
4244 * logged in to a particular machine before; so they want to
4245 * type a username, and then _either_ their key will be
4246 * accepted, _or_ they will type a password. If they mistype
4247 * the username they will want to be able to get back and
4250 s
->username
[0] = '\0';
4251 s
->got_username
= FALSE
;
4256 if (s
->got_username
&& !cfg
.change_username
) {
4258 * We got a username last time round this loop, and
4259 * with change_username turned off we don't try to get
4262 } else if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
4263 if (ssh_get_line
&& !ssh_getline_pw_only
) {
4264 if (!ssh_get_line("login as: ",
4265 s
->username
, sizeof(s
->username
), FALSE
)) {
4267 * get_line failed to get a username.
4270 logevent("No username provided. Abandoning session.");
4271 ssh
->state
= SSH_STATE_CLOSED
;
4275 int ret
; /* need not be saved across crReturn */
4276 c_write_str(ssh
, "login as: ");
4278 setup_userpass_input(ssh
, s
->username
, sizeof(s
->username
), 1);
4280 crWaitUntilV(!ispkt
);
4281 ret
= process_userpass_input(ssh
, in
, inlen
);
4286 c_write_str(ssh
, "\r\n");
4287 s
->username
[strcspn(s
->username
, "\n\r")] = '\0';
4290 strncpy(s
->username
, cfg
.username
, sizeof(s
->username
));
4291 s
->username
[sizeof(s
->username
)-1] = '\0';
4292 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
4293 sprintf(stuff
, "Using username \"%s\".\r\n", s
->username
);
4294 c_write_str(ssh
, stuff
);
4297 s
->got_username
= TRUE
;
4300 * Send an authentication request using method "none": (a)
4301 * just in case it succeeds, and (b) so that we know what
4302 * authentication methods we can usefully try next.
4304 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4306 ssh2_pkt_init(ssh
, SSH2_MSG_USERAUTH_REQUEST
);
4307 ssh2_pkt_addstring(ssh
, s
->username
);
4308 ssh2_pkt_addstring(ssh
, "ssh-connection");/* service requested */
4309 ssh2_pkt_addstring(ssh
, "none"); /* method */
4311 s
->type
= AUTH_TYPE_NONE
;
4313 s
->we_are_in
= FALSE
;
4315 s
->tried_pubkey_config
= FALSE
;
4316 s
->tried_agent
= FALSE
;
4317 s
->tried_keyb_inter
= FALSE
;
4318 s
->kbd_inter_running
= FALSE
;
4319 /* Load the pub half of cfg.keyfile so we notice if it's in Pageant */
4322 logeventf("Reading private key file \"%.150s\"", cfg
.keyfile
);
4323 keytype
= key_type(cfg
.keyfile
);
4324 if (keytype
== SSH_KEYTYPE_SSH2
) {
4326 ssh2_userkey_loadpub(cfg
.keyfile
, NULL
,
4327 &s
->publickey_bloblen
);
4330 logeventf("Unable to use this key file (%s)",
4331 key_type_to_str(keytype
));
4332 sprintf(msgbuf
, "Unable to use key file \"%.150s\" (%s)\r\n",
4333 cfg
.keyfile
, key_type_to_str(keytype
));
4334 c_write_str(ssh
, msgbuf
);
4335 s
->publickey_blob
= NULL
;
4338 s
->publickey_blob
= NULL
;
4342 * Wait for the result of the last authentication request.
4345 crWaitUntilV(ispkt
);
4346 while (ssh
->pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
4350 * Don't show the banner if we're operating in
4351 * non-verbose non-interactive mode. (It's probably
4352 * a script, which means nobody will read the
4353 * banner _anyway_, and moreover the printing of
4354 * the banner will screw up processing on the
4355 * output of (say) plink.)
4357 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
4358 ssh2_pkt_getstring(ssh
, &banner
, &size
);
4360 c_write_untrusted(ssh
, banner
, size
);
4362 crWaitUntilV(ispkt
);
4364 if (ssh
->pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
4365 logevent("Access granted");
4366 s
->we_are_in
= TRUE
;
4370 if (s
->kbd_inter_running
&&
4371 ssh
->pktin
.type
== SSH2_MSG_USERAUTH_INFO_REQUEST
) {
4373 * This is either a further set-of-prompts packet
4374 * in keyboard-interactive authentication, or it's
4375 * the same one and we came back here with `gotit'
4376 * set. In the former case, we must reset the
4377 * curr_prompt variable.
4381 } else if (ssh
->pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
4382 bombout(("Strange packet received during authentication: type %d",
4390 * OK, we're now sitting on a USERAUTH_FAILURE message, so
4391 * we can look at the string in it and know what we can
4392 * helpfully try next.
4394 if (ssh
->pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
) {
4397 ssh2_pkt_getstring(ssh
, &methods
, &methlen
);
4398 s
->kbd_inter_running
= FALSE
;
4399 if (!ssh2_pkt_getbool(ssh
)) {
4401 * We have received an unequivocal Access
4402 * Denied. This can translate to a variety of
4405 * - if we'd just tried "none" authentication,
4406 * it's not worth printing anything at all
4408 * - if we'd just tried a public key _offer_,
4409 * the message should be "Server refused our
4410 * key" (or no message at all if the key
4411 * came from Pageant)
4413 * - if we'd just tried anything else, the
4414 * message really should be "Access denied".
4416 * Additionally, if we'd just tried password
4417 * authentication, we should break out of this
4418 * whole loop so as to go back to the username
4421 if (s
->type
== AUTH_TYPE_NONE
) {
4423 } else if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
4424 s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
4425 if (s
->type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
4426 c_write_str(ssh
, "Server refused our key\r\n");
4427 logevent("Server refused public key");
4428 } else if (s
->type
==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
) {
4429 /* server declined keyboard-interactive; ignore */
4431 c_write_str(ssh
, "Access denied\r\n");
4432 logevent("Access denied");
4433 if (s
->type
== AUTH_TYPE_PASSWORD
) {
4434 s
->we_are_in
= FALSE
;
4439 c_write_str(ssh
, "Further authentication required\r\n");
4440 logevent("Further authentication required");
4444 in_commasep_string("publickey", methods
, methlen
);
4446 in_commasep_string("password", methods
, methlen
);
4447 s
->can_keyb_inter
= cfg
.try_ki_auth
&&
4448 in_commasep_string("keyboard-interactive", methods
, methlen
);
4452 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4455 * Most password/passphrase prompts will be
4456 * non-echoing, so we set this to 0 by default.
4457 * Exception is that some keyboard-interactive prompts
4458 * can be echoing, in which case we'll set this to 1.
4462 if (!s
->method
&& s
->can_pubkey
&&
4463 agent_exists() && !s
->tried_agent
) {
4465 * Attempt public-key authentication using Pageant.
4470 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4471 ssh
->pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
4473 s
->tried_agent
= TRUE
;
4475 logevent("Pageant is running. Requesting keys.");
4477 /* Request the keys held by the agent. */
4478 PUT_32BIT(s
->request
, 1);
4479 s
->request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
4480 agent_query(s
->request
, 5, &r
, &s
->responselen
);
4481 s
->response
= (unsigned char *) r
;
4482 if (s
->response
&& s
->responselen
>= 5 &&
4483 s
->response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
4484 s
->p
= s
->response
+ 5;
4485 s
->nkeys
= GET_32BIT(s
->p
);
4489 sprintf(buf
, "Pageant has %d SSH2 keys", s
->nkeys
);
4492 for (s
->keyi
= 0; s
->keyi
< s
->nkeys
; s
->keyi
++) {
4497 sprintf(buf
, "Trying Pageant key #%d", s
->keyi
);
4500 s
->pklen
= GET_32BIT(s
->p
);
4502 if (s
->publickey_blob
&&
4503 s
->pklen
== s
->publickey_bloblen
&&
4504 !memcmp(s
->p
, s
->publickey_blob
,
4505 s
->publickey_bloblen
)) {
4506 logevent("This key matches configured key file");
4507 s
->tried_pubkey_config
= 1;
4511 s
->alglen
= GET_32BIT(s
->pkblob
);
4512 s
->alg
= s
->pkblob
+ 4;
4513 s
->commentlen
= GET_32BIT(s
->p
);
4516 s
->p
+= s
->commentlen
;
4517 ssh2_pkt_init(ssh
, SSH2_MSG_USERAUTH_REQUEST
);
4518 ssh2_pkt_addstring(ssh
, s
->username
);
4519 ssh2_pkt_addstring(ssh
, "ssh-connection"); /* service requested */
4520 ssh2_pkt_addstring(ssh
, "publickey"); /* method */
4521 ssh2_pkt_addbool(ssh
, FALSE
); /* no signature included */
4522 ssh2_pkt_addstring_start(ssh
);
4523 ssh2_pkt_addstring_data(ssh
, s
->alg
, s
->alglen
);
4524 ssh2_pkt_addstring_start(ssh
);
4525 ssh2_pkt_addstring_data(ssh
, s
->pkblob
, s
->pklen
);
4528 crWaitUntilV(ispkt
);
4529 if (ssh
->pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
4530 logevent("Key refused");
4534 if (flags
& FLAG_VERBOSE
) {
4535 c_write_str(ssh
, "Authenticating with "
4537 c_write(ssh
, s
->commentp
, s
->commentlen
);
4538 c_write_str(ssh
, "\" from agent\r\n");
4542 * Server is willing to accept the key.
4543 * Construct a SIGN_REQUEST.
4545 ssh2_pkt_init(ssh
, SSH2_MSG_USERAUTH_REQUEST
);
4546 ssh2_pkt_addstring(ssh
, s
->username
);
4547 ssh2_pkt_addstring(ssh
, "ssh-connection"); /* service requested */
4548 ssh2_pkt_addstring(ssh
, "publickey"); /* method */
4549 ssh2_pkt_addbool(ssh
, TRUE
);
4550 ssh2_pkt_addstring_start(ssh
);
4551 ssh2_pkt_addstring_data(ssh
, s
->alg
, s
->alglen
);
4552 ssh2_pkt_addstring_start(ssh
);
4553 ssh2_pkt_addstring_data(ssh
, s
->pkblob
, s
->pklen
);
4555 s
->siglen
= ssh
->pktout
.length
- 5 + 4 + 20;
4556 s
->len
= 1; /* message type */
4557 s
->len
+= 4 + s
->pklen
; /* key blob */
4558 s
->len
+= 4 + s
->siglen
; /* data to sign */
4559 s
->len
+= 4; /* flags */
4560 s
->agentreq
= smalloc(4 + s
->len
);
4561 PUT_32BIT(s
->agentreq
, s
->len
);
4562 s
->q
= s
->agentreq
+ 4;
4563 *s
->q
++ = SSH2_AGENTC_SIGN_REQUEST
;
4564 PUT_32BIT(s
->q
, s
->pklen
);
4566 memcpy(s
->q
, s
->pkblob
, s
->pklen
);
4568 PUT_32BIT(s
->q
, s
->siglen
);
4570 /* Now the data to be signed... */
4571 PUT_32BIT(s
->q
, 20);
4573 memcpy(s
->q
, ssh
->v2_session_id
, 20);
4575 memcpy(s
->q
, ssh
->pktout
.data
+ 5,
4576 ssh
->pktout
.length
- 5);
4577 s
->q
+= ssh
->pktout
.length
- 5;
4578 /* And finally the (zero) flags word. */
4580 agent_query(s
->agentreq
, s
->len
+ 4, &vret
, &s
->retlen
);
4584 if (s
->ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
4585 logevent("Sending Pageant's response");
4586 ssh2_add_sigblob(ssh
, s
->pkblob
, s
->pklen
,
4588 GET_32BIT(s
->ret
+ 5));
4594 ("Pageant failed to answer challenge");
4604 if (!s
->method
&& s
->can_pubkey
&& s
->publickey_blob
4605 && !s
->tried_pubkey_config
) {
4606 unsigned char *pub_blob
;
4607 char *algorithm
, *comment
;
4610 s
->tried_pubkey_config
= TRUE
;
4612 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4613 ssh
->pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
4616 * Try the public key supplied in the configuration.
4618 * First, offer the public blob to see if the server is
4619 * willing to accept it.
4621 pub_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, &algorithm
,
4624 ssh2_pkt_init(ssh
, SSH2_MSG_USERAUTH_REQUEST
);
4625 ssh2_pkt_addstring(ssh
, s
->username
);
4626 ssh2_pkt_addstring(ssh
, "ssh-connection"); /* service requested */
4627 ssh2_pkt_addstring(ssh
, "publickey"); /* method */
4628 ssh2_pkt_addbool(ssh
, FALSE
); /* no signature included */
4629 ssh2_pkt_addstring(ssh
, algorithm
);
4630 ssh2_pkt_addstring_start(ssh
);
4631 ssh2_pkt_addstring_data(ssh
, pub_blob
, pub_blob_len
);
4633 logevent("Offered public key"); /* FIXME */
4635 crWaitUntilV(ispkt
);
4636 if (ssh
->pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
4638 s
->type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
4639 continue; /* key refused; give up on it */
4642 logevent("Offer of public key accepted");
4644 * Actually attempt a serious authentication using
4647 if (ssh2_userkey_encrypted(cfg
.keyfile
, &comment
)) {
4648 sprintf(s
->pwprompt
,
4649 "Passphrase for key \"%.100s\": ",
4655 c_write_str(ssh
, "Authenticating with public key \"");
4656 c_write_str(ssh
, comment
);
4657 c_write_str(ssh
, "\"\r\n");
4658 s
->method
= AUTH_PUBLICKEY_FILE
;
4662 if (!s
->method
&& s
->can_keyb_inter
&& !s
->tried_keyb_inter
) {
4663 s
->method
= AUTH_KEYBOARD_INTERACTIVE
;
4664 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4665 s
->tried_keyb_inter
= TRUE
;
4667 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4668 ssh
->pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
4670 ssh2_pkt_init(ssh
, SSH2_MSG_USERAUTH_REQUEST
);
4671 ssh2_pkt_addstring(ssh
, s
->username
);
4672 ssh2_pkt_addstring(ssh
, "ssh-connection"); /* service requested */
4673 ssh2_pkt_addstring(ssh
, "keyboard-interactive"); /* method */
4674 ssh2_pkt_addstring(ssh
, ""); /* lang */
4675 ssh2_pkt_addstring(ssh
, "");
4678 crWaitUntilV(ispkt
);
4679 if (ssh
->pktin
.type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
4680 if (ssh
->pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
)
4682 logevent("Keyboard-interactive authentication refused");
4683 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
;
4687 s
->kbd_inter_running
= TRUE
;
4691 if (s
->kbd_inter_running
) {
4692 s
->method
= AUTH_KEYBOARD_INTERACTIVE
;
4693 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4694 s
->tried_keyb_inter
= TRUE
;
4696 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4697 ssh
->pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
4699 if (s
->curr_prompt
== 0) {
4701 * We've got a fresh USERAUTH_INFO_REQUEST.
4702 * Display header data, and start going through
4705 char *name
, *inst
, *lang
;
4706 int name_len
, inst_len
, lang_len
;
4708 ssh2_pkt_getstring(ssh
, &name
, &name_len
);
4709 ssh2_pkt_getstring(ssh
, &inst
, &inst_len
);
4710 ssh2_pkt_getstring(ssh
, &lang
, &lang_len
);
4712 c_write_untrusted(ssh
, name
, name_len
);
4713 c_write_str(ssh
, "\r\n");
4716 c_write_untrusted(ssh
, inst
, inst_len
);
4717 c_write_str(ssh
, "\r\n");
4719 s
->num_prompts
= ssh2_pkt_getuint32(ssh
);
4723 * If there are prompts remaining in the packet,
4724 * display one and get a response.
4726 if (s
->curr_prompt
< s
->num_prompts
) {
4730 ssh2_pkt_getstring(ssh
, &prompt
, &prompt_len
);
4731 if (prompt_len
> 0) {
4732 strncpy(s
->pwprompt
, prompt
, sizeof(s
->pwprompt
));
4733 s
->pwprompt
[prompt_len
< sizeof(s
->pwprompt
) ?
4734 prompt_len
: sizeof(s
->pwprompt
)-1] = '\0';
4737 "<server failed to send prompt>: ");
4739 s
->echo
= ssh2_pkt_getbool(ssh
);
4745 if (!s
->method
&& s
->can_passwd
) {
4746 s
->method
= AUTH_PASSWORD
;
4747 ssh
->pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4748 ssh
->pkt_ctx
|= SSH2_PKTCTX_PASSWORD
;
4749 sprintf(s
->pwprompt
, "%.90s@%.90s's password: ", s
->username
,
4756 if (!ssh_get_line(s
->pwprompt
, s
->password
,
4757 sizeof(s
->password
), TRUE
)) {
4759 * get_line failed to get a password (for
4760 * example because one was supplied on the
4761 * command line which has already failed to
4764 ssh2_pkt_init(ssh
, SSH2_MSG_DISCONNECT
);
4765 ssh2_pkt_adduint32(ssh
,SSH2_DISCONNECT_BY_APPLICATION
);
4766 ssh2_pkt_addstring(ssh
, "No more passwords available"
4768 ssh2_pkt_addstring(ssh
, "en"); /* language tag */
4770 logevent("Unable to authenticate");
4771 connection_fatal("Unable to authenticate");
4772 ssh
->state
= SSH_STATE_CLOSED
;
4776 int ret
; /* need not be saved across crReturn */
4777 c_write_untrusted(ssh
, s
->pwprompt
, strlen(s
->pwprompt
));
4780 setup_userpass_input(ssh
, s
->password
,
4781 sizeof(s
->password
), s
->echo
);
4783 crWaitUntilV(!ispkt
);
4784 ret
= process_userpass_input(ssh
, in
, inlen
);
4788 c_write_str(ssh
, "\r\n");
4792 if (s
->method
== AUTH_PUBLICKEY_FILE
) {
4794 * We have our passphrase. Now try the actual authentication.
4796 struct ssh2_userkey
*key
;
4798 key
= ssh2_load_userkey(cfg
.keyfile
, s
->password
);
4799 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
4800 if (key
== SSH2_WRONG_PASSPHRASE
) {
4801 c_write_str(ssh
, "Wrong passphrase\r\n");
4802 s
->tried_pubkey_config
= FALSE
;
4804 c_write_str(ssh
, "Unable to load private key\r\n");
4805 s
->tried_pubkey_config
= TRUE
;
4807 /* Send a spurious AUTH_NONE to return to the top. */
4808 ssh2_pkt_init(ssh
, SSH2_MSG_USERAUTH_REQUEST
);
4809 ssh2_pkt_addstring(ssh
, s
->username
);
4810 ssh2_pkt_addstring(ssh
, "ssh-connection"); /* service requested */
4811 ssh2_pkt_addstring(ssh
, "none"); /* method */
4813 s
->type
= AUTH_TYPE_NONE
;
4815 unsigned char *pkblob
, *sigblob
, *sigdata
;
4816 int pkblob_len
, sigblob_len
, sigdata_len
;
4819 * We have loaded the private key and the server
4820 * has announced that it's willing to accept it.
4821 * Hallelujah. Generate a signature and send it.
4823 ssh2_pkt_init(ssh
, SSH2_MSG_USERAUTH_REQUEST
);
4824 ssh2_pkt_addstring(ssh
, s
->username
);
4825 ssh2_pkt_addstring(ssh
, "ssh-connection"); /* service requested */
4826 ssh2_pkt_addstring(ssh
, "publickey"); /* method */
4827 ssh2_pkt_addbool(ssh
, TRUE
);
4828 ssh2_pkt_addstring(ssh
, key
->alg
->name
);
4829 pkblob
= key
->alg
->public_blob(key
->data
, &pkblob_len
);
4830 ssh2_pkt_addstring_start(ssh
);
4831 ssh2_pkt_addstring_data(ssh
, pkblob
, pkblob_len
);
4834 * The data to be signed is:
4838 * followed by everything so far placed in the
4841 sigdata_len
= ssh
->pktout
.length
- 5 + 4 + 20;
4842 sigdata
= smalloc(sigdata_len
);
4843 PUT_32BIT(sigdata
, 20);
4844 memcpy(sigdata
+ 4, ssh
->v2_session_id
, 20);
4845 memcpy(sigdata
+ 24, ssh
->pktout
.data
+ 5,
4846 ssh
->pktout
.length
- 5);
4847 sigblob
= key
->alg
->sign(key
->data
, sigdata
,
4848 sigdata_len
, &sigblob_len
);
4849 ssh2_add_sigblob(ssh
, pkblob
, pkblob_len
,
4850 sigblob
, sigblob_len
);
4856 s
->type
= AUTH_TYPE_PUBLICKEY
;
4858 } else if (s
->method
== AUTH_PASSWORD
) {
4860 * We send the password packet lumped tightly together with
4861 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4862 * string long enough to make the total length of the two
4863 * packets constant. This should ensure that a passive
4864 * listener doing traffic analyis can't work out the length
4867 * For this to work, we need an assumption about the
4868 * maximum length of the password packet. I think 256 is
4869 * pretty conservative. Anyone using a password longer than
4870 * that probably doesn't have much to worry about from
4871 * people who find out how long their password is!
4873 ssh2_pkt_init(ssh
, SSH2_MSG_USERAUTH_REQUEST
);
4874 ssh2_pkt_addstring(ssh
, s
->username
);
4875 ssh2_pkt_addstring(ssh
, "ssh-connection"); /* service requested */
4876 ssh2_pkt_addstring(ssh
, "password");
4877 ssh2_pkt_addbool(ssh
, FALSE
);
4878 ssh2_pkt_addstring(ssh
, s
->password
);
4879 ssh2_pkt_defer(ssh
);
4881 * We'll include a string that's an exact multiple of the
4882 * cipher block size. If the cipher is NULL for some
4883 * reason, we don't do this trick at all because we gain
4886 if (ssh
->cscipher
) {
4889 stringlen
= (256 - ssh
->deferred_len
);
4890 stringlen
+= ssh
->cscipher
->blksize
- 1;
4891 stringlen
-= (stringlen
% ssh
->cscipher
->blksize
);
4894 * Temporarily disable actual compression,
4895 * so we can guarantee to get this string
4896 * exactly the length we want it. The
4897 * compression-disabling routine should
4898 * return an integer indicating how many
4899 * bytes we should adjust our string length
4902 stringlen
-= ssh
->cscomp
->disable_compression();
4904 ssh2_pkt_init(ssh
, SSH2_MSG_IGNORE
);
4905 ssh2_pkt_addstring_start(ssh
);
4906 for (i
= 0; i
< stringlen
; i
++) {
4907 char c
= (char) random_byte();
4908 ssh2_pkt_addstring_data(ssh
, &c
, 1);
4910 ssh2_pkt_defer(ssh
);
4912 ssh_pkt_defersend(ssh
);
4913 logevent("Sent password");
4914 s
->type
= AUTH_TYPE_PASSWORD
;
4915 } else if (s
->method
== AUTH_KEYBOARD_INTERACTIVE
) {
4916 if (s
->curr_prompt
== 0) {
4917 ssh2_pkt_init(ssh
, SSH2_MSG_USERAUTH_INFO_RESPONSE
);
4918 ssh2_pkt_adduint32(ssh
, s
->num_prompts
);
4920 if (s
->need_pw
) { /* only add pw if we just got one! */
4921 ssh2_pkt_addstring(ssh
, s
->password
);
4922 memset(s
->password
, 0, sizeof(s
->password
));
4925 if (s
->curr_prompt
>= s
->num_prompts
) {
4929 * If there are prompts remaining, we set
4930 * `gotit' so that we won't attempt to get
4931 * another packet. Then we go back round the
4932 * loop and will end up retrieving another
4933 * prompt out of the existing packet. Funky or
4938 s
->type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4940 c_write_str(ssh
, "No supported authentication methods"
4941 " left to try!\r\n");
4942 logevent("No supported authentications offered."
4944 ssh2_pkt_init(ssh
, SSH2_MSG_DISCONNECT
);
4945 ssh2_pkt_adduint32(ssh
, SSH2_DISCONNECT_BY_APPLICATION
);
4946 ssh2_pkt_addstring(ssh
, "No supported authentication"
4947 " methods available");
4948 ssh2_pkt_addstring(ssh
, "en"); /* language tag */
4950 ssh
->state
= SSH_STATE_CLOSED
;
4954 } while (!s
->we_are_in
);
4957 * Now we're authenticated for the connection protocol. The
4958 * connection protocol will automatically have started at this
4959 * point; there's no need to send SERVICE_REQUEST.
4963 * So now create a channel with a session in it.
4965 ssh
->channels
= newtree234(ssh_channelcmp
);
4966 ssh
->mainchan
= smalloc(sizeof(struct ssh_channel
));
4967 ssh
->mainchan
->ssh
= ssh
;
4968 ssh
->mainchan
->localid
= alloc_channel_id(ssh
);
4969 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_OPEN
);
4970 ssh2_pkt_addstring(ssh
, "session");
4971 ssh2_pkt_adduint32(ssh
, ssh
->mainchan
->localid
);
4972 ssh
->mainchan
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
4973 ssh2_pkt_adduint32(ssh
, ssh
->mainchan
->v
.v2
.locwindow
);/* our window size */
4974 ssh2_pkt_adduint32(ssh
, 0x4000UL
); /* our max pkt size */
4976 crWaitUntilV(ispkt
);
4977 if (ssh
->pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
4978 bombout(("Server refused to open a session"));
4980 /* FIXME: error data comes back in FAILURE packet */
4982 if (ssh2_pkt_getuint32(ssh
) != ssh
->mainchan
->localid
) {
4983 bombout(("Server's channel confirmation cited wrong channel"));
4986 ssh
->mainchan
->remoteid
= ssh2_pkt_getuint32(ssh
);
4987 ssh
->mainchan
->type
= CHAN_MAINSESSION
;
4988 ssh
->mainchan
->closes
= 0;
4989 ssh
->mainchan
->v
.v2
.remwindow
= ssh2_pkt_getuint32(ssh
);
4990 ssh
->mainchan
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32(ssh
);
4991 bufchain_init(&ssh
->mainchan
->v
.v2
.outbuffer
);
4992 add234(ssh
->channels
, ssh
->mainchan
);
4993 logevent("Opened channel for session");
4996 * Potentially enable X11 forwarding.
4998 if (cfg
.x11_forward
) {
4999 char proto
[20], data
[64];
5000 logevent("Requesting X11 forwarding");
5001 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
5002 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_REQUEST
);
5003 ssh2_pkt_adduint32(ssh
, ssh
->mainchan
->remoteid
);
5004 ssh2_pkt_addstring(ssh
, "x11-req");
5005 ssh2_pkt_addbool(ssh
, 1); /* want reply */
5006 ssh2_pkt_addbool(ssh
, 0); /* many connections */
5007 ssh2_pkt_addstring(ssh
, proto
);
5008 ssh2_pkt_addstring(ssh
, data
);
5009 ssh2_pkt_adduint32(ssh
, 0); /* screen number */
5013 crWaitUntilV(ispkt
);
5014 if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
5015 unsigned i
= ssh2_pkt_getuint32(ssh
);
5016 struct ssh_channel
*c
;
5017 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5019 continue; /* nonexistent channel */
5020 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32(ssh
);
5022 } while (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
5024 if (ssh
->pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
5025 if (ssh
->pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
5026 bombout(("Unexpected response to X11 forwarding request:"
5027 " packet type %d", ssh
->pktin
.type
));
5030 logevent("X11 forwarding refused");
5032 logevent("X11 forwarding enabled");
5033 ssh
->X11_fwd_enabled
= TRUE
;
5038 * Enable port forwardings.
5043 int sport
,dport
,sserv
,dserv
;
5044 char sports
[256], dports
[256], host
[256];
5048 ssh
->rportfwds
= newtree234(ssh_rportcmp_ssh2
);
5049 /* Add port forwardings. */
5050 ssh
->portfwd_strptr
= cfg
.portfwd
;
5051 while (*ssh
->portfwd_strptr
) {
5052 type
= *ssh
->portfwd_strptr
++;
5054 while (*ssh
->portfwd_strptr
&& *ssh
->portfwd_strptr
!= '\t')
5055 sports
[n
++] = *ssh
->portfwd_strptr
++;
5057 if (*ssh
->portfwd_strptr
== '\t')
5058 ssh
->portfwd_strptr
++;
5060 while (*ssh
->portfwd_strptr
&& *ssh
->portfwd_strptr
!= ':')
5061 host
[n
++] = *ssh
->portfwd_strptr
++;
5063 if (*ssh
->portfwd_strptr
== ':')
5064 ssh
->portfwd_strptr
++;
5066 while (*ssh
->portfwd_strptr
)
5067 dports
[n
++] = *ssh
->portfwd_strptr
++;
5069 ssh
->portfwd_strptr
++;
5070 dport
= atoi(dports
);
5074 se
= getservbyname(dports
, NULL
);
5076 dport
= ntohs(se
->s_port
);
5079 "Service lookup failed for destination port \"%s\"",
5084 sport
= atoi(sports
);
5088 se
= getservbyname(sports
, NULL
);
5090 sport
= ntohs(se
->s_port
);
5093 "Service lookup failed for source port \"%s\"",
5098 if (sport
&& dport
) {
5100 pfd_addforward(host
, dport
, sport
);
5101 sprintf(buf
, "Local port %.*s%.*s%d%.*s forwarding to"
5102 " %s:%.*s%.*s%d%.*s",
5103 sserv ?
strlen(sports
) : 0, sports
,
5104 sserv
, "(", sport
, sserv
, ")",
5106 dserv ?
strlen(dports
) : 0, dports
,
5107 dserv
, "(", dport
, dserv
, ")");
5110 struct ssh_rportfwd
*pf
;
5111 pf
= smalloc(sizeof(*pf
));
5112 strcpy(pf
->dhost
, host
);
5115 if (add234(ssh
->rportfwds
, pf
) != pf
) {
5117 "Duplicate remote port forwarding to %s:%d",
5122 sprintf(buf
, "Requesting remote port %.*s%.*s%d%.*s"
5123 " forward to %s:%.*s%.*s%d%.*s",
5124 sserv ?
strlen(sports
) : 0, sports
,
5125 sserv
, "(", sport
, sserv
, ")",
5127 dserv ?
strlen(dports
) : 0, dports
,
5128 dserv
, "(", dport
, dserv
, ")");
5130 ssh2_pkt_init(ssh
, SSH2_MSG_GLOBAL_REQUEST
);
5131 ssh2_pkt_addstring(ssh
, "tcpip-forward");
5132 ssh2_pkt_addbool(ssh
, 1);/* want reply */
5133 if (cfg
.rport_acceptall
)
5134 ssh2_pkt_addstring(ssh
, "0.0.0.0");
5136 ssh2_pkt_addstring(ssh
, "127.0.0.1");
5137 ssh2_pkt_adduint32(ssh
, sport
);
5141 crWaitUntilV(ispkt
);
5142 if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
5143 unsigned i
= ssh2_pkt_getuint32(ssh
);
5144 struct ssh_channel
*c
;
5145 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5147 continue;/* nonexistent channel */
5148 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32(ssh
);
5150 } while (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
5152 if (ssh
->pktin
.type
!= SSH2_MSG_REQUEST_SUCCESS
) {
5153 if (ssh
->pktin
.type
!= SSH2_MSG_REQUEST_FAILURE
) {
5154 bombout(("Unexpected response to port "
5155 "forwarding request: packet type %d",
5159 logevent("Server refused this port forwarding");
5161 logevent("Remote port forwarding enabled");
5170 * Potentially enable agent forwarding.
5172 if (cfg
.agentfwd
&& agent_exists()) {
5173 logevent("Requesting OpenSSH-style agent forwarding");
5174 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_REQUEST
);
5175 ssh2_pkt_adduint32(ssh
, ssh
->mainchan
->remoteid
);
5176 ssh2_pkt_addstring(ssh
, "auth-agent-req@openssh.com");
5177 ssh2_pkt_addbool(ssh
, 1); /* want reply */
5181 crWaitUntilV(ispkt
);
5182 if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
5183 unsigned i
= ssh2_pkt_getuint32(ssh
);
5184 struct ssh_channel
*c
;
5185 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5187 continue; /* nonexistent channel */
5188 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32(ssh
);
5190 } while (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
5192 if (ssh
->pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
5193 if (ssh
->pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
5194 bombout(("Unexpected response to agent forwarding request:"
5195 " packet type %d", ssh
->pktin
.type
));
5198 logevent("Agent forwarding refused");
5200 logevent("Agent forwarding enabled");
5201 ssh
->agentfwd_enabled
= TRUE
;
5206 * Now allocate a pty for the session.
5209 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_REQUEST
);
5210 ssh2_pkt_adduint32(ssh
, ssh
->mainchan
->remoteid
); /* recipient channel */
5211 ssh2_pkt_addstring(ssh
, "pty-req");
5212 ssh2_pkt_addbool(ssh
, 1); /* want reply */
5213 ssh2_pkt_addstring(ssh
, cfg
.termtype
);
5214 ssh2_pkt_adduint32(ssh
, ssh
->term_width
);
5215 ssh2_pkt_adduint32(ssh
, ssh
->term_height
);
5216 ssh2_pkt_adduint32(ssh
, 0); /* pixel width */
5217 ssh2_pkt_adduint32(ssh
, 0); /* pixel height */
5218 ssh2_pkt_addstring_start(ssh
);
5219 ssh2_pkt_addstring_data(ssh
, "\0", 1); /* TTY_OP_END, no special options */
5221 ssh
->state
= SSH_STATE_INTERMED
;
5224 crWaitUntilV(ispkt
);
5225 if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
5226 unsigned i
= ssh2_pkt_getuint32(ssh
);
5227 struct ssh_channel
*c
;
5228 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5230 continue; /* nonexistent channel */
5231 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32(ssh
);
5233 } while (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
5235 if (ssh
->pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
5236 if (ssh
->pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
5237 bombout(("Unexpected response to pty request:"
5238 " packet type %d", ssh
->pktin
.type
));
5241 c_write_str(ssh
, "Server refused to allocate pty\r\n");
5242 ssh
->editing
= ssh
->echoing
= 1;
5244 logevent("Allocated pty");
5247 ssh
->editing
= ssh
->echoing
= 1;
5251 * Start a shell or a remote command. We may have to attempt
5252 * this twice if the config data has provided a second choice
5259 if (ssh
->fallback_cmd
) {
5260 subsys
= cfg
.ssh_subsys2
;
5261 cmd
= cfg
.remote_cmd_ptr2
;
5263 subsys
= cfg
.ssh_subsys
;
5264 cmd
= cfg
.remote_cmd_ptr
;
5267 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_REQUEST
);
5268 ssh2_pkt_adduint32(ssh
, ssh
->mainchan
->remoteid
); /* recipient channel */
5270 ssh2_pkt_addstring(ssh
, "subsystem");
5271 ssh2_pkt_addbool(ssh
, 1); /* want reply */
5272 ssh2_pkt_addstring(ssh
, cmd
);
5274 ssh2_pkt_addstring(ssh
, "exec");
5275 ssh2_pkt_addbool(ssh
, 1); /* want reply */
5276 ssh2_pkt_addstring(ssh
, cmd
);
5278 ssh2_pkt_addstring(ssh
, "shell");
5279 ssh2_pkt_addbool(ssh
, 1); /* want reply */
5283 crWaitUntilV(ispkt
);
5284 if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
5285 unsigned i
= ssh2_pkt_getuint32(ssh
);
5286 struct ssh_channel
*c
;
5287 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5289 continue; /* nonexistent channel */
5290 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32(ssh
);
5292 } while (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
5293 if (ssh
->pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
5294 if (ssh
->pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
5295 bombout(("Unexpected response to shell/command request:"
5296 " packet type %d", ssh
->pktin
.type
));
5300 * We failed to start the command. If this is the
5301 * fallback command, we really are finished; if it's
5302 * not, and if the fallback command exists, try falling
5303 * back to it before complaining.
5305 if (!ssh
->fallback_cmd
&& cfg
.remote_cmd_ptr2
!= NULL
) {
5306 logevent("Primary command failed; attempting fallback");
5307 ssh
->fallback_cmd
= TRUE
;
5310 bombout(("Server refused to start a shell/command"));
5313 logevent("Started a shell/command");
5318 ssh
->state
= SSH_STATE_SESSION
;
5319 if (ssh
->size_needed
)
5320 ssh_size(ssh
, ssh
->term_width
, ssh
->term_height
);
5321 if (ssh
->eof_needed
)
5322 ssh_special(ssh
, TS_EOF
);
5327 ldisc_send(NULL
, 0, 0); /* cause ldisc to notice changes */
5331 s
->try_send
= FALSE
;
5333 if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
5334 ssh
->pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
5337 unsigned i
= ssh2_pkt_getuint32(ssh
);
5338 struct ssh_channel
*c
;
5339 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5341 continue; /* nonexistent channel */
5342 if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
5343 ssh2_pkt_getuint32(ssh
) != SSH2_EXTENDED_DATA_STDERR
)
5344 continue; /* extended but not stderr */
5345 ssh2_pkt_getstring(ssh
, &data
, &length
);
5348 c
->v
.v2
.locwindow
-= length
;
5350 case CHAN_MAINSESSION
:
5352 from_backend(ssh
->frontend
, ssh
->pktin
.type
==
5353 SSH2_MSG_CHANNEL_EXTENDED_DATA
,
5357 bufsize
= x11_send(c
->u
.x11
.s
, data
, length
);
5360 bufsize
= pfd_send(c
->u
.pfd
.s
, data
, length
);
5363 while (length
> 0) {
5364 if (c
->u
.a
.lensofar
< 4) {
5365 int l
= min(4 - c
->u
.a
.lensofar
, length
);
5366 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
5370 c
->u
.a
.lensofar
+= l
;
5372 if (c
->u
.a
.lensofar
== 4) {
5374 4 + GET_32BIT(c
->u
.a
.msglen
);
5375 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
5376 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
5378 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
5380 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
5382 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
5386 c
->u
.a
.lensofar
+= l
;
5388 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
5389 void *reply
, *sentreply
;
5391 agent_query(c
->u
.a
.message
,
5392 c
->u
.a
.totallen
, &reply
,
5397 /* Fake SSH_AGENT_FAILURE. */
5398 sentreply
= "\0\0\0\1\5";
5401 ssh2_add_channel_data(c
, sentreply
, replylen
);
5405 sfree(c
->u
.a
.message
);
5406 c
->u
.a
.lensofar
= 0;
5413 * If we are not buffering too much data,
5414 * enlarge the window again at the remote side.
5416 if (bufsize
< OUR_V2_WINSIZE
)
5417 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
5419 } else if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
5420 unsigned i
= ssh2_pkt_getuint32(ssh
);
5421 struct ssh_channel
*c
;
5423 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5425 continue; /* nonexistent channel */
5427 if (c
->type
== CHAN_X11
) {
5429 * Remote EOF on an X11 channel means we should
5430 * wrap up and close the channel ourselves.
5432 x11_close(c
->u
.x11
.s
);
5434 } else if (c
->type
== CHAN_AGENT
) {
5436 } else if (c
->type
== CHAN_SOCKDATA
) {
5437 pfd_close(c
->u
.pfd
.s
);
5440 } else if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
5441 unsigned i
= ssh2_pkt_getuint32(ssh
);
5442 struct ssh_channel
*c
;
5444 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5445 if (!c
|| ((int)c
->remoteid
) == -1) {
5446 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
5447 c ?
"half-open" : "nonexistent", i
));
5449 /* Do pre-close processing on the channel. */
5451 case CHAN_MAINSESSION
:
5452 break; /* nothing to see here, move along */
5454 if (c
->u
.x11
.s
!= NULL
)
5455 x11_close(c
->u
.x11
.s
);
5462 if (c
->u
.pfd
.s
!= NULL
)
5463 pfd_close(c
->u
.pfd
.s
);
5467 if (c
->closes
== 0) {
5468 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_CLOSE
);
5469 ssh2_pkt_adduint32(ssh
, c
->remoteid
);
5472 del234(ssh
->channels
, c
);
5473 bufchain_clear(&c
->v
.v2
.outbuffer
);
5477 * See if that was the last channel left open.
5479 if (count234(ssh
->channels
) == 0) {
5482 * We used to send SSH_MSG_DISCONNECT here,
5483 * because I'd believed that _every_ conforming
5484 * SSH2 connection had to end with a disconnect
5485 * being sent by at least one side; apparently
5486 * I was wrong and it's perfectly OK to
5487 * unceremoniously slam the connection shut
5488 * when you're done, and indeed OpenSSH feels
5489 * this is more polite than sending a
5490 * DISCONNECT. So now we don't.
5492 logevent("All channels closed. Disconnecting");
5493 ssh2_pkt_init(ssh
, SSH2_MSG_DISCONNECT
);
5494 ssh2_pkt_adduint32(ssh
, SSH2_DISCONNECT_BY_APPLICATION
);
5495 ssh2_pkt_addstring(ssh
, "All open channels closed");
5496 ssh2_pkt_addstring(ssh
, "en"); /* language tag */
5499 ssh
->state
= SSH_STATE_CLOSED
;
5502 continue; /* remote sends close; ignore (FIXME) */
5503 } else if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
5504 unsigned i
= ssh2_pkt_getuint32(ssh
);
5505 struct ssh_channel
*c
;
5506 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5508 continue; /* nonexistent channel */
5509 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32(ssh
);
5511 } else if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
5512 unsigned i
= ssh2_pkt_getuint32(ssh
);
5513 struct ssh_channel
*c
;
5514 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5516 continue; /* nonexistent channel */
5517 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
5518 continue; /* dunno why they're confirming this */
5519 c
->remoteid
= ssh2_pkt_getuint32(ssh
);
5520 c
->type
= CHAN_SOCKDATA
;
5521 c
->v
.v2
.remwindow
= ssh2_pkt_getuint32(ssh
);
5522 c
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32(ssh
);
5524 pfd_confirm(c
->u
.pfd
.s
);
5527 * We have a pending close on this channel,
5528 * which we decided on before the server acked
5529 * the channel open. So now we know the
5530 * remoteid, we can close it again.
5532 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_CLOSE
);
5533 ssh2_pkt_adduint32(ssh
, c
->remoteid
);
5536 } else if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_OPEN_FAILURE
) {
5537 unsigned i
= ssh2_pkt_getuint32(ssh
);
5538 struct ssh_channel
*c
;
5539 c
= find234(ssh
->channels
, &i
, ssh_channelfind
);
5541 continue; /* nonexistent channel */
5542 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
5543 continue; /* dunno why they're failing this */
5545 logevent("Forwarded connection refused by server");
5547 pfd_close(c
->u
.pfd
.s
);
5549 del234(ssh
->channels
, c
);
5551 } else if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
5554 int typelen
, want_reply
;
5555 struct ssh_channel
*c
;
5557 localid
= ssh2_pkt_getuint32(ssh
);
5558 ssh2_pkt_getstring(ssh
, &type
, &typelen
);
5559 want_reply
= ssh2_pkt_getbool(ssh
);
5562 * First, check that the channel exists. Otherwise,
5563 * we can instantly disconnect with a rude message.
5565 c
= find234(ssh
->channels
, &localid
, ssh_channelfind
);
5568 sprintf(buf
, "Received channel request for nonexistent"
5569 " channel %d", localid
);
5571 ssh2_pkt_init(ssh
, SSH2_MSG_DISCONNECT
);
5572 ssh2_pkt_adduint32(ssh
, SSH2_DISCONNECT_BY_APPLICATION
);
5573 ssh2_pkt_addstring(ssh
, buf
);
5574 ssh2_pkt_addstring(ssh
, "en"); /* language tag */
5576 connection_fatal("%s", buf
);
5577 ssh
->state
= SSH_STATE_CLOSED
;
5582 * Having got the channel number, we now look at
5583 * the request type string to see if it's something
5586 if (typelen
== 11 && !memcmp(type
, "exit-status", 11) &&
5587 c
== ssh
->mainchan
) {
5588 /* We recognise "exit-status" on the primary channel. */
5590 ssh
->exitcode
= ssh2_pkt_getuint32(ssh
);
5591 sprintf(buf
, "Server sent command exit status %d",
5595 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_SUCCESS
);
5596 ssh2_pkt_adduint32(ssh
, c
->remoteid
);
5601 * This is a channel request we don't know
5602 * about, so we now either ignore the request
5603 * or respond with CHANNEL_FAILURE, depending
5607 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_FAILURE
);
5608 ssh2_pkt_adduint32(ssh
, c
->remoteid
);
5612 } else if (ssh
->pktin
.type
== SSH2_MSG_GLOBAL_REQUEST
) {
5614 int typelen
, want_reply
;
5616 ssh2_pkt_getstring(ssh
, &type
, &typelen
);
5617 want_reply
= ssh2_pkt_getbool(ssh
);
5620 * We currently don't support any global requests
5621 * at all, so we either ignore the request or
5622 * respond with REQUEST_FAILURE, depending on
5626 ssh2_pkt_init(ssh
, SSH2_MSG_REQUEST_FAILURE
);
5629 } else if (ssh
->pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
5633 struct ssh_channel
*c
;
5634 unsigned remid
, winsize
, pktsize
;
5635 ssh2_pkt_getstring(ssh
, &type
, &typelen
);
5636 c
= smalloc(sizeof(struct ssh_channel
));
5639 remid
= ssh2_pkt_getuint32(ssh
);
5640 winsize
= ssh2_pkt_getuint32(ssh
);
5641 pktsize
= ssh2_pkt_getuint32(ssh
);
5643 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
5644 if (!ssh
->X11_fwd_enabled
)
5645 error
= "X11 forwarding is not enabled";
5646 else if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) !=
5648 error
= "Unable to open an X11 connection";
5652 } else if (typelen
== 15 &&
5653 !memcmp(type
, "forwarded-tcpip", 15)) {
5654 struct ssh_rportfwd pf
, *realpf
;
5657 ssh2_pkt_getstring(ssh
, &dummy
, &dummylen
);/* skip address */
5658 pf
.sport
= ssh2_pkt_getuint32(ssh
);
5659 realpf
= find234(ssh
->rportfwds
, &pf
, NULL
);
5660 if (realpf
== NULL
) {
5661 error
= "Remote port is not recognised";
5663 char *e
= pfd_newconnect(&c
->u
.pfd
.s
, realpf
->dhost
,
5666 sprintf(buf
, "Received remote port open request for %s:%d",
5667 realpf
->dhost
, realpf
->dport
);
5670 sprintf(buf
, "Port open failed: %s", e
);
5672 error
= "Port open failed";
5674 logevent("Forwarded port opened successfully");
5675 c
->type
= CHAN_SOCKDATA
;
5678 } else if (typelen
== 22 &&
5679 !memcmp(type
, "auth-agent@openssh.com", 3)) {
5680 if (!ssh
->agentfwd_enabled
)
5681 error
= "Agent forwarding is not enabled";
5683 c
->type
= CHAN_AGENT
; /* identify channel type */
5684 c
->u
.a
.lensofar
= 0;
5687 error
= "Unsupported channel type requested";
5690 c
->remoteid
= remid
;
5692 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_OPEN_FAILURE
);
5693 ssh2_pkt_adduint32(ssh
, c
->remoteid
);
5694 ssh2_pkt_adduint32(ssh
, SSH2_OPEN_CONNECT_FAILED
);
5695 ssh2_pkt_addstring(ssh
, error
);
5696 ssh2_pkt_addstring(ssh
, "en"); /* language tag */
5700 c
->localid
= alloc_channel_id(ssh
);
5702 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
5703 c
->v
.v2
.remwindow
= winsize
;
5704 c
->v
.v2
.remmaxpkt
= pktsize
;
5705 bufchain_init(&c
->v
.v2
.outbuffer
);
5706 add234(ssh
->channels
, c
);
5707 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
5708 ssh2_pkt_adduint32(ssh
, c
->remoteid
);
5709 ssh2_pkt_adduint32(ssh
, c
->localid
);
5710 ssh2_pkt_adduint32(ssh
, c
->v
.v2
.locwindow
);
5711 ssh2_pkt_adduint32(ssh
, 0x4000UL
); /* our max pkt size */
5715 bombout(("Strange packet received: type %d", ssh
->pktin
.type
));
5720 * We have spare data. Add it to the channel buffer.
5722 ssh2_add_channel_data(ssh
->mainchan
, in
, inlen
);
5727 struct ssh_channel
*c
;
5729 * Try to send data on all channels if we can.
5731 for (i
= 0; NULL
!= (c
= index234(ssh
->channels
, i
)); i
++) {
5732 int bufsize
= ssh2_try_send(c
);
5735 case CHAN_MAINSESSION
:
5736 /* stdin need not receive an unthrottle
5737 * notification since it will be polled */
5740 x11_unthrottle(c
->u
.x11
.s
);
5743 /* agent sockets are request/response and need no
5744 * buffer management */
5747 pfd_unthrottle(c
->u
.pfd
.s
);
5759 * Handle the top-level SSH2 protocol.
5761 static void ssh2_protocol(Ssh ssh
, unsigned char *in
, int inlen
, int ispkt
)
5763 if (do_ssh2_transport(ssh
, in
, inlen
, ispkt
) == 0)
5765 do_ssh2_authconn(ssh
, in
, inlen
, ispkt
);
5769 * Called to set up the connection.
5771 * Returns an error message, or NULL on success.
5773 static char *ssh_init(void *frontend_handle
, void **backend_handle
,
5774 char *host
, int port
, char **realhost
, int nodelay
)
5779 ssh
= smalloc(sizeof(*ssh
));
5782 ssh
->v1_cipher_ctx
= NULL
;
5783 ssh
->cscipher
= NULL
;
5784 ssh
->cs_cipher_ctx
= NULL
;
5785 ssh
->sccipher
= NULL
;
5786 ssh
->sc_cipher_ctx
= NULL
;
5792 ssh
->hostkey
= NULL
;
5794 ssh
->state
= SSH_STATE_PREPACKET
;
5795 ssh
->size_needed
= FALSE
;
5796 ssh
->eof_needed
= FALSE
;
5798 static const struct Packet empty
= { 0, 0, NULL
, NULL
, 0 };
5799 ssh
->pktin
= ssh
->pktout
= empty
;
5801 ssh
->deferred_send_data
= NULL
;
5802 ssh
->deferred_len
= 0;
5803 ssh
->deferred_size
= 0;
5804 ssh
->fallback_cmd
= 0;
5806 ssh
->v2_outgoing_sequence
= 0;
5807 ssh
->ssh1_rdpkt_crstate
= 0;
5808 ssh
->ssh2_rdpkt_crstate
= 0;
5809 ssh
->do_ssh_init_crstate
= 0;
5810 ssh
->ssh_gotdata_crstate
= 0;
5811 ssh
->ssh1_protocol_crstate
= 0;
5812 ssh
->do_ssh1_login_crstate
= 0;
5813 ssh
->do_ssh2_transport_crstate
= 0;
5814 ssh
->do_ssh2_authconn_crstate
= 0;
5815 ssh
->do_ssh_init_state
= NULL
;
5816 ssh
->do_ssh1_login_state
= NULL
;
5817 ssh
->do_ssh2_transport_state
= NULL
;
5818 ssh
->do_ssh2_authconn_state
= NULL
;
5820 *backend_handle
= ssh
;
5823 if (crypto_startup() == 0)
5824 return "Microsoft high encryption pack not installed!";
5827 ssh
->frontend
= frontend_handle
;
5828 ssh
->term_width
= cfg
.width
;
5829 ssh
->term_height
= cfg
.height
;
5834 ssh
->v1_throttle_count
= 0;
5835 ssh
->overall_bufsize
= 0;
5836 ssh
->fallback_cmd
= 0;
5838 p
= connect_to_host(ssh
, host
, port
, realhost
, nodelay
);
5846 * Called to send data down the Telnet connection.
5848 static int ssh_send(void *handle
, char *buf
, int len
)
5850 Ssh ssh
= (Ssh
) handle
;
5852 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
5855 ssh
->protocol(ssh
, buf
, len
, 0);
5857 return ssh_sendbuffer(ssh
);
5861 * Called to query the current amount of buffered stdin data.
5863 static int ssh_sendbuffer(void *handle
)
5865 Ssh ssh
= (Ssh
) handle
;
5868 if (ssh
== NULL
|| ssh
->s
== NULL
|| ssh
->protocol
== NULL
)
5872 * If the SSH socket itself has backed up, add the total backup
5873 * size on that to any individual buffer on the stdin channel.
5876 if (ssh
->throttled_all
)
5877 override_value
= ssh
->overall_bufsize
;
5879 if (ssh
->version
== 1) {
5880 return override_value
;
5881 } else if (ssh
->version
== 2) {
5882 if (!ssh
->mainchan
|| ssh
->mainchan
->closes
> 0)
5883 return override_value
;
5885 return (override_value
+
5886 bufchain_size(&ssh
->mainchan
->v
.v2
.outbuffer
));
5893 * Called to set the size of the window from SSH's POV.
5895 static void ssh_size(void *handle
, int width
, int height
)
5897 Ssh ssh
= (Ssh
) handle
;
5899 ssh
->term_width
= width
;
5900 ssh
->term_height
= height
;
5902 switch (ssh
->state
) {
5903 case SSH_STATE_BEFORE_SIZE
:
5904 case SSH_STATE_PREPACKET
:
5905 case SSH_STATE_CLOSED
:
5906 break; /* do nothing */
5907 case SSH_STATE_INTERMED
:
5908 ssh
->size_needed
= TRUE
; /* buffer for later */
5910 case SSH_STATE_SESSION
:
5914 if (ssh
->version
== 1) {
5915 send_packet(ssh
, SSH1_CMSG_WINDOW_SIZE
,
5916 PKT_INT
, ssh
->term_height
,
5917 PKT_INT
, ssh
->term_width
,
5918 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
5920 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_REQUEST
);
5921 ssh2_pkt_adduint32(ssh
, ssh
->mainchan
->remoteid
);
5922 ssh2_pkt_addstring(ssh
, "window-change");
5923 ssh2_pkt_addbool(ssh
, 0);
5924 ssh2_pkt_adduint32(ssh
, ssh
->term_width
);
5925 ssh2_pkt_adduint32(ssh
, ssh
->term_height
);
5926 ssh2_pkt_adduint32(ssh
, 0);
5927 ssh2_pkt_adduint32(ssh
, 0);
5936 * Send Telnet special codes. TS_EOF is useful for `plink', so you
5937 * can send an EOF and collect resulting output (e.g. `plink
5940 static void ssh_special(void *handle
, Telnet_Special code
)
5942 Ssh ssh
= (Ssh
) handle
;
5944 if (code
== TS_EOF
) {
5945 if (ssh
->state
!= SSH_STATE_SESSION
) {
5947 * Buffer the EOF in case we are pre-SESSION, so we can
5948 * send it as soon as we reach SESSION.
5951 ssh
->eof_needed
= TRUE
;
5954 if (ssh
->version
== 1) {
5955 send_packet(ssh
, SSH1_CMSG_EOF
, PKT_END
);
5957 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_EOF
);
5958 ssh2_pkt_adduint32(ssh
, ssh
->mainchan
->remoteid
);
5961 logevent("Sent EOF message");
5962 } else if (code
== TS_PING
) {
5963 if (ssh
->state
== SSH_STATE_CLOSED
5964 || ssh
->state
== SSH_STATE_PREPACKET
) return;
5965 if (ssh
->version
== 1) {
5966 if (!(ssh
->remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
5967 send_packet(ssh
, SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
5969 ssh2_pkt_init(ssh
, SSH2_MSG_IGNORE
);
5970 ssh2_pkt_addstring_start(ssh
);
5978 void *new_sock_channel(void *handle
, Socket s
)
5980 Ssh ssh
= (Ssh
) handle
;
5981 struct ssh_channel
*c
;
5982 c
= smalloc(sizeof(struct ssh_channel
));
5986 c
->remoteid
= -1; /* to be set when open confirmed */
5987 c
->localid
= alloc_channel_id(ssh
);
5989 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
5991 bufchain_init(&c
->v
.v2
.outbuffer
);
5992 add234(ssh
->channels
, c
);
5998 * This is called when stdout/stderr (the entity to which
5999 * from_backend sends data) manages to clear some backlog.
6001 void ssh_unthrottle(void *handle
, int bufsize
)
6003 Ssh ssh
= (Ssh
) handle
;
6004 if (ssh
->version
== 1) {
6005 if (ssh
->v1_stdout_throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
6006 ssh
->v1_stdout_throttling
= 0;
6007 ssh1_throttle(ssh
, -1);
6010 if (ssh
->mainchan
&& ssh
->mainchan
->closes
== 0)
6011 ssh2_set_window(ssh
->mainchan
, OUR_V2_WINSIZE
- bufsize
);
6015 void ssh_send_port_open(void *handle
, void *channel
, char *hostname
,
6016 int port
, char *org
)
6018 Ssh ssh
= (Ssh
) handle
;
6019 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
6022 sprintf(buf
, "Opening forwarded connection to %.512s:%d", hostname
, port
);
6025 if (ssh
->version
== 1) {
6026 send_packet(ssh
, SSH1_MSG_PORT_OPEN
,
6027 PKT_INT
, c
->localid
,
6030 //PKT_STR, <org:orgport>,
6033 ssh2_pkt_init(ssh
, SSH2_MSG_CHANNEL_OPEN
);
6034 ssh2_pkt_addstring(ssh
, "direct-tcpip");
6035 ssh2_pkt_adduint32(ssh
, c
->localid
);
6036 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
6037 ssh2_pkt_adduint32(ssh
, c
->v
.v2
.locwindow
);/* our window size */
6038 ssh2_pkt_adduint32(ssh
, 0x4000UL
); /* our max pkt size */
6039 ssh2_pkt_addstring(ssh
, hostname
);
6040 ssh2_pkt_adduint32(ssh
, port
);
6042 * We make up values for the originator data; partly it's
6043 * too much hassle to keep track, and partly I'm not
6044 * convinced the server should be told details like that
6045 * about my local network configuration.
6047 ssh2_pkt_addstring(ssh
, "client-side-connection");
6048 ssh2_pkt_adduint32(ssh
, 0);
6054 static Socket
ssh_socket(void *handle
)
6056 Ssh ssh
= (Ssh
) handle
;
6060 static int ssh_sendok(void *handle
)
6062 Ssh ssh
= (Ssh
) handle
;
6063 return ssh
->send_ok
;
6066 static int ssh_ldisc(void *handle
, int option
)
6068 Ssh ssh
= (Ssh
) handle
;
6069 if (option
== LD_ECHO
)
6070 return ssh
->echoing
;
6071 if (option
== LD_EDIT
)
6072 return ssh
->editing
;
6076 static int ssh_return_exitcode(void *handle
)
6078 Ssh ssh
= (Ssh
) handle
;
6079 return ssh
->exitcode
;
6083 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
6084 * that fails. This variable is the means by which scp.c can reach
6085 * into the SSH code and find out which one it got.
6087 extern int ssh_fallback_cmd(void *handle
)
6089 Ssh ssh
= (Ssh
) handle
;
6090 return ssh
->fallback_cmd
;
6093 Backend ssh_backend
= {
6100 ssh_return_exitcode
,