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 (s ? sk_close(s), 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
185 static int ssh_pkt_ctx
= 0;
187 #define translate(x) if (type == x) return #x
188 #define translatec(x,ctx) if (type == x && (ssh_pkt_ctx & ctx)) return #x
189 char *ssh1_pkt_type(int type
)
191 translate(SSH1_MSG_DISCONNECT
);
192 translate(SSH1_SMSG_PUBLIC_KEY
);
193 translate(SSH1_CMSG_SESSION_KEY
);
194 translate(SSH1_CMSG_USER
);
195 translate(SSH1_CMSG_AUTH_RSA
);
196 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE
);
197 translate(SSH1_CMSG_AUTH_RSA_RESPONSE
);
198 translate(SSH1_CMSG_AUTH_PASSWORD
);
199 translate(SSH1_CMSG_REQUEST_PTY
);
200 translate(SSH1_CMSG_WINDOW_SIZE
);
201 translate(SSH1_CMSG_EXEC_SHELL
);
202 translate(SSH1_CMSG_EXEC_CMD
);
203 translate(SSH1_SMSG_SUCCESS
);
204 translate(SSH1_SMSG_FAILURE
);
205 translate(SSH1_CMSG_STDIN_DATA
);
206 translate(SSH1_SMSG_STDOUT_DATA
);
207 translate(SSH1_SMSG_STDERR_DATA
);
208 translate(SSH1_CMSG_EOF
);
209 translate(SSH1_SMSG_EXIT_STATUS
);
210 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
);
211 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE
);
212 translate(SSH1_MSG_CHANNEL_DATA
);
213 translate(SSH1_MSG_CHANNEL_CLOSE
);
214 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
);
215 translate(SSH1_SMSG_X11_OPEN
);
216 translate(SSH1_CMSG_PORT_FORWARD_REQUEST
);
217 translate(SSH1_MSG_PORT_OPEN
);
218 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING
);
219 translate(SSH1_SMSG_AGENT_OPEN
);
220 translate(SSH1_MSG_IGNORE
);
221 translate(SSH1_CMSG_EXIT_CONFIRMATION
);
222 translate(SSH1_CMSG_X11_REQUEST_FORWARDING
);
223 translate(SSH1_CMSG_AUTH_RHOSTS_RSA
);
224 translate(SSH1_MSG_DEBUG
);
225 translate(SSH1_CMSG_REQUEST_COMPRESSION
);
226 translate(SSH1_CMSG_AUTH_TIS
);
227 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE
);
228 translate(SSH1_CMSG_AUTH_TIS_RESPONSE
);
229 translate(SSH1_CMSG_AUTH_CCARD
);
230 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE
);
231 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE
);
234 char *ssh2_pkt_type(int type
)
236 translate(SSH2_MSG_DISCONNECT
);
237 translate(SSH2_MSG_IGNORE
);
238 translate(SSH2_MSG_UNIMPLEMENTED
);
239 translate(SSH2_MSG_DEBUG
);
240 translate(SSH2_MSG_SERVICE_REQUEST
);
241 translate(SSH2_MSG_SERVICE_ACCEPT
);
242 translate(SSH2_MSG_KEXINIT
);
243 translate(SSH2_MSG_NEWKEYS
);
244 translatec(SSH2_MSG_KEXDH_INIT
, SSH2_PKTCTX_DHGROUP1
);
245 translatec(SSH2_MSG_KEXDH_REPLY
, SSH2_PKTCTX_DHGROUP1
);
246 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST
, SSH2_PKTCTX_DHGEX
);
247 translatec(SSH2_MSG_KEX_DH_GEX_GROUP
, SSH2_PKTCTX_DHGEX
);
248 translatec(SSH2_MSG_KEX_DH_GEX_INIT
, SSH2_PKTCTX_DHGEX
);
249 translatec(SSH2_MSG_KEX_DH_GEX_REPLY
, SSH2_PKTCTX_DHGEX
);
250 translate(SSH2_MSG_USERAUTH_REQUEST
);
251 translate(SSH2_MSG_USERAUTH_FAILURE
);
252 translate(SSH2_MSG_USERAUTH_SUCCESS
);
253 translate(SSH2_MSG_USERAUTH_BANNER
);
254 translatec(SSH2_MSG_USERAUTH_PK_OK
, SSH2_PKTCTX_PUBLICKEY
);
255 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ
, SSH2_PKTCTX_PASSWORD
);
256 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST
, SSH2_PKTCTX_KBDINTER
);
257 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE
, SSH2_PKTCTX_KBDINTER
);
258 translate(SSH2_MSG_GLOBAL_REQUEST
);
259 translate(SSH2_MSG_REQUEST_SUCCESS
);
260 translate(SSH2_MSG_REQUEST_FAILURE
);
261 translate(SSH2_MSG_CHANNEL_OPEN
);
262 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
263 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
264 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
265 translate(SSH2_MSG_CHANNEL_DATA
);
266 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA
);
267 translate(SSH2_MSG_CHANNEL_EOF
);
268 translate(SSH2_MSG_CHANNEL_CLOSE
);
269 translate(SSH2_MSG_CHANNEL_REQUEST
);
270 translate(SSH2_MSG_CHANNEL_SUCCESS
);
271 translate(SSH2_MSG_CHANNEL_FAILURE
);
277 #define GET_32BIT(cp) \
278 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
279 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
280 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
281 ((unsigned long)(unsigned char)(cp)[3]))
283 #define PUT_32BIT(cp, value) { \
284 (cp)[0] = (unsigned char)((value) >> 24); \
285 (cp)[1] = (unsigned char)((value) >> 16); \
286 (cp)[2] = (unsigned char)((value) >> 8); \
287 (cp)[3] = (unsigned char)(value); }
289 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
291 /* Coroutine mechanics for the sillier bits of the code */
292 #define crBegin1 static int crLine = 0;
293 #define crBegin2 switch(crLine) { case 0:;
294 #define crBegin crBegin1; crBegin2;
295 #define crFinish(z) } crLine = 0; return (z)
296 #define crFinishV } crLine = 0; return
297 #define crReturn(z) \
299 crLine=__LINE__; return (z); case __LINE__:;\
303 crLine=__LINE__; return; case __LINE__:;\
305 #define crStop(z) do{ crLine = 0; return (z); }while(0)
306 #define crStopV do{ crLine = 0; return; }while(0)
307 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
308 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
310 extern char *x11_init(Socket
*, char *, void *);
311 extern void x11_close(Socket
);
312 extern int x11_send(Socket
, char *, int);
313 extern void x11_invent_auth(char *, int, char *, int);
314 extern void x11_unthrottle(Socket s
);
315 extern void x11_override_throttle(Socket s
, int enable
);
317 extern char *pfd_newconnect(Socket
* s
, char *hostname
, int port
, void *c
);
318 extern char *pfd_addforward(char *desthost
, int destport
, int port
);
319 extern void pfd_close(Socket s
);
320 extern int pfd_send(Socket s
, char *data
, int len
);
321 extern void pfd_confirm(Socket s
);
322 extern void pfd_unthrottle(Socket s
);
323 extern void pfd_override_throttle(Socket s
, int enable
);
325 static void ssh2_pkt_init(int pkt_type
);
326 static void ssh2_pkt_addbool(unsigned char value
);
327 static void ssh2_pkt_adduint32(unsigned long value
);
328 static void ssh2_pkt_addstring_start(void);
329 static void ssh2_pkt_addstring_str(char *data
);
330 static void ssh2_pkt_addstring_data(char *data
, int len
);
331 static void ssh2_pkt_addstring(char *data
);
332 static char *ssh2_mpint_fmt(Bignum b
, int *len
);
333 static void ssh2_pkt_addmp(Bignum b
);
334 static int ssh2_pkt_construct(void);
335 static void ssh2_pkt_send(void);
338 * Buffer management constants. There are several of these for
339 * various different purposes:
341 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
342 * on a local data stream before we throttle the whole SSH
343 * connection (in SSH1 only). Throttling the whole connection is
344 * pretty drastic so we set this high in the hope it won't
347 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
348 * on the SSH connection itself before we defensively throttle
349 * _all_ local data streams. This is pretty drastic too (though
350 * thankfully unlikely in SSH2 since the window mechanism should
351 * ensure that the server never has any need to throttle its end
352 * of the connection), so we set this high as well.
354 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
358 #define SSH1_BUFFER_LIMIT 32768
359 #define SSH_MAX_BACKLOG 32768
360 #define OUR_V2_WINSIZE 16384
362 const static struct ssh_kex
*kex_algs
[] = {
363 &ssh_diffiehellman_gex
,
367 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
369 static void nullmac_key(unsigned char *key
)
372 static void nullmac_generate(unsigned char *blk
, int len
,
376 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
)
380 const static struct ssh_mac ssh_mac_none
= {
381 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
383 const static struct ssh_mac
*macs
[] = {
384 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
386 const static struct ssh_mac
*buggymacs
[] = {
387 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
390 static void ssh_comp_none_init(void)
393 static int ssh_comp_none_block(unsigned char *block
, int len
,
394 unsigned char **outblock
, int *outlen
)
398 static int ssh_comp_none_disable(void)
402 const static struct ssh_compress ssh_comp_none
= {
404 ssh_comp_none_init
, ssh_comp_none_block
,
405 ssh_comp_none_init
, ssh_comp_none_block
,
406 ssh_comp_none_disable
408 extern const struct ssh_compress ssh_zlib
;
409 const static struct ssh_compress
*compressions
[] = {
410 &ssh_zlib
, &ssh_comp_none
413 enum { /* channel types */
418 CHAN_SOCKDATA_DORMANT
/* one the remote hasn't confirmed */
422 * 2-3-4 tree storing channels.
425 unsigned remoteid
, localid
;
429 struct ssh1_data_channel
{
432 struct ssh2_data_channel
{
434 unsigned remwindow
, remmaxpkt
;
439 struct ssh_agent_channel
{
440 unsigned char *message
;
441 unsigned char msglen
[4];
442 int lensofar
, totallen
;
444 struct ssh_x11_channel
{
447 struct ssh_pfd_channel
{
454 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
455 * 2 use this structure in different ways, reflecting SSH 2's
456 * altogether saner approach to port forwarding.
458 * In SSH 1, you arrange a remote forwarding by sending the server
459 * the remote port number, and the local destination host:port.
460 * When a connection comes in, the server sends you back that
461 * host:port pair, and you connect to it. This is a ready-made
462 * security hole if you're not on the ball: a malicious server
463 * could send you back _any_ host:port pair, so if you trustingly
464 * connect to the address it gives you then you've just opened the
465 * entire inside of your corporate network just by connecting
466 * through it to a dodgy SSH server. Hence, we must store a list of
467 * host:port pairs we _are_ trying to forward to, and reject a
468 * connection request from the server if it's not in the list.
470 * In SSH 2, each side of the connection minds its own business and
471 * doesn't send unnecessary information to the other. You arrange a
472 * remote forwarding by sending the server just the remote port
473 * number. When a connection comes in, the server tells you which
474 * of its ports was connected to; and _you_ have to remember what
475 * local host:port pair went with that port number.
477 * Hence: in SSH 1 this structure stores host:port pairs we intend
478 * to allow connections to, and is indexed by those host:port
479 * pairs. In SSH 2 it stores a mapping from source port to
480 * destination host:port pair, and is indexed by source port.
482 struct ssh_rportfwd
{
483 unsigned sport
, dport
;
496 static SHA_State exhash
, exhashbase
;
498 static Socket s
= NULL
;
500 static unsigned char session_key
[32];
501 static int ssh1_compressing
;
502 static int ssh1_remote_protoflags
;
503 static int ssh1_local_protoflags
;
504 static int ssh_agentfwd_enabled
;
505 static int ssh_X11_fwd_enabled
;
506 static int ssh_remote_bugs
;
507 static const struct ssh_cipher
*cipher
= NULL
;
508 static const struct ssh2_cipher
*cscipher
= NULL
;
509 static const struct ssh2_cipher
*sccipher
= NULL
;
510 static const struct ssh_mac
*csmac
= NULL
;
511 static const struct ssh_mac
*scmac
= NULL
;
512 static const struct ssh_compress
*cscomp
= NULL
;
513 static const struct ssh_compress
*sccomp
= NULL
;
514 static const struct ssh_kex
*kex
= NULL
;
515 static const struct ssh_signkey
*hostkey
= NULL
;
516 static unsigned char ssh2_session_id
[20];
517 int (*ssh_get_line
) (const char *prompt
, char *str
, int maxlen
,
520 static char *savedhost
;
521 static int savedport
;
522 static int ssh_send_ok
;
523 static int ssh_echoing
, ssh_editing
;
525 static tree234
*ssh_channels
; /* indexed by local id */
526 static struct ssh_channel
*mainchan
; /* primary session channel */
527 static int ssh_exitcode
= -1;
529 static tree234
*ssh_rportfwds
;
533 SSH_STATE_BEFORE_SIZE
,
537 } ssh_state
= SSH_STATE_PREPACKET
;
539 static int size_needed
= FALSE
, eof_needed
= FALSE
;
541 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
542 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
543 static unsigned char *deferred_send_data
= NULL
;
544 static int deferred_len
= 0, deferred_size
= 0;
547 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
548 * that fails. This variable is the means by which scp.c can reach
549 * into the SSH code and find out which one it got.
551 int ssh_fallback_cmd
= 0;
553 static int ssh_version
;
554 static int ssh1_throttle_count
;
555 static int ssh_overall_bufsize
;
556 static int ssh_throttled_all
;
557 static int ssh1_stdout_throttling
;
558 static void (*ssh_protocol
) (unsigned char *in
, int inlen
, int ispkt
);
559 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
560 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
561 static void ssh_size(void);
562 static void ssh_special(Telnet_Special
);
563 static int ssh2_try_send(struct ssh_channel
*c
);
564 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
566 static void ssh_throttle_all(int enable
, int bufsize
);
567 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
);
568 static int (*s_rdpkt
) (unsigned char **data
, int *datalen
);
569 static int ssh_sendbuffer(void);
571 static struct rdpkt1_state_tag
{
572 long len
, pad
, biglen
, to_read
;
573 unsigned long realcrc
, gotcrc
;
579 static struct rdpkt2_state_tag
{
580 long len
, pad
, payload
, packetlen
, maclen
;
583 unsigned long incoming_sequence
;
586 static int ssh_channelcmp(void *av
, void *bv
)
588 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
589 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
590 if (a
->localid
< b
->localid
)
592 if (a
->localid
> b
->localid
)
596 static int ssh_channelfind(void *av
, void *bv
)
598 unsigned *a
= (unsigned *) av
;
599 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
607 static int ssh_rportcmp_ssh1(void *av
, void *bv
)
609 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
610 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
612 if ( (i
= strcmp(a
->dhost
, b
->dhost
)) != 0)
613 return i
< 0 ?
-1 : +1;
614 if (a
->dport
> b
->dport
)
616 if (a
->dport
< b
->dport
)
621 static int ssh_rportcmp_ssh2(void *av
, void *bv
)
623 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
624 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
626 if (a
->sport
> b
->sport
)
628 if (a
->sport
< b
->sport
)
633 static int alloc_channel_id(void)
635 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
636 unsigned low
, high
, mid
;
638 struct ssh_channel
*c
;
641 * First-fit allocation of channel numbers: always pick the
642 * lowest unused one. To do this, binary-search using the
643 * counted B-tree to find the largest channel ID which is in a
644 * contiguous sequence from the beginning. (Precisely
645 * everything in that sequence must have ID equal to its tree
646 * index plus CHANNEL_NUMBER_OFFSET.)
648 tsize
= count234(ssh_channels
);
652 while (high
- low
> 1) {
653 mid
= (high
+ low
) / 2;
654 c
= index234(ssh_channels
, mid
);
655 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
656 low
= mid
; /* this one is fine */
658 high
= mid
; /* this one is past it */
661 * Now low points to either -1, or the tree index of the
662 * largest ID in the initial sequence.
665 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
666 assert(NULL
== find234(ssh_channels
, &i
, ssh_channelfind
));
668 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
671 static void c_write(char *buf
, int len
)
673 if ((flags
& FLAG_STDERR
)) {
675 for (i
= 0; i
< len
; i
++)
677 fputc(buf
[i
], stderr
);
680 from_backend(1, buf
, len
);
683 static void c_write_untrusted(char *buf
, int len
)
686 for (i
= 0; i
< len
; i
++) {
689 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
694 static void c_write_str(char *buf
)
696 c_write(buf
, strlen(buf
));
700 * Collect incoming data in the incoming packet buffer.
701 * Decipher and verify the packet when it is completely read.
702 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
703 * Update the *data and *datalen variables.
704 * Return the additional nr of bytes needed, or 0 when
705 * a complete packet is available.
707 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
709 struct rdpkt1_state_tag
*st
= &rdpkt1_state
;
718 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
719 while ((*datalen
) == 0)
721 st
->len
= (st
->len
<< 8) + **data
;
722 (*data
)++, (*datalen
)--;
725 st
->pad
= 8 - (st
->len
% 8);
726 st
->biglen
= st
->len
+ st
->pad
;
727 pktin
.length
= st
->len
- 5;
729 if (pktin
.maxlen
< st
->biglen
) {
730 pktin
.maxlen
= st
->biglen
;
731 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->biglen
+ APIEXTRA
) :
732 srealloc(pktin
.data
, st
->biglen
+ APIEXTRA
));
734 fatalbox("Out of memory");
737 st
->to_read
= st
->biglen
;
739 while (st
->to_read
> 0) {
740 st
->chunk
= st
->to_read
;
741 while ((*datalen
) == 0)
742 crReturn(st
->to_read
);
743 if (st
->chunk
> (*datalen
))
744 st
->chunk
= (*datalen
);
745 memcpy(st
->p
, *data
, st
->chunk
);
747 *datalen
-= st
->chunk
;
749 st
->to_read
-= st
->chunk
;
752 if (cipher
&& detect_attack(pktin
.data
, st
->biglen
, NULL
)) {
753 bombout(("Network attack (CRC compensation) detected!"));
758 cipher
->decrypt(pktin
.data
, st
->biglen
);
760 st
->realcrc
= crc32(pktin
.data
, st
->biglen
- 4);
761 st
->gotcrc
= GET_32BIT(pktin
.data
+ st
->biglen
- 4);
762 if (st
->gotcrc
!= st
->realcrc
) {
763 bombout(("Incorrect CRC received on packet"));
767 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
769 if (ssh1_compressing
) {
770 unsigned char *decompblk
;
772 zlib_decompress_block(pktin
.body
- 1, pktin
.length
+ 1,
773 &decompblk
, &decomplen
);
775 if (pktin
.maxlen
< st
->pad
+ decomplen
) {
776 pktin
.maxlen
= st
->pad
+ decomplen
;
777 pktin
.data
= srealloc(pktin
.data
, pktin
.maxlen
+ APIEXTRA
);
778 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
780 fatalbox("Out of memory");
783 memcpy(pktin
.body
- 1, decompblk
, decomplen
);
785 pktin
.length
= decomplen
- 1;
788 pktin
.type
= pktin
.body
[-1];
790 log_packet(PKT_INCOMING
, pktin
.type
, ssh1_pkt_type(pktin
.type
),
791 pktin
.body
, pktin
.length
);
793 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
794 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
795 pktin
.type
== SSH1_MSG_DEBUG
||
796 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
797 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
798 long stringlen
= GET_32BIT(pktin
.body
);
799 if (stringlen
+ 4 != pktin
.length
) {
800 bombout(("Received data packet with bogus string length"));
805 if (pktin
.type
== SSH1_MSG_DEBUG
) {
806 /* log debug message */
808 int stringlen
= GET_32BIT(pktin
.body
);
809 strcpy(buf
, "Remote: ");
812 memcpy(buf
+ 8, pktin
.body
+ 4, stringlen
);
813 buf
[8 + stringlen
] = '\0';
816 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
821 if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
822 /* log reason code in disconnect message */
824 unsigned msglen
= GET_32BIT(pktin
.body
);
826 strcpy(buf
, "Remote sent disconnect: ");
827 nowlen
= strlen(buf
);
828 if (msglen
> sizeof(buf
) - nowlen
- 1)
829 msglen
= sizeof(buf
) - nowlen
- 1;
830 memcpy(buf
+ nowlen
, pktin
.body
+ 4, msglen
);
831 buf
[nowlen
+ msglen
] = '\0';
832 /* logevent(buf); (this is now done within the bombout macro) */
833 bombout(("Server sent disconnect message:\n\"%s\"", buf
+nowlen
));
840 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
842 struct rdpkt2_state_tag
*st
= &rdpkt2_state
;
850 st
->cipherblk
= sccipher
->blksize
;
853 if (st
->cipherblk
< 8)
856 if (pktin
.maxlen
< st
->cipherblk
) {
857 pktin
.maxlen
= st
->cipherblk
;
860 NULL ?
smalloc(st
->cipherblk
+
861 APIEXTRA
) : srealloc(pktin
.data
,
865 fatalbox("Out of memory");
869 * Acquire and decrypt the first block of the packet. This will
870 * contain the length and padding details.
872 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
873 while ((*datalen
) == 0)
874 crReturn(st
->cipherblk
- st
->i
);
875 pktin
.data
[st
->i
] = *(*data
)++;
880 sccipher
->decrypt(pktin
.data
, st
->cipherblk
);
883 * Now get the length and padding figures.
885 st
->len
= GET_32BIT(pktin
.data
);
886 st
->pad
= pktin
.data
[4];
889 * This enables us to deduce the payload length.
891 st
->payload
= st
->len
- st
->pad
- 1;
893 pktin
.length
= st
->payload
+ 5;
896 * So now we can work out the total packet length.
898 st
->packetlen
= st
->len
+ 4;
899 st
->maclen
= scmac ? scmac
->len
: 0;
902 * Adjust memory allocation if packet is too big.
904 if (pktin
.maxlen
< st
->packetlen
+ st
->maclen
) {
905 pktin
.maxlen
= st
->packetlen
+ st
->maclen
;
908 NULL ?
smalloc(pktin
.maxlen
+ APIEXTRA
) : srealloc(pktin
.data
,
913 fatalbox("Out of memory");
917 * Read and decrypt the remainder of the packet.
919 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
921 while ((*datalen
) == 0)
922 crReturn(st
->packetlen
+ st
->maclen
- st
->i
);
923 pktin
.data
[st
->i
] = *(*data
)++;
926 /* Decrypt everything _except_ the MAC. */
928 sccipher
->decrypt(pktin
.data
+ st
->cipherblk
,
929 st
->packetlen
- st
->cipherblk
);
935 && !scmac
->verify(pktin
.data
, st
->len
+ 4,
936 st
->incoming_sequence
)) {
937 bombout(("Incorrect MAC received on packet"));
940 st
->incoming_sequence
++; /* whether or not we MACed */
943 * Decompress packet payload.
946 unsigned char *newpayload
;
948 if (sccomp
&& sccomp
->decompress(pktin
.data
+ 5, pktin
.length
- 5,
949 &newpayload
, &newlen
)) {
950 if (pktin
.maxlen
< newlen
+ 5) {
951 pktin
.maxlen
= newlen
+ 5;
954 NULL ?
smalloc(pktin
.maxlen
+
955 APIEXTRA
) : srealloc(pktin
.data
,
959 fatalbox("Out of memory");
961 pktin
.length
= 5 + newlen
;
962 memcpy(pktin
.data
+ 5, newpayload
, newlen
);
968 pktin
.type
= pktin
.data
[5];
970 log_packet(PKT_INCOMING
, pktin
.type
, ssh2_pkt_type(pktin
.type
),
971 pktin
.data
+6, pktin
.length
-6);
973 switch (pktin
.type
) {
975 * These packets we must handle instantly.
977 case SSH2_MSG_DISCONNECT
:
979 /* log reason code in disconnect message */
981 int reason
= GET_32BIT(pktin
.data
+ 6);
982 unsigned msglen
= GET_32BIT(pktin
.data
+ 10);
984 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
985 sprintf(buf
, "Received disconnect message (%s)",
986 ssh2_disconnect_reasons
[reason
]);
988 sprintf(buf
, "Received disconnect message (unknown type %d)",
992 strcpy(buf
, "Disconnection message text: ");
993 nowlen
= strlen(buf
);
994 if (msglen
> sizeof(buf
) - nowlen
- 1)
995 msglen
= sizeof(buf
) - nowlen
- 1;
996 memcpy(buf
+ nowlen
, pktin
.data
+ 14, msglen
);
997 buf
[nowlen
+ msglen
] = '\0';
999 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
1001 (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) ?
1002 ssh2_disconnect_reasons
[reason
] : "unknown",
1007 case SSH2_MSG_IGNORE
:
1009 case SSH2_MSG_DEBUG
:
1011 /* log the debug message */
1013 /* int display = pktin.body[6]; */
1014 int stringlen
= GET_32BIT(pktin
.data
+7);
1016 strcpy(buf
, "Remote debug message: ");
1017 prefix
= strlen(buf
);
1018 if (stringlen
> sizeof(buf
)-prefix
-1)
1019 stringlen
= sizeof(buf
)-prefix
-1;
1020 memcpy(buf
+ prefix
, pktin
.data
+ 11, stringlen
);
1021 buf
[prefix
+ stringlen
] = '\0';
1024 goto next_packet
; /* FIXME: print the debug message */
1027 * These packets we need do nothing about here.
1029 case SSH2_MSG_UNIMPLEMENTED
:
1030 case SSH2_MSG_SERVICE_REQUEST
:
1031 case SSH2_MSG_SERVICE_ACCEPT
:
1032 case SSH2_MSG_KEXINIT
:
1033 case SSH2_MSG_NEWKEYS
:
1034 case SSH2_MSG_KEXDH_INIT
:
1035 case SSH2_MSG_KEXDH_REPLY
:
1036 /* case SSH2_MSG_KEX_DH_GEX_REQUEST: duplicate case value */
1037 /* case SSH2_MSG_KEX_DH_GEX_GROUP: duplicate case value */
1038 case SSH2_MSG_KEX_DH_GEX_INIT
:
1039 case SSH2_MSG_KEX_DH_GEX_REPLY
:
1040 case SSH2_MSG_USERAUTH_REQUEST
:
1041 case SSH2_MSG_USERAUTH_FAILURE
:
1042 case SSH2_MSG_USERAUTH_SUCCESS
:
1043 case SSH2_MSG_USERAUTH_BANNER
:
1044 case SSH2_MSG_USERAUTH_PK_OK
:
1045 /* case SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: duplicate case value */
1046 /* case SSH2_MSG_USERAUTH_INFO_REQUEST: duplicate case value */
1047 case SSH2_MSG_USERAUTH_INFO_RESPONSE
:
1048 case SSH2_MSG_GLOBAL_REQUEST
:
1049 case SSH2_MSG_REQUEST_SUCCESS
:
1050 case SSH2_MSG_REQUEST_FAILURE
:
1051 case SSH2_MSG_CHANNEL_OPEN
:
1052 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
:
1053 case SSH2_MSG_CHANNEL_OPEN_FAILURE
:
1054 case SSH2_MSG_CHANNEL_WINDOW_ADJUST
:
1055 case SSH2_MSG_CHANNEL_DATA
:
1056 case SSH2_MSG_CHANNEL_EXTENDED_DATA
:
1057 case SSH2_MSG_CHANNEL_EOF
:
1058 case SSH2_MSG_CHANNEL_CLOSE
:
1059 case SSH2_MSG_CHANNEL_REQUEST
:
1060 case SSH2_MSG_CHANNEL_SUCCESS
:
1061 case SSH2_MSG_CHANNEL_FAILURE
:
1065 * For anything else we send SSH2_MSG_UNIMPLEMENTED.
1068 ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED
);
1069 ssh2_pkt_adduint32(st
->incoming_sequence
- 1);
1077 static void ssh1_pktout_size(int len
)
1081 len
+= 5; /* type and CRC */
1082 pad
= 8 - (len
% 8);
1085 pktout
.length
= len
- 5;
1086 if (pktout
.maxlen
< biglen
) {
1087 pktout
.maxlen
= biglen
;
1089 /* Allocate enough buffer space for extra block
1090 * for MS CryptEncrypt() */
1091 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+ 12) :
1092 srealloc(pktout
.data
, biglen
+ 12));
1094 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+ 4) :
1095 srealloc(pktout
.data
, biglen
+ 4));
1098 fatalbox("Out of memory");
1100 pktout
.body
= pktout
.data
+ 4 + pad
+ 1;
1103 static void s_wrpkt_start(int type
, int len
)
1105 ssh1_pktout_size(len
);
1109 static int s_wrpkt_prepare(void)
1111 int pad
, len
, biglen
, i
;
1114 pktout
.body
[-1] = pktout
.type
;
1116 log_packet(PKT_OUTGOING
, pktout
.type
, ssh1_pkt_type(pktout
.type
),
1117 pktout
.body
, pktout
.length
);
1119 if (ssh1_compressing
) {
1120 unsigned char *compblk
;
1122 zlib_compress_block(pktout
.body
- 1, pktout
.length
+ 1,
1123 &compblk
, &complen
);
1124 ssh1_pktout_size(complen
- 1);
1125 memcpy(pktout
.body
- 1, compblk
, complen
);
1129 len
= pktout
.length
+ 5; /* type and CRC */
1130 pad
= 8 - (len
% 8);
1133 for (i
= 0; i
< pad
; i
++)
1134 pktout
.data
[i
+ 4] = random_byte();
1135 crc
= crc32(pktout
.data
+ 4, biglen
- 4);
1136 PUT_32BIT(pktout
.data
+ biglen
, crc
);
1137 PUT_32BIT(pktout
.data
, len
);
1140 cipher
->encrypt(pktout
.data
+ 4, biglen
);
1145 static void s_wrpkt(void)
1148 len
= s_wrpkt_prepare();
1149 backlog
= sk_write(s
, pktout
.data
, len
);
1150 if (backlog
> SSH_MAX_BACKLOG
)
1151 ssh_throttle_all(1, backlog
);
1154 static void s_wrpkt_defer(void)
1157 len
= s_wrpkt_prepare();
1158 if (deferred_len
+ len
> deferred_size
) {
1159 deferred_size
= deferred_len
+ len
+ 128;
1160 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1162 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
1163 deferred_len
+= len
;
1167 * Construct a packet with the specified contents.
1169 static void construct_packet(int pkttype
, va_list ap1
, va_list ap2
)
1171 unsigned char *p
, *argp
, argchar
;
1172 unsigned long argint
;
1173 int pktlen
, argtype
, arglen
;
1177 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
1180 (void) va_arg(ap1
, int);
1184 (void) va_arg(ap1
, char);
1188 (void) va_arg(ap1
, unsigned char *);
1189 arglen
= va_arg(ap1
, int);
1193 argp
= va_arg(ap1
, unsigned char *);
1194 arglen
= strlen(argp
);
1195 pktlen
+= 4 + arglen
;
1198 bn
= va_arg(ap1
, Bignum
);
1199 pktlen
+= ssh1_bignum_length(bn
);
1206 s_wrpkt_start(pkttype
, pktlen
);
1209 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
1212 argint
= va_arg(ap2
, int);
1213 PUT_32BIT(p
, argint
);
1217 argchar
= va_arg(ap2
, unsigned char);
1222 argp
= va_arg(ap2
, unsigned char *);
1223 arglen
= va_arg(ap2
, int);
1224 memcpy(p
, argp
, arglen
);
1228 argp
= va_arg(ap2
, unsigned char *);
1229 arglen
= strlen(argp
);
1230 PUT_32BIT(p
, arglen
);
1231 memcpy(p
+ 4, argp
, arglen
);
1235 bn
= va_arg(ap2
, Bignum
);
1236 p
+= ssh1_write_bignum(p
, bn
);
1242 static void send_packet(int pkttype
, ...)
1245 va_start(ap1
, pkttype
);
1246 va_start(ap2
, pkttype
);
1247 construct_packet(pkttype
, ap1
, ap2
);
1251 static void defer_packet(int pkttype
, ...)
1254 va_start(ap1
, pkttype
);
1255 va_start(ap2
, pkttype
);
1256 construct_packet(pkttype
, ap1
, ap2
);
1260 static int ssh_versioncmp(char *a
, char *b
)
1263 unsigned long av
, bv
;
1265 av
= strtoul(a
, &ae
, 10);
1266 bv
= strtoul(b
, &be
, 10);
1268 return (av
< bv ?
-1 : +1);
1273 av
= strtoul(ae
, &ae
, 10);
1274 bv
= strtoul(be
, &be
, 10);
1276 return (av
< bv ?
-1 : +1);
1282 * Utility routines for putting an SSH-protocol `string' and
1283 * `uint32' into a SHA state.
1286 static void sha_string(SHA_State
* s
, void *str
, int len
)
1288 unsigned char lenblk
[4];
1289 PUT_32BIT(lenblk
, len
);
1290 SHA_Bytes(s
, lenblk
, 4);
1291 SHA_Bytes(s
, str
, len
);
1294 static void sha_uint32(SHA_State
* s
, unsigned i
)
1296 unsigned char intblk
[4];
1297 PUT_32BIT(intblk
, i
);
1298 SHA_Bytes(s
, intblk
, 4);
1302 * SSH2 packet construction functions.
1304 static void ssh2_pkt_ensure(int length
)
1306 if (pktout
.maxlen
< length
) {
1307 pktout
.maxlen
= length
+ 256;
1310 NULL ?
smalloc(pktout
.maxlen
+
1311 APIEXTRA
) : srealloc(pktout
.data
,
1315 fatalbox("Out of memory");
1318 static void ssh2_pkt_adddata(void *data
, int len
)
1320 pktout
.length
+= len
;
1321 ssh2_pkt_ensure(pktout
.length
);
1322 memcpy(pktout
.data
+ pktout
.length
- len
, data
, len
);
1324 static void ssh2_pkt_addbyte(unsigned char byte
)
1326 ssh2_pkt_adddata(&byte
, 1);
1328 static void ssh2_pkt_init(int pkt_type
)
1331 ssh2_pkt_addbyte((unsigned char) pkt_type
);
1333 static void ssh2_pkt_addbool(unsigned char value
)
1335 ssh2_pkt_adddata(&value
, 1);
1337 static void ssh2_pkt_adduint32(unsigned long value
)
1340 PUT_32BIT(x
, value
);
1341 ssh2_pkt_adddata(x
, 4);
1343 static void ssh2_pkt_addstring_start(void)
1345 ssh2_pkt_adduint32(0);
1346 pktout
.savedpos
= pktout
.length
;
1348 static void ssh2_pkt_addstring_str(char *data
)
1350 ssh2_pkt_adddata(data
, strlen(data
));
1351 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1352 pktout
.length
- pktout
.savedpos
);
1354 static void ssh2_pkt_addstring_data(char *data
, int len
)
1356 ssh2_pkt_adddata(data
, len
);
1357 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1358 pktout
.length
- pktout
.savedpos
);
1360 static void ssh2_pkt_addstring(char *data
)
1362 ssh2_pkt_addstring_start();
1363 ssh2_pkt_addstring_str(data
);
1365 static char *ssh2_mpint_fmt(Bignum b
, int *len
)
1368 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1371 fatalbox("out of memory");
1373 for (i
= 1; i
<= n
; i
++)
1374 p
[i
] = bignum_byte(b
, n
- i
);
1376 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1378 memmove(p
, p
+ i
, n
+ 1 - i
);
1382 static void ssh2_pkt_addmp(Bignum b
)
1386 p
= ssh2_mpint_fmt(b
, &len
);
1387 ssh2_pkt_addstring_start();
1388 ssh2_pkt_addstring_data(p
, len
);
1393 * Construct an SSH2 final-form packet: compress it, encrypt it,
1394 * put the MAC on it. Final packet, ready to be sent, is stored in
1395 * pktout.data. Total length is returned.
1397 static int ssh2_pkt_construct(void)
1399 int cipherblk
, maclen
, padding
, i
;
1400 static unsigned long outgoing_sequence
= 0;
1402 log_packet(PKT_OUTGOING
, pktout
.data
[5], ssh2_pkt_type(pktout
.data
[5]),
1403 pktout
.data
+ 6, pktout
.length
- 6);
1406 * Compress packet payload.
1409 unsigned char *newpayload
;
1411 if (cscomp
&& cscomp
->compress(pktout
.data
+ 5, pktout
.length
- 5,
1412 &newpayload
, &newlen
)) {
1414 ssh2_pkt_adddata(newpayload
, newlen
);
1420 * Add padding. At least four bytes, and must also bring total
1421 * length (minus MAC) up to a multiple of the block size.
1423 cipherblk
= cscipher ? cscipher
->blksize
: 8; /* block size */
1424 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1427 (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
1428 maclen
= csmac ? csmac
->len
: 0;
1429 ssh2_pkt_ensure(pktout
.length
+ padding
+ maclen
);
1430 pktout
.data
[4] = padding
;
1431 for (i
= 0; i
< padding
; i
++)
1432 pktout
.data
[pktout
.length
+ i
] = random_byte();
1433 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
1435 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
1437 outgoing_sequence
++; /* whether or not we MACed */
1440 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
1442 /* Ready-to-send packet starts at pktout.data. We return length. */
1443 return pktout
.length
+ padding
+ maclen
;
1447 * Construct and send an SSH2 packet immediately.
1449 static void ssh2_pkt_send(void)
1453 len
= ssh2_pkt_construct();
1454 backlog
= sk_write(s
, pktout
.data
, len
);
1455 if (backlog
> SSH_MAX_BACKLOG
)
1456 ssh_throttle_all(1, backlog
);
1460 * Construct an SSH2 packet and add it to a deferred data block.
1461 * Useful for sending multiple packets in a single sk_write() call,
1462 * to prevent a traffic-analysing listener from being able to work
1463 * out the length of any particular packet (such as the password
1466 * Note that because SSH2 sequence-numbers its packets, this can
1467 * NOT be used as an m4-style `defer' allowing packets to be
1468 * constructed in one order and sent in another.
1470 static void ssh2_pkt_defer(void)
1472 int len
= ssh2_pkt_construct();
1473 if (deferred_len
+ len
> deferred_size
) {
1474 deferred_size
= deferred_len
+ len
+ 128;
1475 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1477 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
1478 deferred_len
+= len
;
1482 * Send the whole deferred data block constructed by
1483 * ssh2_pkt_defer() or SSH1's defer_packet().
1485 static void ssh_pkt_defersend(void)
1488 backlog
= sk_write(s
, deferred_send_data
, deferred_len
);
1489 deferred_len
= deferred_size
= 0;
1490 sfree(deferred_send_data
);
1491 deferred_send_data
= NULL
;
1492 if (backlog
> SSH_MAX_BACKLOG
)
1493 ssh_throttle_all(1, backlog
);
1497 void bndebug(char *string
, Bignum b
)
1501 p
= ssh2_mpint_fmt(b
, &len
);
1502 debug(("%s", string
));
1503 for (i
= 0; i
< len
; i
++)
1504 debug((" %02x", p
[i
]));
1510 static void sha_mpint(SHA_State
* s
, Bignum b
)
1514 p
= ssh2_mpint_fmt(b
, &len
);
1515 sha_string(s
, p
, len
);
1520 * SSH2 packet decode functions.
1522 static unsigned long ssh2_pkt_getuint32(void)
1524 unsigned long value
;
1525 if (pktin
.length
- pktin
.savedpos
< 4)
1526 return 0; /* arrgh, no way to decline (FIXME?) */
1527 value
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1528 pktin
.savedpos
+= 4;
1531 static int ssh2_pkt_getbool(void)
1533 unsigned long value
;
1534 if (pktin
.length
- pktin
.savedpos
< 1)
1535 return 0; /* arrgh, no way to decline (FIXME?) */
1536 value
= pktin
.data
[pktin
.savedpos
] != 0;
1540 static void ssh2_pkt_getstring(char **p
, int *length
)
1543 if (pktin
.length
- pktin
.savedpos
< 4)
1545 *length
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1546 pktin
.savedpos
+= 4;
1547 if (pktin
.length
- pktin
.savedpos
< *length
)
1549 *p
= pktin
.data
+ pktin
.savedpos
;
1550 pktin
.savedpos
+= *length
;
1552 static Bignum
ssh2_pkt_getmp(void)
1558 ssh2_pkt_getstring(&p
, &length
);
1562 bombout(("internal error: Can't handle negative mpints"));
1565 b
= bignum_from_bytes(p
, length
);
1570 * Examine the remote side's version string and compare it against
1571 * a list of known buggy implementations.
1573 static void ssh_detect_bugs(char *vstring
)
1575 char *imp
; /* pointer to implementation part */
1577 imp
+= strcspn(imp
, "-");
1579 imp
+= strcspn(imp
, "-");
1582 ssh_remote_bugs
= 0;
1584 if (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
1585 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
1586 !strcmp(imp
, "1.2.22") || !strcmp(imp
, "Cisco-1.25")) {
1588 * These versions don't support SSH1_MSG_IGNORE, so we have
1589 * to use a different defence against password length
1592 ssh_remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
1593 logevent("We believe remote version has SSH1 ignore bug");
1596 if (!strcmp(imp
, "Cisco-1.25")) {
1598 * These versions need a plain password sent; they can't
1599 * handle having a null and a random length of data after
1602 ssh_remote_bugs
|= BUG_NEEDS_SSH1_PLAIN_PASSWORD
;
1603 logevent("We believe remote version needs a plain SSH1 password");
1606 if (!strcmp(imp
, "Cisco-1.25")) {
1608 * These versions apparently have no clue whatever about
1609 * RSA authentication and will panic and die if they see
1610 * an AUTH_RSA message.
1612 ssh_remote_bugs
|= BUG_CHOKES_ON_RSA
;
1613 logevent("We believe remote version can't handle RSA authentication");
1616 if (!strncmp(imp
, "2.1.0", 5) || !strncmp(imp
, "2.0.", 4) ||
1617 !strncmp(imp
, "2.2.0", 5) || !strncmp(imp
, "2.3.0", 5) ||
1618 !strncmp(imp
, "2.1 ", 4)) {
1620 * These versions have the HMAC bug.
1622 ssh_remote_bugs
|= BUG_SSH2_HMAC
;
1623 logevent("We believe remote version has SSH2 HMAC bug");
1627 static int do_ssh_init(unsigned char c
)
1630 static char version
[10];
1631 static char *vstring
;
1632 static int vstrsize
;
1638 /* Search for the string "SSH-" in the input. */
1641 static const int transS
[] = { 1, 2, 2, 1 };
1642 static const int transH
[] = { 0, 0, 3, 0 };
1643 static const int transminus
[] = { 0, 0, 0, -1 };
1654 crReturn(1); /* get another character */
1658 vstring
= smalloc(vstrsize
);
1659 strcpy(vstring
, "SSH-");
1663 crReturn(1); /* get another char */
1664 if (vslen
>= vstrsize
- 1) {
1666 vstring
= srealloc(vstring
, vstrsize
);
1668 vstring
[vslen
++] = c
;
1673 } else if (i
< sizeof(version
) - 1)
1675 } else if (c
== '\n')
1679 ssh_agentfwd_enabled
= FALSE
;
1680 rdpkt2_state
.incoming_sequence
= 0;
1683 vlog
= smalloc(20 + vslen
);
1684 vstring
[strcspn (vstring
, "\r\n")] = '\0'; /* remove end-of-line chars */
1685 sprintf(vlog
, "Server version: %s", vstring
);
1687 ssh_detect_bugs(vstring
);
1691 * Server version "1.99" means we can choose whether we use v1
1692 * or v2 protocol. Choice is based on cfg.sshprot.
1694 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1696 * This is a v2 server. Begin v2 protocol.
1698 char verstring
[80], vlog
[100];
1699 sprintf(verstring
, "SSH-2.0-%s", sshver
);
1700 SHA_Init(&exhashbase
);
1702 * Hash our version string and their version string.
1704 sha_string(&exhashbase
, verstring
, strlen(verstring
));
1705 sha_string(&exhashbase
, vstring
, strcspn(vstring
, "\r\n"));
1706 sprintf(vlog
, "We claim version: %s", verstring
);
1708 strcat(verstring
, "\n");
1709 logevent("Using SSH protocol version 2");
1710 sk_write(s
, verstring
, strlen(verstring
));
1711 ssh_protocol
= ssh2_protocol
;
1713 s_rdpkt
= ssh2_rdpkt
;
1716 * This is a v1 server. Begin v1 protocol.
1718 char verstring
[80], vlog
[100];
1719 sprintf(verstring
, "SSH-%s-%s",
1720 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"),
1722 sprintf(vlog
, "We claim version: %s", verstring
);
1724 strcat(verstring
, "\n");
1725 logevent("Using SSH protocol version 1");
1726 sk_write(s
, verstring
, strlen(verstring
));
1727 ssh_protocol
= ssh1_protocol
;
1729 s_rdpkt
= ssh1_rdpkt
;
1731 ssh_state
= SSH_STATE_BEFORE_SIZE
;
1738 static void ssh_gotdata(unsigned char *data
, int datalen
)
1743 * To begin with, feed the characters one by one to the
1744 * protocol initialisation / selection function do_ssh_init().
1745 * When that returns 0, we're done with the initial greeting
1746 * exchange and can move on to packet discipline.
1751 crReturnV
; /* more data please */
1752 ret
= do_ssh_init(*data
);
1760 * We emerge from that loop when the initial negotiation is
1761 * over and we have selected an s_rdpkt function. Now pass
1762 * everything to s_rdpkt, and then pass the resulting packets
1763 * to the proper protocol handler.
1768 while (datalen
> 0) {
1769 if (s_rdpkt(&data
, &datalen
) == 0) {
1770 if (ssh_state
== SSH_STATE_CLOSED
) {
1773 ssh_protocol(NULL
, 0, 1);
1774 if (ssh_state
== SSH_STATE_CLOSED
) {
1784 static int ssh_closing(Plug plug
, char *error_msg
, int error_code
,
1787 ssh_state
= SSH_STATE_CLOSED
;
1793 /* A socket error has occurred. */
1794 logevent(error_msg
);
1795 connection_fatal(error_msg
);
1797 /* Otherwise, the remote side closed the connection normally. */
1802 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
1804 ssh_gotdata(data
, len
);
1805 if (ssh_state
== SSH_STATE_CLOSED
) {
1815 static void ssh_sent(Plug plug
, int bufsize
)
1818 * If the send backlog on the SSH socket itself clears, we
1819 * should unthrottle the whole world if it was throttled.
1821 if (bufsize
< SSH_MAX_BACKLOG
)
1822 ssh_throttle_all(0, bufsize
);
1826 * Connect to specified host and port.
1827 * Returns an error message, or NULL on success.
1828 * Also places the canonical host name into `realhost'. It must be
1829 * freed by the caller.
1831 static char *connect_to_host(char *host
, int port
, char **realhost
, int nodelay
)
1833 static struct plug_function_table fn_table
= {
1838 }, *fn_table_ptr
= &fn_table
;
1847 savedhost
= smalloc(1 + strlen(host
));
1849 fatalbox("Out of memory");
1850 strcpy(savedhost
, host
);
1853 port
= 22; /* default ssh port */
1868 sprintf(buf
, "Looking up host \"%.170s\"", host
);
1871 addr
= sk_namelookup(host
, realhost
);
1872 if ((err
= sk_addr_error(addr
)))
1876 *realhost
= strdup(FWhost
);
1883 char buf
[200], addrbuf
[100];
1884 sk_getaddr(addr
, addrbuf
, 100);
1885 sprintf(buf
, "Connecting to %.100s port %d", addrbuf
, port
);
1888 s
= new_connection(addr
, *realhost
, port
, 0, 1, nodelay
, &fn_table_ptr
);
1889 if ((err
= sk_socket_error(s
))) {
1895 sk_write(s
, "connect ", 8);
1896 sk_write(s
, FWhost
, strlen(FWhost
));
1899 sprintf(buf
, " %d\n", FWport
);
1900 sk_write(s
, buf
, strlen(buf
));
1908 * Throttle or unthrottle the SSH connection.
1910 static void ssh1_throttle(int adjust
)
1912 int old_count
= ssh1_throttle_count
;
1913 ssh1_throttle_count
+= adjust
;
1914 assert(ssh1_throttle_count
>= 0);
1915 if (ssh1_throttle_count
&& !old_count
) {
1916 sk_set_frozen(s
, 1);
1917 } else if (!ssh1_throttle_count
&& old_count
) {
1918 sk_set_frozen(s
, 0);
1923 * Throttle or unthrottle _all_ local data streams (for when sends
1924 * on the SSH connection itself back up).
1926 static void ssh_throttle_all(int enable
, int bufsize
)
1929 struct ssh_channel
*c
;
1931 if (enable
== ssh_throttled_all
)
1933 ssh_throttled_all
= enable
;
1934 ssh_overall_bufsize
= bufsize
;
1937 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++) {
1939 case CHAN_MAINSESSION
:
1941 * This is treated separately, outside the switch.
1945 x11_override_throttle(c
->u
.x11
.s
, enable
);
1948 /* Agent channels require no buffer management. */
1951 pfd_override_throttle(c
->u
.x11
.s
, enable
);
1958 * Handle the key exchange and user authentication phases.
1960 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1964 static unsigned char *rsabuf
, *keystr1
, *keystr2
;
1965 unsigned char cookie
[8];
1966 struct RSAKey servkey
, hostkey
;
1967 struct MD5Context md5c
;
1968 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1969 static int tried_publickey
, tried_agent
;
1970 static int tis_auth_refused
, ccard_auth_refused
;
1971 static unsigned char session_id
[16];
1972 static int cipher_type
;
1973 static char username
[100];
1974 static void *publickey_blob
;
1975 int publickey_bloblen
;
1982 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1983 bombout(("Public key packet not received"));
1987 logevent("Received public keys");
1989 memcpy(cookie
, pktin
.body
, 8);
1991 i
= makekey(pktin
.body
+ 8, &servkey
, &keystr1
, 0);
1992 j
= makekey(pktin
.body
+ 8 + i
, &hostkey
, &keystr2
, 0);
1995 * Log the host key fingerprint.
1999 logevent("Host key fingerprint is:");
2000 strcpy(logmsg
, " ");
2001 hostkey
.comment
= NULL
;
2002 rsa_fingerprint(logmsg
+ strlen(logmsg
),
2003 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
2007 ssh1_remote_protoflags
= GET_32BIT(pktin
.body
+ 8 + i
+ j
);
2008 supported_ciphers_mask
= GET_32BIT(pktin
.body
+ 12 + i
+ j
);
2009 supported_auths_mask
= GET_32BIT(pktin
.body
+ 16 + i
+ j
);
2011 ssh1_local_protoflags
=
2012 ssh1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
2013 ssh1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
2016 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
2017 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
2018 MD5Update(&md5c
, pktin
.body
, 8);
2019 MD5Final(session_id
, &md5c
);
2021 for (i
= 0; i
< 32; i
++)
2022 session_key
[i
] = random_byte();
2024 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
2026 rsabuf
= smalloc(len
);
2028 fatalbox("Out of memory");
2031 * Verify the host key.
2035 * First format the key into a string.
2037 int len
= rsastr_len(&hostkey
);
2038 char fingerprint
[100];
2039 char *keystr
= smalloc(len
);
2041 fatalbox("Out of memory");
2042 rsastr_fmt(keystr
, &hostkey
);
2043 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
2044 verify_ssh_host_key(savedhost
, savedport
, "rsa", keystr
,
2049 for (i
= 0; i
< 32; i
++) {
2050 rsabuf
[i
] = session_key
[i
];
2052 rsabuf
[i
] ^= session_id
[i
];
2055 if (hostkey
.bytes
> servkey
.bytes
) {
2056 rsaencrypt(rsabuf
, 32, &servkey
);
2057 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
2059 rsaencrypt(rsabuf
, 32, &hostkey
);
2060 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
2063 logevent("Encrypted session key");
2066 int cipher_chosen
= 0, warn
= 0;
2067 char *cipher_string
= NULL
;
2068 for (i
= 0; !cipher_chosen
&& i
< CIPHER_MAX
; i
++) {
2069 int next_cipher
= cfg
.ssh_cipherlist
[i
];
2070 if (next_cipher
== CIPHER_WARN
) {
2071 /* If/when we choose a cipher, warn about it */
2073 } else if (next_cipher
== CIPHER_AES
) {
2074 /* XXX Probably don't need to mention this. */
2075 logevent("AES not supported in SSH1, skipping");
2077 switch (next_cipher
) {
2078 case CIPHER_3DES
: cipher_type
= SSH_CIPHER_3DES
;
2079 cipher_string
= "3DES"; break;
2080 case CIPHER_BLOWFISH
: cipher_type
= SSH_CIPHER_BLOWFISH
;
2081 cipher_string
= "Blowfish"; break;
2082 case CIPHER_DES
: cipher_type
= SSH_CIPHER_DES
;
2083 cipher_string
= "single-DES"; break;
2085 if (supported_ciphers_mask
& (1 << cipher_type
))
2089 if (!cipher_chosen
) {
2090 if ((supported_ciphers_mask
& (1 << SSH_CIPHER_3DES
)) == 0)
2091 bombout(("Server violates SSH 1 protocol by not "
2092 "supporting 3DES encryption"));
2094 /* shouldn't happen */
2095 bombout(("No supported ciphers found"));
2099 /* Warn about chosen cipher if necessary. */
2101 askcipher(cipher_string
, 0);
2104 switch (cipher_type
) {
2105 case SSH_CIPHER_3DES
:
2106 logevent("Using 3DES encryption");
2108 case SSH_CIPHER_DES
:
2109 logevent("Using single-DES encryption");
2111 case SSH_CIPHER_BLOWFISH
:
2112 logevent("Using Blowfish encryption");
2116 send_packet(SSH1_CMSG_SESSION_KEY
,
2117 PKT_CHAR
, cipher_type
,
2118 PKT_DATA
, cookie
, 8,
2119 PKT_CHAR
, (len
* 8) >> 8, PKT_CHAR
, (len
* 8) & 0xFF,
2120 PKT_DATA
, rsabuf
, len
,
2121 PKT_INT
, ssh1_local_protoflags
, PKT_END
);
2123 logevent("Trying to enable encryption...");
2127 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
2128 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
: &ssh_3des
;
2129 cipher
->sesskey(session_key
);
2133 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2134 bombout(("Encryption not successfully enabled"));
2138 logevent("Successfully started encryption");
2144 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
2146 if (!ssh_get_line("login as: ",
2147 username
, sizeof(username
), FALSE
)) {
2149 * get_line failed to get a username.
2152 logevent("No username provided. Abandoning session.");
2153 ssh_state
= SSH_STATE_CLOSED
;
2157 c_write_str("login as: ");
2160 crWaitUntil(!ispkt
);
2162 switch (c
= *in
++) {
2171 c_write_str("\b \b");
2178 c_write_str("\b \b");
2187 if (((c
>= ' ' && c
<= '~') ||
2188 ((unsigned char) c
>= 160))
2189 && pos
< sizeof(username
)-1) {
2190 username
[pos
++] = c
;
2196 c_write_str("\r\n");
2197 username
[strcspn(username
, "\n\r")] = '\0';
2200 strncpy(username
, cfg
.username
, 99);
2201 username
[99] = '\0';
2204 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
2206 char userlog
[22 + sizeof(username
)];
2207 sprintf(userlog
, "Sent username \"%s\"", username
);
2209 if (flags
& FLAG_INTERACTIVE
&&
2210 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
2211 strcat(userlog
, "\r\n");
2212 c_write_str(userlog
);
2219 if ((ssh_remote_bugs
& BUG_CHOKES_ON_RSA
)) {
2220 /* We must not attempt PK auth. Pretend we've already tried it. */
2221 tried_publickey
= tried_agent
= 1;
2223 tried_publickey
= tried_agent
= 0;
2225 tis_auth_refused
= ccard_auth_refused
= 0;
2226 /* Load the public half of cfg.keyfile so we notice if it's in Pageant */
2228 if (!rsakey_pubblob(cfg
.keyfile
, &publickey_blob
, &publickey_bloblen
))
2229 publickey_blob
= NULL
;
2231 publickey_blob
= NULL
;
2233 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
2234 static char password
[100];
2235 static char prompt
[200];
2238 static int pwpkt_type
;
2239 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
2241 if (agent_exists() && !tried_agent
) {
2243 * Attempt RSA authentication using Pageant.
2245 static unsigned char request
[5], *response
, *p
;
2246 static int responselen
;
2247 static int i
, nkeys
;
2248 static int authed
= FALSE
;
2252 logevent("Pageant is running. Requesting keys.");
2254 /* Request the keys held by the agent. */
2255 PUT_32BIT(request
, 1);
2256 request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
2257 agent_query(request
, 5, &r
, &responselen
);
2258 response
= (unsigned char *) r
;
2259 if (response
&& responselen
>= 5 &&
2260 response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
2262 nkeys
= GET_32BIT(p
);
2266 sprintf(buf
, "Pageant has %d SSH1 keys", nkeys
);
2269 for (i
= 0; i
< nkeys
; i
++) {
2270 static struct RSAKey key
;
2271 static Bignum challenge
;
2272 static char *commentp
;
2273 static int commentlen
;
2277 sprintf(buf
, "Trying Pageant key #%d", i
);
2280 if (publickey_blob
&&
2281 !memcmp(p
, publickey_blob
, publickey_bloblen
)) {
2282 logevent("This key matches configured key file");
2283 tried_publickey
= 1;
2286 p
+= ssh1_read_bignum(p
, &key
.exponent
);
2287 p
+= ssh1_read_bignum(p
, &key
.modulus
);
2288 commentlen
= GET_32BIT(p
);
2292 send_packet(SSH1_CMSG_AUTH_RSA
,
2293 PKT_BIGNUM
, key
.modulus
, PKT_END
);
2295 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2296 logevent("Key refused");
2299 logevent("Received RSA challenge");
2300 ssh1_read_bignum(pktin
.body
, &challenge
);
2302 char *agentreq
, *q
, *ret
;
2305 len
= 1 + 4; /* message type, bit count */
2306 len
+= ssh1_bignum_length(key
.exponent
);
2307 len
+= ssh1_bignum_length(key
.modulus
);
2308 len
+= ssh1_bignum_length(challenge
);
2309 len
+= 16; /* session id */
2310 len
+= 4; /* response format */
2311 agentreq
= smalloc(4 + len
);
2312 PUT_32BIT(agentreq
, len
);
2314 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
2315 PUT_32BIT(q
, bignum_bitcount(key
.modulus
));
2317 q
+= ssh1_write_bignum(q
, key
.exponent
);
2318 q
+= ssh1_write_bignum(q
, key
.modulus
);
2319 q
+= ssh1_write_bignum(q
, challenge
);
2320 memcpy(q
, session_id
, 16);
2322 PUT_32BIT(q
, 1); /* response format */
2323 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
2327 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
2328 logevent("Sending Pageant's response");
2329 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2330 PKT_DATA
, ret
+ 5, 16,
2334 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2336 ("Pageant's response accepted");
2337 if (flags
& FLAG_VERBOSE
) {
2339 ("Authenticated using RSA key \"");
2340 c_write(commentp
, commentlen
);
2341 c_write_str("\" from agent\r\n");
2346 ("Pageant's response not accepted");
2349 ("Pageant failed to answer challenge");
2353 logevent("No reply received from Pageant");
2356 freebn(key
.exponent
);
2357 freebn(key
.modulus
);
2366 if (*cfg
.keyfile
&& !tried_publickey
)
2367 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
2369 if (cfg
.try_tis_auth
&&
2370 (supported_auths_mask
& (1 << SSH1_AUTH_TIS
)) &&
2371 !tis_auth_refused
) {
2372 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
2373 logevent("Requested TIS authentication");
2374 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
2376 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
2377 logevent("TIS authentication declined");
2378 if (flags
& FLAG_INTERACTIVE
)
2379 c_write_str("TIS authentication refused.\r\n");
2380 tis_auth_refused
= 1;
2383 int challengelen
= ((pktin
.body
[0] << 24) |
2384 (pktin
.body
[1] << 16) |
2385 (pktin
.body
[2] << 8) |
2387 logevent("Received TIS challenge");
2388 if (challengelen
> sizeof(prompt
) - 1)
2389 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2390 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2391 /* Prompt heuristic comes from OpenSSH */
2392 strncpy(prompt
+ challengelen
,
2393 memchr(prompt
, '\n', challengelen
) ?
2394 "": "\r\nResponse: ",
2395 (sizeof prompt
) - challengelen
);
2396 prompt
[(sizeof prompt
) - 1] = '\0';
2399 if (cfg
.try_tis_auth
&&
2400 (supported_auths_mask
& (1 << SSH1_AUTH_CCARD
)) &&
2401 !ccard_auth_refused
) {
2402 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
2403 logevent("Requested CryptoCard authentication");
2404 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
2406 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
2407 logevent("CryptoCard authentication declined");
2408 c_write_str("CryptoCard authentication refused.\r\n");
2409 ccard_auth_refused
= 1;
2412 int challengelen
= ((pktin
.body
[0] << 24) |
2413 (pktin
.body
[1] << 16) |
2414 (pktin
.body
[2] << 8) |
2416 logevent("Received CryptoCard challenge");
2417 if (challengelen
> sizeof(prompt
) - 1)
2418 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2419 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2420 strncpy(prompt
+ challengelen
,
2421 memchr(prompt
, '\n', challengelen
) ?
2422 "" : "\r\nResponse: ",
2423 sizeof(prompt
) - challengelen
);
2424 prompt
[sizeof(prompt
) - 1] = '\0';
2427 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2428 sprintf(prompt
, "%.90s@%.90s's password: ",
2429 username
, savedhost
);
2431 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2432 char *comment
= NULL
;
2433 if (flags
& FLAG_VERBOSE
)
2434 c_write_str("Trying public key authentication.\r\n");
2435 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
2436 if (flags
& FLAG_VERBOSE
)
2437 c_write_str("No passphrase required.\r\n");
2440 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
2445 * Show password prompt, having first obtained it via a TIS
2446 * or CryptoCard exchange if we're doing TIS or CryptoCard
2450 if (!ssh_get_line(prompt
, password
, sizeof(password
), TRUE
)) {
2452 * get_line failed to get a password (for example
2453 * because one was supplied on the command line
2454 * which has already failed to work). Terminate.
2456 send_packet(SSH1_MSG_DISCONNECT
,
2457 PKT_STR
, "No more passwords available to try",
2459 logevent("Unable to authenticate");
2460 connection_fatal("Unable to authenticate");
2461 ssh_state
= SSH_STATE_CLOSED
;
2465 /* Prompt may have come from server. We've munged it a bit, so
2466 * we know it to be zero-terminated at least once. */
2467 c_write_untrusted(prompt
, strlen(prompt
));
2471 crWaitUntil(!ispkt
);
2473 switch (c
= *in
++) {
2493 if (pos
< sizeof(password
)-1)
2494 password
[pos
++] = c
;
2498 c_write_str("\r\n");
2502 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2504 * Try public key authentication with the specified
2507 static struct RSAKey pubkey
;
2508 static Bignum challenge
, response
;
2510 static unsigned char buffer
[32];
2512 tried_publickey
= 1;
2513 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
2515 c_write_str("Couldn't load private key from ");
2516 c_write_str(cfg
.keyfile
);
2517 c_write_str(".\r\n");
2518 continue; /* go and try password */
2521 c_write_str("Wrong passphrase.\r\n");
2522 tried_publickey
= 0;
2523 continue; /* try again */
2527 * Send a public key attempt.
2529 send_packet(SSH1_CMSG_AUTH_RSA
,
2530 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
2533 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2534 c_write_str("Server refused our public key.\r\n");
2535 continue; /* go and try password */
2537 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2538 bombout(("Bizarre response to offer of public key"));
2541 ssh1_read_bignum(pktin
.body
, &challenge
);
2542 response
= rsadecrypt(challenge
, &pubkey
);
2543 freebn(pubkey
.private_exponent
); /* burn the evidence */
2545 for (i
= 0; i
< 32; i
++) {
2546 buffer
[i
] = bignum_byte(response
, 31 - i
);
2550 MD5Update(&md5c
, buffer
, 32);
2551 MD5Update(&md5c
, session_id
, 16);
2552 MD5Final(buffer
, &md5c
);
2554 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2555 PKT_DATA
, buffer
, 16, PKT_END
);
2558 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2559 if (flags
& FLAG_VERBOSE
)
2561 ("Failed to authenticate with our public key.\r\n");
2562 continue; /* go and try password */
2563 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2565 ("Bizarre response to RSA authentication response"));
2569 break; /* we're through! */
2571 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2573 * Defence against traffic analysis: we send a
2574 * whole bunch of packets containing strings of
2575 * different lengths. One of these strings is the
2576 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2577 * The others are all random data in
2578 * SSH1_MSG_IGNORE packets. This way a passive
2579 * listener can't tell which is the password, and
2580 * hence can't deduce the password length.
2582 * Anybody with a password length greater than 16
2583 * bytes is going to have enough entropy in their
2584 * password that a listener won't find it _that_
2585 * much help to know how long it is. So what we'll
2588 * - if password length < 16, we send 15 packets
2589 * containing string lengths 1 through 15
2591 * - otherwise, we let N be the nearest multiple
2592 * of 8 below the password length, and send 8
2593 * packets containing string lengths N through
2594 * N+7. This won't obscure the order of
2595 * magnitude of the password length, but it will
2596 * introduce a bit of extra uncertainty.
2598 * A few servers (the old 1.2.18 through 1.2.22)
2599 * can't deal with SSH1_MSG_IGNORE. For these
2600 * servers, we need an alternative defence. We make
2601 * use of the fact that the password is interpreted
2602 * as a C string: so we can append a NUL, then some
2605 * One server (a Cisco one) can deal with neither
2606 * SSH1_MSG_IGNORE _nor_ a padded password string.
2607 * For this server we are left with no defences
2608 * against password length sniffing.
2610 if (!(ssh_remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
)) {
2612 * The server can deal with SSH1_MSG_IGNORE, so
2613 * we can use the primary defence.
2615 int bottom
, top
, pwlen
, i
;
2618 pwlen
= strlen(password
);
2620 bottom
= 0; /* zero length passwords are OK! :-) */
2623 bottom
= pwlen
& ~7;
2627 assert(pwlen
>= bottom
&& pwlen
<= top
);
2629 randomstr
= smalloc(top
+ 1);
2631 for (i
= bottom
; i
<= top
; i
++) {
2633 defer_packet(pwpkt_type
, PKT_STR
, password
,
2636 for (j
= 0; j
< i
; j
++) {
2638 randomstr
[j
] = random_byte();
2639 } while (randomstr
[j
] == '\0');
2641 randomstr
[i
] = '\0';
2642 defer_packet(SSH1_MSG_IGNORE
,
2643 PKT_STR
, randomstr
, PKT_END
);
2646 logevent("Sending password with camouflage packets");
2647 ssh_pkt_defersend();
2649 else if (!(ssh_remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
2651 * The server can't deal with SSH1_MSG_IGNORE
2652 * but can deal with padded passwords, so we
2653 * can use the secondary defence.
2659 len
= strlen(password
);
2660 if (len
< sizeof(string
)) {
2662 strcpy(string
, password
);
2663 len
++; /* cover the zero byte */
2664 while (len
< sizeof(string
)) {
2665 string
[len
++] = (char) random_byte();
2670 logevent("Sending length-padded password");
2671 send_packet(pwpkt_type
, PKT_INT
, len
,
2672 PKT_DATA
, s
, len
, PKT_END
);
2675 * The server has _both_
2676 * BUG_CHOKES_ON_SSH1_IGNORE and
2677 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2678 * therefore nothing we can do.
2681 len
= strlen(password
);
2682 logevent("Sending unpadded password");
2683 send_packet(pwpkt_type
, PKT_INT
, len
,
2684 PKT_DATA
, password
, len
, PKT_END
);
2687 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
2690 logevent("Sent password");
2691 memset(password
, 0, strlen(password
));
2693 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2694 if (flags
& FLAG_VERBOSE
)
2695 c_write_str("Access denied\r\n");
2696 logevent("Authentication refused");
2697 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2698 logevent("Received disconnect request");
2699 ssh_state
= SSH_STATE_CLOSED
;
2701 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2702 bombout(("Strange packet received, type %d", pktin
.type
));
2707 logevent("Authentication successful");
2712 void sshfwd_close(struct ssh_channel
*c
)
2714 if (c
&& !c
->closes
) {
2716 * If the channel's remoteid is -1, we have sent
2717 * CHANNEL_OPEN for this channel, but it hasn't even been
2718 * acknowledged by the server. So we must set a close flag
2719 * on it now, and then when the server acks the channel
2720 * open, we can close it then.
2722 if (c
->remoteid
!= -1) {
2723 if (ssh_version
== 1) {
2724 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
2727 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2728 ssh2_pkt_adduint32(c
->remoteid
);
2733 if (c
->type
== CHAN_X11
) {
2735 logevent("Forwarded X11 connection terminated");
2736 } else if (c
->type
== CHAN_SOCKDATA
||
2737 c
->type
== CHAN_SOCKDATA_DORMANT
) {
2739 logevent("Forwarded port closed");
2744 int sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
2746 if (ssh_version
== 1) {
2747 send_packet(SSH1_MSG_CHANNEL_DATA
,
2748 PKT_INT
, c
->remoteid
,
2749 PKT_INT
, len
, PKT_DATA
, buf
, len
, PKT_END
);
2751 * In SSH1 we can return 0 here - implying that forwarded
2752 * connections are never individually throttled - because
2753 * the only circumstance that can cause throttling will be
2754 * the whole SSH connection backing up, in which case
2755 * _everything_ will be throttled as a whole.
2759 ssh2_add_channel_data(c
, buf
, len
);
2760 return ssh2_try_send(c
);
2764 void sshfwd_unthrottle(struct ssh_channel
*c
, int bufsize
)
2766 if (ssh_version
== 1) {
2767 if (c
->v
.v1
.throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
2768 c
->v
.v1
.throttling
= 0;
2772 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
2776 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
)
2782 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
2785 if (ssh_state
== SSH_STATE_CLOSED
)
2788 if (cfg
.agentfwd
&& agent_exists()) {
2789 logevent("Requesting agent forwarding");
2790 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
2794 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2795 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2796 bombout(("Protocol confusion"));
2798 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2799 logevent("Agent forwarding refused");
2801 logevent("Agent forwarding enabled");
2802 ssh_agentfwd_enabled
= TRUE
;
2806 if (cfg
.x11_forward
) {
2807 char proto
[20], data
[64];
2808 logevent("Requesting X11 forwarding");
2809 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
2810 if (ssh1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
2811 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2812 PKT_STR
, proto
, PKT_STR
, data
,
2813 PKT_INT
, 0, PKT_END
);
2815 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2816 PKT_STR
, proto
, PKT_STR
, data
, PKT_END
);
2821 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2822 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2823 bombout(("Protocol confusion"));
2825 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2826 logevent("X11 forwarding refused");
2828 logevent("X11 forwarding enabled");
2829 ssh_X11_fwd_enabled
= TRUE
;
2836 int sport
,dport
,sserv
,dserv
;
2837 char sports
[256], dports
[256], host
[256];
2841 ssh_rportfwds
= newtree234(ssh_rportcmp_ssh1
);
2842 /* Add port forwardings. */
2847 while (*e
&& *e
!= '\t')
2853 while (*e
&& *e
!= ':')
2863 dport
= atoi(dports
);
2867 se
= getservbyname(dports
, NULL
);
2869 dport
= ntohs(se
->s_port
);
2872 "Service lookup failed for destination port \"%s\"",
2877 sport
= atoi(sports
);
2881 se
= getservbyname(sports
, NULL
);
2883 sport
= ntohs(se
->s_port
);
2886 "Service lookup failed for source port \"%s\"",
2891 if (sport
&& dport
) {
2893 pfd_addforward(host
, dport
, sport
);
2894 sprintf(buf
, "Local port %.*s%.*s%d%.*s forwarding to"
2895 " %s:%.*s%.*s%d%.*s",
2896 sserv ?
strlen(sports
) : 0, sports
,
2897 sserv
, "(", sport
, sserv
, ")",
2899 dserv ?
strlen(dports
) : 0, dports
,
2900 dserv
, "(", dport
, dserv
, ")");
2903 struct ssh_rportfwd
*pf
;
2904 pf
= smalloc(sizeof(*pf
));
2905 strcpy(pf
->dhost
, host
);
2907 if (add234(ssh_rportfwds
, pf
) != pf
) {
2909 "Duplicate remote port forwarding to %s:%d",
2914 sprintf(buf
, "Requesting remote port %.*s%.*s%d%.*s"
2915 " forward to %s:%.*s%.*s%d%.*s",
2916 sserv ?
strlen(sports
) : 0, sports
,
2917 sserv
, "(", sport
, sserv
, ")",
2919 dserv ?
strlen(dports
) : 0, dports
,
2920 dserv
, "(", dport
, dserv
, ")");
2922 send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST
,
2934 send_packet(SSH1_CMSG_REQUEST_PTY
,
2935 PKT_STR
, cfg
.termtype
,
2936 PKT_INT
, rows
, PKT_INT
, cols
,
2937 PKT_INT
, 0, PKT_INT
, 0, PKT_CHAR
, 0, PKT_END
);
2938 ssh_state
= SSH_STATE_INTERMED
;
2942 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2943 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2944 bombout(("Protocol confusion"));
2946 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2947 c_write_str("Server refused to allocate pty\r\n");
2948 ssh_editing
= ssh_echoing
= 1;
2950 logevent("Allocated pty");
2952 ssh_editing
= ssh_echoing
= 1;
2955 if (cfg
.compression
) {
2956 send_packet(SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
2960 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2961 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2962 bombout(("Protocol confusion"));
2964 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2965 c_write_str("Server refused to compress\r\n");
2967 logevent("Started compression");
2968 ssh1_compressing
= TRUE
;
2969 zlib_compress_init();
2970 zlib_decompress_init();
2974 * Start the shell or command.
2976 * Special case: if the first-choice command is an SSH2
2977 * subsystem (hence not usable here) and the second choice
2978 * exists, we fall straight back to that.
2981 char *cmd
= cfg
.remote_cmd_ptr
;
2983 if (cfg
.ssh_subsys
&& cfg
.remote_cmd_ptr2
) {
2984 cmd
= cfg
.remote_cmd_ptr2
;
2985 ssh_fallback_cmd
= TRUE
;
2988 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
2990 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
2991 logevent("Started session");
2994 ssh_state
= SSH_STATE_SESSION
;
2998 ssh_special(TS_EOF
);
3000 ldisc_send(NULL
, 0, 0); /* cause ldisc to notice changes */
3002 ssh_channels
= newtree234(ssh_channelcmp
);
3006 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
3007 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
3008 long len
= GET_32BIT(pktin
.body
);
3010 from_backend(pktin
.type
== SSH1_SMSG_STDERR_DATA
,
3011 pktin
.body
+ 4, len
);
3012 if (!ssh1_stdout_throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
3013 ssh1_stdout_throttling
= 1;
3016 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
3017 ssh_state
= SSH_STATE_CLOSED
;
3018 logevent("Received disconnect request");
3020 } else if (pktin
.type
== SSH1_SMSG_X11_OPEN
) {
3021 /* Remote side is trying to open a channel to talk to our
3022 * X-Server. Give them back a local channel number. */
3023 struct ssh_channel
*c
;
3025 logevent("Received X11 connect request");
3026 /* Refuse if X11 forwarding is disabled. */
3027 if (!ssh_X11_fwd_enabled
) {
3028 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3029 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
3030 logevent("Rejected X11 connect request");
3032 c
= smalloc(sizeof(struct ssh_channel
));
3034 if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
3035 logevent("opening X11 forward connection failed");
3037 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3038 PKT_INT
, GET_32BIT(pktin
.body
),
3042 ("opening X11 forward connection succeeded");
3043 c
->remoteid
= GET_32BIT(pktin
.body
);
3044 c
->localid
= alloc_channel_id();
3046 c
->v
.v1
.throttling
= 0;
3047 c
->type
= CHAN_X11
; /* identify channel type */
3048 add234(ssh_channels
, c
);
3049 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
3050 PKT_INT
, c
->remoteid
, PKT_INT
,
3051 c
->localid
, PKT_END
);
3052 logevent("Opened X11 forward channel");
3055 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
3056 /* Remote side is trying to open a channel to talk to our
3057 * agent. Give them back a local channel number. */
3058 struct ssh_channel
*c
;
3060 /* Refuse if agent forwarding is disabled. */
3061 if (!ssh_agentfwd_enabled
) {
3062 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3063 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
3065 c
= smalloc(sizeof(struct ssh_channel
));
3066 c
->remoteid
= GET_32BIT(pktin
.body
);
3067 c
->localid
= alloc_channel_id();
3069 c
->v
.v1
.throttling
= 0;
3070 c
->type
= CHAN_AGENT
; /* identify channel type */
3071 c
->u
.a
.lensofar
= 0;
3072 add234(ssh_channels
, c
);
3073 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
3074 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
3077 } else if (pktin
.type
== SSH1_MSG_PORT_OPEN
) {
3078 /* Remote side is trying to open a channel to talk to a
3079 * forwarded port. Give them back a local channel number. */
3080 struct ssh_channel
*c
;
3081 struct ssh_rportfwd pf
;
3083 char host
[256], buf
[1024];
3085 c
= smalloc(sizeof(struct ssh_channel
));
3087 hostsize
= GET_32BIT(pktin
.body
+4);
3088 for(h
= host
, p
= pktin
.body
+8; hostsize
!= 0; hostsize
--) {
3089 if (h
+1 < host
+sizeof(host
))
3094 port
= GET_32BIT(p
);
3096 strcpy(pf
.dhost
, host
);
3099 if (find234(ssh_rportfwds
, &pf
, NULL
) == NULL
) {
3100 sprintf(buf
, "Rejected remote port open request for %s:%d",
3103 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3104 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
3106 sprintf(buf
, "Received remote port open request for %s:%d",
3109 e
= pfd_newconnect(&c
->u
.pfd
.s
, host
, port
, c
);
3112 sprintf(buf
, "Port open failed: %s", e
);
3115 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3116 PKT_INT
, GET_32BIT(pktin
.body
),
3119 c
->remoteid
= GET_32BIT(pktin
.body
);
3120 c
->localid
= alloc_channel_id();
3122 c
->v
.v1
.throttling
= 0;
3123 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
3124 add234(ssh_channels
, c
);
3125 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
3126 PKT_INT
, c
->remoteid
, PKT_INT
,
3127 c
->localid
, PKT_END
);
3128 logevent("Forwarded port opened successfully");
3132 } else if (pktin
.type
== SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
) {
3133 unsigned int remoteid
= GET_32BIT(pktin
.body
);
3134 unsigned int localid
= GET_32BIT(pktin
.body
+4);
3135 struct ssh_channel
*c
;
3137 c
= find234(ssh_channels
, &remoteid
, ssh_channelfind
);
3138 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
3139 c
->remoteid
= localid
;
3140 c
->type
= CHAN_SOCKDATA
;
3141 c
->v
.v1
.throttling
= 0;
3142 pfd_confirm(c
->u
.pfd
.s
);
3145 if (c
&& c
->closes
) {
3147 * We have a pending close on this channel,
3148 * which we decided on before the server acked
3149 * the channel open. So now we know the
3150 * remoteid, we can close it again.
3152 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
3156 } else if (pktin
.type
== SSH1_MSG_CHANNEL_OPEN_FAILURE
) {
3157 unsigned int remoteid
= GET_32BIT(pktin
.body
);
3158 unsigned int localid
= GET_32BIT(pktin
.body
+4);
3159 struct ssh_channel
*c
;
3161 c
= find234(ssh_channels
, &remoteid
, ssh_channelfind
);
3162 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
3163 logevent("Forwarded connection refused by server");
3164 pfd_close(c
->u
.pfd
.s
);
3165 del234(ssh_channels
, c
);
3169 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
3170 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
3171 /* Remote side closes a channel. */
3172 unsigned i
= GET_32BIT(pktin
.body
);
3173 struct ssh_channel
*c
;
3174 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3178 (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
3179 if (!(c
->closes
& closetype
))
3180 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
,
3182 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
3183 logevent("Forwarded X11 connection terminated");
3184 assert(c
->u
.x11
.s
!= NULL
);
3185 x11_close(c
->u
.x11
.s
);
3188 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
3189 logevent("Forwarded port closed");
3190 assert(c
->u
.pfd
.s
!= NULL
);
3191 pfd_close(c
->u
.pfd
.s
);
3194 c
->closes
|= closetype
;
3195 if (c
->closes
== 3) {
3196 del234(ssh_channels
, c
);
3200 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
3201 /* Data sent down one of our channels. */
3202 int i
= GET_32BIT(pktin
.body
);
3203 int len
= GET_32BIT(pktin
.body
+ 4);
3204 unsigned char *p
= pktin
.body
+ 8;
3205 struct ssh_channel
*c
;
3206 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3211 bufsize
= x11_send(c
->u
.x11
.s
, p
, len
);
3214 bufsize
= pfd_send(c
->u
.pfd
.s
, p
, len
);
3217 /* Data for an agent message. Buffer it. */
3219 if (c
->u
.a
.lensofar
< 4) {
3220 int l
= min(4 - c
->u
.a
.lensofar
, len
);
3221 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
3225 c
->u
.a
.lensofar
+= l
;
3227 if (c
->u
.a
.lensofar
== 4) {
3229 4 + GET_32BIT(c
->u
.a
.msglen
);
3230 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
3231 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
3233 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
3235 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
3237 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
3241 c
->u
.a
.lensofar
+= l
;
3243 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
3244 void *reply
, *sentreply
;
3246 agent_query(c
->u
.a
.message
,
3247 c
->u
.a
.totallen
, &reply
,
3252 /* Fake SSH_AGENT_FAILURE. */
3253 sentreply
= "\0\0\0\1\5";
3256 send_packet(SSH1_MSG_CHANNEL_DATA
,
3257 PKT_INT
, c
->remoteid
,
3259 PKT_DATA
, sentreply
, replylen
,
3263 sfree(c
->u
.a
.message
);
3264 c
->u
.a
.lensofar
= 0;
3267 bufsize
= 0; /* agent channels never back up */
3270 if (!c
->v
.v1
.throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
3271 c
->v
.v1
.throttling
= 1;
3275 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
3276 /* may be from EXEC_SHELL on some servers */
3277 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
3278 /* may be from EXEC_SHELL on some servers
3279 * if no pty is available or in other odd cases. Ignore */
3280 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
3282 ssh_exitcode
= GET_32BIT(pktin
.body
);
3283 sprintf(buf
, "Server sent command exit status %d",
3286 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
3288 * In case `helpful' firewalls or proxies tack
3289 * extra human-readable text on the end of the
3290 * session which we might mistake for another
3291 * encrypted packet, we close the session once
3292 * we've sent EXIT_CONFIRMATION.
3294 ssh_state
= SSH_STATE_CLOSED
;
3297 bombout(("Strange packet received: type %d", pktin
.type
));
3302 int len
= min(inlen
, 512);
3303 send_packet(SSH1_CMSG_STDIN_DATA
,
3304 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
3315 * Utility routine for decoding comma-separated strings in KEXINIT.
3317 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
3319 int needlen
= strlen(needle
);
3322 * Is it at the start of the string?
3324 if (haylen
>= needlen
&& /* haystack is long enough */
3325 !memcmp(needle
, haystack
, needlen
) && /* initial match */
3326 (haylen
== needlen
|| haystack
[needlen
] == ',')
3327 /* either , or EOS follows */
3331 * If not, search for the next comma and resume after that.
3332 * If no comma found, terminate.
3334 while (haylen
> 0 && *haystack
!= ',')
3335 haylen
--, haystack
++;
3338 haylen
--, haystack
++; /* skip over comma itself */
3343 * SSH2 key creation method.
3345 static void ssh2_mkkey(Bignum K
, char *H
, char *sessid
, char chr
,
3349 /* First 20 bytes. */
3352 SHA_Bytes(&s
, H
, 20);
3353 SHA_Bytes(&s
, &chr
, 1);
3354 SHA_Bytes(&s
, sessid
, 20);
3355 SHA_Final(&s
, keyspace
);
3356 /* Next 20 bytes. */
3359 SHA_Bytes(&s
, H
, 20);
3360 SHA_Bytes(&s
, keyspace
, 20);
3361 SHA_Final(&s
, keyspace
+ 20);
3365 * Handle the SSH2 transport layer.
3367 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
3369 static int i
, j
, len
, nbits
, pbits
, warn
;
3371 static Bignum p
, g
, e
, f
, K
;
3372 static int kex_init_value
, kex_reply_value
;
3373 static const struct ssh_mac
**maclist
;
3375 static const struct ssh2_cipher
*cscipher_tobe
= NULL
;
3376 static const struct ssh2_cipher
*sccipher_tobe
= NULL
;
3377 static const struct ssh_mac
*csmac_tobe
= NULL
;
3378 static const struct ssh_mac
*scmac_tobe
= NULL
;
3379 static const struct ssh_compress
*cscomp_tobe
= NULL
;
3380 static const struct ssh_compress
*sccomp_tobe
= NULL
;
3381 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
3382 static int hostkeylen
, siglen
;
3383 static void *hkey
; /* actual host key */
3384 static unsigned char exchange_hash
[20];
3385 static unsigned char keyspace
[40];
3386 static int n_preferred_ciphers
;
3387 static const struct ssh2_ciphers
*preferred_ciphers
[CIPHER_MAX
];
3388 static const struct ssh_compress
*preferred_comp
;
3389 static int cipherstr_started
;
3390 static int first_kex
;
3397 * Set up the preferred ciphers. (NULL => warn below here)
3399 n_preferred_ciphers
= 0;
3400 for (i
= 0; i
< CIPHER_MAX
; i
++) {
3401 switch (cfg
.ssh_cipherlist
[i
]) {
3402 case CIPHER_BLOWFISH
:
3403 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_blowfish
;
3404 n_preferred_ciphers
++;
3407 if (cfg
.ssh2_des_cbc
) {
3408 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_des
;
3409 n_preferred_ciphers
++;
3413 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_3des
;
3414 n_preferred_ciphers
++;
3417 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_aes
;
3418 n_preferred_ciphers
++;
3421 /* Flag for later. Don't bother if it's the last in
3423 if (i
< CIPHER_MAX
- 1) {
3424 preferred_ciphers
[n_preferred_ciphers
] = NULL
;
3425 n_preferred_ciphers
++;
3432 * Set up preferred compression.
3434 if (cfg
.compression
)
3435 preferred_comp
= &ssh_zlib
;
3437 preferred_comp
= &ssh_comp_none
;
3440 * Be prepared to work around the buggy MAC problem.
3442 if (cfg
.buggymac
|| (ssh_remote_bugs
& BUG_SSH2_HMAC
))
3443 maclist
= buggymacs
, nmacs
= lenof(buggymacs
);
3445 maclist
= macs
, nmacs
= lenof(macs
);
3449 * Construct and send our key exchange packet.
3451 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
3452 for (i
= 0; i
< 16; i
++)
3453 ssh2_pkt_addbyte((unsigned char) random_byte());
3454 /* List key exchange algorithms. */
3455 ssh2_pkt_addstring_start();
3456 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3457 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
3458 if (i
< lenof(kex_algs
) - 1)
3459 ssh2_pkt_addstring_str(",");
3461 /* List server host key algorithms. */
3462 ssh2_pkt_addstring_start();
3463 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3464 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
3465 if (i
< lenof(hostkey_algs
) - 1)
3466 ssh2_pkt_addstring_str(",");
3468 /* List client->server encryption algorithms. */
3469 ssh2_pkt_addstring_start();
3470 cipherstr_started
= 0;
3471 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3472 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3473 if (!c
) continue; /* warning flag */
3474 for (j
= 0; j
< c
->nciphers
; j
++) {
3475 if (cipherstr_started
)
3476 ssh2_pkt_addstring_str(",");
3477 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
3478 cipherstr_started
= 1;
3481 /* List server->client encryption algorithms. */
3482 ssh2_pkt_addstring_start();
3483 cipherstr_started
= 0;
3484 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3485 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3486 if (!c
) continue; /* warning flag */
3487 for (j
= 0; j
< c
->nciphers
; j
++) {
3488 if (cipherstr_started
)
3489 ssh2_pkt_addstring_str(",");
3490 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
3491 cipherstr_started
= 1;
3494 /* List client->server MAC algorithms. */
3495 ssh2_pkt_addstring_start();
3496 for (i
= 0; i
< nmacs
; i
++) {
3497 ssh2_pkt_addstring_str(maclist
[i
]->name
);
3499 ssh2_pkt_addstring_str(",");
3501 /* List server->client MAC algorithms. */
3502 ssh2_pkt_addstring_start();
3503 for (i
= 0; i
< nmacs
; i
++) {
3504 ssh2_pkt_addstring_str(maclist
[i
]->name
);
3506 ssh2_pkt_addstring_str(",");
3508 /* List client->server compression algorithms. */
3509 ssh2_pkt_addstring_start();
3510 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3511 const struct ssh_compress
*c
=
3512 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3513 ssh2_pkt_addstring_str(c
->name
);
3514 if (i
< lenof(compressions
))
3515 ssh2_pkt_addstring_str(",");
3517 /* List server->client compression algorithms. */
3518 ssh2_pkt_addstring_start();
3519 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3520 const struct ssh_compress
*c
=
3521 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3522 ssh2_pkt_addstring_str(c
->name
);
3523 if (i
< lenof(compressions
))
3524 ssh2_pkt_addstring_str(",");
3526 /* List client->server languages. Empty list. */
3527 ssh2_pkt_addstring_start();
3528 /* List server->client languages. Empty list. */
3529 ssh2_pkt_addstring_start();
3530 /* First KEX packet does _not_ follow, because we're not that brave. */
3531 ssh2_pkt_addbool(FALSE
);
3533 ssh2_pkt_adduint32(0);
3535 exhash
= exhashbase
;
3536 sha_string(&exhash
, pktout
.data
+ 5, pktout
.length
- 5);
3542 sha_string(&exhash
, pktin
.data
+ 5, pktin
.length
- 5);
3545 * Now examine the other side's KEXINIT to see what we're up
3548 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
3549 bombout(("expected key exchange packet from server"));
3554 cscipher_tobe
= NULL
;
3555 sccipher_tobe
= NULL
;
3560 pktin
.savedpos
+= 16; /* skip garbage cookie */
3561 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
3562 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3563 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
3568 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
3569 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3570 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
3571 hostkey
= hostkey_algs
[i
];
3575 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
3577 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3578 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3582 for (j
= 0; j
< c
->nciphers
; j
++) {
3583 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3584 cscipher_tobe
= c
->list
[j
];
3589 if (cscipher_tobe
) {
3591 askcipher(cscipher_tobe
->name
, 1);
3595 if (!cscipher_tobe
) {
3596 bombout(("Couldn't agree a client-to-server cipher (available: %s)", str
));
3600 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
3602 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3603 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3607 for (j
= 0; j
< c
->nciphers
; j
++) {
3608 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3609 sccipher_tobe
= c
->list
[j
];
3614 if (sccipher_tobe
) {
3616 askcipher(sccipher_tobe
->name
, 2);
3620 if (!sccipher_tobe
) {
3621 bombout(("Couldn't agree a server-to-client cipher (available: %s)", str
));
3625 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
3626 for (i
= 0; i
< nmacs
; i
++) {
3627 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3628 csmac_tobe
= maclist
[i
];
3632 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
3633 for (i
= 0; i
< nmacs
; i
++) {
3634 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3635 scmac_tobe
= maclist
[i
];
3639 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
3640 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3641 const struct ssh_compress
*c
=
3642 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3643 if (in_commasep_string(c
->name
, str
, len
)) {
3648 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
3649 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3650 const struct ssh_compress
*c
=
3651 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3652 if (in_commasep_string(c
->name
, str
, len
)) {
3659 * Work out the number of bits of key we will need from the key
3660 * exchange. We start with the maximum key length of either
3666 csbits
= cscipher_tobe
->keylen
;
3667 scbits
= sccipher_tobe
->keylen
;
3668 nbits
= (csbits
> scbits ? csbits
: scbits
);
3670 /* The keys only have 160-bit entropy, since they're based on
3671 * a SHA-1 hash. So cap the key size at 160 bits. */
3676 * If we're doing Diffie-Hellman group exchange, start by
3677 * requesting a group.
3679 if (kex
== &ssh_diffiehellman_gex
) {
3680 logevent("Doing Diffie-Hellman group exchange");
3681 ssh_pkt_ctx
|= SSH2_PKTCTX_DHGEX
;
3683 * Work out how big a DH group we will need to allow that
3686 pbits
= 512 << ((nbits
- 1) / 64);
3687 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
3688 ssh2_pkt_adduint32(pbits
);
3692 if (pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
3693 bombout(("expected key exchange group packet from server"));
3696 p
= ssh2_pkt_getmp();
3697 g
= ssh2_pkt_getmp();
3698 dh_setup_group(p
, g
);
3699 kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
3700 kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
3702 ssh_pkt_ctx
|= SSH2_PKTCTX_DHGROUP1
;
3704 kex_init_value
= SSH2_MSG_KEXDH_INIT
;
3705 kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
3708 logevent("Doing Diffie-Hellman key exchange");
3710 * Now generate and send e for Diffie-Hellman.
3712 e
= dh_create_e(nbits
* 2);
3713 ssh2_pkt_init(kex_init_value
);
3718 if (pktin
.type
!= kex_reply_value
) {
3719 bombout(("expected key exchange reply packet from server"));
3722 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
3723 f
= ssh2_pkt_getmp();
3724 ssh2_pkt_getstring(&sigdata
, &siglen
);
3728 sha_string(&exhash
, hostkeydata
, hostkeylen
);
3729 if (kex
== &ssh_diffiehellman_gex
) {
3730 sha_uint32(&exhash
, pbits
);
3731 sha_mpint(&exhash
, p
);
3732 sha_mpint(&exhash
, g
);
3734 sha_mpint(&exhash
, e
);
3735 sha_mpint(&exhash
, f
);
3736 sha_mpint(&exhash
, K
);
3737 SHA_Final(&exhash
, exchange_hash
);
3742 debug(("Exchange hash is:\n"));
3743 dmemdump(exchange_hash
, 20);
3746 hkey
= hostkey
->newkey(hostkeydata
, hostkeylen
);
3748 !hostkey
->verifysig(hkey
, sigdata
, siglen
, exchange_hash
, 20)) {
3749 bombout(("Server's host key did not match the signature supplied"));
3754 * Authenticate remote host: verify host key. (We've already
3755 * checked the signature of the exchange hash.)
3757 keystr
= hostkey
->fmtkey(hkey
);
3758 fingerprint
= hostkey
->fingerprint(hkey
);
3759 verify_ssh_host_key(savedhost
, savedport
, hostkey
->keytype
,
3760 keystr
, fingerprint
);
3761 if (first_kex
) { /* don't bother logging this in rekeys */
3762 logevent("Host key fingerprint is:");
3763 logevent(fingerprint
);
3767 hostkey
->freekey(hkey
);
3770 * Send SSH2_MSG_NEWKEYS.
3772 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
3776 * Expect SSH2_MSG_NEWKEYS from server.
3779 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
3780 bombout(("expected new-keys packet from server"));
3785 * Create and initialise session keys.
3787 cscipher
= cscipher_tobe
;
3788 sccipher
= sccipher_tobe
;
3791 cscomp
= cscomp_tobe
;
3792 sccomp
= sccomp_tobe
;
3793 cscomp
->compress_init();
3794 sccomp
->decompress_init();
3796 * Set IVs after keys. Here we use the exchange hash from the
3797 * _first_ key exchange.
3800 memcpy(ssh2_session_id
, exchange_hash
, sizeof(exchange_hash
));
3801 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'C', keyspace
);
3802 cscipher
->setcskey(keyspace
);
3803 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'D', keyspace
);
3804 sccipher
->setsckey(keyspace
);
3805 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'A', keyspace
);
3806 cscipher
->setcsiv(keyspace
);
3807 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'B', keyspace
);
3808 sccipher
->setsciv(keyspace
);
3809 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'E', keyspace
);
3810 csmac
->setcskey(keyspace
);
3811 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'F', keyspace
);
3812 scmac
->setsckey(keyspace
);
3815 * If this is the first key exchange phase, we must pass the
3816 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
3817 * wants to see it but because it will need time to initialise
3818 * itself before it sees an actual packet. In subsequent key
3819 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
3820 * it would only confuse the layer above.
3828 * Now we're encrypting. Begin returning 1 to the protocol main
3829 * function so that other things can run on top of the
3830 * transport. If we ever see a KEXINIT, we must go back to the
3833 while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
)) {
3836 logevent("Server initiated key re-exchange");
3837 goto begin_key_exchange
;
3843 * Add data to an SSH2 channel output buffer.
3845 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
3848 bufchain_add(&c
->v
.v2
.outbuffer
, buf
, len
);
3852 * Attempt to send data on an SSH2 channel.
3854 static int ssh2_try_send(struct ssh_channel
*c
)
3856 while (c
->v
.v2
.remwindow
> 0 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0) {
3859 bufchain_prefix(&c
->v
.v2
.outbuffer
, &data
, &len
);
3860 if ((unsigned)len
> c
->v
.v2
.remwindow
)
3861 len
= c
->v
.v2
.remwindow
;
3862 if ((unsigned)len
> c
->v
.v2
.remmaxpkt
)
3863 len
= c
->v
.v2
.remmaxpkt
;
3864 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
3865 ssh2_pkt_adduint32(c
->remoteid
);
3866 ssh2_pkt_addstring_start();
3867 ssh2_pkt_addstring_data(data
, len
);
3869 bufchain_consume(&c
->v
.v2
.outbuffer
, len
);
3870 c
->v
.v2
.remwindow
-= len
;
3874 * After having sent as much data as we can, return the amount
3877 return bufchain_size(&c
->v
.v2
.outbuffer
);
3881 * Potentially enlarge the window on an SSH2 channel.
3883 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
)
3886 * Never send WINDOW_ADJUST for a channel that the remote side
3887 * already thinks it's closed; there's no point, since it won't
3888 * be sending any more data anyway.
3893 if (newwin
> c
->v
.v2
.locwindow
) {
3894 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3895 ssh2_pkt_adduint32(c
->remoteid
);
3896 ssh2_pkt_adduint32(newwin
- c
->v
.v2
.locwindow
);
3898 c
->v
.v2
.locwindow
= newwin
;
3903 * Handle the SSH2 userauth and connection layers.
3905 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
3908 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
,
3910 AUTH_KEYBOARD_INTERACTIVE
3914 AUTH_TYPE_PUBLICKEY
,
3915 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
3916 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
3918 AUTH_TYPE_KEYBOARD_INTERACTIVE
,
3919 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
3921 static int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
3922 static int tried_pubkey_config
, tried_agent
, tried_keyb_inter
;
3923 static int kbd_inter_running
;
3924 static int we_are_in
;
3925 static int num_prompts
, echo
;
3926 static char username
[100];
3927 static int got_username
;
3928 static char pwprompt
[200];
3929 static char password
[100];
3930 static void *publickey_blob
;
3931 static int publickey_bloblen
;
3936 * Request userauth protocol, and await a response to it.
3938 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
3939 ssh2_pkt_addstring("ssh-userauth");
3941 crWaitUntilV(ispkt
);
3942 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
3943 bombout(("Server refused user authentication protocol"));
3948 * We repeat this whole loop, including the username prompt,
3949 * until we manage a successful authentication. If the user
3950 * types the wrong _password_, they are sent back to the
3951 * beginning to try another username. (If they specify a
3952 * username in the config, they are never asked, even if they
3953 * do give a wrong password.)
3955 * I think this best serves the needs of
3957 * - the people who have no configuration, no keys, and just
3958 * want to try repeated (username,password) pairs until they
3959 * type both correctly
3961 * - people who have keys and configuration but occasionally
3962 * need to fall back to passwords
3964 * - people with a key held in Pageant, who might not have
3965 * logged in to a particular machine before; so they want to
3966 * type a username, and then _either_ their key will be
3967 * accepted, _or_ they will type a password. If they mistype
3968 * the username they will want to be able to get back and
3972 got_username
= FALSE
;
3981 if (got_username
&& !cfg
.change_username
) {
3983 * We got a username last time round this loop, and
3984 * with change_username turned off we don't try to get
3987 } else if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
3989 if (!ssh_get_line("login as: ",
3990 username
, sizeof(username
), FALSE
)) {
3992 * get_line failed to get a username.
3995 logevent("No username provided. Abandoning session.");
3996 ssh_state
= SSH_STATE_CLOSED
;
4000 c_write_str("login as: ");
4003 crWaitUntilV(!ispkt
);
4005 switch (c
= *in
++) {
4014 c_write_str("\b \b");
4021 c_write_str("\b \b");
4030 if (((c
>= ' ' && c
<= '~') ||
4031 ((unsigned char) c
>= 160))
4032 && pos
< sizeof(username
)-1) {
4033 username
[pos
++] = c
;
4040 c_write_str("\r\n");
4041 username
[strcspn(username
, "\n\r")] = '\0';
4044 strncpy(username
, cfg
.username
, 99);
4045 username
[99] = '\0';
4046 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
4047 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
4051 got_username
= TRUE
;
4054 * Send an authentication request using method "none": (a)
4055 * just in case it succeeds, and (b) so that we know what
4056 * authentication methods we can usefully try next.
4058 ssh_pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4060 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4061 ssh2_pkt_addstring(username
);
4062 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4063 ssh2_pkt_addstring("none"); /* method */
4065 type
= AUTH_TYPE_NONE
;
4069 tried_pubkey_config
= FALSE
;
4070 tried_agent
= FALSE
;
4071 tried_keyb_inter
= FALSE
;
4072 kbd_inter_running
= FALSE
;
4073 /* Load the pub half of cfg.keyfile so we notice if it's in Pageant */
4075 publickey_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, NULL
,
4076 &publickey_bloblen
);
4078 publickey_blob
= NULL
;
4082 * Wait for the result of the last authentication request.
4085 crWaitUntilV(ispkt
);
4086 while (pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
4090 * Don't show the banner if we're operating in
4091 * non-verbose non-interactive mode. (It's probably
4092 * a script, which means nobody will read the
4093 * banner _anyway_, and moreover the printing of
4094 * the banner will screw up processing on the
4095 * output of (say) plink.)
4097 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
4098 ssh2_pkt_getstring(&banner
, &size
);
4100 c_write_untrusted(banner
, size
);
4102 crWaitUntilV(ispkt
);
4104 if (pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
4105 logevent("Access granted");
4110 if (kbd_inter_running
&&
4111 pktin
.type
== SSH2_MSG_USERAUTH_INFO_REQUEST
) {
4113 * This is a further prompt in keyboard-interactive
4114 * authentication. Do nothing.
4116 } else if (pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
4117 bombout(("Strange packet received during authentication: type %d",
4125 * OK, we're now sitting on a USERAUTH_FAILURE message, so
4126 * we can look at the string in it and know what we can
4127 * helpfully try next.
4129 if (pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
) {
4132 ssh2_pkt_getstring(&methods
, &methlen
);
4133 kbd_inter_running
= FALSE
;
4134 if (!ssh2_pkt_getbool()) {
4136 * We have received an unequivocal Access
4137 * Denied. This can translate to a variety of
4140 * - if we'd just tried "none" authentication,
4141 * it's not worth printing anything at all
4143 * - if we'd just tried a public key _offer_,
4144 * the message should be "Server refused our
4145 * key" (or no message at all if the key
4146 * came from Pageant)
4148 * - if we'd just tried anything else, the
4149 * message really should be "Access denied".
4151 * Additionally, if we'd just tried password
4152 * authentication, we should break out of this
4153 * whole loop so as to go back to the username
4156 if (type
== AUTH_TYPE_NONE
) {
4158 } else if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
4159 type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
4160 if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
4161 c_write_str("Server refused our key\r\n");
4162 logevent("Server refused public key");
4163 } else if (type
== AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
) {
4164 /* server declined keyboard-interactive; ignore */
4166 c_write_str("Access denied\r\n");
4167 logevent("Access denied");
4168 if (type
== AUTH_TYPE_PASSWORD
) {
4174 c_write_str("Further authentication required\r\n");
4175 logevent("Further authentication required");
4179 in_commasep_string("publickey", methods
, methlen
);
4181 in_commasep_string("password", methods
, methlen
);
4182 can_keyb_inter
= cfg
.try_ki_auth
&&
4183 in_commasep_string("keyboard-interactive", methods
, methlen
);
4187 ssh_pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4189 if (!method
&& can_pubkey
&& agent_exists() && !tried_agent
) {
4191 * Attempt public-key authentication using Pageant.
4193 static unsigned char request
[5], *response
, *p
;
4194 static int responselen
;
4195 static int i
, nkeys
;
4196 static int authed
= FALSE
;
4199 ssh_pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
4203 logevent("Pageant is running. Requesting keys.");
4205 /* Request the keys held by the agent. */
4206 PUT_32BIT(request
, 1);
4207 request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
4208 agent_query(request
, 5, &r
, &responselen
);
4209 response
= (unsigned char *) r
;
4210 if (response
&& responselen
>= 5 &&
4211 response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
4213 nkeys
= GET_32BIT(p
);
4217 sprintf(buf
, "Pageant has %d SSH2 keys", nkeys
);
4220 for (i
= 0; i
< nkeys
; i
++) {
4221 static char *pkblob
, *alg
, *commentp
;
4222 static int pklen
, alglen
, commentlen
;
4223 static int siglen
, retlen
, len
;
4224 static char *q
, *agentreq
, *ret
;
4229 sprintf(buf
, "Trying Pageant key #%d", i
);
4232 pklen
= GET_32BIT(p
);
4234 if (publickey_blob
&&
4235 pklen
== publickey_bloblen
&&
4236 !memcmp(p
, publickey_blob
, publickey_bloblen
)) {
4237 logevent("This key matches configured key file");
4238 tried_pubkey_config
= 1;
4242 alglen
= GET_32BIT(pkblob
);
4244 commentlen
= GET_32BIT(p
);
4248 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4249 ssh2_pkt_addstring(username
);
4250 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4251 ssh2_pkt_addstring("publickey"); /* method */
4252 ssh2_pkt_addbool(FALSE
); /* no signature included */
4253 ssh2_pkt_addstring_start();
4254 ssh2_pkt_addstring_data(alg
, alglen
);
4255 ssh2_pkt_addstring_start();
4256 ssh2_pkt_addstring_data(pkblob
, pklen
);
4259 crWaitUntilV(ispkt
);
4260 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
4261 logevent("Key refused");
4265 if (flags
& FLAG_VERBOSE
) {
4267 ("Authenticating with public key \"");
4268 c_write(commentp
, commentlen
);
4269 c_write_str("\" from agent\r\n");
4273 * Server is willing to accept the key.
4274 * Construct a SIGN_REQUEST.
4276 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4277 ssh2_pkt_addstring(username
);
4278 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4279 ssh2_pkt_addstring("publickey"); /* method */
4280 ssh2_pkt_addbool(TRUE
);
4281 ssh2_pkt_addstring_start();
4282 ssh2_pkt_addstring_data(alg
, alglen
);
4283 ssh2_pkt_addstring_start();
4284 ssh2_pkt_addstring_data(pkblob
, pklen
);
4286 siglen
= pktout
.length
- 5 + 4 + 20;
4287 len
= 1; /* message type */
4288 len
+= 4 + pklen
; /* key blob */
4289 len
+= 4 + siglen
; /* data to sign */
4290 len
+= 4; /* flags */
4291 agentreq
= smalloc(4 + len
);
4292 PUT_32BIT(agentreq
, len
);
4294 *q
++ = SSH2_AGENTC_SIGN_REQUEST
;
4295 PUT_32BIT(q
, pklen
);
4297 memcpy(q
, pkblob
, pklen
);
4299 PUT_32BIT(q
, siglen
);
4301 /* Now the data to be signed... */
4304 memcpy(q
, ssh2_session_id
, 20);
4306 memcpy(q
, pktout
.data
+ 5, pktout
.length
- 5);
4307 q
+= pktout
.length
- 5;
4308 /* And finally the (zero) flags word. */
4310 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
4314 if (ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
4315 logevent("Sending Pageant's response");
4316 ssh2_pkt_addstring_start();
4317 ssh2_pkt_addstring_data(ret
+ 9,
4325 ("Pageant failed to answer challenge");
4335 if (!method
&& can_pubkey
&& *cfg
.keyfile
4336 && !tried_pubkey_config
) {
4337 unsigned char *pub_blob
;
4338 char *algorithm
, *comment
;
4341 tried_pubkey_config
= TRUE
;
4343 ssh_pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
4346 * Try the public key supplied in the configuration.
4348 * First, offer the public blob to see if the server is
4349 * willing to accept it.
4351 pub_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, &algorithm
,
4354 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4355 ssh2_pkt_addstring(username
);
4356 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4357 ssh2_pkt_addstring("publickey"); /* method */
4358 ssh2_pkt_addbool(FALSE
); /* no signature included */
4359 ssh2_pkt_addstring(algorithm
);
4360 ssh2_pkt_addstring_start();
4361 ssh2_pkt_addstring_data(pub_blob
, pub_blob_len
);
4363 logevent("Offered public key"); /* FIXME */
4365 crWaitUntilV(ispkt
);
4366 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
4368 type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
4369 continue; /* key refused; give up on it */
4372 logevent("Offer of public key accepted");
4374 * Actually attempt a serious authentication using
4377 if (ssh2_userkey_encrypted(cfg
.keyfile
, &comment
)) {
4379 "Passphrase for key \"%.100s\": ",
4385 c_write_str("Authenticating with public key \"");
4386 c_write_str(comment
);
4387 c_write_str("\"\r\n");
4388 method
= AUTH_PUBLICKEY_FILE
;
4392 if (!method
&& can_keyb_inter
&& !tried_keyb_inter
) {
4393 method
= AUTH_KEYBOARD_INTERACTIVE
;
4394 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4395 tried_keyb_inter
= TRUE
;
4397 ssh_pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
4399 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4400 ssh2_pkt_addstring(username
);
4401 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4402 ssh2_pkt_addstring("keyboard-interactive"); /* method */
4403 ssh2_pkt_addstring(""); /* lang */
4404 ssh2_pkt_addstring("");
4407 crWaitUntilV(ispkt
);
4408 if (pktin
.type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
4409 if (pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
)
4411 logevent("Keyboard-interactive authentication refused");
4412 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
;
4416 kbd_inter_running
= TRUE
;
4419 if (kbd_inter_running
) {
4420 method
= AUTH_KEYBOARD_INTERACTIVE
;
4421 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4422 tried_keyb_inter
= TRUE
;
4424 ssh_pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
4426 /* We've got packet with that "interactive" info
4427 dump banners, and set its prompt as ours */
4429 char *name
, *inst
, *lang
, *prompt
;
4430 int name_len
, inst_len
, lang_len
, prompt_len
;
4431 ssh2_pkt_getstring(&name
, &name_len
);
4432 ssh2_pkt_getstring(&inst
, &inst_len
);
4433 ssh2_pkt_getstring(&lang
, &lang_len
);
4435 c_write_untrusted(name
, name_len
);
4437 c_write_untrusted(inst
, inst_len
);
4438 num_prompts
= ssh2_pkt_getuint32();
4440 ssh2_pkt_getstring(&prompt
, &prompt_len
);
4441 strncpy(pwprompt
, prompt
, sizeof(pwprompt
));
4442 pwprompt
[prompt_len
< sizeof(pwprompt
) ?
4443 prompt_len
: sizeof(pwprompt
)-1] = '\0';
4446 echo
= ssh2_pkt_getbool();
4450 if (!method
&& can_passwd
) {
4451 method
= AUTH_PASSWORD
;
4452 ssh_pkt_ctx
|= SSH2_PKTCTX_PASSWORD
;
4453 sprintf(pwprompt
, "%.90s@%.90s's password: ", username
,
4460 if (!ssh_get_line(pwprompt
, password
,
4461 sizeof(password
), TRUE
)) {
4463 * get_line failed to get a password (for
4464 * example because one was supplied on the
4465 * command line which has already failed to
4468 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4469 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4471 ("No more passwords available to try");
4472 ssh2_pkt_addstring("en"); /* language tag */
4474 logevent("Unable to authenticate");
4475 connection_fatal("Unable to authenticate");
4476 ssh_state
= SSH_STATE_CLOSED
;
4483 c_write_untrusted(pwprompt
, strlen(pwprompt
));
4488 crWaitUntilV(!ispkt
);
4490 switch (c
= *in
++) {
4510 if (pos
< sizeof(password
)-1)
4511 password
[pos
++] = c
;
4515 c_write_str("\r\n");
4519 if (method
== AUTH_PUBLICKEY_FILE
) {
4521 * We have our passphrase. Now try the actual authentication.
4523 struct ssh2_userkey
*key
;
4525 key
= ssh2_load_userkey(cfg
.keyfile
, password
);
4526 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
4527 if (key
== SSH2_WRONG_PASSPHRASE
) {
4528 c_write_str("Wrong passphrase\r\n");
4529 tried_pubkey_config
= FALSE
;
4531 c_write_str("Unable to load private key\r\n");
4532 tried_pubkey_config
= TRUE
;
4534 /* Send a spurious AUTH_NONE to return to the top. */
4535 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4536 ssh2_pkt_addstring(username
);
4537 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4538 ssh2_pkt_addstring("none"); /* method */
4540 type
= AUTH_TYPE_NONE
;
4542 unsigned char *blob
, *sigdata
;
4543 int blob_len
, sigdata_len
;
4546 * We have loaded the private key and the server
4547 * has announced that it's willing to accept it.
4548 * Hallelujah. Generate a signature and send it.
4550 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4551 ssh2_pkt_addstring(username
);
4552 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4553 ssh2_pkt_addstring("publickey"); /* method */
4554 ssh2_pkt_addbool(TRUE
);
4555 ssh2_pkt_addstring(key
->alg
->name
);
4556 blob
= key
->alg
->public_blob(key
->data
, &blob_len
);
4557 ssh2_pkt_addstring_start();
4558 ssh2_pkt_addstring_data(blob
, blob_len
);
4562 * The data to be signed is:
4566 * followed by everything so far placed in the
4569 sigdata_len
= pktout
.length
- 5 + 4 + 20;
4570 sigdata
= smalloc(sigdata_len
);
4571 PUT_32BIT(sigdata
, 20);
4572 memcpy(sigdata
+ 4, ssh2_session_id
, 20);
4573 memcpy(sigdata
+ 24, pktout
.data
+ 5,
4576 key
->alg
->sign(key
->data
, sigdata
, sigdata_len
,
4578 ssh2_pkt_addstring_start();
4579 ssh2_pkt_addstring_data(blob
, blob_len
);
4584 type
= AUTH_TYPE_PUBLICKEY
;
4586 } else if (method
== AUTH_PASSWORD
) {
4588 * We send the password packet lumped tightly together with
4589 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4590 * string long enough to make the total length of the two
4591 * packets constant. This should ensure that a passive
4592 * listener doing traffic analyis can't work out the length
4595 * For this to work, we need an assumption about the
4596 * maximum length of the password packet. I think 256 is
4597 * pretty conservative. Anyone using a password longer than
4598 * that probably doesn't have much to worry about from
4599 * people who find out how long their password is!
4601 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4602 ssh2_pkt_addstring(username
);
4603 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4604 ssh2_pkt_addstring("password");
4605 ssh2_pkt_addbool(FALSE
);
4606 ssh2_pkt_addstring(password
);
4609 * We'll include a string that's an exact multiple of the
4610 * cipher block size. If the cipher is NULL for some
4611 * reason, we don't do this trick at all because we gain
4617 stringlen
= (256 - deferred_len
);
4618 stringlen
+= cscipher
->blksize
- 1;
4619 stringlen
-= (stringlen
% cscipher
->blksize
);
4622 * Temporarily disable actual compression,
4623 * so we can guarantee to get this string
4624 * exactly the length we want it. The
4625 * compression-disabling routine should
4626 * return an integer indicating how many
4627 * bytes we should adjust our string length
4630 stringlen
-= cscomp
->disable_compression();
4632 ssh2_pkt_init(SSH2_MSG_IGNORE
);
4633 ssh2_pkt_addstring_start();
4634 for (i
= 0; i
< stringlen
; i
++) {
4635 char c
= (char) random_byte();
4636 ssh2_pkt_addstring_data(&c
, 1);
4640 ssh_pkt_defersend();
4641 logevent("Sent password");
4642 type
= AUTH_TYPE_PASSWORD
;
4643 } else if (method
== AUTH_KEYBOARD_INTERACTIVE
) {
4644 ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE
);
4645 ssh2_pkt_adduint32(num_prompts
);
4646 ssh2_pkt_addstring(password
);
4647 memset(password
, 0, sizeof(password
));
4649 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4652 ("No supported authentication methods left to try!\r\n");
4654 ("No supported authentications offered. Disconnecting");
4655 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4656 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4658 ("No supported authentication methods available");
4659 ssh2_pkt_addstring("en"); /* language tag */
4661 ssh_state
= SSH_STATE_CLOSED
;
4665 } while (!we_are_in
);
4668 * Now we're authenticated for the connection protocol. The
4669 * connection protocol will automatically have started at this
4670 * point; there's no need to send SERVICE_REQUEST.
4674 * So now create a channel with a session in it.
4676 ssh_channels
= newtree234(ssh_channelcmp
);
4677 mainchan
= smalloc(sizeof(struct ssh_channel
));
4678 mainchan
->localid
= alloc_channel_id();
4679 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
4680 ssh2_pkt_addstring("session");
4681 ssh2_pkt_adduint32(mainchan
->localid
);
4682 mainchan
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
4683 ssh2_pkt_adduint32(mainchan
->v
.v2
.locwindow
); /* our window size */
4684 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
4686 crWaitUntilV(ispkt
);
4687 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
4688 bombout(("Server refused to open a session"));
4690 /* FIXME: error data comes back in FAILURE packet */
4692 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
4693 bombout(("Server's channel confirmation cited wrong channel"));
4696 mainchan
->remoteid
= ssh2_pkt_getuint32();
4697 mainchan
->type
= CHAN_MAINSESSION
;
4698 mainchan
->closes
= 0;
4699 mainchan
->v
.v2
.remwindow
= ssh2_pkt_getuint32();
4700 mainchan
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
4701 bufchain_init(&mainchan
->v
.v2
.outbuffer
);
4702 add234(ssh_channels
, mainchan
);
4703 logevent("Opened channel for session");
4706 * Potentially enable X11 forwarding.
4708 if (cfg
.x11_forward
) {
4709 char proto
[20], data
[64];
4710 logevent("Requesting X11 forwarding");
4711 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
4712 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4713 ssh2_pkt_adduint32(mainchan
->remoteid
);
4714 ssh2_pkt_addstring("x11-req");
4715 ssh2_pkt_addbool(1); /* want reply */
4716 ssh2_pkt_addbool(0); /* many connections */
4717 ssh2_pkt_addstring(proto
);
4718 ssh2_pkt_addstring(data
);
4719 ssh2_pkt_adduint32(0); /* screen number */
4723 crWaitUntilV(ispkt
);
4724 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4725 unsigned i
= ssh2_pkt_getuint32();
4726 struct ssh_channel
*c
;
4727 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4729 continue; /* nonexistent channel */
4730 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4732 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4734 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4735 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4736 bombout(("Unexpected response to X11 forwarding request:"
4737 " packet type %d", pktin
.type
));
4740 logevent("X11 forwarding refused");
4742 logevent("X11 forwarding enabled");
4743 ssh_X11_fwd_enabled
= TRUE
;
4748 * Enable port forwardings.
4751 static char *e
; /* preserve across crReturn */
4754 int sport
,dport
,sserv
,dserv
;
4755 char sports
[256], dports
[256], host
[256];
4759 ssh_rportfwds
= newtree234(ssh_rportcmp_ssh2
);
4760 /* Add port forwardings. */
4765 while (*e
&& *e
!= '\t')
4771 while (*e
&& *e
!= ':')
4781 dport
= atoi(dports
);
4785 se
= getservbyname(dports
, NULL
);
4787 dport
= ntohs(se
->s_port
);
4790 "Service lookup failed for destination port \"%s\"",
4795 sport
= atoi(sports
);
4799 se
= getservbyname(sports
, NULL
);
4801 sport
= ntohs(se
->s_port
);
4804 "Service lookup failed for source port \"%s\"",
4809 if (sport
&& dport
) {
4811 pfd_addforward(host
, dport
, sport
);
4812 sprintf(buf
, "Local port %.*s%.*s%d%.*s forwarding to"
4813 " %s:%.*s%.*s%d%.*s",
4814 sserv ?
strlen(sports
) : 0, sports
,
4815 sserv
, "(", sport
, sserv
, ")",
4817 dserv ?
strlen(dports
) : 0, dports
,
4818 dserv
, "(", dport
, dserv
, ")");
4821 struct ssh_rportfwd
*pf
;
4822 pf
= smalloc(sizeof(*pf
));
4823 strcpy(pf
->dhost
, host
);
4826 if (add234(ssh_rportfwds
, pf
) != pf
) {
4828 "Duplicate remote port forwarding to %s:%d",
4833 sprintf(buf
, "Requesting remote port %.*s%.*s%d%.*s"
4834 " forward to %s:%.*s%.*s%d%.*s",
4835 sserv ?
strlen(sports
) : 0, sports
,
4836 sserv
, "(", sport
, sserv
, ")",
4838 dserv ?
strlen(dports
) : 0, dports
,
4839 dserv
, "(", dport
, dserv
, ")");
4841 ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
4842 ssh2_pkt_addstring("tcpip-forward");
4843 ssh2_pkt_addbool(1);/* want reply */
4844 if (cfg
.rport_acceptall
)
4845 ssh2_pkt_addstring("0.0.0.0");
4847 ssh2_pkt_addstring("127.0.0.1");
4848 ssh2_pkt_adduint32(sport
);
4852 crWaitUntilV(ispkt
);
4853 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4854 unsigned i
= ssh2_pkt_getuint32();
4855 struct ssh_channel
*c
;
4856 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4858 continue;/* nonexistent channel */
4859 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4861 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4863 if (pktin
.type
!= SSH2_MSG_REQUEST_SUCCESS
) {
4864 if (pktin
.type
!= SSH2_MSG_REQUEST_FAILURE
) {
4865 bombout(("Unexpected response to port "
4866 "forwarding request: packet type %d",
4870 logevent("Server refused this port forwarding");
4872 logevent("Remote port forwarding enabled");
4881 * Potentially enable agent forwarding.
4883 if (cfg
.agentfwd
&& agent_exists()) {
4884 logevent("Requesting OpenSSH-style agent forwarding");
4885 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4886 ssh2_pkt_adduint32(mainchan
->remoteid
);
4887 ssh2_pkt_addstring("auth-agent-req@openssh.com");
4888 ssh2_pkt_addbool(1); /* want reply */
4892 crWaitUntilV(ispkt
);
4893 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4894 unsigned i
= ssh2_pkt_getuint32();
4895 struct ssh_channel
*c
;
4896 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4898 continue; /* nonexistent channel */
4899 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4901 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4903 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4904 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4905 bombout(("Unexpected response to agent forwarding request:"
4906 " packet type %d", pktin
.type
));
4909 logevent("Agent forwarding refused");
4911 logevent("Agent forwarding enabled");
4912 ssh_agentfwd_enabled
= TRUE
;
4917 * Now allocate a pty for the session.
4920 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4921 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
4922 ssh2_pkt_addstring("pty-req");
4923 ssh2_pkt_addbool(1); /* want reply */
4924 ssh2_pkt_addstring(cfg
.termtype
);
4925 ssh2_pkt_adduint32(cols
);
4926 ssh2_pkt_adduint32(rows
);
4927 ssh2_pkt_adduint32(0); /* pixel width */
4928 ssh2_pkt_adduint32(0); /* pixel height */
4929 ssh2_pkt_addstring_start();
4930 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
4932 ssh_state
= SSH_STATE_INTERMED
;
4935 crWaitUntilV(ispkt
);
4936 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4937 unsigned i
= ssh2_pkt_getuint32();
4938 struct ssh_channel
*c
;
4939 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4941 continue; /* nonexistent channel */
4942 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4944 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4946 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4947 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4948 bombout(("Unexpected response to pty request:"
4949 " packet type %d", pktin
.type
));
4952 c_write_str("Server refused to allocate pty\r\n");
4953 ssh_editing
= ssh_echoing
= 1;
4955 logevent("Allocated pty");
4958 ssh_editing
= ssh_echoing
= 1;
4962 * Start a shell or a remote command. We may have to attempt
4963 * this twice if the config data has provided a second choice
4970 if (ssh_fallback_cmd
) {
4971 subsys
= cfg
.ssh_subsys2
;
4972 cmd
= cfg
.remote_cmd_ptr2
;
4974 subsys
= cfg
.ssh_subsys
;
4975 cmd
= cfg
.remote_cmd_ptr
;
4978 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4979 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
4981 ssh2_pkt_addstring("subsystem");
4982 ssh2_pkt_addbool(1); /* want reply */
4983 ssh2_pkt_addstring(cmd
);
4985 ssh2_pkt_addstring("exec");
4986 ssh2_pkt_addbool(1); /* want reply */
4987 ssh2_pkt_addstring(cmd
);
4989 ssh2_pkt_addstring("shell");
4990 ssh2_pkt_addbool(1); /* want reply */
4994 crWaitUntilV(ispkt
);
4995 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4996 unsigned i
= ssh2_pkt_getuint32();
4997 struct ssh_channel
*c
;
4998 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5000 continue; /* nonexistent channel */
5001 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
5003 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
5004 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
5005 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
5006 bombout(("Unexpected response to shell/command request:"
5007 " packet type %d", pktin
.type
));
5011 * We failed to start the command. If this is the
5012 * fallback command, we really are finished; if it's
5013 * not, and if the fallback command exists, try falling
5014 * back to it before complaining.
5016 if (!ssh_fallback_cmd
&& cfg
.remote_cmd_ptr2
!= NULL
) {
5017 logevent("Primary command failed; attempting fallback");
5018 ssh_fallback_cmd
= TRUE
;
5021 bombout(("Server refused to start a shell/command"));
5024 logevent("Started a shell/command");
5029 ssh_state
= SSH_STATE_SESSION
;
5033 ssh_special(TS_EOF
);
5038 ldisc_send(NULL
, 0, 0); /* cause ldisc to notice changes */
5041 static int try_send
;
5045 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
5046 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
5049 unsigned i
= ssh2_pkt_getuint32();
5050 struct ssh_channel
*c
;
5051 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5053 continue; /* nonexistent channel */
5054 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
5055 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
5056 continue; /* extended but not stderr */
5057 ssh2_pkt_getstring(&data
, &length
);
5060 c
->v
.v2
.locwindow
-= length
;
5062 case CHAN_MAINSESSION
:
5064 from_backend(pktin
.type
==
5065 SSH2_MSG_CHANNEL_EXTENDED_DATA
,
5069 bufsize
= x11_send(c
->u
.x11
.s
, data
, length
);
5072 bufsize
= pfd_send(c
->u
.pfd
.s
, data
, length
);
5075 while (length
> 0) {
5076 if (c
->u
.a
.lensofar
< 4) {
5077 int l
= min(4 - c
->u
.a
.lensofar
, length
);
5078 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
5082 c
->u
.a
.lensofar
+= l
;
5084 if (c
->u
.a
.lensofar
== 4) {
5086 4 + GET_32BIT(c
->u
.a
.msglen
);
5087 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
5088 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
5090 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
5092 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
5094 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
5098 c
->u
.a
.lensofar
+= l
;
5100 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
5101 void *reply
, *sentreply
;
5103 agent_query(c
->u
.a
.message
,
5104 c
->u
.a
.totallen
, &reply
,
5109 /* Fake SSH_AGENT_FAILURE. */
5110 sentreply
= "\0\0\0\1\5";
5113 ssh2_add_channel_data(c
, sentreply
,
5118 sfree(c
->u
.a
.message
);
5119 c
->u
.a
.lensofar
= 0;
5126 * If we are not buffering too much data,
5127 * enlarge the window again at the remote side.
5129 if (bufsize
< OUR_V2_WINSIZE
)
5130 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
5132 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
5133 ssh_state
= SSH_STATE_CLOSED
;
5134 logevent("Received disconnect message");
5136 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
5137 unsigned i
= ssh2_pkt_getuint32();
5138 struct ssh_channel
*c
;
5140 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5142 continue; /* nonexistent channel */
5144 if (c
->type
== CHAN_X11
) {
5146 * Remote EOF on an X11 channel means we should
5147 * wrap up and close the channel ourselves.
5149 x11_close(c
->u
.x11
.s
);
5151 } else if (c
->type
== CHAN_AGENT
) {
5153 } else if (c
->type
== CHAN_SOCKDATA
) {
5154 pfd_close(c
->u
.pfd
.s
);
5157 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
5158 unsigned i
= ssh2_pkt_getuint32();
5159 struct ssh_channel
*c
;
5161 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5163 continue; /* nonexistent channel */
5164 /* Do pre-close processing on the channel. */
5166 case CHAN_MAINSESSION
:
5167 break; /* nothing to see here, move along */
5169 if (c
->u
.x11
.s
!= NULL
)
5170 x11_close(c
->u
.x11
.s
);
5177 if (c
->u
.pfd
.s
!= NULL
)
5178 pfd_close(c
->u
.pfd
.s
);
5182 if (c
->closes
== 0) {
5183 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
5184 ssh2_pkt_adduint32(c
->remoteid
);
5187 del234(ssh_channels
, c
);
5188 bufchain_clear(&c
->v
.v2
.outbuffer
);
5192 * See if that was the last channel left open.
5194 if (count234(ssh_channels
) == 0) {
5197 * We used to send SSH_MSG_DISCONNECT here,
5198 * because I'd believed that _every_ conforming
5199 * SSH2 connection had to end with a disconnect
5200 * being sent by at least one side; apparently
5201 * I was wrong and it's perfectly OK to
5202 * unceremoniously slam the connection shut
5203 * when you're done, and indeed OpenSSH feels
5204 * this is more polite than sending a
5205 * DISCONNECT. So now we don't.
5207 logevent("All channels closed. Disconnecting");
5208 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
5209 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
5210 ssh2_pkt_addstring("All open channels closed");
5211 ssh2_pkt_addstring("en"); /* language tag */
5214 ssh_state
= SSH_STATE_CLOSED
;
5217 continue; /* remote sends close; ignore (FIXME) */
5218 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
5219 unsigned i
= ssh2_pkt_getuint32();
5220 struct ssh_channel
*c
;
5221 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5223 continue; /* nonexistent channel */
5224 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
5226 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
5227 unsigned i
= ssh2_pkt_getuint32();
5228 struct ssh_channel
*c
;
5229 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5231 continue; /* nonexistent channel */
5232 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
5233 continue; /* dunno why they're confirming this */
5234 c
->remoteid
= ssh2_pkt_getuint32();
5235 c
->type
= CHAN_SOCKDATA
;
5236 c
->v
.v2
.remwindow
= ssh2_pkt_getuint32();
5237 c
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
5238 bufchain_init(&c
->v
.v2
.outbuffer
);
5240 pfd_confirm(c
->u
.pfd
.s
);
5243 * We have a pending close on this channel,
5244 * which we decided on before the server acked
5245 * the channel open. So now we know the
5246 * remoteid, we can close it again.
5248 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
5249 ssh2_pkt_adduint32(c
->remoteid
);
5252 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN_FAILURE
) {
5253 unsigned i
= ssh2_pkt_getuint32();
5254 struct ssh_channel
*c
;
5255 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5257 continue; /* nonexistent channel */
5258 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
5259 continue; /* dunno why they're failing this */
5261 logevent("Forwarded connection refused by server");
5263 pfd_close(c
->u
.pfd
.s
);
5265 del234(ssh_channels
, c
);
5267 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
5270 int typelen
, want_reply
;
5271 struct ssh_channel
*c
;
5273 localid
= ssh2_pkt_getuint32();
5274 ssh2_pkt_getstring(&type
, &typelen
);
5275 want_reply
= ssh2_pkt_getbool();
5278 * First, check that the channel exists. Otherwise,
5279 * we can instantly disconnect with a rude message.
5281 c
= find234(ssh_channels
, &localid
, ssh_channelfind
);
5284 sprintf(buf
, "Received channel request for nonexistent"
5285 " channel %d", localid
);
5287 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
5288 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
5289 ssh2_pkt_addstring(buf
);
5290 ssh2_pkt_addstring("en"); /* language tag */
5292 connection_fatal("%s", buf
);
5293 ssh_state
= SSH_STATE_CLOSED
;
5298 * Having got the channel number, we now look at
5299 * the request type string to see if it's something
5302 if (typelen
== 11 && !memcmp(type
, "exit-status", 11) &&
5304 /* We recognise "exit-status" on the primary channel. */
5306 ssh_exitcode
= ssh2_pkt_getuint32();
5307 sprintf(buf
, "Server sent command exit status %d",
5311 ssh2_pkt_init(SSH2_MSG_CHANNEL_SUCCESS
);
5312 ssh2_pkt_adduint32(c
->remoteid
);
5317 * This is a channel request we don't know
5318 * about, so we now either ignore the request
5319 * or respond with CHANNEL_FAILURE, depending
5323 ssh2_pkt_init(SSH2_MSG_CHANNEL_FAILURE
);
5324 ssh2_pkt_adduint32(c
->remoteid
);
5328 } else if (pktin
.type
== SSH2_MSG_GLOBAL_REQUEST
) {
5330 int typelen
, want_reply
;
5332 ssh2_pkt_getstring(&type
, &typelen
);
5333 want_reply
= ssh2_pkt_getbool();
5336 * We currently don't support any global requests
5337 * at all, so we either ignore the request or
5338 * respond with REQUEST_FAILURE, depending on
5342 ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE
);
5345 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
5349 struct ssh_channel
*c
;
5350 unsigned remid
, winsize
, pktsize
;
5351 ssh2_pkt_getstring(&type
, &typelen
);
5352 c
= smalloc(sizeof(struct ssh_channel
));
5354 remid
= ssh2_pkt_getuint32();
5355 winsize
= ssh2_pkt_getuint32();
5356 pktsize
= ssh2_pkt_getuint32();
5358 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
5359 if (!ssh_X11_fwd_enabled
)
5360 error
= "X11 forwarding is not enabled";
5361 else if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) !=
5363 error
= "Unable to open an X11 connection";
5367 } else if (typelen
== 15 &&
5368 !memcmp(type
, "forwarded-tcpip", 15)) {
5369 struct ssh_rportfwd pf
, *realpf
;
5372 ssh2_pkt_getstring(&dummy
, &dummylen
);/* skip address */
5373 pf
.sport
= ssh2_pkt_getuint32();
5374 realpf
= find234(ssh_rportfwds
, &pf
, NULL
);
5375 if (realpf
== NULL
) {
5376 error
= "Remote port is not recognised";
5378 char *e
= pfd_newconnect(&c
->u
.pfd
.s
, realpf
->dhost
,
5381 sprintf(buf
, "Received remote port open request for %s:%d",
5382 realpf
->dhost
, realpf
->dport
);
5385 sprintf(buf
, "Port open failed: %s", e
);
5387 error
= "Port open failed";
5389 logevent("Forwarded port opened successfully");
5390 c
->type
= CHAN_SOCKDATA
;
5393 } else if (typelen
== 22 &&
5394 !memcmp(type
, "auth-agent@openssh.com", 3)) {
5395 if (!ssh_agentfwd_enabled
)
5396 error
= "Agent forwarding is not enabled";
5398 c
->type
= CHAN_AGENT
; /* identify channel type */
5399 c
->u
.a
.lensofar
= 0;
5402 error
= "Unsupported channel type requested";
5405 c
->remoteid
= remid
;
5407 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
5408 ssh2_pkt_adduint32(c
->remoteid
);
5409 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED
);
5410 ssh2_pkt_addstring(error
);
5411 ssh2_pkt_addstring("en"); /* language tag */
5415 c
->localid
= alloc_channel_id();
5417 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
5418 c
->v
.v2
.remwindow
= winsize
;
5419 c
->v
.v2
.remmaxpkt
= pktsize
;
5420 bufchain_init(&c
->v
.v2
.outbuffer
);
5421 add234(ssh_channels
, c
);
5422 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
5423 ssh2_pkt_adduint32(c
->remoteid
);
5424 ssh2_pkt_adduint32(c
->localid
);
5425 ssh2_pkt_adduint32(c
->v
.v2
.locwindow
);
5426 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
5430 bombout(("Strange packet received: type %d", pktin
.type
));
5435 * We have spare data. Add it to the channel buffer.
5437 ssh2_add_channel_data(mainchan
, in
, inlen
);
5442 struct ssh_channel
*c
;
5444 * Try to send data on all channels if we can.
5446 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++) {
5447 int bufsize
= ssh2_try_send(c
);
5450 case CHAN_MAINSESSION
:
5451 /* stdin need not receive an unthrottle
5452 * notification since it will be polled */
5455 x11_unthrottle(c
->u
.x11
.s
);
5458 /* agent sockets are request/response and need no
5459 * buffer management */
5462 pfd_unthrottle(c
->u
.pfd
.s
);
5474 * Handle the top-level SSH2 protocol.
5476 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
5478 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
5480 do_ssh2_authconn(in
, inlen
, ispkt
);
5484 * Called to set up the connection.
5486 * Returns an error message, or NULL on success.
5488 static char *ssh_init(char *host
, int port
, char **realhost
, int nodelay
)
5493 if (crypto_startup() == 0)
5494 return "Microsoft high encryption pack not installed!";
5500 ssh1_throttle_count
= 0;
5501 ssh_overall_bufsize
= 0;
5502 ssh_fallback_cmd
= 0;
5504 p
= connect_to_host(host
, port
, realhost
, nodelay
);
5512 * Called to send data down the Telnet connection.
5514 static int ssh_send(char *buf
, int len
)
5516 if (s
== NULL
|| ssh_protocol
== NULL
)
5519 ssh_protocol(buf
, len
, 0);
5521 return ssh_sendbuffer();
5525 * Called to query the current amount of buffered stdin data.
5527 static int ssh_sendbuffer(void)
5531 if (s
== NULL
|| ssh_protocol
== NULL
)
5535 * If the SSH socket itself has backed up, add the total backup
5536 * size on that to any individual buffer on the stdin channel.
5539 if (ssh_throttled_all
)
5540 override_value
= ssh_overall_bufsize
;
5542 if (ssh_version
== 1) {
5543 return override_value
;
5544 } else if (ssh_version
== 2) {
5545 if (!mainchan
|| mainchan
->closes
> 0)
5546 return override_value
;
5548 return override_value
+ bufchain_size(&mainchan
->v
.v2
.outbuffer
);
5555 * Called to set the size of the window from SSH's POV.
5557 static void ssh_size(void)
5559 switch (ssh_state
) {
5560 case SSH_STATE_BEFORE_SIZE
:
5561 case SSH_STATE_PREPACKET
:
5562 case SSH_STATE_CLOSED
:
5563 break; /* do nothing */
5564 case SSH_STATE_INTERMED
:
5565 size_needed
= TRUE
; /* buffer for later */
5567 case SSH_STATE_SESSION
:
5569 if (ssh_version
== 1) {
5570 send_packet(SSH1_CMSG_WINDOW_SIZE
,
5571 PKT_INT
, rows
, PKT_INT
, cols
,
5572 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
5574 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
5575 ssh2_pkt_adduint32(mainchan
->remoteid
);
5576 ssh2_pkt_addstring("window-change");
5577 ssh2_pkt_addbool(0);
5578 ssh2_pkt_adduint32(cols
);
5579 ssh2_pkt_adduint32(rows
);
5580 ssh2_pkt_adduint32(0);
5581 ssh2_pkt_adduint32(0);
5590 * Send Telnet special codes. TS_EOF is useful for `plink', so you
5591 * can send an EOF and collect resulting output (e.g. `plink
5594 static void ssh_special(Telnet_Special code
)
5596 if (code
== TS_EOF
) {
5597 if (ssh_state
!= SSH_STATE_SESSION
) {
5599 * Buffer the EOF in case we are pre-SESSION, so we can
5600 * send it as soon as we reach SESSION.
5606 if (ssh_version
== 1) {
5607 send_packet(SSH1_CMSG_EOF
, PKT_END
);
5609 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
5610 ssh2_pkt_adduint32(mainchan
->remoteid
);
5613 logevent("Sent EOF message");
5614 } else if (code
== TS_PING
) {
5615 if (ssh_state
== SSH_STATE_CLOSED
5616 || ssh_state
== SSH_STATE_PREPACKET
) return;
5617 if (ssh_version
== 1) {
5618 send_packet(SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
5620 ssh2_pkt_init(SSH2_MSG_IGNORE
);
5621 ssh2_pkt_addstring_start();
5629 void *new_sock_channel(Socket s
)
5631 struct ssh_channel
*c
;
5632 c
= smalloc(sizeof(struct ssh_channel
));
5635 c
->remoteid
= -1; /* to be set when open confirmed */
5636 c
->localid
= alloc_channel_id();
5638 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
5640 add234(ssh_channels
, c
);
5646 * This is called when stdout/stderr (the entity to which
5647 * from_backend sends data) manages to clear some backlog.
5649 void ssh_unthrottle(int bufsize
)
5651 if (ssh_version
== 1) {
5652 if (ssh1_stdout_throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
5653 ssh1_stdout_throttling
= 0;
5657 if (mainchan
&& mainchan
->closes
== 0)
5658 ssh2_set_window(mainchan
, OUR_V2_WINSIZE
- bufsize
);
5662 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
5664 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
5667 sprintf(buf
, "Opening forwarded connection to %.512s:%d", hostname
, port
);
5670 if (ssh_version
== 1) {
5671 send_packet(SSH1_MSG_PORT_OPEN
,
5672 PKT_INT
, c
->localid
,
5675 //PKT_STR, <org:orgport>,
5678 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
5679 ssh2_pkt_addstring("direct-tcpip");
5680 ssh2_pkt_adduint32(c
->localid
);
5681 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
5682 ssh2_pkt_adduint32(c
->v
.v2
.locwindow
);/* our window size */
5683 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
5684 ssh2_pkt_addstring(hostname
);
5685 ssh2_pkt_adduint32(port
);
5687 * We make up values for the originator data; partly it's
5688 * too much hassle to keep track, and partly I'm not
5689 * convinced the server should be told details like that
5690 * about my local network configuration.
5692 ssh2_pkt_addstring("client-side-connection");
5693 ssh2_pkt_adduint32(0);
5699 static Socket
ssh_socket(void)
5704 static int ssh_sendok(void)
5709 static int ssh_ldisc(int option
)
5711 if (option
== LD_ECHO
)
5713 if (option
== LD_EDIT
)
5718 static int ssh_return_exitcode(void)
5720 return ssh_exitcode
;
5723 Backend ssh_backend
= {
5730 ssh_return_exitcode
,