19 #define logevent(s) { logevent(s); \
20 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
21 { fprintf(stderr, "%s\n", s); fflush(stderr); } }
23 /* logevent, only printf-formatted. */
24 void logeventf(char *fmt
, ...)
30 vsprintf(stuff
, fmt
, ap
);
35 #define bombout(msg) ( ssh_state = SSH_STATE_CLOSED, \
36 (s ? sk_close(s), s = NULL : 0), \
37 logeventf msg, connection_fatal msg )
39 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
40 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
41 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
42 #define SSH1_CMSG_USER 4 /* 0x4 */
43 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
44 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
45 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
46 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
47 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
48 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
49 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
50 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
51 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
52 #define SSH1_SMSG_FAILURE 15 /* 0xf */
53 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
54 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
55 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
56 #define SSH1_CMSG_EOF 19 /* 0x13 */
57 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
58 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
59 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
60 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
61 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
62 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
63 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
64 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
65 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
66 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
67 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
68 #define SSH1_MSG_IGNORE 32 /* 0x20 */
69 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
70 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
71 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
72 #define SSH1_MSG_DEBUG 36 /* 0x24 */
73 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
74 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
75 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
76 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
77 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
78 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
79 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
81 #define SSH1_AUTH_TIS 5 /* 0x5 */
82 #define SSH1_AUTH_CCARD 16 /* 0x10 */
84 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
85 /* Mask for protoflags we will echo back to server if seen */
86 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
88 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
89 #define SSH2_MSG_IGNORE 2 /* 0x2 */
90 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
91 #define SSH2_MSG_DEBUG 4 /* 0x4 */
92 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
93 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
94 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
95 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
96 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
97 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
98 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
99 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
100 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
101 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
102 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
103 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
104 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
105 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
106 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
107 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
108 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
109 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
110 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
111 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
112 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
113 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
114 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
115 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
116 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
117 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
118 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
119 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
120 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
121 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
122 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
123 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
126 * Packet type contexts, so that ssh2_pkt_type can correctly decode
127 * the ambiguous type numbers back into the correct type strings.
129 #define SSH2_PKTCTX_DHGROUP1 0x0001
130 #define SSH2_PKTCTX_DHGEX 0x0002
131 #define SSH2_PKTCTX_PUBLICKEY 0x0010
132 #define SSH2_PKTCTX_PASSWORD 0x0020
133 #define SSH2_PKTCTX_KBDINTER 0x0040
134 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
136 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
137 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
138 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
139 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
140 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
141 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
142 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
143 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
144 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
145 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
146 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
147 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
148 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
149 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
150 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
152 static const char *const ssh2_disconnect_reasons
[] = {
154 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
155 "SSH_DISCONNECT_PROTOCOL_ERROR",
156 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
157 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
158 "SSH_DISCONNECT_MAC_ERROR",
159 "SSH_DISCONNECT_COMPRESSION_ERROR",
160 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
161 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
162 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
163 "SSH_DISCONNECT_CONNECTION_LOST",
164 "SSH_DISCONNECT_BY_APPLICATION",
165 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
166 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
167 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
168 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
171 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
172 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
173 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
174 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
176 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
179 * Various remote-bug flags.
181 #define BUG_CHOKES_ON_SSH1_IGNORE 1
182 #define BUG_SSH2_HMAC 2
183 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
184 #define BUG_CHOKES_ON_RSA 8
185 #define BUG_SSH2_RSA_PADDING 16
186 #define BUG_SSH2_DERIVEKEY 32
187 #define BUG_SSH2_DH_GEX 64
189 static int ssh_pkt_ctx
= 0;
191 #define translate(x) if (type == x) return #x
192 #define translatec(x,ctx) if (type == x && (ssh_pkt_ctx & ctx)) return #x
193 char *ssh1_pkt_type(int type
)
195 translate(SSH1_MSG_DISCONNECT
);
196 translate(SSH1_SMSG_PUBLIC_KEY
);
197 translate(SSH1_CMSG_SESSION_KEY
);
198 translate(SSH1_CMSG_USER
);
199 translate(SSH1_CMSG_AUTH_RSA
);
200 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE
);
201 translate(SSH1_CMSG_AUTH_RSA_RESPONSE
);
202 translate(SSH1_CMSG_AUTH_PASSWORD
);
203 translate(SSH1_CMSG_REQUEST_PTY
);
204 translate(SSH1_CMSG_WINDOW_SIZE
);
205 translate(SSH1_CMSG_EXEC_SHELL
);
206 translate(SSH1_CMSG_EXEC_CMD
);
207 translate(SSH1_SMSG_SUCCESS
);
208 translate(SSH1_SMSG_FAILURE
);
209 translate(SSH1_CMSG_STDIN_DATA
);
210 translate(SSH1_SMSG_STDOUT_DATA
);
211 translate(SSH1_SMSG_STDERR_DATA
);
212 translate(SSH1_CMSG_EOF
);
213 translate(SSH1_SMSG_EXIT_STATUS
);
214 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
);
215 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE
);
216 translate(SSH1_MSG_CHANNEL_DATA
);
217 translate(SSH1_MSG_CHANNEL_CLOSE
);
218 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
);
219 translate(SSH1_SMSG_X11_OPEN
);
220 translate(SSH1_CMSG_PORT_FORWARD_REQUEST
);
221 translate(SSH1_MSG_PORT_OPEN
);
222 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING
);
223 translate(SSH1_SMSG_AGENT_OPEN
);
224 translate(SSH1_MSG_IGNORE
);
225 translate(SSH1_CMSG_EXIT_CONFIRMATION
);
226 translate(SSH1_CMSG_X11_REQUEST_FORWARDING
);
227 translate(SSH1_CMSG_AUTH_RHOSTS_RSA
);
228 translate(SSH1_MSG_DEBUG
);
229 translate(SSH1_CMSG_REQUEST_COMPRESSION
);
230 translate(SSH1_CMSG_AUTH_TIS
);
231 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE
);
232 translate(SSH1_CMSG_AUTH_TIS_RESPONSE
);
233 translate(SSH1_CMSG_AUTH_CCARD
);
234 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE
);
235 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE
);
238 char *ssh2_pkt_type(int type
)
240 translate(SSH2_MSG_DISCONNECT
);
241 translate(SSH2_MSG_IGNORE
);
242 translate(SSH2_MSG_UNIMPLEMENTED
);
243 translate(SSH2_MSG_DEBUG
);
244 translate(SSH2_MSG_SERVICE_REQUEST
);
245 translate(SSH2_MSG_SERVICE_ACCEPT
);
246 translate(SSH2_MSG_KEXINIT
);
247 translate(SSH2_MSG_NEWKEYS
);
248 translatec(SSH2_MSG_KEXDH_INIT
, SSH2_PKTCTX_DHGROUP1
);
249 translatec(SSH2_MSG_KEXDH_REPLY
, SSH2_PKTCTX_DHGROUP1
);
250 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST
, SSH2_PKTCTX_DHGEX
);
251 translatec(SSH2_MSG_KEX_DH_GEX_GROUP
, SSH2_PKTCTX_DHGEX
);
252 translatec(SSH2_MSG_KEX_DH_GEX_INIT
, SSH2_PKTCTX_DHGEX
);
253 translatec(SSH2_MSG_KEX_DH_GEX_REPLY
, SSH2_PKTCTX_DHGEX
);
254 translate(SSH2_MSG_USERAUTH_REQUEST
);
255 translate(SSH2_MSG_USERAUTH_FAILURE
);
256 translate(SSH2_MSG_USERAUTH_SUCCESS
);
257 translate(SSH2_MSG_USERAUTH_BANNER
);
258 translatec(SSH2_MSG_USERAUTH_PK_OK
, SSH2_PKTCTX_PUBLICKEY
);
259 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ
, SSH2_PKTCTX_PASSWORD
);
260 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST
, SSH2_PKTCTX_KBDINTER
);
261 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE
, SSH2_PKTCTX_KBDINTER
);
262 translate(SSH2_MSG_GLOBAL_REQUEST
);
263 translate(SSH2_MSG_REQUEST_SUCCESS
);
264 translate(SSH2_MSG_REQUEST_FAILURE
);
265 translate(SSH2_MSG_CHANNEL_OPEN
);
266 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
267 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
268 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
269 translate(SSH2_MSG_CHANNEL_DATA
);
270 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA
);
271 translate(SSH2_MSG_CHANNEL_EOF
);
272 translate(SSH2_MSG_CHANNEL_CLOSE
);
273 translate(SSH2_MSG_CHANNEL_REQUEST
);
274 translate(SSH2_MSG_CHANNEL_SUCCESS
);
275 translate(SSH2_MSG_CHANNEL_FAILURE
);
281 #define GET_32BIT(cp) \
282 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
283 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
284 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
285 ((unsigned long)(unsigned char)(cp)[3]))
287 #define PUT_32BIT(cp, value) { \
288 (cp)[0] = (unsigned char)((value) >> 24); \
289 (cp)[1] = (unsigned char)((value) >> 16); \
290 (cp)[2] = (unsigned char)((value) >> 8); \
291 (cp)[3] = (unsigned char)(value); }
293 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
295 /* Coroutine mechanics for the sillier bits of the code */
296 #define crBegin1 static int crLine = 0;
297 #define crBegin2 switch(crLine) { case 0:;
298 #define crBegin crBegin1; crBegin2;
299 #define crFinish(z) } crLine = 0; return (z)
300 #define crFinishV } crLine = 0; return
301 #define crReturn(z) \
303 crLine=__LINE__; return (z); case __LINE__:;\
307 crLine=__LINE__; return; case __LINE__:;\
309 #define crStop(z) do{ crLine = 0; return (z); }while(0)
310 #define crStopV do{ crLine = 0; return; }while(0)
311 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
312 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
314 extern char *x11_init(Socket
*, char *, void *);
315 extern void x11_close(Socket
);
316 extern int x11_send(Socket
, char *, int);
317 extern void x11_invent_auth(char *, int, char *, int);
318 extern void x11_unthrottle(Socket s
);
319 extern void x11_override_throttle(Socket s
, int enable
);
321 extern char *pfd_newconnect(Socket
* s
, char *hostname
, int port
, void *c
);
322 extern char *pfd_addforward(char *desthost
, int destport
, int port
);
323 extern void pfd_close(Socket s
);
324 extern int pfd_send(Socket s
, char *data
, int len
);
325 extern void pfd_confirm(Socket s
);
326 extern void pfd_unthrottle(Socket s
);
327 extern void pfd_override_throttle(Socket s
, int enable
);
329 static void ssh2_pkt_init(int pkt_type
);
330 static void ssh2_pkt_addbool(unsigned char value
);
331 static void ssh2_pkt_adduint32(unsigned long value
);
332 static void ssh2_pkt_addstring_start(void);
333 static void ssh2_pkt_addstring_str(char *data
);
334 static void ssh2_pkt_addstring_data(char *data
, int len
);
335 static void ssh2_pkt_addstring(char *data
);
336 static char *ssh2_mpint_fmt(Bignum b
, int *len
);
337 static void ssh2_pkt_addmp(Bignum b
);
338 static int ssh2_pkt_construct(void);
339 static void ssh2_pkt_send(void);
342 * Buffer management constants. There are several of these for
343 * various different purposes:
345 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
346 * on a local data stream before we throttle the whole SSH
347 * connection (in SSH1 only). Throttling the whole connection is
348 * pretty drastic so we set this high in the hope it won't
351 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
352 * on the SSH connection itself before we defensively throttle
353 * _all_ local data streams. This is pretty drastic too (though
354 * thankfully unlikely in SSH2 since the window mechanism should
355 * ensure that the server never has any need to throttle its end
356 * of the connection), so we set this high as well.
358 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
362 #define SSH1_BUFFER_LIMIT 32768
363 #define SSH_MAX_BACKLOG 32768
364 #define OUR_V2_WINSIZE 16384
366 const static struct ssh_kex
*kex_algs
[] = {
367 &ssh_diffiehellman_gex
,
371 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
373 static void nullmac_key(unsigned char *key
)
376 static void nullmac_generate(unsigned char *blk
, int len
,
380 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
)
384 const static struct ssh_mac ssh_mac_none
= {
385 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
387 const static struct ssh_mac
*macs
[] = {
388 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
390 const static struct ssh_mac
*buggymacs
[] = {
391 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
394 static void ssh_comp_none_init(void)
397 static int ssh_comp_none_block(unsigned char *block
, int len
,
398 unsigned char **outblock
, int *outlen
)
402 static int ssh_comp_none_disable(void)
406 const static struct ssh_compress ssh_comp_none
= {
408 ssh_comp_none_init
, ssh_comp_none_block
,
409 ssh_comp_none_init
, ssh_comp_none_block
,
410 ssh_comp_none_disable
412 extern const struct ssh_compress ssh_zlib
;
413 const static struct ssh_compress
*compressions
[] = {
414 &ssh_zlib
, &ssh_comp_none
417 enum { /* channel types */
422 CHAN_SOCKDATA_DORMANT
/* one the remote hasn't confirmed */
426 * 2-3-4 tree storing channels.
429 unsigned remoteid
, localid
;
432 * In SSH1, this value contains four bits:
434 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
435 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
436 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
437 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
439 * A channel is completely finished with when all four bits are set.
443 struct ssh1_data_channel
{
446 struct ssh2_data_channel
{
448 unsigned remwindow
, remmaxpkt
;
453 struct ssh_agent_channel
{
454 unsigned char *message
;
455 unsigned char msglen
[4];
456 int lensofar
, totallen
;
458 struct ssh_x11_channel
{
461 struct ssh_pfd_channel
{
468 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
469 * 2 use this structure in different ways, reflecting SSH 2's
470 * altogether saner approach to port forwarding.
472 * In SSH 1, you arrange a remote forwarding by sending the server
473 * the remote port number, and the local destination host:port.
474 * When a connection comes in, the server sends you back that
475 * host:port pair, and you connect to it. This is a ready-made
476 * security hole if you're not on the ball: a malicious server
477 * could send you back _any_ host:port pair, so if you trustingly
478 * connect to the address it gives you then you've just opened the
479 * entire inside of your corporate network just by connecting
480 * through it to a dodgy SSH server. Hence, we must store a list of
481 * host:port pairs we _are_ trying to forward to, and reject a
482 * connection request from the server if it's not in the list.
484 * In SSH 2, each side of the connection minds its own business and
485 * doesn't send unnecessary information to the other. You arrange a
486 * remote forwarding by sending the server just the remote port
487 * number. When a connection comes in, the server tells you which
488 * of its ports was connected to; and _you_ have to remember what
489 * local host:port pair went with that port number.
491 * Hence: in SSH 1 this structure stores host:port pairs we intend
492 * to allow connections to, and is indexed by those host:port
493 * pairs. In SSH 2 it stores a mapping from source port to
494 * destination host:port pair, and is indexed by source port.
496 struct ssh_rportfwd
{
497 unsigned sport
, dport
;
510 static SHA_State exhash
, exhashbase
;
512 static Socket s
= NULL
;
514 static unsigned char session_key
[32];
515 static int ssh1_compressing
;
516 static int ssh1_remote_protoflags
;
517 static int ssh1_local_protoflags
;
518 static int ssh_agentfwd_enabled
;
519 static int ssh_X11_fwd_enabled
;
520 static int ssh_remote_bugs
;
521 static const struct ssh_cipher
*cipher
= NULL
;
522 static const struct ssh2_cipher
*cscipher
= NULL
;
523 static const struct ssh2_cipher
*sccipher
= NULL
;
524 static const struct ssh_mac
*csmac
= NULL
;
525 static const struct ssh_mac
*scmac
= NULL
;
526 static const struct ssh_compress
*cscomp
= NULL
;
527 static const struct ssh_compress
*sccomp
= NULL
;
528 static const struct ssh_kex
*kex
= NULL
;
529 static const struct ssh_signkey
*hostkey
= NULL
;
530 static unsigned char ssh2_session_id
[20];
532 static char *savedhost
;
533 static int savedport
;
534 static int ssh_send_ok
;
535 static int ssh_echoing
, ssh_editing
;
537 static void *frontend
;
539 static tree234
*ssh_channels
; /* indexed by local id */
540 static struct ssh_channel
*mainchan
; /* primary session channel */
541 static int ssh_exitcode
= -1;
543 static tree234
*ssh_rportfwds
;
547 SSH_STATE_BEFORE_SIZE
,
551 } ssh_state
= SSH_STATE_PREPACKET
;
553 static int size_needed
= FALSE
, eof_needed
= FALSE
;
555 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
556 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
557 static unsigned char *deferred_send_data
= NULL
;
558 static int deferred_len
= 0, deferred_size
= 0;
561 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
562 * that fails. This variable is the means by which scp.c can reach
563 * into the SSH code and find out which one it got.
565 int ssh_fallback_cmd
= 0;
567 static int ssh_version
;
568 static int ssh1_throttle_count
;
569 static int ssh_overall_bufsize
;
570 static int ssh_throttled_all
;
571 static int ssh1_stdout_throttling
;
572 static void (*ssh_protocol
) (unsigned char *in
, int inlen
, int ispkt
);
573 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
574 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
575 static void ssh_size(void);
576 static void ssh_special(Telnet_Special
);
577 static int ssh2_try_send(struct ssh_channel
*c
);
578 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
580 static void ssh_throttle_all(int enable
, int bufsize
);
581 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
);
582 static int (*s_rdpkt
) (unsigned char **data
, int *datalen
);
583 static int ssh_sendbuffer(void);
585 static struct rdpkt1_state_tag
{
586 long len
, pad
, biglen
, to_read
;
587 unsigned long realcrc
, gotcrc
;
593 static struct rdpkt2_state_tag
{
594 long len
, pad
, payload
, packetlen
, maclen
;
597 unsigned long incoming_sequence
;
600 static int ssh_channelcmp(void *av
, void *bv
)
602 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
603 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
604 if (a
->localid
< b
->localid
)
606 if (a
->localid
> b
->localid
)
610 static int ssh_channelfind(void *av
, void *bv
)
612 unsigned *a
= (unsigned *) av
;
613 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
621 static int ssh_rportcmp_ssh1(void *av
, void *bv
)
623 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
624 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
626 if ( (i
= strcmp(a
->dhost
, b
->dhost
)) != 0)
627 return i
< 0 ?
-1 : +1;
628 if (a
->dport
> b
->dport
)
630 if (a
->dport
< b
->dport
)
635 static int ssh_rportcmp_ssh2(void *av
, void *bv
)
637 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
638 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
640 if (a
->sport
> b
->sport
)
642 if (a
->sport
< b
->sport
)
647 static int alloc_channel_id(void)
649 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
650 unsigned low
, high
, mid
;
652 struct ssh_channel
*c
;
655 * First-fit allocation of channel numbers: always pick the
656 * lowest unused one. To do this, binary-search using the
657 * counted B-tree to find the largest channel ID which is in a
658 * contiguous sequence from the beginning. (Precisely
659 * everything in that sequence must have ID equal to its tree
660 * index plus CHANNEL_NUMBER_OFFSET.)
662 tsize
= count234(ssh_channels
);
666 while (high
- low
> 1) {
667 mid
= (high
+ low
) / 2;
668 c
= index234(ssh_channels
, mid
);
669 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
670 low
= mid
; /* this one is fine */
672 high
= mid
; /* this one is past it */
675 * Now low points to either -1, or the tree index of the
676 * largest ID in the initial sequence.
679 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
680 assert(NULL
== find234(ssh_channels
, &i
, ssh_channelfind
));
682 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
685 static void c_write(char *buf
, int len
)
687 if ((flags
& FLAG_STDERR
)) {
689 for (i
= 0; i
< len
; i
++)
691 fputc(buf
[i
], stderr
);
694 from_backend(frontend
, 1, buf
, len
);
697 static void c_write_untrusted(char *buf
, int len
)
700 for (i
= 0; i
< len
; i
++) {
703 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
708 static void c_write_str(char *buf
)
710 c_write(buf
, strlen(buf
));
714 * Collect incoming data in the incoming packet buffer.
715 * Decipher and verify the packet when it is completely read.
716 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
717 * Update the *data and *datalen variables.
718 * Return the additional nr of bytes needed, or 0 when
719 * a complete packet is available.
721 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
723 struct rdpkt1_state_tag
*st
= &rdpkt1_state
;
732 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
733 while ((*datalen
) == 0)
735 st
->len
= (st
->len
<< 8) + **data
;
736 (*data
)++, (*datalen
)--;
739 st
->pad
= 8 - (st
->len
% 8);
740 st
->biglen
= st
->len
+ st
->pad
;
741 pktin
.length
= st
->len
- 5;
743 if (pktin
.maxlen
< st
->biglen
) {
744 pktin
.maxlen
= st
->biglen
;
745 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->biglen
+ APIEXTRA
) :
746 srealloc(pktin
.data
, st
->biglen
+ APIEXTRA
));
748 fatalbox("Out of memory");
751 st
->to_read
= st
->biglen
;
753 while (st
->to_read
> 0) {
754 st
->chunk
= st
->to_read
;
755 while ((*datalen
) == 0)
756 crReturn(st
->to_read
);
757 if (st
->chunk
> (*datalen
))
758 st
->chunk
= (*datalen
);
759 memcpy(st
->p
, *data
, st
->chunk
);
761 *datalen
-= st
->chunk
;
763 st
->to_read
-= st
->chunk
;
766 if (cipher
&& detect_attack(pktin
.data
, st
->biglen
, NULL
)) {
767 bombout(("Network attack (CRC compensation) detected!"));
772 cipher
->decrypt(pktin
.data
, st
->biglen
);
774 st
->realcrc
= crc32(pktin
.data
, st
->biglen
- 4);
775 st
->gotcrc
= GET_32BIT(pktin
.data
+ st
->biglen
- 4);
776 if (st
->gotcrc
!= st
->realcrc
) {
777 bombout(("Incorrect CRC received on packet"));
781 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
783 if (ssh1_compressing
) {
784 unsigned char *decompblk
;
786 zlib_decompress_block(pktin
.body
- 1, pktin
.length
+ 1,
787 &decompblk
, &decomplen
);
789 if (pktin
.maxlen
< st
->pad
+ decomplen
) {
790 pktin
.maxlen
= st
->pad
+ decomplen
;
791 pktin
.data
= srealloc(pktin
.data
, pktin
.maxlen
+ APIEXTRA
);
792 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
794 fatalbox("Out of memory");
797 memcpy(pktin
.body
- 1, decompblk
, decomplen
);
799 pktin
.length
= decomplen
- 1;
802 pktin
.type
= pktin
.body
[-1];
804 log_packet(PKT_INCOMING
, pktin
.type
, ssh1_pkt_type(pktin
.type
),
805 pktin
.body
, pktin
.length
);
807 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
808 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
809 pktin
.type
== SSH1_MSG_DEBUG
||
810 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
811 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
812 long stringlen
= GET_32BIT(pktin
.body
);
813 if (stringlen
+ 4 != pktin
.length
) {
814 bombout(("Received data packet with bogus string length"));
819 if (pktin
.type
== SSH1_MSG_DEBUG
) {
820 /* log debug message */
822 int stringlen
= GET_32BIT(pktin
.body
);
823 strcpy(buf
, "Remote debug message: ");
826 memcpy(buf
+ 8, pktin
.body
+ 4, stringlen
);
827 buf
[8 + stringlen
] = '\0';
830 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
835 if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
836 /* log reason code in disconnect message */
838 unsigned msglen
= GET_32BIT(pktin
.body
);
840 strcpy(buf
, "Remote sent disconnect: ");
841 nowlen
= strlen(buf
);
842 if (msglen
> sizeof(buf
) - nowlen
- 1)
843 msglen
= sizeof(buf
) - nowlen
- 1;
844 memcpy(buf
+ nowlen
, pktin
.body
+ 4, msglen
);
845 buf
[nowlen
+ msglen
] = '\0';
846 /* logevent(buf); (this is now done within the bombout macro) */
847 bombout(("Server sent disconnect message:\n\"%s\"", buf
+nowlen
));
854 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
856 struct rdpkt2_state_tag
*st
= &rdpkt2_state
;
864 st
->cipherblk
= sccipher
->blksize
;
867 if (st
->cipherblk
< 8)
870 if (pktin
.maxlen
< st
->cipherblk
) {
871 pktin
.maxlen
= st
->cipherblk
;
874 NULL ?
smalloc(st
->cipherblk
+
875 APIEXTRA
) : srealloc(pktin
.data
,
879 fatalbox("Out of memory");
883 * Acquire and decrypt the first block of the packet. This will
884 * contain the length and padding details.
886 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
887 while ((*datalen
) == 0)
888 crReturn(st
->cipherblk
- st
->i
);
889 pktin
.data
[st
->i
] = *(*data
)++;
894 sccipher
->decrypt(pktin
.data
, st
->cipherblk
);
897 * Now get the length and padding figures.
899 st
->len
= GET_32BIT(pktin
.data
);
900 st
->pad
= pktin
.data
[4];
903 * _Completely_ silly lengths should be stomped on before they
904 * do us any more damage.
906 if (st
->len
< 0 || st
->pad
< 0 || st
->len
+ st
->pad
< 0) {
907 bombout(("Incoming packet was garbled on decryption"));
912 * This enables us to deduce the payload length.
914 st
->payload
= st
->len
- st
->pad
- 1;
916 pktin
.length
= st
->payload
+ 5;
919 * So now we can work out the total packet length.
921 st
->packetlen
= st
->len
+ 4;
922 st
->maclen
= scmac ? scmac
->len
: 0;
925 * Adjust memory allocation if packet is too big.
927 if (pktin
.maxlen
< st
->packetlen
+ st
->maclen
) {
928 pktin
.maxlen
= st
->packetlen
+ st
->maclen
;
931 NULL ?
smalloc(pktin
.maxlen
+ APIEXTRA
) : srealloc(pktin
.data
,
936 fatalbox("Out of memory");
940 * Read and decrypt the remainder of the packet.
942 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
944 while ((*datalen
) == 0)
945 crReturn(st
->packetlen
+ st
->maclen
- st
->i
);
946 pktin
.data
[st
->i
] = *(*data
)++;
949 /* Decrypt everything _except_ the MAC. */
951 sccipher
->decrypt(pktin
.data
+ st
->cipherblk
,
952 st
->packetlen
- st
->cipherblk
);
958 && !scmac
->verify(pktin
.data
, st
->len
+ 4,
959 st
->incoming_sequence
)) {
960 bombout(("Incorrect MAC received on packet"));
963 st
->incoming_sequence
++; /* whether or not we MACed */
966 * Decompress packet payload.
969 unsigned char *newpayload
;
971 if (sccomp
&& sccomp
->decompress(pktin
.data
+ 5, pktin
.length
- 5,
972 &newpayload
, &newlen
)) {
973 if (pktin
.maxlen
< newlen
+ 5) {
974 pktin
.maxlen
= newlen
+ 5;
977 NULL ?
smalloc(pktin
.maxlen
+
978 APIEXTRA
) : srealloc(pktin
.data
,
982 fatalbox("Out of memory");
984 pktin
.length
= 5 + newlen
;
985 memcpy(pktin
.data
+ 5, newpayload
, newlen
);
991 pktin
.type
= pktin
.data
[5];
993 log_packet(PKT_INCOMING
, pktin
.type
, ssh2_pkt_type(pktin
.type
),
994 pktin
.data
+6, pktin
.length
-6);
996 switch (pktin
.type
) {
998 * These packets we must handle instantly.
1000 case SSH2_MSG_DISCONNECT
:
1002 /* log reason code in disconnect message */
1004 int reason
= GET_32BIT(pktin
.data
+ 6);
1005 unsigned msglen
= GET_32BIT(pktin
.data
+ 10);
1007 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
1008 sprintf(buf
, "Received disconnect message (%s)",
1009 ssh2_disconnect_reasons
[reason
]);
1011 sprintf(buf
, "Received disconnect message (unknown type %d)",
1015 strcpy(buf
, "Disconnection message text: ");
1016 nowlen
= strlen(buf
);
1017 if (msglen
> sizeof(buf
) - nowlen
- 1)
1018 msglen
= sizeof(buf
) - nowlen
- 1;
1019 memcpy(buf
+ nowlen
, pktin
.data
+ 14, msglen
);
1020 buf
[nowlen
+ msglen
] = '\0';
1022 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
1024 (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) ?
1025 ssh2_disconnect_reasons
[reason
] : "unknown",
1030 case SSH2_MSG_IGNORE
:
1032 case SSH2_MSG_DEBUG
:
1034 /* log the debug message */
1036 /* int display = pktin.body[6]; */
1037 int stringlen
= GET_32BIT(pktin
.data
+7);
1039 strcpy(buf
, "Remote debug message: ");
1040 prefix
= strlen(buf
);
1041 if (stringlen
> sizeof(buf
)-prefix
-1)
1042 stringlen
= sizeof(buf
)-prefix
-1;
1043 memcpy(buf
+ prefix
, pktin
.data
+ 11, stringlen
);
1044 buf
[prefix
+ stringlen
] = '\0';
1047 goto next_packet
; /* FIXME: print the debug message */
1050 * These packets we need do nothing about here.
1052 case SSH2_MSG_UNIMPLEMENTED
:
1053 case SSH2_MSG_SERVICE_REQUEST
:
1054 case SSH2_MSG_SERVICE_ACCEPT
:
1055 case SSH2_MSG_KEXINIT
:
1056 case SSH2_MSG_NEWKEYS
:
1057 case SSH2_MSG_KEXDH_INIT
:
1058 case SSH2_MSG_KEXDH_REPLY
:
1059 /* case SSH2_MSG_KEX_DH_GEX_REQUEST: duplicate case value */
1060 /* case SSH2_MSG_KEX_DH_GEX_GROUP: duplicate case value */
1061 case SSH2_MSG_KEX_DH_GEX_INIT
:
1062 case SSH2_MSG_KEX_DH_GEX_REPLY
:
1063 case SSH2_MSG_USERAUTH_REQUEST
:
1064 case SSH2_MSG_USERAUTH_FAILURE
:
1065 case SSH2_MSG_USERAUTH_SUCCESS
:
1066 case SSH2_MSG_USERAUTH_BANNER
:
1067 case SSH2_MSG_USERAUTH_PK_OK
:
1068 /* case SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: duplicate case value */
1069 /* case SSH2_MSG_USERAUTH_INFO_REQUEST: duplicate case value */
1070 case SSH2_MSG_USERAUTH_INFO_RESPONSE
:
1071 case SSH2_MSG_GLOBAL_REQUEST
:
1072 case SSH2_MSG_REQUEST_SUCCESS
:
1073 case SSH2_MSG_REQUEST_FAILURE
:
1074 case SSH2_MSG_CHANNEL_OPEN
:
1075 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
:
1076 case SSH2_MSG_CHANNEL_OPEN_FAILURE
:
1077 case SSH2_MSG_CHANNEL_WINDOW_ADJUST
:
1078 case SSH2_MSG_CHANNEL_DATA
:
1079 case SSH2_MSG_CHANNEL_EXTENDED_DATA
:
1080 case SSH2_MSG_CHANNEL_EOF
:
1081 case SSH2_MSG_CHANNEL_CLOSE
:
1082 case SSH2_MSG_CHANNEL_REQUEST
:
1083 case SSH2_MSG_CHANNEL_SUCCESS
:
1084 case SSH2_MSG_CHANNEL_FAILURE
:
1088 * For anything else we send SSH2_MSG_UNIMPLEMENTED.
1091 ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED
);
1092 ssh2_pkt_adduint32(st
->incoming_sequence
- 1);
1100 static void ssh1_pktout_size(int len
)
1104 len
+= 5; /* type and CRC */
1105 pad
= 8 - (len
% 8);
1108 pktout
.length
= len
- 5;
1109 if (pktout
.maxlen
< biglen
) {
1110 pktout
.maxlen
= biglen
;
1112 /* Allocate enough buffer space for extra block
1113 * for MS CryptEncrypt() */
1114 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+ 12) :
1115 srealloc(pktout
.data
, biglen
+ 12));
1117 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+ 4) :
1118 srealloc(pktout
.data
, biglen
+ 4));
1121 fatalbox("Out of memory");
1123 pktout
.body
= pktout
.data
+ 4 + pad
+ 1;
1126 static void s_wrpkt_start(int type
, int len
)
1128 ssh1_pktout_size(len
);
1132 static int s_wrpkt_prepare(void)
1134 int pad
, len
, biglen
, i
;
1137 pktout
.body
[-1] = pktout
.type
;
1139 log_packet(PKT_OUTGOING
, pktout
.type
, ssh1_pkt_type(pktout
.type
),
1140 pktout
.body
, pktout
.length
);
1142 if (ssh1_compressing
) {
1143 unsigned char *compblk
;
1145 zlib_compress_block(pktout
.body
- 1, pktout
.length
+ 1,
1146 &compblk
, &complen
);
1147 ssh1_pktout_size(complen
- 1);
1148 memcpy(pktout
.body
- 1, compblk
, complen
);
1152 len
= pktout
.length
+ 5; /* type and CRC */
1153 pad
= 8 - (len
% 8);
1156 for (i
= 0; i
< pad
; i
++)
1157 pktout
.data
[i
+ 4] = random_byte();
1158 crc
= crc32(pktout
.data
+ 4, biglen
- 4);
1159 PUT_32BIT(pktout
.data
+ biglen
, crc
);
1160 PUT_32BIT(pktout
.data
, len
);
1163 cipher
->encrypt(pktout
.data
+ 4, biglen
);
1168 static void s_wrpkt(void)
1171 len
= s_wrpkt_prepare();
1172 backlog
= sk_write(s
, pktout
.data
, len
);
1173 if (backlog
> SSH_MAX_BACKLOG
)
1174 ssh_throttle_all(1, backlog
);
1177 static void s_wrpkt_defer(void)
1180 len
= s_wrpkt_prepare();
1181 if (deferred_len
+ len
> deferred_size
) {
1182 deferred_size
= deferred_len
+ len
+ 128;
1183 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1185 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
1186 deferred_len
+= len
;
1190 * Construct a packet with the specified contents.
1192 static void construct_packet(int pkttype
, va_list ap1
, va_list ap2
)
1194 unsigned char *p
, *argp
, argchar
;
1195 unsigned long argint
;
1196 int pktlen
, argtype
, arglen
;
1200 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
1203 (void) va_arg(ap1
, int);
1207 (void) va_arg(ap1
, char);
1211 (void) va_arg(ap1
, unsigned char *);
1212 arglen
= va_arg(ap1
, int);
1216 argp
= va_arg(ap1
, unsigned char *);
1217 arglen
= strlen(argp
);
1218 pktlen
+= 4 + arglen
;
1221 bn
= va_arg(ap1
, Bignum
);
1222 pktlen
+= ssh1_bignum_length(bn
);
1229 s_wrpkt_start(pkttype
, pktlen
);
1232 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
1235 argint
= va_arg(ap2
, int);
1236 PUT_32BIT(p
, argint
);
1240 argchar
= va_arg(ap2
, unsigned char);
1245 argp
= va_arg(ap2
, unsigned char *);
1246 arglen
= va_arg(ap2
, int);
1247 memcpy(p
, argp
, arglen
);
1251 argp
= va_arg(ap2
, unsigned char *);
1252 arglen
= strlen(argp
);
1253 PUT_32BIT(p
, arglen
);
1254 memcpy(p
+ 4, argp
, arglen
);
1258 bn
= va_arg(ap2
, Bignum
);
1259 p
+= ssh1_write_bignum(p
, bn
);
1265 static void send_packet(int pkttype
, ...)
1268 va_start(ap1
, pkttype
);
1269 va_start(ap2
, pkttype
);
1270 construct_packet(pkttype
, ap1
, ap2
);
1274 static void defer_packet(int pkttype
, ...)
1277 va_start(ap1
, pkttype
);
1278 va_start(ap2
, pkttype
);
1279 construct_packet(pkttype
, ap1
, ap2
);
1283 static int ssh_versioncmp(char *a
, char *b
)
1286 unsigned long av
, bv
;
1288 av
= strtoul(a
, &ae
, 10);
1289 bv
= strtoul(b
, &be
, 10);
1291 return (av
< bv ?
-1 : +1);
1296 av
= strtoul(ae
, &ae
, 10);
1297 bv
= strtoul(be
, &be
, 10);
1299 return (av
< bv ?
-1 : +1);
1305 * Utility routines for putting an SSH-protocol `string' and
1306 * `uint32' into a SHA state.
1309 static void sha_string(SHA_State
* s
, void *str
, int len
)
1311 unsigned char lenblk
[4];
1312 PUT_32BIT(lenblk
, len
);
1313 SHA_Bytes(s
, lenblk
, 4);
1314 SHA_Bytes(s
, str
, len
);
1317 static void sha_uint32(SHA_State
* s
, unsigned i
)
1319 unsigned char intblk
[4];
1320 PUT_32BIT(intblk
, i
);
1321 SHA_Bytes(s
, intblk
, 4);
1325 * SSH2 packet construction functions.
1327 static void ssh2_pkt_ensure(int length
)
1329 if (pktout
.maxlen
< length
) {
1330 pktout
.maxlen
= length
+ 256;
1333 NULL ?
smalloc(pktout
.maxlen
+
1334 APIEXTRA
) : srealloc(pktout
.data
,
1338 fatalbox("Out of memory");
1341 static void ssh2_pkt_adddata(void *data
, int len
)
1343 pktout
.length
+= len
;
1344 ssh2_pkt_ensure(pktout
.length
);
1345 memcpy(pktout
.data
+ pktout
.length
- len
, data
, len
);
1347 static void ssh2_pkt_addbyte(unsigned char byte
)
1349 ssh2_pkt_adddata(&byte
, 1);
1351 static void ssh2_pkt_init(int pkt_type
)
1354 ssh2_pkt_addbyte((unsigned char) pkt_type
);
1356 static void ssh2_pkt_addbool(unsigned char value
)
1358 ssh2_pkt_adddata(&value
, 1);
1360 static void ssh2_pkt_adduint32(unsigned long value
)
1363 PUT_32BIT(x
, value
);
1364 ssh2_pkt_adddata(x
, 4);
1366 static void ssh2_pkt_addstring_start(void)
1368 ssh2_pkt_adduint32(0);
1369 pktout
.savedpos
= pktout
.length
;
1371 static void ssh2_pkt_addstring_str(char *data
)
1373 ssh2_pkt_adddata(data
, strlen(data
));
1374 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1375 pktout
.length
- pktout
.savedpos
);
1377 static void ssh2_pkt_addstring_data(char *data
, int len
)
1379 ssh2_pkt_adddata(data
, len
);
1380 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1381 pktout
.length
- pktout
.savedpos
);
1383 static void ssh2_pkt_addstring(char *data
)
1385 ssh2_pkt_addstring_start();
1386 ssh2_pkt_addstring_str(data
);
1388 static char *ssh2_mpint_fmt(Bignum b
, int *len
)
1391 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1394 fatalbox("out of memory");
1396 for (i
= 1; i
<= n
; i
++)
1397 p
[i
] = bignum_byte(b
, n
- i
);
1399 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1401 memmove(p
, p
+ i
, n
+ 1 - i
);
1405 static void ssh2_pkt_addmp(Bignum b
)
1409 p
= ssh2_mpint_fmt(b
, &len
);
1410 ssh2_pkt_addstring_start();
1411 ssh2_pkt_addstring_data(p
, len
);
1416 * Construct an SSH2 final-form packet: compress it, encrypt it,
1417 * put the MAC on it. Final packet, ready to be sent, is stored in
1418 * pktout.data. Total length is returned.
1420 static int ssh2_pkt_construct(void)
1422 int cipherblk
, maclen
, padding
, i
;
1423 static unsigned long outgoing_sequence
= 0;
1425 log_packet(PKT_OUTGOING
, pktout
.data
[5], ssh2_pkt_type(pktout
.data
[5]),
1426 pktout
.data
+ 6, pktout
.length
- 6);
1429 * Compress packet payload.
1432 unsigned char *newpayload
;
1434 if (cscomp
&& cscomp
->compress(pktout
.data
+ 5, pktout
.length
- 5,
1435 &newpayload
, &newlen
)) {
1437 ssh2_pkt_adddata(newpayload
, newlen
);
1443 * Add padding. At least four bytes, and must also bring total
1444 * length (minus MAC) up to a multiple of the block size.
1446 cipherblk
= cscipher ? cscipher
->blksize
: 8; /* block size */
1447 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1450 (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
1451 maclen
= csmac ? csmac
->len
: 0;
1452 ssh2_pkt_ensure(pktout
.length
+ padding
+ maclen
);
1453 pktout
.data
[4] = padding
;
1454 for (i
= 0; i
< padding
; i
++)
1455 pktout
.data
[pktout
.length
+ i
] = random_byte();
1456 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
1458 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
1460 outgoing_sequence
++; /* whether or not we MACed */
1463 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
1465 /* Ready-to-send packet starts at pktout.data. We return length. */
1466 return pktout
.length
+ padding
+ maclen
;
1470 * Construct and send an SSH2 packet immediately.
1472 static void ssh2_pkt_send(void)
1476 len
= ssh2_pkt_construct();
1477 backlog
= sk_write(s
, pktout
.data
, len
);
1478 if (backlog
> SSH_MAX_BACKLOG
)
1479 ssh_throttle_all(1, backlog
);
1483 * Construct an SSH2 packet and add it to a deferred data block.
1484 * Useful for sending multiple packets in a single sk_write() call,
1485 * to prevent a traffic-analysing listener from being able to work
1486 * out the length of any particular packet (such as the password
1489 * Note that because SSH2 sequence-numbers its packets, this can
1490 * NOT be used as an m4-style `defer' allowing packets to be
1491 * constructed in one order and sent in another.
1493 static void ssh2_pkt_defer(void)
1495 int len
= ssh2_pkt_construct();
1496 if (deferred_len
+ len
> deferred_size
) {
1497 deferred_size
= deferred_len
+ len
+ 128;
1498 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1500 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
1501 deferred_len
+= len
;
1505 * Send the whole deferred data block constructed by
1506 * ssh2_pkt_defer() or SSH1's defer_packet().
1508 static void ssh_pkt_defersend(void)
1511 backlog
= sk_write(s
, deferred_send_data
, deferred_len
);
1512 deferred_len
= deferred_size
= 0;
1513 sfree(deferred_send_data
);
1514 deferred_send_data
= NULL
;
1515 if (backlog
> SSH_MAX_BACKLOG
)
1516 ssh_throttle_all(1, backlog
);
1520 void bndebug(char *string
, Bignum b
)
1524 p
= ssh2_mpint_fmt(b
, &len
);
1525 debug(("%s", string
));
1526 for (i
= 0; i
< len
; i
++)
1527 debug((" %02x", p
[i
]));
1533 static void sha_mpint(SHA_State
* s
, Bignum b
)
1537 p
= ssh2_mpint_fmt(b
, &len
);
1538 sha_string(s
, p
, len
);
1543 * SSH2 packet decode functions.
1545 static unsigned long ssh2_pkt_getuint32(void)
1547 unsigned long value
;
1548 if (pktin
.length
- pktin
.savedpos
< 4)
1549 return 0; /* arrgh, no way to decline (FIXME?) */
1550 value
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1551 pktin
.savedpos
+= 4;
1554 static int ssh2_pkt_getbool(void)
1556 unsigned long value
;
1557 if (pktin
.length
- pktin
.savedpos
< 1)
1558 return 0; /* arrgh, no way to decline (FIXME?) */
1559 value
= pktin
.data
[pktin
.savedpos
] != 0;
1563 static void ssh2_pkt_getstring(char **p
, int *length
)
1567 if (pktin
.length
- pktin
.savedpos
< 4)
1569 *length
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1570 pktin
.savedpos
+= 4;
1571 if (pktin
.length
- pktin
.savedpos
< *length
)
1573 *p
= pktin
.data
+ pktin
.savedpos
;
1574 pktin
.savedpos
+= *length
;
1576 static Bignum
ssh2_pkt_getmp(void)
1582 ssh2_pkt_getstring(&p
, &length
);
1586 bombout(("internal error: Can't handle negative mpints"));
1589 b
= bignum_from_bytes(p
, length
);
1594 * Helper function to add an SSH2 signature blob to a packet.
1595 * Expects to be shown the public key blob as well as the signature
1596 * blob. Normally works just like ssh2_pkt_addstring, but will
1597 * fiddle with the signature packet if necessary for
1598 * BUG_SSH2_RSA_PADDING.
1600 static void ssh2_add_sigblob(void *pkblob_v
, int pkblob_len
,
1601 void *sigblob_v
, int sigblob_len
)
1603 unsigned char *pkblob
= (unsigned char *)pkblob_v
;
1604 unsigned char *sigblob
= (unsigned char *)sigblob_v
;
1606 /* dmemdump(pkblob, pkblob_len); */
1607 /* dmemdump(sigblob, sigblob_len); */
1610 * See if this is in fact an ssh-rsa signature and a buggy
1611 * server; otherwise we can just do this the easy way.
1613 if ((ssh_remote_bugs
& BUG_SSH2_RSA_PADDING
) &&
1614 (GET_32BIT(pkblob
) == 7 && !memcmp(pkblob
+4, "ssh-rsa", 7))) {
1615 int pos
, len
, siglen
;
1618 * Find the byte length of the modulus.
1621 pos
= 4+7; /* skip over "ssh-rsa" */
1622 pos
+= 4 + GET_32BIT(pkblob
+pos
); /* skip over exponent */
1623 len
= GET_32BIT(pkblob
+pos
); /* find length of modulus */
1624 pos
+= 4; /* find modulus itself */
1625 while (len
> 0 && pkblob
[pos
] == 0)
1627 /* debug(("modulus length is %d\n", len)); */
1630 * Now find the signature integer.
1632 pos
= 4+7; /* skip over "ssh-rsa" */
1633 siglen
= GET_32BIT(sigblob
+pos
);
1634 /* debug(("signature length is %d\n", siglen)); */
1636 if (len
!= siglen
) {
1637 unsigned char newlen
[4];
1638 ssh2_pkt_addstring_start();
1639 ssh2_pkt_addstring_data(sigblob
, pos
);
1640 /* dmemdump(sigblob, pos); */
1641 pos
+= 4; /* point to start of actual sig */
1642 PUT_32BIT(newlen
, len
);
1643 ssh2_pkt_addstring_data(newlen
, 4);
1644 /* dmemdump(newlen, 4); */
1646 while (len
-- > siglen
) {
1647 ssh2_pkt_addstring_data(newlen
, 1);
1648 /* dmemdump(newlen, 1); */
1650 ssh2_pkt_addstring_data(sigblob
+pos
, siglen
);
1651 /* dmemdump(sigblob+pos, siglen); */
1655 /* Otherwise fall through and do it the easy way. */
1658 ssh2_pkt_addstring_start();
1659 ssh2_pkt_addstring_data(sigblob
, sigblob_len
);
1663 * Examine the remote side's version string and compare it against
1664 * a list of known buggy implementations.
1666 static void ssh_detect_bugs(char *vstring
)
1668 char *imp
; /* pointer to implementation part */
1670 imp
+= strcspn(imp
, "-");
1672 imp
+= strcspn(imp
, "-");
1675 ssh_remote_bugs
= 0;
1677 if (cfg
.sshbug_ignore1
== BUG_ON
||
1678 (cfg
.sshbug_ignore1
== BUG_AUTO
&&
1679 (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
1680 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
1681 !strcmp(imp
, "1.2.22") || !strcmp(imp
, "Cisco-1.25")))) {
1683 * These versions don't support SSH1_MSG_IGNORE, so we have
1684 * to use a different defence against password length
1687 ssh_remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
1688 logevent("We believe remote version has SSH1 ignore bug");
1691 if (cfg
.sshbug_plainpw1
== BUG_ON
||
1692 (cfg
.sshbug_plainpw1
== BUG_AUTO
&&
1693 (!strcmp(imp
, "Cisco-1.25")))) {
1695 * These versions need a plain password sent; they can't
1696 * handle having a null and a random length of data after
1699 ssh_remote_bugs
|= BUG_NEEDS_SSH1_PLAIN_PASSWORD
;
1700 logevent("We believe remote version needs a plain SSH1 password");
1703 if (cfg
.sshbug_rsa1
== BUG_ON
||
1704 (cfg
.sshbug_rsa1
== BUG_AUTO
&&
1705 (!strcmp(imp
, "Cisco-1.25")))) {
1707 * These versions apparently have no clue whatever about
1708 * RSA authentication and will panic and die if they see
1709 * an AUTH_RSA message.
1711 ssh_remote_bugs
|= BUG_CHOKES_ON_RSA
;
1712 logevent("We believe remote version can't handle RSA authentication");
1715 if (cfg
.sshbug_hmac2
== BUG_ON
||
1716 (cfg
.sshbug_hmac2
== BUG_AUTO
&&
1717 (!strncmp(imp
, "2.1.0", 5) || !strncmp(imp
, "2.0.", 4) ||
1718 !strncmp(imp
, "2.2.0", 5) || !strncmp(imp
, "2.3.0", 5) ||
1719 !strncmp(imp
, "2.1 ", 4)))) {
1721 * These versions have the HMAC bug.
1723 ssh_remote_bugs
|= BUG_SSH2_HMAC
;
1724 logevent("We believe remote version has SSH2 HMAC bug");
1727 if (cfg
.sshbug_derivekey2
== BUG_ON
||
1728 (cfg
.sshbug_derivekey2
== BUG_AUTO
&&
1729 (!strncmp(imp
, "2.0.", 4)))) {
1731 * These versions have the key-derivation bug (failing to
1732 * include the literal shared secret in the hashes that
1733 * generate the keys).
1735 ssh_remote_bugs
|= BUG_SSH2_DERIVEKEY
;
1736 logevent("We believe remote version has SSH2 key-derivation bug");
1739 if (cfg
.sshbug_rsapad2
== BUG_ON
||
1740 (cfg
.sshbug_rsapad2
== BUG_AUTO
&&
1741 ((!strncmp(imp
, "OpenSSH_2.", 10) && imp
[10]>='5' && imp
[10]<='9') ||
1742 (!strncmp(imp
, "OpenSSH_3.", 10) && imp
[10]>='0' && imp
[10]<='2')))){
1744 * These versions have the SSH2 RSA padding bug.
1746 ssh_remote_bugs
|= BUG_SSH2_RSA_PADDING
;
1747 logevent("We believe remote version has SSH2 RSA padding bug");
1750 if (cfg
.sshbug_dhgex2
== BUG_ON
) {
1752 * These versions have the SSH2 DH GEX bug.
1754 ssh_remote_bugs
|= BUG_SSH2_DH_GEX
;
1755 logevent("We believe remote version has SSH2 DH group exchange bug");
1759 static int do_ssh_init(unsigned char c
)
1762 static char version
[10];
1763 static char *vstring
;
1764 static int vstrsize
;
1767 static int proto1
, proto2
;
1771 /* Search for the string "SSH-" in the input. */
1774 static const int transS
[] = { 1, 2, 2, 1 };
1775 static const int transH
[] = { 0, 0, 3, 0 };
1776 static const int transminus
[] = { 0, 0, 0, -1 };
1787 crReturn(1); /* get another character */
1791 vstring
= smalloc(vstrsize
);
1792 strcpy(vstring
, "SSH-");
1796 crReturn(1); /* get another char */
1797 if (vslen
>= vstrsize
- 1) {
1799 vstring
= srealloc(vstring
, vstrsize
);
1801 vstring
[vslen
++] = c
;
1806 } else if (i
< sizeof(version
) - 1)
1808 } else if (c
== '\n')
1812 ssh_agentfwd_enabled
= FALSE
;
1813 rdpkt2_state
.incoming_sequence
= 0;
1816 vlog
= smalloc(20 + vslen
);
1817 vstring
[strcspn (vstring
, "\r\n")] = '\0'; /* remove end-of-line chars */
1818 sprintf(vlog
, "Server version: %s", vstring
);
1820 ssh_detect_bugs(vstring
);
1824 * Decide which SSH protocol version to support.
1827 /* Anything strictly below "2.0" means protocol 1 is supported. */
1828 proto1
= ssh_versioncmp(version
, "2.0") < 0;
1829 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
1830 proto2
= ssh_versioncmp(version
, "1.99") >= 0;
1832 if (cfg
.sshprot
== 0 && !proto1
) {
1833 bombout(("SSH protocol version 1 required by user but not provided by server"));
1836 if (cfg
.sshprot
== 3 && !proto2
) {
1837 bombout(("SSH protocol version 2 required by user but not provided by server"));
1841 if (proto2
&& (cfg
.sshprot
>= 2 || !proto1
)) {
1845 char verstring
[80], vlog
[100];
1846 sprintf(verstring
, "SSH-2.0-%s", sshver
);
1847 SHA_Init(&exhashbase
);
1849 * Hash our version string and their version string.
1851 sha_string(&exhashbase
, verstring
, strlen(verstring
));
1852 sha_string(&exhashbase
, vstring
, strcspn(vstring
, "\r\n"));
1853 sprintf(vlog
, "We claim version: %s", verstring
);
1855 strcat(verstring
, "\n");
1856 logevent("Using SSH protocol version 2");
1857 sk_write(s
, verstring
, strlen(verstring
));
1858 ssh_protocol
= ssh2_protocol
;
1860 s_rdpkt
= ssh2_rdpkt
;
1865 char verstring
[80], vlog
[100];
1866 sprintf(verstring
, "SSH-%s-%s",
1867 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"),
1869 sprintf(vlog
, "We claim version: %s", verstring
);
1871 strcat(verstring
, "\n");
1873 logevent("Using SSH protocol version 1");
1874 sk_write(s
, verstring
, strlen(verstring
));
1875 ssh_protocol
= ssh1_protocol
;
1877 s_rdpkt
= ssh1_rdpkt
;
1879 ssh_state
= SSH_STATE_BEFORE_SIZE
;
1886 static void ssh_gotdata(unsigned char *data
, int datalen
)
1891 * To begin with, feed the characters one by one to the
1892 * protocol initialisation / selection function do_ssh_init().
1893 * When that returns 0, we're done with the initial greeting
1894 * exchange and can move on to packet discipline.
1899 crReturnV
; /* more data please */
1900 ret
= do_ssh_init(*data
);
1908 * We emerge from that loop when the initial negotiation is
1909 * over and we have selected an s_rdpkt function. Now pass
1910 * everything to s_rdpkt, and then pass the resulting packets
1911 * to the proper protocol handler.
1916 while (datalen
> 0) {
1917 if (s_rdpkt(&data
, &datalen
) == 0) {
1918 if (ssh_state
== SSH_STATE_CLOSED
) {
1921 ssh_protocol(NULL
, 0, 1);
1922 if (ssh_state
== SSH_STATE_CLOSED
) {
1932 static int ssh_closing(Plug plug
, char *error_msg
, int error_code
,
1935 ssh_state
= SSH_STATE_CLOSED
;
1941 /* A socket error has occurred. */
1942 logevent(error_msg
);
1943 connection_fatal(error_msg
);
1945 /* Otherwise, the remote side closed the connection normally. */
1950 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
1952 ssh_gotdata(data
, len
);
1953 if (ssh_state
== SSH_STATE_CLOSED
) {
1963 static void ssh_sent(Plug plug
, int bufsize
)
1966 * If the send backlog on the SSH socket itself clears, we
1967 * should unthrottle the whole world if it was throttled.
1969 if (bufsize
< SSH_MAX_BACKLOG
)
1970 ssh_throttle_all(0, bufsize
);
1974 * Connect to specified host and port.
1975 * Returns an error message, or NULL on success.
1976 * Also places the canonical host name into `realhost'. It must be
1977 * freed by the caller.
1979 static char *connect_to_host(char *host
, int port
, char **realhost
, int nodelay
)
1981 static struct plug_function_table fn_table
= {
1986 }, *fn_table_ptr
= &fn_table
;
1995 savedhost
= smalloc(1 + strlen(host
));
1997 fatalbox("Out of memory");
1998 strcpy(savedhost
, host
);
2001 port
= 22; /* default ssh port */
2016 sprintf(buf
, "Looking up host \"%.170s\"", host
);
2019 addr
= sk_namelookup(host
, realhost
);
2020 if ((err
= sk_addr_error(addr
)))
2024 *realhost
= strdup(FWhost
);
2031 char buf
[200], addrbuf
[100];
2032 sk_getaddr(addr
, addrbuf
, 100);
2033 sprintf(buf
, "Connecting to %.100s port %d", addrbuf
, port
);
2036 s
= new_connection(addr
, *realhost
, port
, 0, 1, nodelay
, &fn_table_ptr
);
2037 if ((err
= sk_socket_error(s
))) {
2043 sk_write(s
, "connect ", 8);
2044 sk_write(s
, FWhost
, strlen(FWhost
));
2047 sprintf(buf
, " %d\n", FWport
);
2048 sk_write(s
, buf
, strlen(buf
));
2056 * Throttle or unthrottle the SSH connection.
2058 static void ssh1_throttle(int adjust
)
2060 int old_count
= ssh1_throttle_count
;
2061 ssh1_throttle_count
+= adjust
;
2062 assert(ssh1_throttle_count
>= 0);
2063 if (ssh1_throttle_count
&& !old_count
) {
2064 sk_set_frozen(s
, 1);
2065 } else if (!ssh1_throttle_count
&& old_count
) {
2066 sk_set_frozen(s
, 0);
2071 * Throttle or unthrottle _all_ local data streams (for when sends
2072 * on the SSH connection itself back up).
2074 static void ssh_throttle_all(int enable
, int bufsize
)
2077 struct ssh_channel
*c
;
2079 if (enable
== ssh_throttled_all
)
2081 ssh_throttled_all
= enable
;
2082 ssh_overall_bufsize
= bufsize
;
2085 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++) {
2087 case CHAN_MAINSESSION
:
2089 * This is treated separately, outside the switch.
2093 x11_override_throttle(c
->u
.x11
.s
, enable
);
2096 /* Agent channels require no buffer management. */
2099 pfd_override_throttle(c
->u
.x11
.s
, enable
);
2106 * Username and password input, abstracted off into reusable
2107 * routines (hopefully even reusable between SSH1 and SSH2!).
2109 static char *ssh_userpass_input_buffer
;
2110 static int ssh_userpass_input_buflen
;
2111 static int ssh_userpass_input_bufpos
;
2112 static int ssh_userpass_input_echo
;
2114 /* Set up a username or password input loop on a given buffer. */
2115 void setup_userpass_input(char *buffer
, int buflen
, int echo
)
2117 ssh_userpass_input_buffer
= buffer
;
2118 ssh_userpass_input_buflen
= buflen
;
2119 ssh_userpass_input_bufpos
= 0;
2120 ssh_userpass_input_echo
= echo
;
2124 * Process some terminal data in the course of username/password
2125 * input. Returns >0 for success (line of input returned in
2126 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2127 * for inconclusive (keep waiting for more input please).
2129 int process_userpass_input(unsigned char *in
, int inlen
)
2134 switch (c
= *in
++) {
2137 ssh_userpass_input_buffer
[ssh_userpass_input_bufpos
] = 0;
2138 ssh_userpass_input_buffer
[ssh_userpass_input_buflen
-1] = 0;
2143 if (ssh_userpass_input_bufpos
> 0) {
2144 if (ssh_userpass_input_echo
)
2145 c_write_str("\b \b");
2146 ssh_userpass_input_bufpos
--;
2151 while (ssh_userpass_input_bufpos
> 0) {
2152 if (ssh_userpass_input_echo
)
2153 c_write_str("\b \b");
2154 ssh_userpass_input_bufpos
--;
2162 if (((c
>= ' ' && c
<= '~') ||
2163 ((unsigned char) c
>= 160))
2164 && ssh_userpass_input_bufpos
< ssh_userpass_input_buflen
-1) {
2165 ssh_userpass_input_buffer
[ssh_userpass_input_bufpos
++] = c
;
2166 if (ssh_userpass_input_echo
)
2176 * Handle the key exchange and user authentication phases.
2178 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
2182 static unsigned char *rsabuf
, *keystr1
, *keystr2
;
2183 unsigned char cookie
[8];
2184 struct RSAKey servkey
, hostkey
;
2185 struct MD5Context md5c
;
2186 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
2187 static int tried_publickey
, tried_agent
;
2188 static int tis_auth_refused
, ccard_auth_refused
;
2189 static unsigned char session_id
[16];
2190 static int cipher_type
;
2191 static char username
[100];
2192 static void *publickey_blob
;
2193 int publickey_bloblen
;
2200 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
2201 bombout(("Public key packet not received"));
2205 logevent("Received public keys");
2207 memcpy(cookie
, pktin
.body
, 8);
2209 i
= makekey(pktin
.body
+ 8, &servkey
, &keystr1
, 0);
2210 j
= makekey(pktin
.body
+ 8 + i
, &hostkey
, &keystr2
, 0);
2213 * Log the host key fingerprint.
2217 logevent("Host key fingerprint is:");
2218 strcpy(logmsg
, " ");
2219 hostkey
.comment
= NULL
;
2220 rsa_fingerprint(logmsg
+ strlen(logmsg
),
2221 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
2225 ssh1_remote_protoflags
= GET_32BIT(pktin
.body
+ 8 + i
+ j
);
2226 supported_ciphers_mask
= GET_32BIT(pktin
.body
+ 12 + i
+ j
);
2227 supported_auths_mask
= GET_32BIT(pktin
.body
+ 16 + i
+ j
);
2229 ssh1_local_protoflags
=
2230 ssh1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
2231 ssh1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
2234 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
2235 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
2236 MD5Update(&md5c
, pktin
.body
, 8);
2237 MD5Final(session_id
, &md5c
);
2239 for (i
= 0; i
< 32; i
++)
2240 session_key
[i
] = random_byte();
2242 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
2244 rsabuf
= smalloc(len
);
2246 fatalbox("Out of memory");
2249 * Verify the host key.
2253 * First format the key into a string.
2255 int len
= rsastr_len(&hostkey
);
2256 char fingerprint
[100];
2257 char *keystr
= smalloc(len
);
2259 fatalbox("Out of memory");
2260 rsastr_fmt(keystr
, &hostkey
);
2261 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
2262 verify_ssh_host_key(savedhost
, savedport
, "rsa", keystr
,
2267 for (i
= 0; i
< 32; i
++) {
2268 rsabuf
[i
] = session_key
[i
];
2270 rsabuf
[i
] ^= session_id
[i
];
2273 if (hostkey
.bytes
> servkey
.bytes
) {
2274 rsaencrypt(rsabuf
, 32, &servkey
);
2275 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
2277 rsaencrypt(rsabuf
, 32, &hostkey
);
2278 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
2281 logevent("Encrypted session key");
2284 int cipher_chosen
= 0, warn
= 0;
2285 char *cipher_string
= NULL
;
2286 for (i
= 0; !cipher_chosen
&& i
< CIPHER_MAX
; i
++) {
2287 int next_cipher
= cfg
.ssh_cipherlist
[i
];
2288 if (next_cipher
== CIPHER_WARN
) {
2289 /* If/when we choose a cipher, warn about it */
2291 } else if (next_cipher
== CIPHER_AES
) {
2292 /* XXX Probably don't need to mention this. */
2293 logevent("AES not supported in SSH1, skipping");
2295 switch (next_cipher
) {
2296 case CIPHER_3DES
: cipher_type
= SSH_CIPHER_3DES
;
2297 cipher_string
= "3DES"; break;
2298 case CIPHER_BLOWFISH
: cipher_type
= SSH_CIPHER_BLOWFISH
;
2299 cipher_string
= "Blowfish"; break;
2300 case CIPHER_DES
: cipher_type
= SSH_CIPHER_DES
;
2301 cipher_string
= "single-DES"; break;
2303 if (supported_ciphers_mask
& (1 << cipher_type
))
2307 if (!cipher_chosen
) {
2308 if ((supported_ciphers_mask
& (1 << SSH_CIPHER_3DES
)) == 0)
2309 bombout(("Server violates SSH 1 protocol by not "
2310 "supporting 3DES encryption"));
2312 /* shouldn't happen */
2313 bombout(("No supported ciphers found"));
2317 /* Warn about chosen cipher if necessary. */
2319 askcipher(cipher_string
, 0);
2322 switch (cipher_type
) {
2323 case SSH_CIPHER_3DES
:
2324 logevent("Using 3DES encryption");
2326 case SSH_CIPHER_DES
:
2327 logevent("Using single-DES encryption");
2329 case SSH_CIPHER_BLOWFISH
:
2330 logevent("Using Blowfish encryption");
2334 send_packet(SSH1_CMSG_SESSION_KEY
,
2335 PKT_CHAR
, cipher_type
,
2336 PKT_DATA
, cookie
, 8,
2337 PKT_CHAR
, (len
* 8) >> 8, PKT_CHAR
, (len
* 8) & 0xFF,
2338 PKT_DATA
, rsabuf
, len
,
2339 PKT_INT
, ssh1_local_protoflags
, PKT_END
);
2341 logevent("Trying to enable encryption...");
2345 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
2346 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
: &ssh_3des
;
2347 cipher
->sesskey(session_key
);
2351 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2352 bombout(("Encryption not successfully enabled"));
2356 logevent("Successfully started encryption");
2360 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
2361 if (ssh_get_line
&& !ssh_getline_pw_only
) {
2362 if (!ssh_get_line("login as: ",
2363 username
, sizeof(username
), FALSE
)) {
2365 * get_line failed to get a username.
2368 logevent("No username provided. Abandoning session.");
2369 ssh_state
= SSH_STATE_CLOSED
;
2374 c_write_str("login as: ");
2377 setup_userpass_input(username
, sizeof(username
), 1);
2379 crWaitUntil(!ispkt
);
2380 ret
= process_userpass_input(in
, inlen
);
2384 c_write_str("\r\n");
2387 strncpy(username
, cfg
.username
, sizeof(username
));
2388 username
[sizeof(username
)-1] = '\0';
2391 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
2393 char userlog
[22 + sizeof(username
)];
2394 sprintf(userlog
, "Sent username \"%s\"", username
);
2396 if (flags
& FLAG_INTERACTIVE
&&
2397 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
2398 strcat(userlog
, "\r\n");
2399 c_write_str(userlog
);
2406 if ((ssh_remote_bugs
& BUG_CHOKES_ON_RSA
)) {
2407 /* We must not attempt PK auth. Pretend we've already tried it. */
2408 tried_publickey
= tried_agent
= 1;
2410 tried_publickey
= tried_agent
= 0;
2412 tis_auth_refused
= ccard_auth_refused
= 0;
2413 /* Load the public half of cfg.keyfile so we notice if it's in Pageant */
2415 if (!rsakey_pubblob(cfg
.keyfile
, &publickey_blob
, &publickey_bloblen
))
2416 publickey_blob
= NULL
;
2418 publickey_blob
= NULL
;
2420 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
2421 static char password
[100];
2422 static char prompt
[200];
2425 static int pwpkt_type
;
2426 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
2428 if (agent_exists() && !tried_agent
) {
2430 * Attempt RSA authentication using Pageant.
2432 static unsigned char request
[5], *response
, *p
;
2433 static int responselen
;
2434 static int i
, nkeys
;
2435 static int authed
= FALSE
;
2439 logevent("Pageant is running. Requesting keys.");
2441 /* Request the keys held by the agent. */
2442 PUT_32BIT(request
, 1);
2443 request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
2444 agent_query(request
, 5, &r
, &responselen
);
2445 response
= (unsigned char *) r
;
2446 if (response
&& responselen
>= 5 &&
2447 response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
2449 nkeys
= GET_32BIT(p
);
2453 sprintf(buf
, "Pageant has %d SSH1 keys", nkeys
);
2456 for (i
= 0; i
< nkeys
; i
++) {
2457 static struct RSAKey key
;
2458 static Bignum challenge
;
2459 static char *commentp
;
2460 static int commentlen
;
2464 sprintf(buf
, "Trying Pageant key #%d", i
);
2467 if (publickey_blob
&&
2468 !memcmp(p
, publickey_blob
, publickey_bloblen
)) {
2469 logevent("This key matches configured key file");
2470 tried_publickey
= 1;
2473 p
+= ssh1_read_bignum(p
, &key
.exponent
);
2474 p
+= ssh1_read_bignum(p
, &key
.modulus
);
2475 commentlen
= GET_32BIT(p
);
2479 send_packet(SSH1_CMSG_AUTH_RSA
,
2480 PKT_BIGNUM
, key
.modulus
, PKT_END
);
2482 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2483 logevent("Key refused");
2486 logevent("Received RSA challenge");
2487 ssh1_read_bignum(pktin
.body
, &challenge
);
2489 char *agentreq
, *q
, *ret
;
2492 len
= 1 + 4; /* message type, bit count */
2493 len
+= ssh1_bignum_length(key
.exponent
);
2494 len
+= ssh1_bignum_length(key
.modulus
);
2495 len
+= ssh1_bignum_length(challenge
);
2496 len
+= 16; /* session id */
2497 len
+= 4; /* response format */
2498 agentreq
= smalloc(4 + len
);
2499 PUT_32BIT(agentreq
, len
);
2501 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
2502 PUT_32BIT(q
, bignum_bitcount(key
.modulus
));
2504 q
+= ssh1_write_bignum(q
, key
.exponent
);
2505 q
+= ssh1_write_bignum(q
, key
.modulus
);
2506 q
+= ssh1_write_bignum(q
, challenge
);
2507 memcpy(q
, session_id
, 16);
2509 PUT_32BIT(q
, 1); /* response format */
2510 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
2514 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
2515 logevent("Sending Pageant's response");
2516 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2517 PKT_DATA
, ret
+ 5, 16,
2521 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2523 ("Pageant's response accepted");
2524 if (flags
& FLAG_VERBOSE
) {
2526 ("Authenticated using RSA key \"");
2527 c_write(commentp
, commentlen
);
2528 c_write_str("\" from agent\r\n");
2533 ("Pageant's response not accepted");
2536 ("Pageant failed to answer challenge");
2540 logevent("No reply received from Pageant");
2543 freebn(key
.exponent
);
2544 freebn(key
.modulus
);
2553 if (*cfg
.keyfile
&& !tried_publickey
)
2554 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
2556 if (cfg
.try_tis_auth
&&
2557 (supported_auths_mask
& (1 << SSH1_AUTH_TIS
)) &&
2558 !tis_auth_refused
) {
2559 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
2560 logevent("Requested TIS authentication");
2561 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
2563 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
2564 logevent("TIS authentication declined");
2565 if (flags
& FLAG_INTERACTIVE
)
2566 c_write_str("TIS authentication refused.\r\n");
2567 tis_auth_refused
= 1;
2570 int challengelen
= ((pktin
.body
[0] << 24) |
2571 (pktin
.body
[1] << 16) |
2572 (pktin
.body
[2] << 8) |
2574 logevent("Received TIS challenge");
2575 if (challengelen
> sizeof(prompt
) - 1)
2576 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2577 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2578 /* Prompt heuristic comes from OpenSSH */
2579 strncpy(prompt
+ challengelen
,
2580 memchr(prompt
, '\n', challengelen
) ?
2581 "": "\r\nResponse: ",
2582 (sizeof prompt
) - challengelen
);
2583 prompt
[(sizeof prompt
) - 1] = '\0';
2586 if (cfg
.try_tis_auth
&&
2587 (supported_auths_mask
& (1 << SSH1_AUTH_CCARD
)) &&
2588 !ccard_auth_refused
) {
2589 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
2590 logevent("Requested CryptoCard authentication");
2591 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
2593 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
2594 logevent("CryptoCard authentication declined");
2595 c_write_str("CryptoCard authentication refused.\r\n");
2596 ccard_auth_refused
= 1;
2599 int challengelen
= ((pktin
.body
[0] << 24) |
2600 (pktin
.body
[1] << 16) |
2601 (pktin
.body
[2] << 8) |
2603 logevent("Received CryptoCard challenge");
2604 if (challengelen
> sizeof(prompt
) - 1)
2605 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2606 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2607 strncpy(prompt
+ challengelen
,
2608 memchr(prompt
, '\n', challengelen
) ?
2609 "" : "\r\nResponse: ",
2610 sizeof(prompt
) - challengelen
);
2611 prompt
[sizeof(prompt
) - 1] = '\0';
2614 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2615 sprintf(prompt
, "%.90s@%.90s's password: ",
2616 username
, savedhost
);
2618 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2619 char *comment
= NULL
;
2622 if (flags
& FLAG_VERBOSE
)
2623 c_write_str("Trying public key authentication.\r\n");
2624 sprintf(msgbuf
, "Trying public key \"%.200s\"", cfg
.keyfile
);
2626 type
= key_type(cfg
.keyfile
);
2627 if (type
!= SSH_KEYTYPE_SSH1
) {
2628 sprintf(msgbuf
, "Key is of wrong type (%s)",
2629 key_type_to_str(type
));
2631 c_write_str(msgbuf
);
2632 c_write_str("\r\n");
2633 tried_publickey
= 1;
2636 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
2637 if (flags
& FLAG_VERBOSE
)
2638 c_write_str("No passphrase required.\r\n");
2641 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
2646 * Show password prompt, having first obtained it via a TIS
2647 * or CryptoCard exchange if we're doing TIS or CryptoCard
2651 if (!ssh_get_line(prompt
, password
, sizeof(password
), TRUE
)) {
2653 * get_line failed to get a password (for example
2654 * because one was supplied on the command line
2655 * which has already failed to work). Terminate.
2657 send_packet(SSH1_MSG_DISCONNECT
,
2658 PKT_STR
, "No more passwords available to try",
2660 logevent("Unable to authenticate");
2661 connection_fatal("Unable to authenticate");
2662 ssh_state
= SSH_STATE_CLOSED
;
2666 /* Prompt may have come from server. We've munged it a bit, so
2667 * we know it to be zero-terminated at least once. */
2669 c_write_untrusted(prompt
, strlen(prompt
));
2672 setup_userpass_input(password
, sizeof(password
), 0);
2674 crWaitUntil(!ispkt
);
2675 ret
= process_userpass_input(in
, inlen
);
2679 c_write_str("\r\n");
2683 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2685 * Try public key authentication with the specified
2688 static struct RSAKey pubkey
;
2689 static Bignum challenge
, response
;
2691 static unsigned char buffer
[32];
2693 tried_publickey
= 1;
2694 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
2696 c_write_str("Couldn't load private key from ");
2697 c_write_str(cfg
.keyfile
);
2698 c_write_str(".\r\n");
2699 continue; /* go and try password */
2702 c_write_str("Wrong passphrase.\r\n");
2703 tried_publickey
= 0;
2704 continue; /* try again */
2708 * Send a public key attempt.
2710 send_packet(SSH1_CMSG_AUTH_RSA
,
2711 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
2714 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2715 c_write_str("Server refused our public key.\r\n");
2716 continue; /* go and try password */
2718 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2719 bombout(("Bizarre response to offer of public key"));
2722 ssh1_read_bignum(pktin
.body
, &challenge
);
2723 response
= rsadecrypt(challenge
, &pubkey
);
2724 freebn(pubkey
.private_exponent
); /* burn the evidence */
2726 for (i
= 0; i
< 32; i
++) {
2727 buffer
[i
] = bignum_byte(response
, 31 - i
);
2731 MD5Update(&md5c
, buffer
, 32);
2732 MD5Update(&md5c
, session_id
, 16);
2733 MD5Final(buffer
, &md5c
);
2735 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2736 PKT_DATA
, buffer
, 16, PKT_END
);
2739 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2740 if (flags
& FLAG_VERBOSE
)
2742 ("Failed to authenticate with our public key.\r\n");
2743 continue; /* go and try password */
2744 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2746 ("Bizarre response to RSA authentication response"));
2750 break; /* we're through! */
2752 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2754 * Defence against traffic analysis: we send a
2755 * whole bunch of packets containing strings of
2756 * different lengths. One of these strings is the
2757 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2758 * The others are all random data in
2759 * SSH1_MSG_IGNORE packets. This way a passive
2760 * listener can't tell which is the password, and
2761 * hence can't deduce the password length.
2763 * Anybody with a password length greater than 16
2764 * bytes is going to have enough entropy in their
2765 * password that a listener won't find it _that_
2766 * much help to know how long it is. So what we'll
2769 * - if password length < 16, we send 15 packets
2770 * containing string lengths 1 through 15
2772 * - otherwise, we let N be the nearest multiple
2773 * of 8 below the password length, and send 8
2774 * packets containing string lengths N through
2775 * N+7. This won't obscure the order of
2776 * magnitude of the password length, but it will
2777 * introduce a bit of extra uncertainty.
2779 * A few servers (the old 1.2.18 through 1.2.22)
2780 * can't deal with SSH1_MSG_IGNORE. For these
2781 * servers, we need an alternative defence. We make
2782 * use of the fact that the password is interpreted
2783 * as a C string: so we can append a NUL, then some
2786 * One server (a Cisco one) can deal with neither
2787 * SSH1_MSG_IGNORE _nor_ a padded password string.
2788 * For this server we are left with no defences
2789 * against password length sniffing.
2791 if (!(ssh_remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
)) {
2793 * The server can deal with SSH1_MSG_IGNORE, so
2794 * we can use the primary defence.
2796 int bottom
, top
, pwlen
, i
;
2799 pwlen
= strlen(password
);
2801 bottom
= 0; /* zero length passwords are OK! :-) */
2804 bottom
= pwlen
& ~7;
2808 assert(pwlen
>= bottom
&& pwlen
<= top
);
2810 randomstr
= smalloc(top
+ 1);
2812 for (i
= bottom
; i
<= top
; i
++) {
2814 defer_packet(pwpkt_type
, PKT_STR
, password
,
2817 for (j
= 0; j
< i
; j
++) {
2819 randomstr
[j
] = random_byte();
2820 } while (randomstr
[j
] == '\0');
2822 randomstr
[i
] = '\0';
2823 defer_packet(SSH1_MSG_IGNORE
,
2824 PKT_STR
, randomstr
, PKT_END
);
2827 logevent("Sending password with camouflage packets");
2828 ssh_pkt_defersend();
2830 else if (!(ssh_remote_bugs
& BUG_NEEDS_SSH1_PLAIN_PASSWORD
)) {
2832 * The server can't deal with SSH1_MSG_IGNORE
2833 * but can deal with padded passwords, so we
2834 * can use the secondary defence.
2840 len
= strlen(password
);
2841 if (len
< sizeof(string
)) {
2843 strcpy(string
, password
);
2844 len
++; /* cover the zero byte */
2845 while (len
< sizeof(string
)) {
2846 string
[len
++] = (char) random_byte();
2851 logevent("Sending length-padded password");
2852 send_packet(pwpkt_type
, PKT_INT
, len
,
2853 PKT_DATA
, s
, len
, PKT_END
);
2856 * The server has _both_
2857 * BUG_CHOKES_ON_SSH1_IGNORE and
2858 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2859 * therefore nothing we can do.
2862 len
= strlen(password
);
2863 logevent("Sending unpadded password");
2864 send_packet(pwpkt_type
, PKT_INT
, len
,
2865 PKT_DATA
, password
, len
, PKT_END
);
2868 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
2871 logevent("Sent password");
2872 memset(password
, 0, strlen(password
));
2874 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2875 if (flags
& FLAG_VERBOSE
)
2876 c_write_str("Access denied\r\n");
2877 logevent("Authentication refused");
2878 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2879 logevent("Received disconnect request");
2880 ssh_state
= SSH_STATE_CLOSED
;
2882 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2883 bombout(("Strange packet received, type %d", pktin
.type
));
2888 logevent("Authentication successful");
2893 void sshfwd_close(struct ssh_channel
*c
)
2895 if (c
&& !c
->closes
) {
2897 * If the channel's remoteid is -1, we have sent
2898 * CHANNEL_OPEN for this channel, but it hasn't even been
2899 * acknowledged by the server. So we must set a close flag
2900 * on it now, and then when the server acks the channel
2901 * open, we can close it then.
2903 if (((int)c
->remoteid
) != -1) {
2904 if (ssh_version
== 1) {
2905 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
2908 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2909 ssh2_pkt_adduint32(c
->remoteid
);
2913 c
->closes
= 1; /* sent MSG_CLOSE */
2914 if (c
->type
== CHAN_X11
) {
2916 logevent("Forwarded X11 connection terminated");
2917 } else if (c
->type
== CHAN_SOCKDATA
||
2918 c
->type
== CHAN_SOCKDATA_DORMANT
) {
2920 logevent("Forwarded port closed");
2925 int sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
2927 if (ssh_version
== 1) {
2928 send_packet(SSH1_MSG_CHANNEL_DATA
,
2929 PKT_INT
, c
->remoteid
,
2930 PKT_INT
, len
, PKT_DATA
, buf
, len
, PKT_END
);
2932 * In SSH1 we can return 0 here - implying that forwarded
2933 * connections are never individually throttled - because
2934 * the only circumstance that can cause throttling will be
2935 * the whole SSH connection backing up, in which case
2936 * _everything_ will be throttled as a whole.
2940 ssh2_add_channel_data(c
, buf
, len
);
2941 return ssh2_try_send(c
);
2945 void sshfwd_unthrottle(struct ssh_channel
*c
, int bufsize
)
2947 if (ssh_version
== 1) {
2948 if (c
->v
.v1
.throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
2949 c
->v
.v1
.throttling
= 0;
2953 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
2957 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
)
2963 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
2966 if (ssh_state
== SSH_STATE_CLOSED
)
2969 if (cfg
.agentfwd
&& agent_exists()) {
2970 logevent("Requesting agent forwarding");
2971 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
2975 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2976 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2977 bombout(("Protocol confusion"));
2979 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2980 logevent("Agent forwarding refused");
2982 logevent("Agent forwarding enabled");
2983 ssh_agentfwd_enabled
= TRUE
;
2987 if (cfg
.x11_forward
) {
2988 char proto
[20], data
[64];
2989 logevent("Requesting X11 forwarding");
2990 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
2991 if (ssh1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
2992 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2993 PKT_STR
, proto
, PKT_STR
, data
,
2994 PKT_INT
, 0, PKT_END
);
2996 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2997 PKT_STR
, proto
, PKT_STR
, data
, PKT_END
);
3002 if (pktin
.type
!= SSH1_SMSG_SUCCESS
3003 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
3004 bombout(("Protocol confusion"));
3006 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
3007 logevent("X11 forwarding refused");
3009 logevent("X11 forwarding enabled");
3010 ssh_X11_fwd_enabled
= TRUE
;
3018 int sport
,dport
,sserv
,dserv
;
3019 char sports
[256], dports
[256], host
[256];
3023 ssh_rportfwds
= newtree234(ssh_rportcmp_ssh1
);
3024 /* Add port forwardings. */
3029 while (*e
&& *e
!= '\t')
3035 while (*e
&& *e
!= ':')
3045 dport
= atoi(dports
);
3049 se
= getservbyname(dports
, NULL
);
3051 dport
= ntohs(se
->s_port
);
3054 "Service lookup failed for destination port \"%s\"",
3059 sport
= atoi(sports
);
3063 se
= getservbyname(sports
, NULL
);
3065 sport
= ntohs(se
->s_port
);
3068 "Service lookup failed for source port \"%s\"",
3073 if (sport
&& dport
) {
3075 pfd_addforward(host
, dport
, sport
);
3076 sprintf(buf
, "Local port %.*s%.*s%d%.*s forwarding to"
3077 " %s:%.*s%.*s%d%.*s",
3078 sserv ?
strlen(sports
) : 0, sports
,
3079 sserv
, "(", sport
, sserv
, ")",
3081 dserv ?
strlen(dports
) : 0, dports
,
3082 dserv
, "(", dport
, dserv
, ")");
3085 struct ssh_rportfwd
*pf
;
3086 pf
= smalloc(sizeof(*pf
));
3087 strcpy(pf
->dhost
, host
);
3089 if (add234(ssh_rportfwds
, pf
) != pf
) {
3091 "Duplicate remote port forwarding to %s:%d",
3096 sprintf(buf
, "Requesting remote port %.*s%.*s%d%.*s"
3097 " forward to %s:%.*s%.*s%d%.*s",
3098 sserv ?
strlen(sports
) : 0, sports
,
3099 sserv
, "(", sport
, sserv
, ")",
3101 dserv ?
strlen(dports
) : 0, dports
,
3102 dserv
, "(", dport
, dserv
, ")");
3104 send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST
,
3112 if (pktin
.type
!= SSH1_SMSG_SUCCESS
3113 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
3114 bombout(("Protocol confusion"));
3116 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
3117 c_write_str("Server refused port forwarding\r\n");
3118 ssh_editing
= ssh_echoing
= 1;
3120 logevent("Remote port forwarding enabled");
3128 send_packet(SSH1_CMSG_REQUEST_PTY
,
3129 PKT_STR
, cfg
.termtype
,
3130 PKT_INT
, term ? term
->rows
: 24,
3131 PKT_INT
, term ? term
->cols
: 80,
3132 PKT_INT
, 0, PKT_INT
, 0, PKT_CHAR
, 0, PKT_END
);
3133 ssh_state
= SSH_STATE_INTERMED
;
3137 if (pktin
.type
!= SSH1_SMSG_SUCCESS
3138 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
3139 bombout(("Protocol confusion"));
3141 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
3142 c_write_str("Server refused to allocate pty\r\n");
3143 ssh_editing
= ssh_echoing
= 1;
3145 logevent("Allocated pty");
3147 ssh_editing
= ssh_echoing
= 1;
3150 if (cfg
.compression
) {
3151 send_packet(SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
3155 if (pktin
.type
!= SSH1_SMSG_SUCCESS
3156 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
3157 bombout(("Protocol confusion"));
3159 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
3160 c_write_str("Server refused to compress\r\n");
3162 logevent("Started compression");
3163 ssh1_compressing
= TRUE
;
3164 zlib_compress_init();
3165 zlib_decompress_init();
3169 * Start the shell or command.
3171 * Special case: if the first-choice command is an SSH2
3172 * subsystem (hence not usable here) and the second choice
3173 * exists, we fall straight back to that.
3176 char *cmd
= cfg
.remote_cmd_ptr
;
3178 if (cfg
.ssh_subsys
&& cfg
.remote_cmd_ptr2
) {
3179 cmd
= cfg
.remote_cmd_ptr2
;
3180 ssh_fallback_cmd
= TRUE
;
3183 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
3185 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
3186 logevent("Started session");
3189 ssh_state
= SSH_STATE_SESSION
;
3193 ssh_special(TS_EOF
);
3195 ldisc_send(NULL
, 0, 0); /* cause ldisc to notice changes */
3197 ssh_channels
= newtree234(ssh_channelcmp
);
3201 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
3202 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
3203 long len
= GET_32BIT(pktin
.body
);
3205 from_backend(frontend
, pktin
.type
== SSH1_SMSG_STDERR_DATA
,
3206 pktin
.body
+ 4, len
);
3207 if (!ssh1_stdout_throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
3208 ssh1_stdout_throttling
= 1;
3211 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
3212 ssh_state
= SSH_STATE_CLOSED
;
3213 logevent("Received disconnect request");
3215 } else if (pktin
.type
== SSH1_SMSG_X11_OPEN
) {
3216 /* Remote side is trying to open a channel to talk to our
3217 * X-Server. Give them back a local channel number. */
3218 struct ssh_channel
*c
;
3220 logevent("Received X11 connect request");
3221 /* Refuse if X11 forwarding is disabled. */
3222 if (!ssh_X11_fwd_enabled
) {
3223 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3224 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
3225 logevent("Rejected X11 connect request");
3227 c
= smalloc(sizeof(struct ssh_channel
));
3229 if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
3230 logevent("opening X11 forward connection failed");
3232 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3233 PKT_INT
, GET_32BIT(pktin
.body
),
3237 ("opening X11 forward connection succeeded");
3238 c
->remoteid
= GET_32BIT(pktin
.body
);
3239 c
->localid
= alloc_channel_id();
3241 c
->v
.v1
.throttling
= 0;
3242 c
->type
= CHAN_X11
; /* identify channel type */
3243 add234(ssh_channels
, c
);
3244 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
3245 PKT_INT
, c
->remoteid
, PKT_INT
,
3246 c
->localid
, PKT_END
);
3247 logevent("Opened X11 forward channel");
3250 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
3251 /* Remote side is trying to open a channel to talk to our
3252 * agent. Give them back a local channel number. */
3253 struct ssh_channel
*c
;
3255 /* Refuse if agent forwarding is disabled. */
3256 if (!ssh_agentfwd_enabled
) {
3257 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3258 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
3260 c
= smalloc(sizeof(struct ssh_channel
));
3261 c
->remoteid
= GET_32BIT(pktin
.body
);
3262 c
->localid
= alloc_channel_id();
3264 c
->v
.v1
.throttling
= 0;
3265 c
->type
= CHAN_AGENT
; /* identify channel type */
3266 c
->u
.a
.lensofar
= 0;
3267 add234(ssh_channels
, c
);
3268 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
3269 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
3272 } else if (pktin
.type
== SSH1_MSG_PORT_OPEN
) {
3273 /* Remote side is trying to open a channel to talk to a
3274 * forwarded port. Give them back a local channel number. */
3275 struct ssh_channel
*c
;
3276 struct ssh_rportfwd pf
;
3278 char host
[256], buf
[1024];
3280 c
= smalloc(sizeof(struct ssh_channel
));
3282 hostsize
= GET_32BIT(pktin
.body
+4);
3283 for(h
= host
, p
= pktin
.body
+8; hostsize
!= 0; hostsize
--) {
3284 if (h
+1 < host
+sizeof(host
))
3289 port
= GET_32BIT(p
);
3291 strcpy(pf
.dhost
, host
);
3294 if (find234(ssh_rportfwds
, &pf
, NULL
) == NULL
) {
3295 sprintf(buf
, "Rejected remote port open request for %s:%d",
3298 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3299 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
3301 sprintf(buf
, "Received remote port open request for %s:%d",
3304 e
= pfd_newconnect(&c
->u
.pfd
.s
, host
, port
, c
);
3307 sprintf(buf
, "Port open failed: %s", e
);
3310 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
3311 PKT_INT
, GET_32BIT(pktin
.body
),
3314 c
->remoteid
= GET_32BIT(pktin
.body
);
3315 c
->localid
= alloc_channel_id();
3317 c
->v
.v1
.throttling
= 0;
3318 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
3319 add234(ssh_channels
, c
);
3320 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
3321 PKT_INT
, c
->remoteid
, PKT_INT
,
3322 c
->localid
, PKT_END
);
3323 logevent("Forwarded port opened successfully");
3327 } else if (pktin
.type
== SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
) {
3328 unsigned int remoteid
= GET_32BIT(pktin
.body
);
3329 unsigned int localid
= GET_32BIT(pktin
.body
+4);
3330 struct ssh_channel
*c
;
3332 c
= find234(ssh_channels
, &remoteid
, ssh_channelfind
);
3333 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
3334 c
->remoteid
= localid
;
3335 c
->type
= CHAN_SOCKDATA
;
3336 c
->v
.v1
.throttling
= 0;
3337 pfd_confirm(c
->u
.pfd
.s
);
3340 if (c
&& c
->closes
) {
3342 * We have a pending close on this channel,
3343 * which we decided on before the server acked
3344 * the channel open. So now we know the
3345 * remoteid, we can close it again.
3347 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
3351 } else if (pktin
.type
== SSH1_MSG_CHANNEL_OPEN_FAILURE
) {
3352 unsigned int remoteid
= GET_32BIT(pktin
.body
);
3353 unsigned int localid
= GET_32BIT(pktin
.body
+4);
3354 struct ssh_channel
*c
;
3356 c
= find234(ssh_channels
, &remoteid
, ssh_channelfind
);
3357 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
3358 logevent("Forwarded connection refused by server");
3359 pfd_close(c
->u
.pfd
.s
);
3360 del234(ssh_channels
, c
);
3364 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
3365 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
3366 /* Remote side closes a channel. */
3367 unsigned i
= GET_32BIT(pktin
.body
);
3368 struct ssh_channel
*c
;
3369 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3370 if (c
&& ((int)c
->remoteid
) != -1) {
3373 (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
3375 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
3376 logevent("Forwarded X11 connection terminated");
3377 assert(c
->u
.x11
.s
!= NULL
);
3378 x11_close(c
->u
.x11
.s
);
3381 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
3382 logevent("Forwarded port closed");
3383 assert(c
->u
.pfd
.s
!= NULL
);
3384 pfd_close(c
->u
.pfd
.s
);
3388 c
->closes
|= (closetype
<< 2); /* seen this message */
3389 if (!(c
->closes
& closetype
)) {
3390 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
,
3392 c
->closes
|= closetype
; /* sent it too */
3395 if (c
->closes
== 15) {
3396 del234(ssh_channels
, c
);
3400 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
3401 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
"" :
3402 "_CONFIRMATION", c ?
"half-open" : "nonexistent",
3405 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
3406 /* Data sent down one of our channels. */
3407 int i
= GET_32BIT(pktin
.body
);
3408 int len
= GET_32BIT(pktin
.body
+ 4);
3409 unsigned char *p
= pktin
.body
+ 8;
3410 struct ssh_channel
*c
;
3411 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3416 bufsize
= x11_send(c
->u
.x11
.s
, p
, len
);
3419 bufsize
= pfd_send(c
->u
.pfd
.s
, p
, len
);
3422 /* Data for an agent message. Buffer it. */
3424 if (c
->u
.a
.lensofar
< 4) {
3425 int l
= min(4 - c
->u
.a
.lensofar
, len
);
3426 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
3430 c
->u
.a
.lensofar
+= l
;
3432 if (c
->u
.a
.lensofar
== 4) {
3434 4 + GET_32BIT(c
->u
.a
.msglen
);
3435 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
3436 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
3438 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
3440 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
3442 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
3446 c
->u
.a
.lensofar
+= l
;
3448 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
3449 void *reply
, *sentreply
;
3451 agent_query(c
->u
.a
.message
,
3452 c
->u
.a
.totallen
, &reply
,
3457 /* Fake SSH_AGENT_FAILURE. */
3458 sentreply
= "\0\0\0\1\5";
3461 send_packet(SSH1_MSG_CHANNEL_DATA
,
3462 PKT_INT
, c
->remoteid
,
3464 PKT_DATA
, sentreply
, replylen
,
3468 sfree(c
->u
.a
.message
);
3469 c
->u
.a
.lensofar
= 0;
3472 bufsize
= 0; /* agent channels never back up */
3475 if (!c
->v
.v1
.throttling
&& bufsize
> SSH1_BUFFER_LIMIT
) {
3476 c
->v
.v1
.throttling
= 1;
3480 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
3481 /* may be from EXEC_SHELL on some servers */
3482 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
3483 /* may be from EXEC_SHELL on some servers
3484 * if no pty is available or in other odd cases. Ignore */
3485 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
3487 ssh_exitcode
= GET_32BIT(pktin
.body
);
3488 sprintf(buf
, "Server sent command exit status %d",
3491 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
3493 * In case `helpful' firewalls or proxies tack
3494 * extra human-readable text on the end of the
3495 * session which we might mistake for another
3496 * encrypted packet, we close the session once
3497 * we've sent EXIT_CONFIRMATION.
3499 ssh_state
= SSH_STATE_CLOSED
;
3502 bombout(("Strange packet received: type %d", pktin
.type
));
3507 int len
= min(inlen
, 512);
3508 send_packet(SSH1_CMSG_STDIN_DATA
,
3509 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
3520 * Utility routine for decoding comma-separated strings in KEXINIT.
3522 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
3524 int needlen
= strlen(needle
);
3527 * Is it at the start of the string?
3529 if (haylen
>= needlen
&& /* haystack is long enough */
3530 !memcmp(needle
, haystack
, needlen
) && /* initial match */
3531 (haylen
== needlen
|| haystack
[needlen
] == ',')
3532 /* either , or EOS follows */
3536 * If not, search for the next comma and resume after that.
3537 * If no comma found, terminate.
3539 while (haylen
> 0 && *haystack
!= ',')
3540 haylen
--, haystack
++;
3543 haylen
--, haystack
++; /* skip over comma itself */
3548 * SSH2 key creation method.
3550 static void ssh2_mkkey(Bignum K
, char *H
, char *sessid
, char chr
,
3554 /* First 20 bytes. */
3556 if (!(ssh_remote_bugs
& BUG_SSH2_DERIVEKEY
))
3558 SHA_Bytes(&s
, H
, 20);
3559 SHA_Bytes(&s
, &chr
, 1);
3560 SHA_Bytes(&s
, sessid
, 20);
3561 SHA_Final(&s
, keyspace
);
3562 /* Next 20 bytes. */
3564 if (!(ssh_remote_bugs
& BUG_SSH2_DERIVEKEY
))
3566 SHA_Bytes(&s
, H
, 20);
3567 SHA_Bytes(&s
, keyspace
, 20);
3568 SHA_Final(&s
, keyspace
+ 20);
3572 * Handle the SSH2 transport layer.
3574 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
3576 static int i
, j
, len
, nbits
, pbits
, warn
;
3578 static Bignum p
, g
, e
, f
, K
;
3579 static int kex_init_value
, kex_reply_value
;
3580 static const struct ssh_mac
**maclist
;
3582 static const struct ssh2_cipher
*cscipher_tobe
= NULL
;
3583 static const struct ssh2_cipher
*sccipher_tobe
= NULL
;
3584 static const struct ssh_mac
*csmac_tobe
= NULL
;
3585 static const struct ssh_mac
*scmac_tobe
= NULL
;
3586 static const struct ssh_compress
*cscomp_tobe
= NULL
;
3587 static const struct ssh_compress
*sccomp_tobe
= NULL
;
3588 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
3589 static int hostkeylen
, siglen
;
3590 static void *hkey
; /* actual host key */
3591 static unsigned char exchange_hash
[20];
3592 static unsigned char keyspace
[40];
3593 static int n_preferred_ciphers
;
3594 static const struct ssh2_ciphers
*preferred_ciphers
[CIPHER_MAX
];
3595 static const struct ssh_compress
*preferred_comp
;
3596 static int cipherstr_started
;
3597 static int first_kex
;
3604 * Set up the preferred ciphers. (NULL => warn below here)
3606 n_preferred_ciphers
= 0;
3607 for (i
= 0; i
< CIPHER_MAX
; i
++) {
3608 switch (cfg
.ssh_cipherlist
[i
]) {
3609 case CIPHER_BLOWFISH
:
3610 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_blowfish
;
3611 n_preferred_ciphers
++;
3614 if (cfg
.ssh2_des_cbc
) {
3615 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_des
;
3616 n_preferred_ciphers
++;
3620 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_3des
;
3621 n_preferred_ciphers
++;
3624 preferred_ciphers
[n_preferred_ciphers
] = &ssh2_aes
;
3625 n_preferred_ciphers
++;
3628 /* Flag for later. Don't bother if it's the last in
3630 if (i
< CIPHER_MAX
- 1) {
3631 preferred_ciphers
[n_preferred_ciphers
] = NULL
;
3632 n_preferred_ciphers
++;
3639 * Set up preferred compression.
3641 if (cfg
.compression
)
3642 preferred_comp
= &ssh_zlib
;
3644 preferred_comp
= &ssh_comp_none
;
3647 * Be prepared to work around the buggy MAC problem.
3649 if (ssh_remote_bugs
& BUG_SSH2_HMAC
)
3650 maclist
= buggymacs
, nmacs
= lenof(buggymacs
);
3652 maclist
= macs
, nmacs
= lenof(macs
);
3656 * Construct and send our key exchange packet.
3658 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
3659 for (i
= 0; i
< 16; i
++)
3660 ssh2_pkt_addbyte((unsigned char) random_byte());
3661 /* List key exchange algorithms. */
3662 ssh2_pkt_addstring_start();
3663 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3664 if (kex_algs
[i
] == &ssh_diffiehellman_gex
&&
3665 (ssh_remote_bugs
& BUG_SSH2_DH_GEX
))
3667 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
3668 if (i
< lenof(kex_algs
) - 1)
3669 ssh2_pkt_addstring_str(",");
3671 /* List server host key algorithms. */
3672 ssh2_pkt_addstring_start();
3673 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3674 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
3675 if (i
< lenof(hostkey_algs
) - 1)
3676 ssh2_pkt_addstring_str(",");
3678 /* List client->server encryption algorithms. */
3679 ssh2_pkt_addstring_start();
3680 cipherstr_started
= 0;
3681 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3682 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3683 if (!c
) continue; /* warning flag */
3684 for (j
= 0; j
< c
->nciphers
; j
++) {
3685 if (cipherstr_started
)
3686 ssh2_pkt_addstring_str(",");
3687 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
3688 cipherstr_started
= 1;
3691 /* List server->client encryption algorithms. */
3692 ssh2_pkt_addstring_start();
3693 cipherstr_started
= 0;
3694 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3695 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3696 if (!c
) continue; /* warning flag */
3697 for (j
= 0; j
< c
->nciphers
; j
++) {
3698 if (cipherstr_started
)
3699 ssh2_pkt_addstring_str(",");
3700 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
3701 cipherstr_started
= 1;
3704 /* List client->server MAC algorithms. */
3705 ssh2_pkt_addstring_start();
3706 for (i
= 0; i
< nmacs
; i
++) {
3707 ssh2_pkt_addstring_str(maclist
[i
]->name
);
3709 ssh2_pkt_addstring_str(",");
3711 /* List server->client MAC algorithms. */
3712 ssh2_pkt_addstring_start();
3713 for (i
= 0; i
< nmacs
; i
++) {
3714 ssh2_pkt_addstring_str(maclist
[i
]->name
);
3716 ssh2_pkt_addstring_str(",");
3718 /* List client->server compression algorithms. */
3719 ssh2_pkt_addstring_start();
3720 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3721 const struct ssh_compress
*c
=
3722 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3723 ssh2_pkt_addstring_str(c
->name
);
3724 if (i
< lenof(compressions
))
3725 ssh2_pkt_addstring_str(",");
3727 /* List server->client compression algorithms. */
3728 ssh2_pkt_addstring_start();
3729 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3730 const struct ssh_compress
*c
=
3731 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3732 ssh2_pkt_addstring_str(c
->name
);
3733 if (i
< lenof(compressions
))
3734 ssh2_pkt_addstring_str(",");
3736 /* List client->server languages. Empty list. */
3737 ssh2_pkt_addstring_start();
3738 /* List server->client languages. Empty list. */
3739 ssh2_pkt_addstring_start();
3740 /* First KEX packet does _not_ follow, because we're not that brave. */
3741 ssh2_pkt_addbool(FALSE
);
3743 ssh2_pkt_adduint32(0);
3745 exhash
= exhashbase
;
3746 sha_string(&exhash
, pktout
.data
+ 5, pktout
.length
- 5);
3752 sha_string(&exhash
, pktin
.data
+ 5, pktin
.length
- 5);
3755 * Now examine the other side's KEXINIT to see what we're up
3758 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
3759 bombout(("expected key exchange packet from server"));
3764 cscipher_tobe
= NULL
;
3765 sccipher_tobe
= NULL
;
3770 pktin
.savedpos
+= 16; /* skip garbage cookie */
3771 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
3772 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3773 if (kex_algs
[i
] == &ssh_diffiehellman_gex
&&
3774 (ssh_remote_bugs
& BUG_SSH2_DH_GEX
))
3776 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
3781 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
3782 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3783 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
3784 hostkey
= hostkey_algs
[i
];
3788 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
3790 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3791 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3795 for (j
= 0; j
< c
->nciphers
; j
++) {
3796 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3797 cscipher_tobe
= c
->list
[j
];
3802 if (cscipher_tobe
) {
3804 askcipher(cscipher_tobe
->name
, 1);
3808 if (!cscipher_tobe
) {
3809 bombout(("Couldn't agree a client-to-server cipher (available: %s)", str
));
3813 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
3815 for (i
= 0; i
< n_preferred_ciphers
; i
++) {
3816 const struct ssh2_ciphers
*c
= preferred_ciphers
[i
];
3820 for (j
= 0; j
< c
->nciphers
; j
++) {
3821 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3822 sccipher_tobe
= c
->list
[j
];
3827 if (sccipher_tobe
) {
3829 askcipher(sccipher_tobe
->name
, 2);
3833 if (!sccipher_tobe
) {
3834 bombout(("Couldn't agree a server-to-client cipher (available: %s)", str
));
3838 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
3839 for (i
= 0; i
< nmacs
; i
++) {
3840 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3841 csmac_tobe
= maclist
[i
];
3845 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
3846 for (i
= 0; i
< nmacs
; i
++) {
3847 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3848 scmac_tobe
= maclist
[i
];
3852 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
3853 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3854 const struct ssh_compress
*c
=
3855 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3856 if (in_commasep_string(c
->name
, str
, len
)) {
3861 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
3862 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3863 const struct ssh_compress
*c
=
3864 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3865 if (in_commasep_string(c
->name
, str
, len
)) {
3872 * Work out the number of bits of key we will need from the key
3873 * exchange. We start with the maximum key length of either
3879 csbits
= cscipher_tobe
->keylen
;
3880 scbits
= sccipher_tobe
->keylen
;
3881 nbits
= (csbits
> scbits ? csbits
: scbits
);
3883 /* The keys only have 160-bit entropy, since they're based on
3884 * a SHA-1 hash. So cap the key size at 160 bits. */
3889 * If we're doing Diffie-Hellman group exchange, start by
3890 * requesting a group.
3892 if (kex
== &ssh_diffiehellman_gex
) {
3893 logevent("Doing Diffie-Hellman group exchange");
3894 ssh_pkt_ctx
|= SSH2_PKTCTX_DHGEX
;
3896 * Work out how big a DH group we will need to allow that
3899 pbits
= 512 << ((nbits
- 1) / 64);
3900 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
3901 ssh2_pkt_adduint32(pbits
);
3905 if (pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
3906 bombout(("expected key exchange group packet from server"));
3909 p
= ssh2_pkt_getmp();
3910 g
= ssh2_pkt_getmp();
3911 dh_setup_group(p
, g
);
3912 kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
3913 kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
3915 ssh_pkt_ctx
|= SSH2_PKTCTX_DHGROUP1
;
3917 kex_init_value
= SSH2_MSG_KEXDH_INIT
;
3918 kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
3921 logevent("Doing Diffie-Hellman key exchange");
3923 * Now generate and send e for Diffie-Hellman.
3925 e
= dh_create_e(nbits
* 2);
3926 ssh2_pkt_init(kex_init_value
);
3931 if (pktin
.type
!= kex_reply_value
) {
3932 bombout(("expected key exchange reply packet from server"));
3935 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
3936 f
= ssh2_pkt_getmp();
3937 ssh2_pkt_getstring(&sigdata
, &siglen
);
3941 sha_string(&exhash
, hostkeydata
, hostkeylen
);
3942 if (kex
== &ssh_diffiehellman_gex
) {
3943 sha_uint32(&exhash
, pbits
);
3944 sha_mpint(&exhash
, p
);
3945 sha_mpint(&exhash
, g
);
3947 sha_mpint(&exhash
, e
);
3948 sha_mpint(&exhash
, f
);
3949 sha_mpint(&exhash
, K
);
3950 SHA_Final(&exhash
, exchange_hash
);
3955 debug(("Exchange hash is:\n"));
3956 dmemdump(exchange_hash
, 20);
3959 hkey
= hostkey
->newkey(hostkeydata
, hostkeylen
);
3961 !hostkey
->verifysig(hkey
, sigdata
, siglen
, exchange_hash
, 20)) {
3962 bombout(("Server's host key did not match the signature supplied"));
3967 * Authenticate remote host: verify host key. (We've already
3968 * checked the signature of the exchange hash.)
3970 keystr
= hostkey
->fmtkey(hkey
);
3971 fingerprint
= hostkey
->fingerprint(hkey
);
3972 verify_ssh_host_key(savedhost
, savedport
, hostkey
->keytype
,
3973 keystr
, fingerprint
);
3974 if (first_kex
) { /* don't bother logging this in rekeys */
3975 logevent("Host key fingerprint is:");
3976 logevent(fingerprint
);
3980 hostkey
->freekey(hkey
);
3983 * Send SSH2_MSG_NEWKEYS.
3985 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
3989 * Expect SSH2_MSG_NEWKEYS from server.
3992 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
3993 bombout(("expected new-keys packet from server"));
3998 * Create and initialise session keys.
4000 cscipher
= cscipher_tobe
;
4001 sccipher
= sccipher_tobe
;
4004 cscomp
= cscomp_tobe
;
4005 sccomp
= sccomp_tobe
;
4006 cscomp
->compress_init();
4007 sccomp
->decompress_init();
4009 * Set IVs after keys. Here we use the exchange hash from the
4010 * _first_ key exchange.
4013 memcpy(ssh2_session_id
, exchange_hash
, sizeof(exchange_hash
));
4014 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'C', keyspace
);
4015 cscipher
->setcskey(keyspace
);
4016 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'D', keyspace
);
4017 sccipher
->setsckey(keyspace
);
4018 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'A', keyspace
);
4019 cscipher
->setcsiv(keyspace
);
4020 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'B', keyspace
);
4021 sccipher
->setsciv(keyspace
);
4022 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'E', keyspace
);
4023 csmac
->setcskey(keyspace
);
4024 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'F', keyspace
);
4025 scmac
->setsckey(keyspace
);
4028 * If this is the first key exchange phase, we must pass the
4029 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
4030 * wants to see it but because it will need time to initialise
4031 * itself before it sees an actual packet. In subsequent key
4032 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
4033 * it would only confuse the layer above.
4041 * Now we're encrypting. Begin returning 1 to the protocol main
4042 * function so that other things can run on top of the
4043 * transport. If we ever see a KEXINIT, we must go back to the
4046 while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
)) {
4049 logevent("Server initiated key re-exchange");
4050 goto begin_key_exchange
;
4056 * Add data to an SSH2 channel output buffer.
4058 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
4061 bufchain_add(&c
->v
.v2
.outbuffer
, buf
, len
);
4065 * Attempt to send data on an SSH2 channel.
4067 static int ssh2_try_send(struct ssh_channel
*c
)
4069 while (c
->v
.v2
.remwindow
> 0 && bufchain_size(&c
->v
.v2
.outbuffer
) > 0) {
4072 bufchain_prefix(&c
->v
.v2
.outbuffer
, &data
, &len
);
4073 if ((unsigned)len
> c
->v
.v2
.remwindow
)
4074 len
= c
->v
.v2
.remwindow
;
4075 if ((unsigned)len
> c
->v
.v2
.remmaxpkt
)
4076 len
= c
->v
.v2
.remmaxpkt
;
4077 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
4078 ssh2_pkt_adduint32(c
->remoteid
);
4079 ssh2_pkt_addstring_start();
4080 ssh2_pkt_addstring_data(data
, len
);
4082 bufchain_consume(&c
->v
.v2
.outbuffer
, len
);
4083 c
->v
.v2
.remwindow
-= len
;
4087 * After having sent as much data as we can, return the amount
4090 return bufchain_size(&c
->v
.v2
.outbuffer
);
4094 * Potentially enlarge the window on an SSH2 channel.
4096 static void ssh2_set_window(struct ssh_channel
*c
, unsigned newwin
)
4099 * Never send WINDOW_ADJUST for a channel that the remote side
4100 * already thinks it's closed; there's no point, since it won't
4101 * be sending any more data anyway.
4106 if (newwin
> c
->v
.v2
.locwindow
) {
4107 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4108 ssh2_pkt_adduint32(c
->remoteid
);
4109 ssh2_pkt_adduint32(newwin
- c
->v
.v2
.locwindow
);
4111 c
->v
.v2
.locwindow
= newwin
;
4116 * Handle the SSH2 userauth and connection layers.
4118 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
4121 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
,
4123 AUTH_KEYBOARD_INTERACTIVE
4127 AUTH_TYPE_PUBLICKEY
,
4128 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
4129 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
4131 AUTH_TYPE_KEYBOARD_INTERACTIVE
,
4132 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
4134 static int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
4135 static int tried_pubkey_config
, tried_agent
, tried_keyb_inter
;
4136 static int kbd_inter_running
;
4137 static int we_are_in
;
4138 static int num_prompts
, curr_prompt
, echo
;
4139 static char username
[100];
4140 static int got_username
;
4141 static char pwprompt
[200];
4142 static char password
[100];
4143 static void *publickey_blob
;
4144 static int publickey_bloblen
;
4149 * Request userauth protocol, and await a response to it.
4151 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
4152 ssh2_pkt_addstring("ssh-userauth");
4154 crWaitUntilV(ispkt
);
4155 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
4156 bombout(("Server refused user authentication protocol"));
4161 * We repeat this whole loop, including the username prompt,
4162 * until we manage a successful authentication. If the user
4163 * types the wrong _password_, they are sent back to the
4164 * beginning to try another username. (If they specify a
4165 * username in the config, they are never asked, even if they
4166 * do give a wrong password.)
4168 * I think this best serves the needs of
4170 * - the people who have no configuration, no keys, and just
4171 * want to try repeated (username,password) pairs until they
4172 * type both correctly
4174 * - people who have keys and configuration but occasionally
4175 * need to fall back to passwords
4177 * - people with a key held in Pageant, who might not have
4178 * logged in to a particular machine before; so they want to
4179 * type a username, and then _either_ their key will be
4180 * accepted, _or_ they will type a password. If they mistype
4181 * the username they will want to be able to get back and
4185 got_username
= FALSE
;
4190 if (got_username
&& !cfg
.change_username
) {
4192 * We got a username last time round this loop, and
4193 * with change_username turned off we don't try to get
4196 } else if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
4197 if (ssh_get_line
&& !ssh_getline_pw_only
) {
4198 if (!ssh_get_line("login as: ",
4199 username
, sizeof(username
), FALSE
)) {
4201 * get_line failed to get a username.
4204 logevent("No username provided. Abandoning session.");
4205 ssh_state
= SSH_STATE_CLOSED
;
4210 c_write_str("login as: ");
4212 setup_userpass_input(username
, sizeof(username
), 1);
4214 crWaitUntilV(!ispkt
);
4215 ret
= process_userpass_input(in
, inlen
);
4220 c_write_str("\r\n");
4221 username
[strcspn(username
, "\n\r")] = '\0';
4224 strncpy(username
, cfg
.username
, sizeof(username
));
4225 username
[sizeof(username
)-1] = '\0';
4226 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
4227 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
4231 got_username
= TRUE
;
4234 * Send an authentication request using method "none": (a)
4235 * just in case it succeeds, and (b) so that we know what
4236 * authentication methods we can usefully try next.
4238 ssh_pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4240 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4241 ssh2_pkt_addstring(username
);
4242 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4243 ssh2_pkt_addstring("none"); /* method */
4245 type
= AUTH_TYPE_NONE
;
4249 tried_pubkey_config
= FALSE
;
4250 tried_agent
= FALSE
;
4251 tried_keyb_inter
= FALSE
;
4252 kbd_inter_running
= FALSE
;
4253 /* Load the pub half of cfg.keyfile so we notice if it's in Pageant */
4256 logeventf("Reading private key file \"%.150s\"", cfg
.keyfile
);
4257 keytype
= key_type(cfg
.keyfile
);
4258 if (keytype
== SSH_KEYTYPE_SSH2
)
4259 publickey_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, NULL
,
4260 &publickey_bloblen
);
4263 logeventf("Unable to use this key file (%s)",
4264 key_type_to_str(keytype
));
4265 sprintf(msgbuf
, "Unable to use key file \"%.150s\" (%s)\r\n",
4266 cfg
.keyfile
, key_type_to_str(keytype
));
4267 c_write_str(msgbuf
);
4268 publickey_blob
= NULL
;
4271 publickey_blob
= NULL
;
4275 * Wait for the result of the last authentication request.
4278 crWaitUntilV(ispkt
);
4279 while (pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
4283 * Don't show the banner if we're operating in
4284 * non-verbose non-interactive mode. (It's probably
4285 * a script, which means nobody will read the
4286 * banner _anyway_, and moreover the printing of
4287 * the banner will screw up processing on the
4288 * output of (say) plink.)
4290 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
4291 ssh2_pkt_getstring(&banner
, &size
);
4293 c_write_untrusted(banner
, size
);
4295 crWaitUntilV(ispkt
);
4297 if (pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
4298 logevent("Access granted");
4303 if (kbd_inter_running
&&
4304 pktin
.type
== SSH2_MSG_USERAUTH_INFO_REQUEST
) {
4306 * This is either a further set-of-prompts packet
4307 * in keyboard-interactive authentication, or it's
4308 * the same one and we came back here with `gotit'
4309 * set. In the former case, we must reset the
4310 * curr_prompt variable.
4314 } else if (pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
4315 bombout(("Strange packet received during authentication: type %d",
4323 * OK, we're now sitting on a USERAUTH_FAILURE message, so
4324 * we can look at the string in it and know what we can
4325 * helpfully try next.
4327 if (pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
) {
4330 ssh2_pkt_getstring(&methods
, &methlen
);
4331 kbd_inter_running
= FALSE
;
4332 if (!ssh2_pkt_getbool()) {
4334 * We have received an unequivocal Access
4335 * Denied. This can translate to a variety of
4338 * - if we'd just tried "none" authentication,
4339 * it's not worth printing anything at all
4341 * - if we'd just tried a public key _offer_,
4342 * the message should be "Server refused our
4343 * key" (or no message at all if the key
4344 * came from Pageant)
4346 * - if we'd just tried anything else, the
4347 * message really should be "Access denied".
4349 * Additionally, if we'd just tried password
4350 * authentication, we should break out of this
4351 * whole loop so as to go back to the username
4354 if (type
== AUTH_TYPE_NONE
) {
4356 } else if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
4357 type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
4358 if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
4359 c_write_str("Server refused our key\r\n");
4360 logevent("Server refused public key");
4361 } else if (type
== AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
) {
4362 /* server declined keyboard-interactive; ignore */
4364 c_write_str("Access denied\r\n");
4365 logevent("Access denied");
4366 if (type
== AUTH_TYPE_PASSWORD
) {
4372 c_write_str("Further authentication required\r\n");
4373 logevent("Further authentication required");
4377 in_commasep_string("publickey", methods
, methlen
);
4379 in_commasep_string("password", methods
, methlen
);
4380 can_keyb_inter
= cfg
.try_ki_auth
&&
4381 in_commasep_string("keyboard-interactive", methods
, methlen
);
4385 ssh_pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4388 * Most password/passphrase prompts will be
4389 * non-echoing, so we set this to 0 by default.
4390 * Exception is that some keyboard-interactive prompts
4391 * can be echoing, in which case we'll set this to 1.
4395 if (!method
&& can_pubkey
&& agent_exists() && !tried_agent
) {
4397 * Attempt public-key authentication using Pageant.
4399 static unsigned char request
[5], *response
, *p
;
4400 static int responselen
;
4401 static int i
, nkeys
;
4402 static int authed
= FALSE
;
4405 ssh_pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4406 ssh_pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
4410 logevent("Pageant is running. Requesting keys.");
4412 /* Request the keys held by the agent. */
4413 PUT_32BIT(request
, 1);
4414 request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
4415 agent_query(request
, 5, &r
, &responselen
);
4416 response
= (unsigned char *) r
;
4417 if (response
&& responselen
>= 5 &&
4418 response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
4420 nkeys
= GET_32BIT(p
);
4424 sprintf(buf
, "Pageant has %d SSH2 keys", nkeys
);
4427 for (i
= 0; i
< nkeys
; i
++) {
4428 static char *pkblob
, *alg
, *commentp
;
4429 static int pklen
, alglen
, commentlen
;
4430 static int siglen
, retlen
, len
;
4431 static char *q
, *agentreq
, *ret
;
4436 sprintf(buf
, "Trying Pageant key #%d", i
);
4439 pklen
= GET_32BIT(p
);
4441 if (publickey_blob
&&
4442 pklen
== publickey_bloblen
&&
4443 !memcmp(p
, publickey_blob
, publickey_bloblen
)) {
4444 logevent("This key matches configured key file");
4445 tried_pubkey_config
= 1;
4449 alglen
= GET_32BIT(pkblob
);
4451 commentlen
= GET_32BIT(p
);
4455 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4456 ssh2_pkt_addstring(username
);
4457 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4458 ssh2_pkt_addstring("publickey"); /* method */
4459 ssh2_pkt_addbool(FALSE
); /* no signature included */
4460 ssh2_pkt_addstring_start();
4461 ssh2_pkt_addstring_data(alg
, alglen
);
4462 ssh2_pkt_addstring_start();
4463 ssh2_pkt_addstring_data(pkblob
, pklen
);
4466 crWaitUntilV(ispkt
);
4467 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
4468 logevent("Key refused");
4472 if (flags
& FLAG_VERBOSE
) {
4474 ("Authenticating with public key \"");
4475 c_write(commentp
, commentlen
);
4476 c_write_str("\" from agent\r\n");
4480 * Server is willing to accept the key.
4481 * Construct a SIGN_REQUEST.
4483 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4484 ssh2_pkt_addstring(username
);
4485 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4486 ssh2_pkt_addstring("publickey"); /* method */
4487 ssh2_pkt_addbool(TRUE
);
4488 ssh2_pkt_addstring_start();
4489 ssh2_pkt_addstring_data(alg
, alglen
);
4490 ssh2_pkt_addstring_start();
4491 ssh2_pkt_addstring_data(pkblob
, pklen
);
4493 siglen
= pktout
.length
- 5 + 4 + 20;
4494 len
= 1; /* message type */
4495 len
+= 4 + pklen
; /* key blob */
4496 len
+= 4 + siglen
; /* data to sign */
4497 len
+= 4; /* flags */
4498 agentreq
= smalloc(4 + len
);
4499 PUT_32BIT(agentreq
, len
);
4501 *q
++ = SSH2_AGENTC_SIGN_REQUEST
;
4502 PUT_32BIT(q
, pklen
);
4504 memcpy(q
, pkblob
, pklen
);
4506 PUT_32BIT(q
, siglen
);
4508 /* Now the data to be signed... */
4511 memcpy(q
, ssh2_session_id
, 20);
4513 memcpy(q
, pktout
.data
+ 5, pktout
.length
- 5);
4514 q
+= pktout
.length
- 5;
4515 /* And finally the (zero) flags word. */
4517 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
4521 if (ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
4522 logevent("Sending Pageant's response");
4523 ssh2_add_sigblob(pkblob
, pklen
,
4524 ret
+ 9, GET_32BIT(ret
+ 5));
4530 ("Pageant failed to answer challenge");
4540 if (!method
&& can_pubkey
&& publickey_blob
4541 && !tried_pubkey_config
) {
4542 unsigned char *pub_blob
;
4543 char *algorithm
, *comment
;
4546 tried_pubkey_config
= TRUE
;
4548 ssh_pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4549 ssh_pkt_ctx
|= SSH2_PKTCTX_PUBLICKEY
;
4552 * Try the public key supplied in the configuration.
4554 * First, offer the public blob to see if the server is
4555 * willing to accept it.
4557 pub_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, &algorithm
,
4560 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4561 ssh2_pkt_addstring(username
);
4562 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4563 ssh2_pkt_addstring("publickey"); /* method */
4564 ssh2_pkt_addbool(FALSE
); /* no signature included */
4565 ssh2_pkt_addstring(algorithm
);
4566 ssh2_pkt_addstring_start();
4567 ssh2_pkt_addstring_data(pub_blob
, pub_blob_len
);
4569 logevent("Offered public key"); /* FIXME */
4571 crWaitUntilV(ispkt
);
4572 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
4574 type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
4575 continue; /* key refused; give up on it */
4578 logevent("Offer of public key accepted");
4580 * Actually attempt a serious authentication using
4583 if (ssh2_userkey_encrypted(cfg
.keyfile
, &comment
)) {
4585 "Passphrase for key \"%.100s\": ",
4591 c_write_str("Authenticating with public key \"");
4592 c_write_str(comment
);
4593 c_write_str("\"\r\n");
4594 method
= AUTH_PUBLICKEY_FILE
;
4598 if (!method
&& can_keyb_inter
&& !tried_keyb_inter
) {
4599 method
= AUTH_KEYBOARD_INTERACTIVE
;
4600 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4601 tried_keyb_inter
= TRUE
;
4603 ssh_pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4604 ssh_pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
4606 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4607 ssh2_pkt_addstring(username
);
4608 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4609 ssh2_pkt_addstring("keyboard-interactive"); /* method */
4610 ssh2_pkt_addstring(""); /* lang */
4611 ssh2_pkt_addstring("");
4614 crWaitUntilV(ispkt
);
4615 if (pktin
.type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
4616 if (pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
)
4618 logevent("Keyboard-interactive authentication refused");
4619 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
;
4623 kbd_inter_running
= TRUE
;
4627 if (kbd_inter_running
) {
4628 method
= AUTH_KEYBOARD_INTERACTIVE
;
4629 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4630 tried_keyb_inter
= TRUE
;
4632 ssh_pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4633 ssh_pkt_ctx
|= SSH2_PKTCTX_KBDINTER
;
4635 if (curr_prompt
== 0) {
4637 * We've got a fresh USERAUTH_INFO_REQUEST.
4638 * Display header data, and start going through
4641 char *name
, *inst
, *lang
;
4642 int name_len
, inst_len
, lang_len
;
4644 ssh2_pkt_getstring(&name
, &name_len
);
4645 ssh2_pkt_getstring(&inst
, &inst_len
);
4646 ssh2_pkt_getstring(&lang
, &lang_len
);
4648 c_write_untrusted(name
, name_len
);
4649 c_write_str("\r\n");
4652 c_write_untrusted(inst
, inst_len
);
4653 c_write_str("\r\n");
4655 num_prompts
= ssh2_pkt_getuint32();
4659 * If there are prompts remaining in the packet,
4660 * display one and get a response.
4662 if (curr_prompt
< num_prompts
) {
4666 ssh2_pkt_getstring(&prompt
, &prompt_len
);
4667 if (prompt_len
> 0) {
4668 strncpy(pwprompt
, prompt
, sizeof(pwprompt
));
4669 pwprompt
[prompt_len
< sizeof(pwprompt
) ?
4670 prompt_len
: sizeof(pwprompt
)-1] = '\0';
4673 "<server failed to send prompt>: ");
4675 echo
= ssh2_pkt_getbool();
4681 if (!method
&& can_passwd
) {
4682 method
= AUTH_PASSWORD
;
4683 ssh_pkt_ctx
&= ~SSH2_PKTCTX_AUTH_MASK
;
4684 ssh_pkt_ctx
|= SSH2_PKTCTX_PASSWORD
;
4685 sprintf(pwprompt
, "%.90s@%.90s's password: ", username
,
4692 if (!ssh_get_line(pwprompt
, password
,
4693 sizeof(password
), TRUE
)) {
4695 * get_line failed to get a password (for
4696 * example because one was supplied on the
4697 * command line which has already failed to
4700 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4701 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4703 ("No more passwords available to try");
4704 ssh2_pkt_addstring("en"); /* language tag */
4706 logevent("Unable to authenticate");
4707 connection_fatal("Unable to authenticate");
4708 ssh_state
= SSH_STATE_CLOSED
;
4713 c_write_untrusted(pwprompt
, strlen(pwprompt
));
4716 setup_userpass_input(password
, sizeof(password
), echo
);
4718 crWaitUntilV(!ispkt
);
4719 ret
= process_userpass_input(in
, inlen
);
4723 c_write_str("\r\n");
4727 if (method
== AUTH_PUBLICKEY_FILE
) {
4729 * We have our passphrase. Now try the actual authentication.
4731 struct ssh2_userkey
*key
;
4733 key
= ssh2_load_userkey(cfg
.keyfile
, password
);
4734 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
4735 if (key
== SSH2_WRONG_PASSPHRASE
) {
4736 c_write_str("Wrong passphrase\r\n");
4737 tried_pubkey_config
= FALSE
;
4739 c_write_str("Unable to load private key\r\n");
4740 tried_pubkey_config
= TRUE
;
4742 /* Send a spurious AUTH_NONE to return to the top. */
4743 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4744 ssh2_pkt_addstring(username
);
4745 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4746 ssh2_pkt_addstring("none"); /* method */
4748 type
= AUTH_TYPE_NONE
;
4750 unsigned char *pkblob
, *sigblob
, *sigdata
;
4751 int pkblob_len
, sigblob_len
, sigdata_len
;
4754 * We have loaded the private key and the server
4755 * has announced that it's willing to accept it.
4756 * Hallelujah. Generate a signature and send it.
4758 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4759 ssh2_pkt_addstring(username
);
4760 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4761 ssh2_pkt_addstring("publickey"); /* method */
4762 ssh2_pkt_addbool(TRUE
);
4763 ssh2_pkt_addstring(key
->alg
->name
);
4764 pkblob
= key
->alg
->public_blob(key
->data
, &pkblob_len
);
4765 ssh2_pkt_addstring_start();
4766 ssh2_pkt_addstring_data(pkblob
, pkblob_len
);
4769 * The data to be signed is:
4773 * followed by everything so far placed in the
4776 sigdata_len
= pktout
.length
- 5 + 4 + 20;
4777 sigdata
= smalloc(sigdata_len
);
4778 PUT_32BIT(sigdata
, 20);
4779 memcpy(sigdata
+ 4, ssh2_session_id
, 20);
4780 memcpy(sigdata
+ 24, pktout
.data
+ 5,
4782 sigblob
= key
->alg
->sign(key
->data
, sigdata
,
4783 sigdata_len
, &sigblob_len
);
4784 ssh2_add_sigblob(pkblob
, pkblob_len
,
4785 sigblob
, sigblob_len
);
4791 type
= AUTH_TYPE_PUBLICKEY
;
4793 } else if (method
== AUTH_PASSWORD
) {
4795 * We send the password packet lumped tightly together with
4796 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4797 * string long enough to make the total length of the two
4798 * packets constant. This should ensure that a passive
4799 * listener doing traffic analyis can't work out the length
4802 * For this to work, we need an assumption about the
4803 * maximum length of the password packet. I think 256 is
4804 * pretty conservative. Anyone using a password longer than
4805 * that probably doesn't have much to worry about from
4806 * people who find out how long their password is!
4808 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
4809 ssh2_pkt_addstring(username
);
4810 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4811 ssh2_pkt_addstring("password");
4812 ssh2_pkt_addbool(FALSE
);
4813 ssh2_pkt_addstring(password
);
4816 * We'll include a string that's an exact multiple of the
4817 * cipher block size. If the cipher is NULL for some
4818 * reason, we don't do this trick at all because we gain
4824 stringlen
= (256 - deferred_len
);
4825 stringlen
+= cscipher
->blksize
- 1;
4826 stringlen
-= (stringlen
% cscipher
->blksize
);
4829 * Temporarily disable actual compression,
4830 * so we can guarantee to get this string
4831 * exactly the length we want it. The
4832 * compression-disabling routine should
4833 * return an integer indicating how many
4834 * bytes we should adjust our string length
4837 stringlen
-= cscomp
->disable_compression();
4839 ssh2_pkt_init(SSH2_MSG_IGNORE
);
4840 ssh2_pkt_addstring_start();
4841 for (i
= 0; i
< stringlen
; i
++) {
4842 char c
= (char) random_byte();
4843 ssh2_pkt_addstring_data(&c
, 1);
4847 ssh_pkt_defersend();
4848 logevent("Sent password");
4849 type
= AUTH_TYPE_PASSWORD
;
4850 } else if (method
== AUTH_KEYBOARD_INTERACTIVE
) {
4851 if (curr_prompt
== 0) {
4852 ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE
);
4853 ssh2_pkt_adduint32(num_prompts
);
4855 if (need_pw
) { /* only add pw if we just got one! */
4856 ssh2_pkt_addstring(password
);
4857 memset(password
, 0, sizeof(password
));
4860 if (curr_prompt
>= num_prompts
) {
4864 * If there are prompts remaining, we set
4865 * `gotit' so that we won't attempt to get
4866 * another packet. Then we go back round the
4867 * loop and will end up retrieving another
4868 * prompt out of the existing packet. Funky or
4873 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4876 ("No supported authentication methods left to try!\r\n");
4878 ("No supported authentications offered. Disconnecting");
4879 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4880 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4882 ("No supported authentication methods available");
4883 ssh2_pkt_addstring("en"); /* language tag */
4885 ssh_state
= SSH_STATE_CLOSED
;
4889 } while (!we_are_in
);
4892 * Now we're authenticated for the connection protocol. The
4893 * connection protocol will automatically have started at this
4894 * point; there's no need to send SERVICE_REQUEST.
4898 * So now create a channel with a session in it.
4900 ssh_channels
= newtree234(ssh_channelcmp
);
4901 mainchan
= smalloc(sizeof(struct ssh_channel
));
4902 mainchan
->localid
= alloc_channel_id();
4903 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
4904 ssh2_pkt_addstring("session");
4905 ssh2_pkt_adduint32(mainchan
->localid
);
4906 mainchan
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
4907 ssh2_pkt_adduint32(mainchan
->v
.v2
.locwindow
); /* our window size */
4908 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
4910 crWaitUntilV(ispkt
);
4911 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
4912 bombout(("Server refused to open a session"));
4914 /* FIXME: error data comes back in FAILURE packet */
4916 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
4917 bombout(("Server's channel confirmation cited wrong channel"));
4920 mainchan
->remoteid
= ssh2_pkt_getuint32();
4921 mainchan
->type
= CHAN_MAINSESSION
;
4922 mainchan
->closes
= 0;
4923 mainchan
->v
.v2
.remwindow
= ssh2_pkt_getuint32();
4924 mainchan
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
4925 bufchain_init(&mainchan
->v
.v2
.outbuffer
);
4926 add234(ssh_channels
, mainchan
);
4927 logevent("Opened channel for session");
4930 * Potentially enable X11 forwarding.
4932 if (cfg
.x11_forward
) {
4933 char proto
[20], data
[64];
4934 logevent("Requesting X11 forwarding");
4935 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
4936 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4937 ssh2_pkt_adduint32(mainchan
->remoteid
);
4938 ssh2_pkt_addstring("x11-req");
4939 ssh2_pkt_addbool(1); /* want reply */
4940 ssh2_pkt_addbool(0); /* many connections */
4941 ssh2_pkt_addstring(proto
);
4942 ssh2_pkt_addstring(data
);
4943 ssh2_pkt_adduint32(0); /* screen number */
4947 crWaitUntilV(ispkt
);
4948 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4949 unsigned i
= ssh2_pkt_getuint32();
4950 struct ssh_channel
*c
;
4951 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4953 continue; /* nonexistent channel */
4954 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
4956 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4958 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4959 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4960 bombout(("Unexpected response to X11 forwarding request:"
4961 " packet type %d", pktin
.type
));
4964 logevent("X11 forwarding refused");
4966 logevent("X11 forwarding enabled");
4967 ssh_X11_fwd_enabled
= TRUE
;
4972 * Enable port forwardings.
4975 static char *e
; /* preserve across crReturn */
4978 int sport
,dport
,sserv
,dserv
;
4979 char sports
[256], dports
[256], host
[256];
4983 ssh_rportfwds
= newtree234(ssh_rportcmp_ssh2
);
4984 /* Add port forwardings. */
4989 while (*e
&& *e
!= '\t')
4995 while (*e
&& *e
!= ':')
5005 dport
= atoi(dports
);
5009 se
= getservbyname(dports
, NULL
);
5011 dport
= ntohs(se
->s_port
);
5014 "Service lookup failed for destination port \"%s\"",
5019 sport
= atoi(sports
);
5023 se
= getservbyname(sports
, NULL
);
5025 sport
= ntohs(se
->s_port
);
5028 "Service lookup failed for source port \"%s\"",
5033 if (sport
&& dport
) {
5035 pfd_addforward(host
, dport
, sport
);
5036 sprintf(buf
, "Local port %.*s%.*s%d%.*s forwarding to"
5037 " %s:%.*s%.*s%d%.*s",
5038 sserv ?
strlen(sports
) : 0, sports
,
5039 sserv
, "(", sport
, sserv
, ")",
5041 dserv ?
strlen(dports
) : 0, dports
,
5042 dserv
, "(", dport
, dserv
, ")");
5045 struct ssh_rportfwd
*pf
;
5046 pf
= smalloc(sizeof(*pf
));
5047 strcpy(pf
->dhost
, host
);
5050 if (add234(ssh_rportfwds
, pf
) != pf
) {
5052 "Duplicate remote port forwarding to %s:%d",
5057 sprintf(buf
, "Requesting remote port %.*s%.*s%d%.*s"
5058 " forward to %s:%.*s%.*s%d%.*s",
5059 sserv ?
strlen(sports
) : 0, sports
,
5060 sserv
, "(", sport
, sserv
, ")",
5062 dserv ?
strlen(dports
) : 0, dports
,
5063 dserv
, "(", dport
, dserv
, ")");
5065 ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
5066 ssh2_pkt_addstring("tcpip-forward");
5067 ssh2_pkt_addbool(1);/* want reply */
5068 if (cfg
.rport_acceptall
)
5069 ssh2_pkt_addstring("0.0.0.0");
5071 ssh2_pkt_addstring("127.0.0.1");
5072 ssh2_pkt_adduint32(sport
);
5076 crWaitUntilV(ispkt
);
5077 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
5078 unsigned i
= ssh2_pkt_getuint32();
5079 struct ssh_channel
*c
;
5080 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5082 continue;/* nonexistent channel */
5083 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
5085 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
5087 if (pktin
.type
!= SSH2_MSG_REQUEST_SUCCESS
) {
5088 if (pktin
.type
!= SSH2_MSG_REQUEST_FAILURE
) {
5089 bombout(("Unexpected response to port "
5090 "forwarding request: packet type %d",
5094 logevent("Server refused this port forwarding");
5096 logevent("Remote port forwarding enabled");
5105 * Potentially enable agent forwarding.
5107 if (cfg
.agentfwd
&& agent_exists()) {
5108 logevent("Requesting OpenSSH-style agent forwarding");
5109 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
5110 ssh2_pkt_adduint32(mainchan
->remoteid
);
5111 ssh2_pkt_addstring("auth-agent-req@openssh.com");
5112 ssh2_pkt_addbool(1); /* want reply */
5116 crWaitUntilV(ispkt
);
5117 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
5118 unsigned i
= ssh2_pkt_getuint32();
5119 struct ssh_channel
*c
;
5120 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5122 continue; /* nonexistent channel */
5123 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
5125 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
5127 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
5128 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
5129 bombout(("Unexpected response to agent forwarding request:"
5130 " packet type %d", pktin
.type
));
5133 logevent("Agent forwarding refused");
5135 logevent("Agent forwarding enabled");
5136 ssh_agentfwd_enabled
= TRUE
;
5141 * Now allocate a pty for the session.
5144 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
5145 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
5146 ssh2_pkt_addstring("pty-req");
5147 ssh2_pkt_addbool(1); /* want reply */
5148 ssh2_pkt_addstring(cfg
.termtype
);
5149 ssh2_pkt_adduint32(term ? term
->cols
: 80);
5150 ssh2_pkt_adduint32(term ? term
->rows
: 24);
5151 ssh2_pkt_adduint32(0); /* pixel width */
5152 ssh2_pkt_adduint32(0); /* pixel height */
5153 ssh2_pkt_addstring_start();
5154 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
5156 ssh_state
= SSH_STATE_INTERMED
;
5159 crWaitUntilV(ispkt
);
5160 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
5161 unsigned i
= ssh2_pkt_getuint32();
5162 struct ssh_channel
*c
;
5163 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5165 continue; /* nonexistent channel */
5166 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
5168 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
5170 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
5171 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
5172 bombout(("Unexpected response to pty request:"
5173 " packet type %d", pktin
.type
));
5176 c_write_str("Server refused to allocate pty\r\n");
5177 ssh_editing
= ssh_echoing
= 1;
5179 logevent("Allocated pty");
5182 ssh_editing
= ssh_echoing
= 1;
5186 * Start a shell or a remote command. We may have to attempt
5187 * this twice if the config data has provided a second choice
5194 if (ssh_fallback_cmd
) {
5195 subsys
= cfg
.ssh_subsys2
;
5196 cmd
= cfg
.remote_cmd_ptr2
;
5198 subsys
= cfg
.ssh_subsys
;
5199 cmd
= cfg
.remote_cmd_ptr
;
5202 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
5203 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
5205 ssh2_pkt_addstring("subsystem");
5206 ssh2_pkt_addbool(1); /* want reply */
5207 ssh2_pkt_addstring(cmd
);
5209 ssh2_pkt_addstring("exec");
5210 ssh2_pkt_addbool(1); /* want reply */
5211 ssh2_pkt_addstring(cmd
);
5213 ssh2_pkt_addstring("shell");
5214 ssh2_pkt_addbool(1); /* want reply */
5218 crWaitUntilV(ispkt
);
5219 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
5220 unsigned i
= ssh2_pkt_getuint32();
5221 struct ssh_channel
*c
;
5222 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5224 continue; /* nonexistent channel */
5225 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
5227 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
5228 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
5229 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
5230 bombout(("Unexpected response to shell/command request:"
5231 " packet type %d", pktin
.type
));
5235 * We failed to start the command. If this is the
5236 * fallback command, we really are finished; if it's
5237 * not, and if the fallback command exists, try falling
5238 * back to it before complaining.
5240 if (!ssh_fallback_cmd
&& cfg
.remote_cmd_ptr2
!= NULL
) {
5241 logevent("Primary command failed; attempting fallback");
5242 ssh_fallback_cmd
= TRUE
;
5245 bombout(("Server refused to start a shell/command"));
5248 logevent("Started a shell/command");
5253 ssh_state
= SSH_STATE_SESSION
;
5257 ssh_special(TS_EOF
);
5262 ldisc_send(NULL
, 0, 0); /* cause ldisc to notice changes */
5265 static int try_send
;
5269 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
5270 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
5273 unsigned i
= ssh2_pkt_getuint32();
5274 struct ssh_channel
*c
;
5275 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5277 continue; /* nonexistent channel */
5278 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
5279 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
5280 continue; /* extended but not stderr */
5281 ssh2_pkt_getstring(&data
, &length
);
5284 c
->v
.v2
.locwindow
-= length
;
5286 case CHAN_MAINSESSION
:
5288 from_backend(frontend
, pktin
.type
==
5289 SSH2_MSG_CHANNEL_EXTENDED_DATA
,
5293 bufsize
= x11_send(c
->u
.x11
.s
, data
, length
);
5296 bufsize
= pfd_send(c
->u
.pfd
.s
, data
, length
);
5299 while (length
> 0) {
5300 if (c
->u
.a
.lensofar
< 4) {
5301 int l
= min(4 - c
->u
.a
.lensofar
, length
);
5302 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
5306 c
->u
.a
.lensofar
+= l
;
5308 if (c
->u
.a
.lensofar
== 4) {
5310 4 + GET_32BIT(c
->u
.a
.msglen
);
5311 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
5312 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
5314 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
5316 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
5318 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
5322 c
->u
.a
.lensofar
+= l
;
5324 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
5325 void *reply
, *sentreply
;
5327 agent_query(c
->u
.a
.message
,
5328 c
->u
.a
.totallen
, &reply
,
5333 /* Fake SSH_AGENT_FAILURE. */
5334 sentreply
= "\0\0\0\1\5";
5337 ssh2_add_channel_data(c
, sentreply
,
5342 sfree(c
->u
.a
.message
);
5343 c
->u
.a
.lensofar
= 0;
5350 * If we are not buffering too much data,
5351 * enlarge the window again at the remote side.
5353 if (bufsize
< OUR_V2_WINSIZE
)
5354 ssh2_set_window(c
, OUR_V2_WINSIZE
- bufsize
);
5356 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
5357 ssh_state
= SSH_STATE_CLOSED
;
5358 logevent("Received disconnect message");
5360 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
5361 unsigned i
= ssh2_pkt_getuint32();
5362 struct ssh_channel
*c
;
5364 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5366 continue; /* nonexistent channel */
5368 if (c
->type
== CHAN_X11
) {
5370 * Remote EOF on an X11 channel means we should
5371 * wrap up and close the channel ourselves.
5373 x11_close(c
->u
.x11
.s
);
5375 } else if (c
->type
== CHAN_AGENT
) {
5377 } else if (c
->type
== CHAN_SOCKDATA
) {
5378 pfd_close(c
->u
.pfd
.s
);
5381 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
5382 unsigned i
= ssh2_pkt_getuint32();
5383 struct ssh_channel
*c
;
5385 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5386 if (!c
|| ((int)c
->remoteid
) == -1) {
5387 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
5388 c ?
"half-open" : "nonexistent", i
));
5390 /* Do pre-close processing on the channel. */
5392 case CHAN_MAINSESSION
:
5393 break; /* nothing to see here, move along */
5395 if (c
->u
.x11
.s
!= NULL
)
5396 x11_close(c
->u
.x11
.s
);
5403 if (c
->u
.pfd
.s
!= NULL
)
5404 pfd_close(c
->u
.pfd
.s
);
5408 if (c
->closes
== 0) {
5409 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
5410 ssh2_pkt_adduint32(c
->remoteid
);
5413 del234(ssh_channels
, c
);
5414 bufchain_clear(&c
->v
.v2
.outbuffer
);
5418 * See if that was the last channel left open.
5420 if (count234(ssh_channels
) == 0) {
5423 * We used to send SSH_MSG_DISCONNECT here,
5424 * because I'd believed that _every_ conforming
5425 * SSH2 connection had to end with a disconnect
5426 * being sent by at least one side; apparently
5427 * I was wrong and it's perfectly OK to
5428 * unceremoniously slam the connection shut
5429 * when you're done, and indeed OpenSSH feels
5430 * this is more polite than sending a
5431 * DISCONNECT. So now we don't.
5433 logevent("All channels closed. Disconnecting");
5434 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
5435 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
5436 ssh2_pkt_addstring("All open channels closed");
5437 ssh2_pkt_addstring("en"); /* language tag */
5440 ssh_state
= SSH_STATE_CLOSED
;
5443 continue; /* remote sends close; ignore (FIXME) */
5444 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
5445 unsigned i
= ssh2_pkt_getuint32();
5446 struct ssh_channel
*c
;
5447 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5449 continue; /* nonexistent channel */
5450 c
->v
.v2
.remwindow
+= ssh2_pkt_getuint32();
5452 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
5453 unsigned i
= ssh2_pkt_getuint32();
5454 struct ssh_channel
*c
;
5455 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5457 continue; /* nonexistent channel */
5458 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
5459 continue; /* dunno why they're confirming this */
5460 c
->remoteid
= ssh2_pkt_getuint32();
5461 c
->type
= CHAN_SOCKDATA
;
5462 c
->v
.v2
.remwindow
= ssh2_pkt_getuint32();
5463 c
->v
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
5465 pfd_confirm(c
->u
.pfd
.s
);
5468 * We have a pending close on this channel,
5469 * which we decided on before the server acked
5470 * the channel open. So now we know the
5471 * remoteid, we can close it again.
5473 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
5474 ssh2_pkt_adduint32(c
->remoteid
);
5477 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN_FAILURE
) {
5478 unsigned i
= ssh2_pkt_getuint32();
5479 struct ssh_channel
*c
;
5480 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
5482 continue; /* nonexistent channel */
5483 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
5484 continue; /* dunno why they're failing this */
5486 logevent("Forwarded connection refused by server");
5488 pfd_close(c
->u
.pfd
.s
);
5490 del234(ssh_channels
, c
);
5492 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
5495 int typelen
, want_reply
;
5496 struct ssh_channel
*c
;
5498 localid
= ssh2_pkt_getuint32();
5499 ssh2_pkt_getstring(&type
, &typelen
);
5500 want_reply
= ssh2_pkt_getbool();
5503 * First, check that the channel exists. Otherwise,
5504 * we can instantly disconnect with a rude message.
5506 c
= find234(ssh_channels
, &localid
, ssh_channelfind
);
5509 sprintf(buf
, "Received channel request for nonexistent"
5510 " channel %d", localid
);
5512 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
5513 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
5514 ssh2_pkt_addstring(buf
);
5515 ssh2_pkt_addstring("en"); /* language tag */
5517 connection_fatal("%s", buf
);
5518 ssh_state
= SSH_STATE_CLOSED
;
5523 * Having got the channel number, we now look at
5524 * the request type string to see if it's something
5527 if (typelen
== 11 && !memcmp(type
, "exit-status", 11) &&
5529 /* We recognise "exit-status" on the primary channel. */
5531 ssh_exitcode
= ssh2_pkt_getuint32();
5532 sprintf(buf
, "Server sent command exit status %d",
5536 ssh2_pkt_init(SSH2_MSG_CHANNEL_SUCCESS
);
5537 ssh2_pkt_adduint32(c
->remoteid
);
5542 * This is a channel request we don't know
5543 * about, so we now either ignore the request
5544 * or respond with CHANNEL_FAILURE, depending
5548 ssh2_pkt_init(SSH2_MSG_CHANNEL_FAILURE
);
5549 ssh2_pkt_adduint32(c
->remoteid
);
5553 } else if (pktin
.type
== SSH2_MSG_GLOBAL_REQUEST
) {
5555 int typelen
, want_reply
;
5557 ssh2_pkt_getstring(&type
, &typelen
);
5558 want_reply
= ssh2_pkt_getbool();
5561 * We currently don't support any global requests
5562 * at all, so we either ignore the request or
5563 * respond with REQUEST_FAILURE, depending on
5567 ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE
);
5570 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
5574 struct ssh_channel
*c
;
5575 unsigned remid
, winsize
, pktsize
;
5576 ssh2_pkt_getstring(&type
, &typelen
);
5577 c
= smalloc(sizeof(struct ssh_channel
));
5579 remid
= ssh2_pkt_getuint32();
5580 winsize
= ssh2_pkt_getuint32();
5581 pktsize
= ssh2_pkt_getuint32();
5583 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
5584 if (!ssh_X11_fwd_enabled
)
5585 error
= "X11 forwarding is not enabled";
5586 else if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) !=
5588 error
= "Unable to open an X11 connection";
5592 } else if (typelen
== 15 &&
5593 !memcmp(type
, "forwarded-tcpip", 15)) {
5594 struct ssh_rportfwd pf
, *realpf
;
5597 ssh2_pkt_getstring(&dummy
, &dummylen
);/* skip address */
5598 pf
.sport
= ssh2_pkt_getuint32();
5599 realpf
= find234(ssh_rportfwds
, &pf
, NULL
);
5600 if (realpf
== NULL
) {
5601 error
= "Remote port is not recognised";
5603 char *e
= pfd_newconnect(&c
->u
.pfd
.s
, realpf
->dhost
,
5606 sprintf(buf
, "Received remote port open request for %s:%d",
5607 realpf
->dhost
, realpf
->dport
);
5610 sprintf(buf
, "Port open failed: %s", e
);
5612 error
= "Port open failed";
5614 logevent("Forwarded port opened successfully");
5615 c
->type
= CHAN_SOCKDATA
;
5618 } else if (typelen
== 22 &&
5619 !memcmp(type
, "auth-agent@openssh.com", 3)) {
5620 if (!ssh_agentfwd_enabled
)
5621 error
= "Agent forwarding is not enabled";
5623 c
->type
= CHAN_AGENT
; /* identify channel type */
5624 c
->u
.a
.lensofar
= 0;
5627 error
= "Unsupported channel type requested";
5630 c
->remoteid
= remid
;
5632 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
5633 ssh2_pkt_adduint32(c
->remoteid
);
5634 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED
);
5635 ssh2_pkt_addstring(error
);
5636 ssh2_pkt_addstring("en"); /* language tag */
5640 c
->localid
= alloc_channel_id();
5642 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
5643 c
->v
.v2
.remwindow
= winsize
;
5644 c
->v
.v2
.remmaxpkt
= pktsize
;
5645 bufchain_init(&c
->v
.v2
.outbuffer
);
5646 add234(ssh_channels
, c
);
5647 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
5648 ssh2_pkt_adduint32(c
->remoteid
);
5649 ssh2_pkt_adduint32(c
->localid
);
5650 ssh2_pkt_adduint32(c
->v
.v2
.locwindow
);
5651 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
5655 bombout(("Strange packet received: type %d", pktin
.type
));
5660 * We have spare data. Add it to the channel buffer.
5662 ssh2_add_channel_data(mainchan
, in
, inlen
);
5667 struct ssh_channel
*c
;
5669 * Try to send data on all channels if we can.
5671 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++) {
5672 int bufsize
= ssh2_try_send(c
);
5675 case CHAN_MAINSESSION
:
5676 /* stdin need not receive an unthrottle
5677 * notification since it will be polled */
5680 x11_unthrottle(c
->u
.x11
.s
);
5683 /* agent sockets are request/response and need no
5684 * buffer management */
5687 pfd_unthrottle(c
->u
.pfd
.s
);
5699 * Handle the top-level SSH2 protocol.
5701 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
5703 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
5705 do_ssh2_authconn(in
, inlen
, ispkt
);
5709 * Called to set up the connection.
5711 * Returns an error message, or NULL on success.
5713 static char *ssh_init(void *frontend_handle
,
5714 char *host
, int port
, char **realhost
, int nodelay
)
5719 if (crypto_startup() == 0)
5720 return "Microsoft high encryption pack not installed!";
5723 frontend
= frontend_handle
;
5728 ssh1_throttle_count
= 0;
5729 ssh_overall_bufsize
= 0;
5730 ssh_fallback_cmd
= 0;
5732 p
= connect_to_host(host
, port
, realhost
, nodelay
);
5740 * Called to send data down the Telnet connection.
5742 static int ssh_send(char *buf
, int len
)
5744 if (s
== NULL
|| ssh_protocol
== NULL
)
5747 ssh_protocol(buf
, len
, 0);
5749 return ssh_sendbuffer();
5753 * Called to query the current amount of buffered stdin data.
5755 static int ssh_sendbuffer(void)
5759 if (s
== NULL
|| ssh_protocol
== NULL
)
5763 * If the SSH socket itself has backed up, add the total backup
5764 * size on that to any individual buffer on the stdin channel.
5767 if (ssh_throttled_all
)
5768 override_value
= ssh_overall_bufsize
;
5770 if (ssh_version
== 1) {
5771 return override_value
;
5772 } else if (ssh_version
== 2) {
5773 if (!mainchan
|| mainchan
->closes
> 0)
5774 return override_value
;
5776 return override_value
+ bufchain_size(&mainchan
->v
.v2
.outbuffer
);
5783 * Called to set the size of the window from SSH's POV.
5785 static void ssh_size(void)
5787 switch (ssh_state
) {
5788 case SSH_STATE_BEFORE_SIZE
:
5789 case SSH_STATE_PREPACKET
:
5790 case SSH_STATE_CLOSED
:
5791 break; /* do nothing */
5792 case SSH_STATE_INTERMED
:
5793 size_needed
= TRUE
; /* buffer for later */
5795 case SSH_STATE_SESSION
:
5799 if (ssh_version
== 1) {
5800 send_packet(SSH1_CMSG_WINDOW_SIZE
,
5801 PKT_INT
, term
->rows
, PKT_INT
, term
->cols
,
5802 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
5804 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
5805 ssh2_pkt_adduint32(mainchan
->remoteid
);
5806 ssh2_pkt_addstring("window-change");
5807 ssh2_pkt_addbool(0);
5808 ssh2_pkt_adduint32(term
->cols
);
5809 ssh2_pkt_adduint32(term
->rows
);
5810 ssh2_pkt_adduint32(0);
5811 ssh2_pkt_adduint32(0);
5820 * Send Telnet special codes. TS_EOF is useful for `plink', so you
5821 * can send an EOF and collect resulting output (e.g. `plink
5824 static void ssh_special(Telnet_Special code
)
5826 if (code
== TS_EOF
) {
5827 if (ssh_state
!= SSH_STATE_SESSION
) {
5829 * Buffer the EOF in case we are pre-SESSION, so we can
5830 * send it as soon as we reach SESSION.
5836 if (ssh_version
== 1) {
5837 send_packet(SSH1_CMSG_EOF
, PKT_END
);
5839 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
5840 ssh2_pkt_adduint32(mainchan
->remoteid
);
5843 logevent("Sent EOF message");
5844 } else if (code
== TS_PING
) {
5845 if (ssh_state
== SSH_STATE_CLOSED
5846 || ssh_state
== SSH_STATE_PREPACKET
) return;
5847 if (ssh_version
== 1) {
5848 if (!(ssh_remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
))
5849 send_packet(SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
5851 ssh2_pkt_init(SSH2_MSG_IGNORE
);
5852 ssh2_pkt_addstring_start();
5860 void *new_sock_channel(Socket s
)
5862 struct ssh_channel
*c
;
5863 c
= smalloc(sizeof(struct ssh_channel
));
5866 c
->remoteid
= -1; /* to be set when open confirmed */
5867 c
->localid
= alloc_channel_id();
5869 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
5871 bufchain_init(&c
->v
.v2
.outbuffer
);
5872 add234(ssh_channels
, c
);
5878 * This is called when stdout/stderr (the entity to which
5879 * from_backend sends data) manages to clear some backlog.
5881 void ssh_unthrottle(int bufsize
)
5883 if (ssh_version
== 1) {
5884 if (ssh1_stdout_throttling
&& bufsize
< SSH1_BUFFER_LIMIT
) {
5885 ssh1_stdout_throttling
= 0;
5889 if (mainchan
&& mainchan
->closes
== 0)
5890 ssh2_set_window(mainchan
, OUR_V2_WINSIZE
- bufsize
);
5894 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
5896 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
5899 sprintf(buf
, "Opening forwarded connection to %.512s:%d", hostname
, port
);
5902 if (ssh_version
== 1) {
5903 send_packet(SSH1_MSG_PORT_OPEN
,
5904 PKT_INT
, c
->localid
,
5907 //PKT_STR, <org:orgport>,
5910 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
5911 ssh2_pkt_addstring("direct-tcpip");
5912 ssh2_pkt_adduint32(c
->localid
);
5913 c
->v
.v2
.locwindow
= OUR_V2_WINSIZE
;
5914 ssh2_pkt_adduint32(c
->v
.v2
.locwindow
);/* our window size */
5915 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
5916 ssh2_pkt_addstring(hostname
);
5917 ssh2_pkt_adduint32(port
);
5919 * We make up values for the originator data; partly it's
5920 * too much hassle to keep track, and partly I'm not
5921 * convinced the server should be told details like that
5922 * about my local network configuration.
5924 ssh2_pkt_addstring("client-side-connection");
5925 ssh2_pkt_adduint32(0);
5931 static Socket
ssh_socket(void)
5936 static int ssh_sendok(void)
5941 static int ssh_ldisc(int option
)
5943 if (option
== LD_ECHO
)
5945 if (option
== LD_EDIT
)
5950 static int ssh_return_exitcode(void)
5952 return ssh_exitcode
;
5955 Backend ssh_backend
= {
5962 ssh_return_exitcode
,