18 /* uncomment this for packet level debugging */
19 /* #define DUMP_PACKETS */
21 #define logevent(s) { logevent(s); \
22 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
23 { fprintf(stderr, "%s\n", s); fflush(stderr); } }
25 #define bombout(msg) ( ssh_state = SSH_STATE_CLOSED, \
26 (s ? sk_close(s), s = NULL : 0), \
27 connection_fatal msg )
29 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
30 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
31 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
32 #define SSH1_CMSG_USER 4 /* 0x4 */
33 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
34 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
35 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
36 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
37 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
38 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
39 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
40 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
41 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
42 #define SSH1_SMSG_FAILURE 15 /* 0xf */
43 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
44 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
45 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
46 #define SSH1_CMSG_EOF 19 /* 0x13 */
47 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
48 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
49 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
50 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
51 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
52 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
53 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
54 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
55 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
56 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
57 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
58 #define SSH1_MSG_IGNORE 32 /* 0x20 */
59 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
60 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
61 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
62 #define SSH1_MSG_DEBUG 36 /* 0x24 */
63 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
64 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
65 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
66 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
67 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
68 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
69 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
71 #define SSH1_AUTH_TIS 5 /* 0x5 */
72 #define SSH1_AUTH_CCARD 16 /* 0x10 */
74 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
75 /* Mask for protoflags we will echo back to server if seen */
76 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
78 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
79 #define SSH2_MSG_IGNORE 2 /* 0x2 */
80 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
81 #define SSH2_MSG_DEBUG 4 /* 0x4 */
82 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
83 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
84 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
85 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
86 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
87 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
88 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
89 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
90 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
91 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
92 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
93 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
94 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
95 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
96 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
97 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
98 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
99 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
100 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
101 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
102 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
103 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
104 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
105 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
106 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
107 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
108 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
109 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
110 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
111 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
112 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
113 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
115 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
116 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
117 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
118 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
119 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
120 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
121 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
122 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
123 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
124 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
125 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
126 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
127 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
128 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
129 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
131 static const char *const ssh2_disconnect_reasons
[] = {
133 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
134 "SSH_DISCONNECT_PROTOCOL_ERROR",
135 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
136 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
137 "SSH_DISCONNECT_MAC_ERROR",
138 "SSH_DISCONNECT_COMPRESSION_ERROR",
139 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
140 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
141 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
142 "SSH_DISCONNECT_CONNECTION_LOST",
143 "SSH_DISCONNECT_BY_APPLICATION",
144 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
145 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
146 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
147 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
150 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
151 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
152 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
153 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
155 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
158 * Various remote-bug flags.
160 #define BUG_CHOKES_ON_SSH1_IGNORE 1
161 #define BUG_SSH2_HMAC 2
163 #define GET_32BIT(cp) \
164 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
165 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
166 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
167 ((unsigned long)(unsigned char)(cp)[3]))
169 #define PUT_32BIT(cp, value) { \
170 (cp)[0] = (unsigned char)((value) >> 24); \
171 (cp)[1] = (unsigned char)((value) >> 16); \
172 (cp)[2] = (unsigned char)((value) >> 8); \
173 (cp)[3] = (unsigned char)(value); }
175 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
177 /* Coroutine mechanics for the sillier bits of the code */
178 #define crBegin1 static int crLine = 0;
179 #define crBegin2 switch(crLine) { case 0:;
180 #define crBegin crBegin1; crBegin2;
181 #define crFinish(z) } crLine = 0; return (z)
182 #define crFinishV } crLine = 0; return
183 #define crReturn(z) \
185 crLine=__LINE__; return (z); case __LINE__:;\
189 crLine=__LINE__; return; case __LINE__:;\
191 #define crStop(z) do{ crLine = 0; return (z); }while(0)
192 #define crStopV do{ crLine = 0; return; }while(0)
193 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
194 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
196 extern char *x11_init(Socket
*, char *, void *);
197 extern void x11_close(Socket
);
198 extern void x11_send(Socket
, char *, int);
199 extern void x11_invent_auth(char *, int, char *, int);
201 extern char *pfd_newconnect(Socket
* s
, char *hostname
, int port
, void *c
);
202 extern char *pfd_addforward(char *desthost
, int destport
, int port
);
203 extern void pfd_close(Socket s
);
204 extern void pfd_send(Socket s
, char *data
, int len
);
205 extern void pfd_confirm(Socket s
);
208 * Ciphers for SSH2. We miss out single-DES because it isn't
209 * supported; also 3DES and Blowfish are both done differently from
210 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
211 * endianness and different-sized keys.)
213 const static struct ssh2_ciphers
*ciphers
[] = {
219 const static struct ssh_kex
*kex_algs
[] = {
220 &ssh_diffiehellman_gex
,
224 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
226 static void nullmac_key(unsigned char *key
)
229 static void nullmac_generate(unsigned char *blk
, int len
,
233 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
)
237 const static struct ssh_mac ssh_mac_none
= {
238 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
240 const static struct ssh_mac
*macs
[] = {
241 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
243 const static struct ssh_mac
*buggymacs
[] = {
244 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
247 static void ssh_comp_none_init(void)
250 static int ssh_comp_none_block(unsigned char *block
, int len
,
251 unsigned char **outblock
, int *outlen
)
255 static int ssh_comp_none_disable(void)
259 const static struct ssh_compress ssh_comp_none
= {
261 ssh_comp_none_init
, ssh_comp_none_block
,
262 ssh_comp_none_init
, ssh_comp_none_block
,
263 ssh_comp_none_disable
265 extern const struct ssh_compress ssh_zlib
;
266 const static struct ssh_compress
*compressions
[] = {
267 &ssh_zlib
, &ssh_comp_none
270 enum { /* channel types */
275 CHAN_SOCKDATA_DORMANT
/* one the remote hasn't confirmed */
279 * 2-3-4 tree storing channels.
282 unsigned remoteid
, localid
;
285 struct ssh2_data_channel
{
286 unsigned char *outbuffer
;
287 unsigned outbuflen
, outbufsize
;
288 unsigned remwindow
, remmaxpkt
;
291 struct ssh_agent_channel
{
292 unsigned char *message
;
293 unsigned char msglen
[4];
294 int lensofar
, totallen
;
296 struct ssh_x11_channel
{
299 struct ssh_pfd_channel
{
306 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
307 * 2 use this structure in different ways, reflecting SSH 2's
308 * altogether saner approach to port forwarding.
310 * In SSH 1, you arrange a remote forwarding by sending the server
311 * the remote port number, and the local destination host:port.
312 * When a connection comes in, the server sends you back that
313 * host:port pair, and you connect to it. This is a ready-made
314 * security hole if you're not on the ball: a malicious server
315 * could send you back _any_ host:port pair, so if you trustingly
316 * connect to the address it gives you then you've just opened the
317 * entire inside of your corporate network just by connecting
318 * through it to a dodgy SSH server. Hence, we must store a list of
319 * host:port pairs we _are_ trying to forward to, and reject a
320 * connection request from the server if it's not in the list.
322 * In SSH 2, each side of the connection minds its own business and
323 * doesn't send unnecessary information to the other. You arrange a
324 * remote forwarding by sending the server just the remote port
325 * number. When a connection comes in, the server tells you which
326 * of its ports was connected to; and _you_ have to remember what
327 * local host:port pair went with that port number.
329 * Hence: in SSH 1 this structure stores host:port pairs we intend
330 * to allow connections to, and is indexed by those host:port
331 * pairs. In SSH 2 it stores a mapping from source port to
332 * destination host:port pair, and is indexed by source port.
334 struct ssh_rportfwd
{
335 unsigned sport
, dport
;
348 static SHA_State exhash
, exhashbase
;
350 static Socket s
= NULL
;
352 static unsigned char session_key
[32];
353 static int ssh1_compressing
;
354 static int ssh1_remote_protoflags
;
355 static int ssh1_local_protoflags
;
356 static int ssh_agentfwd_enabled
;
357 static int ssh_X11_fwd_enabled
;
358 static int ssh_remote_bugs
;
359 static const struct ssh_cipher
*cipher
= NULL
;
360 static const struct ssh2_cipher
*cscipher
= NULL
;
361 static const struct ssh2_cipher
*sccipher
= NULL
;
362 static const struct ssh_mac
*csmac
= NULL
;
363 static const struct ssh_mac
*scmac
= NULL
;
364 static const struct ssh_compress
*cscomp
= NULL
;
365 static const struct ssh_compress
*sccomp
= NULL
;
366 static const struct ssh_kex
*kex
= NULL
;
367 static const struct ssh_signkey
*hostkey
= NULL
;
368 static unsigned char ssh2_session_id
[20];
369 int (*ssh_get_line
) (const char *prompt
, char *str
, int maxlen
,
372 static char *savedhost
;
373 static int savedport
;
374 static int ssh_send_ok
;
375 static int ssh_echoing
, ssh_editing
;
377 static tree234
*ssh_channels
; /* indexed by local id */
378 static struct ssh_channel
*mainchan
; /* primary session channel */
380 static tree234
*ssh_rportfwds
;
384 SSH_STATE_BEFORE_SIZE
,
388 } ssh_state
= SSH_STATE_PREPACKET
;
390 static int size_needed
= FALSE
, eof_needed
= FALSE
;
392 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
393 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
394 static unsigned char *deferred_send_data
= NULL
;
395 static int deferred_len
= 0, deferred_size
= 0;
397 static int ssh_version
;
398 static void (*ssh_protocol
) (unsigned char *in
, int inlen
, int ispkt
);
399 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
400 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
401 static void ssh_size(void);
402 static void ssh_special(Telnet_Special
);
403 static void ssh2_try_send(struct ssh_channel
*c
);
404 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
407 static int (*s_rdpkt
) (unsigned char **data
, int *datalen
);
409 static struct rdpkt1_state_tag
{
410 long len
, pad
, biglen
, to_read
;
411 unsigned long realcrc
, gotcrc
;
417 static struct rdpkt2_state_tag
{
418 long len
, pad
, payload
, packetlen
, maclen
;
421 unsigned long incoming_sequence
;
424 static int ssh_channelcmp(void *av
, void *bv
)
426 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
427 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
428 if (a
->localid
< b
->localid
)
430 if (a
->localid
> b
->localid
)
434 static int ssh_channelfind(void *av
, void *bv
)
436 unsigned *a
= (unsigned *) av
;
437 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
445 static int ssh_rportcmp_ssh1(void *av
, void *bv
)
447 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
448 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
450 if ( (i
= strcmp(a
->dhost
, b
->dhost
)) != 0)
451 return i
< 0 ?
-1 : +1;
452 if (a
->dport
> b
->dport
)
454 if (a
->dport
< b
->dport
)
459 static int ssh_rportcmp_ssh2(void *av
, void *bv
)
461 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
462 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
464 if (a
->sport
> b
->sport
)
466 if (a
->sport
< b
->sport
)
471 static int alloc_channel_id(void)
473 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
474 unsigned low
, high
, mid
;
476 struct ssh_channel
*c
;
479 * First-fit allocation of channel numbers: always pick the
480 * lowest unused one. To do this, binary-search using the
481 * counted B-tree to find the largest channel ID which is in a
482 * contiguous sequence from the beginning. (Precisely
483 * everything in that sequence must have ID equal to its tree
484 * index plus CHANNEL_NUMBER_OFFSET.)
486 tsize
= count234(ssh_channels
);
490 while (high
- low
> 1) {
491 mid
= (high
+ low
) / 2;
492 c
= index234(ssh_channels
, mid
);
493 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
494 low
= mid
; /* this one is fine */
496 high
= mid
; /* this one is past it */
499 * Now low points to either -1, or the tree index of the
500 * largest ID in the initial sequence.
503 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
504 assert(NULL
== find234(ssh_channels
, &i
, ssh_channelfind
));
506 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
509 static void c_write(char *buf
, int len
)
511 if ((flags
& FLAG_STDERR
)) {
513 for (i
= 0; i
< len
; i
++)
515 fputc(buf
[i
], stderr
);
518 from_backend(1, buf
, len
);
521 static void c_write_untrusted(char *buf
, int len
)
524 for (i
= 0; i
< len
; i
++) {
527 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
532 static void c_write_str(char *buf
)
534 c_write(buf
, strlen(buf
));
538 * Collect incoming data in the incoming packet buffer.
539 * Decipher and verify the packet when it is completely read.
540 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
541 * Update the *data and *datalen variables.
542 * Return the additional nr of bytes needed, or 0 when
543 * a complete packet is available.
545 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
547 struct rdpkt1_state_tag
*st
= &rdpkt1_state
;
556 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
557 while ((*datalen
) == 0)
559 st
->len
= (st
->len
<< 8) + **data
;
560 (*data
)++, (*datalen
)--;
564 if (st
->len
== 0x52656d6f) { /* "Remo"te server has closed ... */
565 st
->len
= 0x300; /* big enough to carry to end */
569 st
->pad
= 8 - (st
->len
% 8);
570 st
->biglen
= st
->len
+ st
->pad
;
571 pktin
.length
= st
->len
- 5;
573 if (pktin
.maxlen
< st
->biglen
) {
574 pktin
.maxlen
= st
->biglen
;
575 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->biglen
+ APIEXTRA
) :
576 srealloc(pktin
.data
, st
->biglen
+ APIEXTRA
));
578 fatalbox("Out of memory");
581 st
->to_read
= st
->biglen
;
583 while (st
->to_read
> 0) {
584 st
->chunk
= st
->to_read
;
585 while ((*datalen
) == 0)
586 crReturn(st
->to_read
);
587 if (st
->chunk
> (*datalen
))
588 st
->chunk
= (*datalen
);
589 memcpy(st
->p
, *data
, st
->chunk
);
591 *datalen
-= st
->chunk
;
593 st
->to_read
-= st
->chunk
;
597 cipher
->decrypt(pktin
.data
, st
->biglen
);
599 debug(("Got packet len=%d pad=%d\n", st
->len
, st
->pad
));
600 dmemdump(pktin
.data
, st
->biglen
);
603 st
->realcrc
= crc32(pktin
.data
, st
->biglen
- 4);
604 st
->gotcrc
= GET_32BIT(pktin
.data
+ st
->biglen
- 4);
605 if (st
->gotcrc
!= st
->realcrc
) {
606 bombout(("Incorrect CRC received on packet"));
610 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
612 if (ssh1_compressing
) {
613 unsigned char *decompblk
;
616 debug(("Packet payload pre-decompression:\n"));
617 dmemdump(pktin
.body
- 1, pktin
.length
+ 1);
619 zlib_decompress_block(pktin
.body
- 1, pktin
.length
+ 1,
620 &decompblk
, &decomplen
);
622 if (pktin
.maxlen
< st
->pad
+ decomplen
) {
623 pktin
.maxlen
= st
->pad
+ decomplen
;
624 pktin
.data
= srealloc(pktin
.data
, pktin
.maxlen
+ APIEXTRA
);
625 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
627 fatalbox("Out of memory");
630 memcpy(pktin
.body
- 1, decompblk
, decomplen
);
632 pktin
.length
= decomplen
- 1;
634 debug(("Packet payload post-decompression:\n"));
635 dmemdump(pktin
.body
- 1, pktin
.length
+ 1);
639 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
640 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
641 pktin
.type
== SSH1_MSG_DEBUG
||
642 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
643 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
644 long strlen
= GET_32BIT(pktin
.body
);
645 if (strlen
+ 4 != pktin
.length
) {
646 bombout(("Received data packet with bogus string length"));
651 pktin
.type
= pktin
.body
[-1];
653 if (pktin
.type
== SSH1_MSG_DEBUG
) {
654 /* log debug message */
656 int strlen
= GET_32BIT(pktin
.body
);
657 strcpy(buf
, "Remote: ");
660 memcpy(buf
+ 8, pktin
.body
+ 4, strlen
);
661 buf
[8 + strlen
] = '\0';
664 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
669 if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
670 /* log reason code in disconnect message */
672 unsigned msglen
= GET_32BIT(pktin
.body
);
674 strcpy(buf
, "Remote sent disconnect: ");
675 nowlen
= strlen(buf
);
676 if (msglen
> sizeof(buf
) - nowlen
- 1)
677 msglen
= sizeof(buf
) - nowlen
- 1;
678 memcpy(buf
+ nowlen
, pktin
.body
+ 4, msglen
);
679 buf
[nowlen
+ msglen
] = '\0';
686 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
688 struct rdpkt2_state_tag
*st
= &rdpkt2_state
;
696 st
->cipherblk
= sccipher
->blksize
;
699 if (st
->cipherblk
< 8)
702 if (pktin
.maxlen
< st
->cipherblk
) {
703 pktin
.maxlen
= st
->cipherblk
;
706 NULL ?
smalloc(st
->cipherblk
+
707 APIEXTRA
) : srealloc(pktin
.data
,
711 fatalbox("Out of memory");
715 * Acquire and decrypt the first block of the packet. This will
716 * contain the length and padding details.
718 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
719 while ((*datalen
) == 0)
720 crReturn(st
->cipherblk
- st
->i
);
721 pktin
.data
[st
->i
] = *(*data
)++;
725 if (!memcmp(pktin
.data
, "Remo", 4)) { /* "Remo"te server has closed ... */
730 sccipher
->decrypt(pktin
.data
, st
->cipherblk
);
733 * Now get the length and padding figures.
735 st
->len
= GET_32BIT(pktin
.data
);
736 st
->pad
= pktin
.data
[4];
739 * This enables us to deduce the payload length.
741 st
->payload
= st
->len
- st
->pad
- 1;
743 pktin
.length
= st
->payload
+ 5;
746 * So now we can work out the total packet length.
748 st
->packetlen
= st
->len
+ 4;
749 st
->maclen
= scmac ? scmac
->len
: 0;
752 * Adjust memory allocation if packet is too big.
754 if (pktin
.maxlen
< st
->packetlen
+ st
->maclen
) {
755 pktin
.maxlen
= st
->packetlen
+ st
->maclen
;
758 NULL ?
smalloc(pktin
.maxlen
+ APIEXTRA
) : srealloc(pktin
.data
,
763 fatalbox("Out of memory");
767 * Read and decrypt the remainder of the packet.
769 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
771 while ((*datalen
) == 0)
772 crReturn(st
->packetlen
+ st
->maclen
- st
->i
);
773 pktin
.data
[st
->i
] = *(*data
)++;
776 /* Decrypt everything _except_ the MAC. */
778 sccipher
->decrypt(pktin
.data
+ st
->cipherblk
,
779 st
->packetlen
- st
->cipherblk
);
782 debug(("Got packet len=%d pad=%d\n", st
->len
, st
->pad
));
783 dmemdump(pktin
.data
, st
->packetlen
);
790 && !scmac
->verify(pktin
.data
, st
->len
+ 4,
791 st
->incoming_sequence
)) {
792 bombout(("Incorrect MAC received on packet"));
795 st
->incoming_sequence
++; /* whether or not we MACed */
798 * Decompress packet payload.
801 unsigned char *newpayload
;
803 if (sccomp
&& sccomp
->decompress(pktin
.data
+ 5, pktin
.length
- 5,
804 &newpayload
, &newlen
)) {
805 if (pktin
.maxlen
< newlen
+ 5) {
806 pktin
.maxlen
= newlen
+ 5;
809 NULL ?
smalloc(pktin
.maxlen
+
810 APIEXTRA
) : srealloc(pktin
.data
,
814 fatalbox("Out of memory");
816 pktin
.length
= 5 + newlen
;
817 memcpy(pktin
.data
+ 5, newpayload
, newlen
);
819 debug(("Post-decompression payload:\n"));
820 dmemdump(pktin
.data
+ 5, newlen
);
828 pktin
.type
= pktin
.data
[5];
830 if (pktin
.type
== SSH2_MSG_IGNORE
|| pktin
.type
== SSH2_MSG_DEBUG
)
831 goto next_packet
; /* FIXME: print DEBUG message */
833 if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
834 /* log reason code in disconnect message */
836 int reason
= GET_32BIT(pktin
.data
+ 6);
837 unsigned msglen
= GET_32BIT(pktin
.data
+ 10);
839 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
840 sprintf(buf
, "Received disconnect message (%s)",
841 ssh2_disconnect_reasons
[reason
]);
843 sprintf(buf
, "Received disconnect message (unknown type %d)",
847 strcpy(buf
, "Disconnection message text: ");
848 nowlen
= strlen(buf
);
849 if (msglen
> sizeof(buf
) - nowlen
- 1)
850 msglen
= sizeof(buf
) - nowlen
- 1;
851 memcpy(buf
+ nowlen
, pktin
.data
+ 14, msglen
);
852 buf
[nowlen
+ msglen
] = '\0';
859 static void ssh1_pktout_size(int len
)
863 len
+= 5; /* type and CRC */
867 pktout
.length
= len
- 5;
868 if (pktout
.maxlen
< biglen
) {
869 pktout
.maxlen
= biglen
;
871 /* Allocate enough buffer space for extra block
872 * for MS CryptEncrypt() */
873 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+ 12) :
874 srealloc(pktout
.data
, biglen
+ 12));
876 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+ 4) :
877 srealloc(pktout
.data
, biglen
+ 4));
880 fatalbox("Out of memory");
882 pktout
.body
= pktout
.data
+ 4 + pad
+ 1;
885 static void s_wrpkt_start(int type
, int len
)
887 ssh1_pktout_size(len
);
891 static int s_wrpkt_prepare(void)
893 int pad
, len
, biglen
, i
;
896 pktout
.body
[-1] = pktout
.type
;
899 debug(("Packet payload pre-compression:\n"));
900 dmemdump(pktout
.body
- 1, pktout
.length
+ 1);
903 if (ssh1_compressing
) {
904 unsigned char *compblk
;
906 zlib_compress_block(pktout
.body
- 1, pktout
.length
+ 1,
908 ssh1_pktout_size(complen
- 1);
909 memcpy(pktout
.body
- 1, compblk
, complen
);
912 debug(("Packet payload post-compression:\n"));
913 dmemdump(pktout
.body
- 1, pktout
.length
+ 1);
917 len
= pktout
.length
+ 5; /* type and CRC */
921 for (i
= 0; i
< pad
; i
++)
922 pktout
.data
[i
+ 4] = random_byte();
923 crc
= crc32(pktout
.data
+ 4, biglen
- 4);
924 PUT_32BIT(pktout
.data
+ biglen
, crc
);
925 PUT_32BIT(pktout
.data
, len
);
928 debug(("Sending packet len=%d\n", biglen
+ 4));
929 dmemdump(pktout
.data
, biglen
+ 4);
932 cipher
->encrypt(pktout
.data
+ 4, biglen
);
937 static void s_wrpkt(void)
940 len
= s_wrpkt_prepare();
941 sk_write(s
, pktout
.data
, len
);
944 static void s_wrpkt_defer(void)
947 len
= s_wrpkt_prepare();
948 if (deferred_len
+ len
> deferred_size
) {
949 deferred_size
= deferred_len
+ len
+ 128;
950 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
952 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
957 * Construct a packet with the specified contents.
959 static void construct_packet(int pkttype
, va_list ap1
, va_list ap2
)
961 unsigned char *p
, *argp
, argchar
;
962 unsigned long argint
;
963 int pktlen
, argtype
, arglen
;
967 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
970 (void) va_arg(ap1
, int);
974 (void) va_arg(ap1
, char);
978 (void) va_arg(ap1
, unsigned char *);
979 arglen
= va_arg(ap1
, int);
983 argp
= va_arg(ap1
, unsigned char *);
984 arglen
= strlen(argp
);
985 pktlen
+= 4 + arglen
;
988 bn
= va_arg(ap1
, Bignum
);
989 pktlen
+= ssh1_bignum_length(bn
);
996 s_wrpkt_start(pkttype
, pktlen
);
999 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
1002 argint
= va_arg(ap2
, int);
1003 PUT_32BIT(p
, argint
);
1007 argchar
= va_arg(ap2
, unsigned char);
1012 argp
= va_arg(ap2
, unsigned char *);
1013 arglen
= va_arg(ap2
, int);
1014 memcpy(p
, argp
, arglen
);
1018 argp
= va_arg(ap2
, unsigned char *);
1019 arglen
= strlen(argp
);
1020 PUT_32BIT(p
, arglen
);
1021 memcpy(p
+ 4, argp
, arglen
);
1025 bn
= va_arg(ap2
, Bignum
);
1026 p
+= ssh1_write_bignum(p
, bn
);
1032 static void send_packet(int pkttype
, ...)
1035 va_start(ap1
, pkttype
);
1036 va_start(ap2
, pkttype
);
1037 construct_packet(pkttype
, ap1
, ap2
);
1041 static void defer_packet(int pkttype
, ...)
1044 va_start(ap1
, pkttype
);
1045 va_start(ap2
, pkttype
);
1046 construct_packet(pkttype
, ap1
, ap2
);
1050 static int ssh_versioncmp(char *a
, char *b
)
1053 unsigned long av
, bv
;
1055 av
= strtoul(a
, &ae
, 10);
1056 bv
= strtoul(b
, &be
, 10);
1058 return (av
< bv ?
-1 : +1);
1063 av
= strtoul(ae
, &ae
, 10);
1064 bv
= strtoul(be
, &be
, 10);
1066 return (av
< bv ?
-1 : +1);
1072 * Utility routines for putting an SSH-protocol `string' and
1073 * `uint32' into a SHA state.
1076 static void sha_string(SHA_State
* s
, void *str
, int len
)
1078 unsigned char lenblk
[4];
1079 PUT_32BIT(lenblk
, len
);
1080 SHA_Bytes(s
, lenblk
, 4);
1081 SHA_Bytes(s
, str
, len
);
1084 static void sha_uint32(SHA_State
* s
, unsigned i
)
1086 unsigned char intblk
[4];
1087 PUT_32BIT(intblk
, i
);
1088 SHA_Bytes(s
, intblk
, 4);
1092 * SSH2 packet construction functions.
1094 static void ssh2_pkt_ensure(int length
)
1096 if (pktout
.maxlen
< length
) {
1097 pktout
.maxlen
= length
+ 256;
1100 NULL ?
smalloc(pktout
.maxlen
+
1101 APIEXTRA
) : srealloc(pktout
.data
,
1105 fatalbox("Out of memory");
1108 static void ssh2_pkt_adddata(void *data
, int len
)
1110 pktout
.length
+= len
;
1111 ssh2_pkt_ensure(pktout
.length
);
1112 memcpy(pktout
.data
+ pktout
.length
- len
, data
, len
);
1114 static void ssh2_pkt_addbyte(unsigned char byte
)
1116 ssh2_pkt_adddata(&byte
, 1);
1118 static void ssh2_pkt_init(int pkt_type
)
1121 ssh2_pkt_addbyte((unsigned char) pkt_type
);
1123 static void ssh2_pkt_addbool(unsigned char value
)
1125 ssh2_pkt_adddata(&value
, 1);
1127 static void ssh2_pkt_adduint32(unsigned long value
)
1130 PUT_32BIT(x
, value
);
1131 ssh2_pkt_adddata(x
, 4);
1133 static void ssh2_pkt_addstring_start(void)
1135 ssh2_pkt_adduint32(0);
1136 pktout
.savedpos
= pktout
.length
;
1138 static void ssh2_pkt_addstring_str(char *data
)
1140 ssh2_pkt_adddata(data
, strlen(data
));
1141 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1142 pktout
.length
- pktout
.savedpos
);
1144 static void ssh2_pkt_addstring_data(char *data
, int len
)
1146 ssh2_pkt_adddata(data
, len
);
1147 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1148 pktout
.length
- pktout
.savedpos
);
1150 static void ssh2_pkt_addstring(char *data
)
1152 ssh2_pkt_addstring_start();
1153 ssh2_pkt_addstring_str(data
);
1155 static char *ssh2_mpint_fmt(Bignum b
, int *len
)
1158 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1161 fatalbox("out of memory");
1163 for (i
= 1; i
<= n
; i
++)
1164 p
[i
] = bignum_byte(b
, n
- i
);
1166 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1168 memmove(p
, p
+ i
, n
+ 1 - i
);
1172 static void ssh2_pkt_addmp(Bignum b
)
1176 p
= ssh2_mpint_fmt(b
, &len
);
1177 ssh2_pkt_addstring_start();
1178 ssh2_pkt_addstring_data(p
, len
);
1183 * Construct an SSH2 final-form packet: compress it, encrypt it,
1184 * put the MAC on it. Final packet, ready to be sent, is stored in
1185 * pktout.data. Total length is returned.
1187 static int ssh2_pkt_construct(void)
1189 int cipherblk
, maclen
, padding
, i
;
1190 static unsigned long outgoing_sequence
= 0;
1193 * Compress packet payload.
1196 debug(("Pre-compression payload:\n"));
1197 dmemdump(pktout
.data
+ 5, pktout
.length
- 5);
1200 unsigned char *newpayload
;
1202 if (cscomp
&& cscomp
->compress(pktout
.data
+ 5, pktout
.length
- 5,
1203 &newpayload
, &newlen
)) {
1205 ssh2_pkt_adddata(newpayload
, newlen
);
1211 * Add padding. At least four bytes, and must also bring total
1212 * length (minus MAC) up to a multiple of the block size.
1214 cipherblk
= cscipher ? cscipher
->blksize
: 8; /* block size */
1215 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1218 (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
1219 maclen
= csmac ? csmac
->len
: 0;
1220 ssh2_pkt_ensure(pktout
.length
+ padding
+ maclen
);
1221 pktout
.data
[4] = padding
;
1222 for (i
= 0; i
< padding
; i
++)
1223 pktout
.data
[pktout
.length
+ i
] = random_byte();
1224 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
1226 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
1228 outgoing_sequence
++; /* whether or not we MACed */
1231 debug(("Sending packet len=%d\n", pktout
.length
+ padding
));
1232 dmemdump(pktout
.data
, pktout
.length
+ padding
);
1236 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
1238 /* Ready-to-send packet starts at pktout.data. We return length. */
1239 return pktout
.length
+ padding
+ maclen
;
1243 * Construct and send an SSH2 packet immediately.
1245 static void ssh2_pkt_send(void)
1247 int len
= ssh2_pkt_construct();
1248 sk_write(s
, pktout
.data
, len
);
1252 * Construct an SSH2 packet and add it to a deferred data block.
1253 * Useful for sending multiple packets in a single sk_write() call,
1254 * to prevent a traffic-analysing listener from being able to work
1255 * out the length of any particular packet (such as the password
1258 * Note that because SSH2 sequence-numbers its packets, this can
1259 * NOT be used as an m4-style `defer' allowing packets to be
1260 * constructed in one order and sent in another.
1262 static void ssh2_pkt_defer(void)
1264 int len
= ssh2_pkt_construct();
1265 if (deferred_len
+ len
> deferred_size
) {
1266 deferred_size
= deferred_len
+ len
+ 128;
1267 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1269 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
1270 deferred_len
+= len
;
1274 * Send the whole deferred data block constructed by
1275 * ssh2_pkt_defer() or SSH1's defer_packet().
1277 static void ssh_pkt_defersend(void)
1279 sk_write(s
, deferred_send_data
, deferred_len
);
1280 deferred_len
= deferred_size
= 0;
1281 sfree(deferred_send_data
);
1282 deferred_send_data
= NULL
;
1286 void bndebug(char *string
, Bignum b
)
1290 p
= ssh2_mpint_fmt(b
, &len
);
1291 debug(("%s", string
));
1292 for (i
= 0; i
< len
; i
++)
1293 debug((" %02x", p
[i
]));
1299 static void sha_mpint(SHA_State
* s
, Bignum b
)
1303 p
= ssh2_mpint_fmt(b
, &len
);
1304 sha_string(s
, p
, len
);
1309 * SSH2 packet decode functions.
1311 static unsigned long ssh2_pkt_getuint32(void)
1313 unsigned long value
;
1314 if (pktin
.length
- pktin
.savedpos
< 4)
1315 return 0; /* arrgh, no way to decline (FIXME?) */
1316 value
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1317 pktin
.savedpos
+= 4;
1320 static int ssh2_pkt_getbool(void)
1322 unsigned long value
;
1323 if (pktin
.length
- pktin
.savedpos
< 1)
1324 return 0; /* arrgh, no way to decline (FIXME?) */
1325 value
= pktin
.data
[pktin
.savedpos
] != 0;
1329 static void ssh2_pkt_getstring(char **p
, int *length
)
1332 if (pktin
.length
- pktin
.savedpos
< 4)
1334 *length
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1335 pktin
.savedpos
+= 4;
1336 if (pktin
.length
- pktin
.savedpos
< *length
)
1338 *p
= pktin
.data
+ pktin
.savedpos
;
1339 pktin
.savedpos
+= *length
;
1341 static Bignum
ssh2_pkt_getmp(void)
1347 ssh2_pkt_getstring(&p
, &length
);
1351 bombout(("internal error: Can't handle negative mpints"));
1354 b
= bignum_from_bytes(p
, length
);
1359 * Examine the remote side's version string and compare it against
1360 * a list of known buggy implementations.
1362 static void ssh_detect_bugs(char *vstring
)
1364 char *imp
; /* pointer to implementation part */
1366 imp
+= strcspn(imp
, "-");
1369 imp
+= strcspn(imp
, "-");
1373 ssh_remote_bugs
= 0;
1375 if (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
1376 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
1377 !strcmp(imp
, "1.2.22")) {
1379 * These versions don't support SSH1_MSG_IGNORE, so we have
1380 * to use a different defence against password length
1383 ssh_remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
1384 logevent("We believe remote version has SSH1 ignore bug");
1387 if (!strncmp(imp
, "2.1.0", 5) || !strncmp(imp
, "2.0.", 4) ||
1388 !strncmp(imp
, "2.2.0", 5) || !strncmp(imp
, "2.3.0", 5) ||
1389 !strncmp(imp
, "2.1 ", 4)) {
1391 * These versions have the HMAC bug.
1393 ssh_remote_bugs
|= BUG_SSH2_HMAC
;
1394 logevent("We believe remote version has SSH2 HMAC bug");
1398 static int do_ssh_init(unsigned char c
)
1401 static char version
[10];
1402 static char *vstring
;
1403 static int vstrsize
;
1409 /* Search for the string "SSH-" in the input. */
1412 static const int transS
[] = { 1, 2, 2, 1 };
1413 static const int transH
[] = { 0, 0, 3, 0 };
1414 static const int transminus
[] = { 0, 0, 0, -1 };
1425 crReturn(1); /* get another character */
1428 vstring
= smalloc(16);
1430 strcpy(vstring
, "SSH-");
1434 crReturn(1); /* get another char */
1435 if (vslen
>= vstrsize
- 1) {
1437 vstring
= srealloc(vstring
, vstrsize
);
1439 vstring
[vslen
++] = c
;
1444 } else if (i
< sizeof(version
) - 1)
1446 } else if (c
== '\n')
1450 ssh_agentfwd_enabled
= FALSE
;
1451 rdpkt2_state
.incoming_sequence
= 0;
1454 vlog
= smalloc(20 + vslen
);
1455 sprintf(vlog
, "Server version: %s", vstring
);
1456 ssh_detect_bugs(vstring
);
1457 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1462 * Server version "1.99" means we can choose whether we use v1
1463 * or v2 protocol. Choice is based on cfg.sshprot.
1465 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1467 * This is a v2 server. Begin v2 protocol.
1469 char verstring
[80], vlog
[100];
1470 sprintf(verstring
, "SSH-2.0-%s", sshver
);
1471 SHA_Init(&exhashbase
);
1473 * Hash our version string and their version string.
1475 sha_string(&exhashbase
, verstring
, strlen(verstring
));
1476 sha_string(&exhashbase
, vstring
, strcspn(vstring
, "\r\n"));
1477 sprintf(vlog
, "We claim version: %s", verstring
);
1479 strcat(verstring
, "\n");
1480 logevent("Using SSH protocol version 2");
1481 sk_write(s
, verstring
, strlen(verstring
));
1482 ssh_protocol
= ssh2_protocol
;
1484 s_rdpkt
= ssh2_rdpkt
;
1487 * This is a v1 server. Begin v1 protocol.
1489 char verstring
[80], vlog
[100];
1490 sprintf(verstring
, "SSH-%s-%s",
1491 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"),
1493 sprintf(vlog
, "We claim version: %s", verstring
);
1495 strcat(verstring
, "\n");
1496 logevent("Using SSH protocol version 1");
1497 sk_write(s
, verstring
, strlen(verstring
));
1498 ssh_protocol
= ssh1_protocol
;
1500 s_rdpkt
= ssh1_rdpkt
;
1502 ssh_state
= SSH_STATE_BEFORE_SIZE
;
1509 static void ssh_gotdata(unsigned char *data
, int datalen
)
1514 * To begin with, feed the characters one by one to the
1515 * protocol initialisation / selection function do_ssh_init().
1516 * When that returns 0, we're done with the initial greeting
1517 * exchange and can move on to packet discipline.
1522 crReturnV
; /* more data please */
1523 ret
= do_ssh_init(*data
);
1531 * We emerge from that loop when the initial negotiation is
1532 * over and we have selected an s_rdpkt function. Now pass
1533 * everything to s_rdpkt, and then pass the resulting packets
1534 * to the proper protocol handler.
1539 while (datalen
> 0) {
1540 if (s_rdpkt(&data
, &datalen
) == 0) {
1541 ssh_protocol(NULL
, 0, 1);
1542 if (ssh_state
== SSH_STATE_CLOSED
) {
1552 static int ssh_closing(Plug plug
, char *error_msg
, int error_code
,
1555 ssh_state
= SSH_STATE_CLOSED
;
1561 /* A socket error has occurred. */
1562 connection_fatal(error_msg
);
1564 /* Otherwise, the remote side closed the connection normally. */
1569 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
1571 ssh_gotdata(data
, len
);
1572 if (ssh_state
== SSH_STATE_CLOSED
) {
1583 * Connect to specified host and port.
1584 * Returns an error message, or NULL on success.
1585 * Also places the canonical host name into `realhost'. It must be
1586 * freed by the caller.
1588 static char *connect_to_host(char *host
, int port
, char **realhost
)
1590 static struct plug_function_table fn_table
= {
1593 }, *fn_table_ptr
= &fn_table
;
1602 savedhost
= smalloc(1 + strlen(host
));
1604 fatalbox("Out of memory");
1605 strcpy(savedhost
, host
);
1608 port
= 22; /* default ssh port */
1621 addr
= sk_namelookup(host
, realhost
);
1622 if ((err
= sk_addr_error(addr
)))
1626 *realhost
= strdup(FWhost
);
1632 s
= sk_new(addr
, port
, 0, 1, &fn_table_ptr
);
1633 if ((err
= sk_socket_error(s
)))
1637 sk_write(s
, "connect ", 8);
1638 sk_write(s
, FWhost
, strlen(FWhost
));
1641 sprintf(buf
, " %d\n", FWport
);
1642 sk_write(s
, buf
, strlen(buf
));
1650 * Handle the key exchange and user authentication phases.
1652 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1656 static unsigned char *rsabuf
, *keystr1
, *keystr2
;
1657 unsigned char cookie
[8];
1658 struct RSAKey servkey
, hostkey
;
1659 struct MD5Context md5c
;
1660 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1661 static int tried_publickey
;
1662 static unsigned char session_id
[16];
1663 static int cipher_type
;
1664 static char username
[100];
1671 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1672 bombout(("Public key packet not received"));
1676 logevent("Received public keys");
1678 memcpy(cookie
, pktin
.body
, 8);
1680 i
= makekey(pktin
.body
+ 8, &servkey
, &keystr1
, 0);
1681 j
= makekey(pktin
.body
+ 8 + i
, &hostkey
, &keystr2
, 0);
1684 * Log the host key fingerprint.
1688 logevent("Host key fingerprint is:");
1689 strcpy(logmsg
, " ");
1690 hostkey
.comment
= NULL
;
1691 rsa_fingerprint(logmsg
+ strlen(logmsg
),
1692 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
1696 ssh1_remote_protoflags
= GET_32BIT(pktin
.body
+ 8 + i
+ j
);
1697 supported_ciphers_mask
= GET_32BIT(pktin
.body
+ 12 + i
+ j
);
1698 supported_auths_mask
= GET_32BIT(pktin
.body
+ 16 + i
+ j
);
1700 ssh1_local_protoflags
=
1701 ssh1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
1702 ssh1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
1705 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1706 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1707 MD5Update(&md5c
, pktin
.body
, 8);
1708 MD5Final(session_id
, &md5c
);
1710 for (i
= 0; i
< 32; i
++)
1711 session_key
[i
] = random_byte();
1713 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1715 rsabuf
= smalloc(len
);
1717 fatalbox("Out of memory");
1720 * Verify the host key.
1724 * First format the key into a string.
1726 int len
= rsastr_len(&hostkey
);
1727 char fingerprint
[100];
1728 char *keystr
= smalloc(len
);
1730 fatalbox("Out of memory");
1731 rsastr_fmt(keystr
, &hostkey
);
1732 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
1733 verify_ssh_host_key(savedhost
, savedport
, "rsa", keystr
,
1738 for (i
= 0; i
< 32; i
++) {
1739 rsabuf
[i
] = session_key
[i
];
1741 rsabuf
[i
] ^= session_id
[i
];
1744 if (hostkey
.bytes
> servkey
.bytes
) {
1745 rsaencrypt(rsabuf
, 32, &servkey
);
1746 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1748 rsaencrypt(rsabuf
, 32, &hostkey
);
1749 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1752 logevent("Encrypted session key");
1754 switch (cfg
.cipher
) {
1755 case CIPHER_BLOWFISH
:
1756 cipher_type
= SSH_CIPHER_BLOWFISH
;
1759 cipher_type
= SSH_CIPHER_DES
;
1762 cipher_type
= SSH_CIPHER_3DES
;
1765 c_write_str("AES not supported in SSH1, falling back to 3DES\r\n");
1766 cipher_type
= SSH_CIPHER_3DES
;
1769 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1771 ("Selected cipher not supported, falling back to 3DES\r\n");
1772 cipher_type
= SSH_CIPHER_3DES
;
1773 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1774 bombout(("Server violates SSH 1 protocol by "
1775 "not supporting 3DES encryption"));
1779 switch (cipher_type
) {
1780 case SSH_CIPHER_3DES
:
1781 logevent("Using 3DES encryption");
1783 case SSH_CIPHER_DES
:
1784 logevent("Using single-DES encryption");
1786 case SSH_CIPHER_BLOWFISH
:
1787 logevent("Using Blowfish encryption");
1791 send_packet(SSH1_CMSG_SESSION_KEY
,
1792 PKT_CHAR
, cipher_type
,
1793 PKT_DATA
, cookie
, 8,
1794 PKT_CHAR
, (len
* 8) >> 8, PKT_CHAR
, (len
* 8) & 0xFF,
1795 PKT_DATA
, rsabuf
, len
,
1796 PKT_INT
, ssh1_local_protoflags
, PKT_END
);
1798 logevent("Trying to enable encryption...");
1802 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
1803 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
: &ssh_3des
;
1804 cipher
->sesskey(session_key
);
1808 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1809 bombout(("Encryption not successfully enabled"));
1813 logevent("Successfully started encryption");
1819 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
1821 if (!ssh_get_line("login as: ",
1822 username
, sizeof(username
), FALSE
)) {
1824 * get_line failed to get a username.
1827 logevent("No username provided. Abandoning session.");
1828 ssh_state
= SSH_STATE_CLOSED
;
1832 c_write_str("login as: ");
1835 crWaitUntil(!ispkt
);
1837 switch (c
= *in
++) {
1846 c_write_str("\b \b");
1853 c_write_str("\b \b");
1863 if (((c
>= ' ' && c
<= '~') ||
1864 ((unsigned char) c
>= 160))
1865 && pos
< sizeof(username
)-1) {
1866 username
[pos
++] = c
;
1872 c_write_str("\r\n");
1873 username
[strcspn(username
, "\n\r")] = '\0';
1876 strncpy(username
, cfg
.username
, 99);
1877 username
[99] = '\0';
1880 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
1882 char userlog
[22 + sizeof(username
)];
1883 sprintf(userlog
, "Sent username \"%s\"", username
);
1885 if (flags
& FLAG_INTERACTIVE
&&
1886 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
1887 strcat(userlog
, "\r\n");
1888 c_write_str(userlog
);
1895 tried_publickey
= 0;
1897 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
1898 static char password
[100];
1899 static char prompt
[200];
1902 static int pwpkt_type
;
1904 * Show password prompt, having first obtained it via a TIS
1905 * or CryptoCard exchange if we're doing TIS or CryptoCard
1908 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
1909 if (agent_exists()) {
1911 * Attempt RSA authentication using Pageant.
1913 static unsigned char request
[5], *response
, *p
;
1914 static int responselen
;
1915 static int i
, nkeys
;
1916 static int authed
= FALSE
;
1919 logevent("Pageant is running. Requesting keys.");
1921 /* Request the keys held by the agent. */
1922 PUT_32BIT(request
, 1);
1923 request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
1924 agent_query(request
, 5, &r
, &responselen
);
1925 response
= (unsigned char *) r
;
1926 if (response
&& responselen
>= 5 &&
1927 response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
1929 nkeys
= GET_32BIT(p
);
1933 sprintf(buf
, "Pageant has %d SSH1 keys", nkeys
);
1936 for (i
= 0; i
< nkeys
; i
++) {
1937 static struct RSAKey key
;
1938 static Bignum challenge
;
1939 static char *commentp
;
1940 static int commentlen
;
1944 sprintf(buf
, "Trying Pageant key #%d", i
);
1948 p
+= ssh1_read_bignum(p
, &key
.exponent
);
1949 p
+= ssh1_read_bignum(p
, &key
.modulus
);
1950 commentlen
= GET_32BIT(p
);
1954 send_packet(SSH1_CMSG_AUTH_RSA
,
1955 PKT_BIGNUM
, key
.modulus
, PKT_END
);
1957 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1958 logevent("Key refused");
1961 logevent("Received RSA challenge");
1962 ssh1_read_bignum(pktin
.body
, &challenge
);
1964 char *agentreq
, *q
, *ret
;
1967 len
= 1 + 4; /* message type, bit count */
1968 len
+= ssh1_bignum_length(key
.exponent
);
1969 len
+= ssh1_bignum_length(key
.modulus
);
1970 len
+= ssh1_bignum_length(challenge
);
1971 len
+= 16; /* session id */
1972 len
+= 4; /* response format */
1973 agentreq
= smalloc(4 + len
);
1974 PUT_32BIT(agentreq
, len
);
1976 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
1977 PUT_32BIT(q
, bignum_bitcount(key
.modulus
));
1979 q
+= ssh1_write_bignum(q
, key
.exponent
);
1980 q
+= ssh1_write_bignum(q
, key
.modulus
);
1981 q
+= ssh1_write_bignum(q
, challenge
);
1982 memcpy(q
, session_id
, 16);
1984 PUT_32BIT(q
, 1); /* response format */
1985 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
1989 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
1990 logevent("Sending Pageant's response");
1991 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1992 PKT_DATA
, ret
+ 5, 16,
1996 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1998 ("Pageant's response accepted");
1999 if (flags
& FLAG_VERBOSE
) {
2001 ("Authenticated using RSA key \"");
2002 c_write(commentp
, commentlen
);
2003 c_write_str("\" from agent\r\n");
2008 ("Pageant's response not accepted");
2011 ("Pageant failed to answer challenge");
2015 logevent("No reply received from Pageant");
2018 freebn(key
.exponent
);
2019 freebn(key
.modulus
);
2028 if (*cfg
.keyfile
&& !tried_publickey
)
2029 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
2031 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
2033 (supported_auths_mask
& (1 << SSH1_AUTH_TIS
))) {
2034 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
2035 logevent("Requested TIS authentication");
2036 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
2038 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
2039 logevent("TIS authentication declined");
2040 if (flags
& FLAG_INTERACTIVE
)
2041 c_write_str("TIS authentication refused.\r\n");
2043 int challengelen
= ((pktin
.body
[0] << 24) |
2044 (pktin
.body
[1] << 16) |
2045 (pktin
.body
[2] << 8) |
2047 logevent("Received TIS challenge");
2048 if (challengelen
> sizeof(prompt
) - 1)
2049 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2050 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2051 prompt
[challengelen
] = '\0';
2054 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
2056 (supported_auths_mask
& (1 << SSH1_AUTH_CCARD
))) {
2057 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
2058 logevent("Requested CryptoCard authentication");
2059 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
2061 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
2062 logevent("CryptoCard authentication declined");
2063 c_write_str("CryptoCard authentication refused.\r\n");
2065 int challengelen
= ((pktin
.body
[0] << 24) |
2066 (pktin
.body
[1] << 16) |
2067 (pktin
.body
[2] << 8) |
2069 logevent("Received CryptoCard challenge");
2070 if (challengelen
> sizeof(prompt
) - 1)
2071 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2072 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2073 strncpy(prompt
+ challengelen
, "\r\nResponse : ",
2074 sizeof(prompt
) - challengelen
);
2075 prompt
[sizeof(prompt
) - 1] = '\0';
2078 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2079 sprintf(prompt
, "%.90s@%.90s's password: ",
2080 username
, savedhost
);
2082 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2083 char *comment
= NULL
;
2084 if (flags
& FLAG_VERBOSE
)
2085 c_write_str("Trying public key authentication.\r\n");
2086 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
2087 if (flags
& FLAG_VERBOSE
)
2088 c_write_str("No passphrase required.\r\n");
2091 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
2096 if (!ssh_get_line(prompt
, password
, sizeof(password
), TRUE
)) {
2098 * get_line failed to get a password (for example
2099 * because one was supplied on the command line
2100 * which has already failed to work). Terminate.
2102 send_packet(SSH1_MSG_DISCONNECT
,
2103 PKT_STR
, "No more passwords available to try",
2105 connection_fatal("Unable to authenticate");
2106 ssh_state
= SSH_STATE_CLOSED
;
2110 c_write_str(prompt
);
2114 crWaitUntil(!ispkt
);
2116 switch (c
= *in
++) {
2137 if (pos
< sizeof(password
)-1)
2138 password
[pos
++] = c
;
2142 c_write_str("\r\n");
2146 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2148 * Try public key authentication with the specified
2151 static struct RSAKey pubkey
;
2152 static Bignum challenge
, response
;
2154 static unsigned char buffer
[32];
2156 tried_publickey
= 1;
2157 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
2159 c_write_str("Couldn't load public key from ");
2160 c_write_str(cfg
.keyfile
);
2161 c_write_str(".\r\n");
2162 continue; /* go and try password */
2165 c_write_str("Wrong passphrase.\r\n");
2166 tried_publickey
= 0;
2167 continue; /* try again */
2171 * Send a public key attempt.
2173 send_packet(SSH1_CMSG_AUTH_RSA
,
2174 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
2177 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2178 c_write_str("Server refused our public key.\r\n");
2179 continue; /* go and try password */
2181 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2182 bombout(("Bizarre response to offer of public key"));
2185 ssh1_read_bignum(pktin
.body
, &challenge
);
2186 response
= rsadecrypt(challenge
, &pubkey
);
2187 freebn(pubkey
.private_exponent
); /* burn the evidence */
2189 for (i
= 0; i
< 32; i
++) {
2190 buffer
[i
] = bignum_byte(response
, 31 - i
);
2194 MD5Update(&md5c
, buffer
, 32);
2195 MD5Update(&md5c
, session_id
, 16);
2196 MD5Final(buffer
, &md5c
);
2198 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2199 PKT_DATA
, buffer
, 16, PKT_END
);
2202 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2203 if (flags
& FLAG_VERBOSE
)
2205 ("Failed to authenticate with our public key.\r\n");
2206 continue; /* go and try password */
2207 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2209 ("Bizarre response to RSA authentication response"));
2213 break; /* we're through! */
2215 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2217 * Defence against traffic analysis: we send a
2218 * whole bunch of packets containing strings of
2219 * different lengths. One of these strings is the
2220 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2221 * The others are all random data in
2222 * SSH1_MSG_IGNORE packets. This way a passive
2223 * listener can't tell which is the password, and
2224 * hence can't deduce the password length.
2226 * Anybody with a password length greater than 16
2227 * bytes is going to have enough entropy in their
2228 * password that a listener won't find it _that_
2229 * much help to know how long it is. So what we'll
2232 * - if password length < 16, we send 15 packets
2233 * containing string lengths 1 through 15
2235 * - otherwise, we let N be the nearest multiple
2236 * of 8 below the password length, and send 8
2237 * packets containing string lengths N through
2238 * N+7. This won't obscure the order of
2239 * magnitude of the password length, but it will
2240 * introduce a bit of extra uncertainty.
2242 * A few servers (the old 1.2.18 through 1.2.22)
2243 * can't deal with SSH1_MSG_IGNORE. For these
2244 * servers, we need an alternative defence. We make
2245 * use of the fact that the password is interpreted
2246 * as a C string: so we can append a NUL, then some
2249 if (ssh_remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
) {
2254 len
= strlen(password
);
2255 if (len
< sizeof(string
)) {
2257 strcpy(string
, password
);
2258 len
++; /* cover the zero byte */
2259 while (len
< sizeof(string
)) {
2260 string
[len
++] = (char) random_byte();
2265 send_packet(pwpkt_type
, PKT_INT
, len
,
2266 PKT_DATA
, s
, len
, PKT_END
);
2268 int bottom
, top
, pwlen
, i
;
2271 pwlen
= strlen(password
);
2273 bottom
= 0; /* zero length passwords are OK! :-) */
2276 bottom
= pwlen
& ~7;
2280 assert(pwlen
>= bottom
&& pwlen
<= top
);
2282 randomstr
= smalloc(top
+ 1);
2284 for (i
= bottom
; i
<= top
; i
++) {
2286 defer_packet(pwpkt_type
, PKT_STR
, password
,
2289 for (j
= 0; j
< i
; j
++) {
2291 randomstr
[j
] = random_byte();
2292 } while (randomstr
[j
] == '\0');
2294 randomstr
[i
] = '\0';
2295 defer_packet(SSH1_MSG_IGNORE
,
2296 PKT_STR
, randomstr
, PKT_END
);
2299 ssh_pkt_defersend();
2302 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
2305 logevent("Sent password");
2306 memset(password
, 0, strlen(password
));
2308 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2309 if (flags
& FLAG_VERBOSE
)
2310 c_write_str("Access denied\r\n");
2311 logevent("Authentication refused");
2312 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2313 logevent("Received disconnect request");
2314 ssh_state
= SSH_STATE_CLOSED
;
2316 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2317 bombout(("Strange packet received, type %d", pktin
.type
));
2322 logevent("Authentication successful");
2327 void sshfwd_close(struct ssh_channel
*c
)
2329 if (c
&& !c
->closes
) {
2330 if (ssh_version
== 1) {
2331 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
2334 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2335 ssh2_pkt_adduint32(c
->remoteid
);
2339 if (c
->type
== CHAN_X11
) {
2341 logevent("Forwarded X11 connection terminated");
2342 } else if (c
->type
== CHAN_SOCKDATA
) {
2344 logevent("Forwarded port closed");
2349 void sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
2351 if (ssh_version
== 1) {
2352 send_packet(SSH1_MSG_CHANNEL_DATA
,
2353 PKT_INT
, c
->remoteid
,
2354 PKT_INT
, len
, PKT_DATA
, buf
, len
, PKT_END
);
2356 ssh2_add_channel_data(c
, buf
, len
);
2361 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
)
2367 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
2370 if (ssh_state
== SSH_STATE_CLOSED
)
2373 if (cfg
.agentfwd
&& agent_exists()) {
2374 logevent("Requesting agent forwarding");
2375 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
2379 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2380 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2381 bombout(("Protocol confusion"));
2383 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2384 logevent("Agent forwarding refused");
2386 logevent("Agent forwarding enabled");
2387 ssh_agentfwd_enabled
= TRUE
;
2391 if (cfg
.x11_forward
) {
2392 char proto
[20], data
[64];
2393 logevent("Requesting X11 forwarding");
2394 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
2395 if (ssh1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
2396 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2397 PKT_STR
, proto
, PKT_STR
, data
,
2398 PKT_INT
, 0, PKT_END
);
2400 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2401 PKT_STR
, proto
, PKT_STR
, data
, PKT_END
);
2406 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2407 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2408 bombout(("Protocol confusion"));
2410 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2411 logevent("X11 forwarding refused");
2413 logevent("X11 forwarding enabled");
2414 ssh_X11_fwd_enabled
= TRUE
;
2422 char sports
[256], dports
[256], host
[256];
2425 ssh_rportfwds
= newtree234(ssh_rportcmp_ssh1
);
2426 /* Add port forwardings. */
2431 while (*e
&& *e
!= '\t')
2437 while (*e
&& *e
!= ':')
2447 dport
= atoi(dports
);
2448 sport
= atoi(sports
);
2449 if (sport
&& dport
) {
2451 pfd_addforward(host
, dport
, sport
);
2452 sprintf(buf
, "Local port %d forwarding to %s:%d",
2453 sport
, host
, dport
);
2456 struct ssh_rportfwd
*pf
;
2457 pf
= smalloc(sizeof(*pf
));
2458 strcpy(pf
->dhost
, host
);
2460 if (add234(ssh_rportfwds
, pf
) != pf
) {
2462 "Duplicate remote port forwarding to %s:%s",
2467 sprintf(buf
, "Requesting remote port %d forward to %s:%d",
2468 sport
, host
, dport
);
2470 send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST
,
2482 send_packet(SSH1_CMSG_REQUEST_PTY
,
2483 PKT_STR
, cfg
.termtype
,
2484 PKT_INT
, rows
, PKT_INT
, cols
,
2485 PKT_INT
, 0, PKT_INT
, 0, PKT_CHAR
, 0, PKT_END
);
2486 ssh_state
= SSH_STATE_INTERMED
;
2490 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2491 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2492 bombout(("Protocol confusion"));
2494 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2495 c_write_str("Server refused to allocate pty\r\n");
2496 ssh_editing
= ssh_echoing
= 1;
2498 logevent("Allocated pty");
2500 ssh_editing
= ssh_echoing
= 1;
2503 if (cfg
.compression
) {
2504 send_packet(SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
2508 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2509 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2510 bombout(("Protocol confusion"));
2512 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2513 c_write_str("Server refused to compress\r\n");
2515 logevent("Started compression");
2516 ssh1_compressing
= TRUE
;
2517 zlib_compress_init();
2518 zlib_decompress_init();
2521 if (*cfg
.remote_cmd_ptr
)
2522 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cfg
.remote_cmd_ptr
,
2525 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
2526 logevent("Started session");
2528 ssh_state
= SSH_STATE_SESSION
;
2532 ssh_special(TS_EOF
);
2534 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
2536 ssh_channels
= newtree234(ssh_channelcmp
);
2540 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
2541 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
2542 long len
= GET_32BIT(pktin
.body
);
2543 from_backend(pktin
.type
== SSH1_SMSG_STDERR_DATA
,
2544 pktin
.body
+ 4, len
);
2545 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2546 ssh_state
= SSH_STATE_CLOSED
;
2547 logevent("Received disconnect request");
2549 } else if (pktin
.type
== SSH1_SMSG_X11_OPEN
) {
2550 /* Remote side is trying to open a channel to talk to our
2551 * X-Server. Give them back a local channel number. */
2552 struct ssh_channel
*c
;
2554 logevent("Received X11 connect request");
2555 /* Refuse if X11 forwarding is disabled. */
2556 if (!ssh_X11_fwd_enabled
) {
2557 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2558 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2559 logevent("Rejected X11 connect request");
2561 c
= smalloc(sizeof(struct ssh_channel
));
2563 if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
2564 logevent("opening X11 forward connection failed");
2566 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2567 PKT_INT
, GET_32BIT(pktin
.body
),
2571 ("opening X11 forward connection succeeded");
2572 c
->remoteid
= GET_32BIT(pktin
.body
);
2573 c
->localid
= alloc_channel_id();
2575 c
->type
= CHAN_X11
; /* identify channel type */
2576 add234(ssh_channels
, c
);
2577 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2578 PKT_INT
, c
->remoteid
, PKT_INT
,
2579 c
->localid
, PKT_END
);
2580 logevent("Opened X11 forward channel");
2583 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
2584 /* Remote side is trying to open a channel to talk to our
2585 * agent. Give them back a local channel number. */
2586 struct ssh_channel
*c
;
2588 /* Refuse if agent forwarding is disabled. */
2589 if (!ssh_agentfwd_enabled
) {
2590 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2591 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2593 c
= smalloc(sizeof(struct ssh_channel
));
2594 c
->remoteid
= GET_32BIT(pktin
.body
);
2595 c
->localid
= alloc_channel_id();
2597 c
->type
= CHAN_AGENT
; /* identify channel type */
2598 c
->u
.a
.lensofar
= 0;
2599 add234(ssh_channels
, c
);
2600 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2601 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2604 } else if (pktin
.type
== SSH1_MSG_PORT_OPEN
) {
2605 /* Remote side is trying to open a channel to talk to a
2606 * forwarded port. Give them back a local channel number. */
2607 struct ssh_channel
*c
;
2608 struct ssh_rportfwd pf
;
2610 char host
[256], buf
[1024];
2612 c
= smalloc(sizeof(struct ssh_channel
));
2614 hostsize
= GET_32BIT(pktin
.body
+4);
2615 for(h
= host
, p
= pktin
.body
+8; hostsize
!= 0; hostsize
--) {
2616 if (h
+1 < host
+sizeof(host
))
2621 port
= GET_32BIT(p
);
2623 strcpy(pf
.dhost
, host
);
2626 if (find234(ssh_rportfwds
, &pf
, NULL
) == NULL
) {
2627 sprintf(buf
, "Rejected remote port open request for %s:%d",
2630 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2631 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2633 sprintf(buf
, "Received remote port open request for %s:%d",
2636 e
= pfd_newconnect(&c
->u
.pfd
.s
, host
, port
, c
);
2639 sprintf(buf
, "Port open failed: %s", e
);
2642 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2643 PKT_INT
, GET_32BIT(pktin
.body
),
2646 c
->remoteid
= GET_32BIT(pktin
.body
);
2647 c
->localid
= alloc_channel_id();
2649 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
2650 add234(ssh_channels
, c
);
2651 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2652 PKT_INT
, c
->remoteid
, PKT_INT
,
2653 c
->localid
, PKT_END
);
2654 logevent("Forwarded port opened successfully");
2658 } else if (pktin
.type
== SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
) {
2659 unsigned int remoteid
= GET_32BIT(pktin
.body
);
2660 unsigned int localid
= GET_32BIT(pktin
.body
+4);
2661 struct ssh_channel
*c
;
2663 c
= find234(ssh_channels
, &remoteid
, ssh_channelfind
);
2664 if (c
&& c
->type
== CHAN_SOCKDATA_DORMANT
) {
2665 c
->remoteid
= localid
;
2666 c
->type
= CHAN_SOCKDATA
;
2667 pfd_confirm(c
->u
.pfd
.s
);
2670 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
2671 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
2672 /* Remote side closes a channel. */
2673 unsigned i
= GET_32BIT(pktin
.body
);
2674 struct ssh_channel
*c
;
2675 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2679 (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
2680 if (!(c
->closes
& closetype
))
2681 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
,
2683 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
2684 logevent("Forwarded X11 connection terminated");
2685 assert(c
->u
.x11
.s
!= NULL
);
2686 x11_close(c
->u
.x11
.s
);
2689 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
2690 logevent("Forwarded port closed");
2691 assert(c
->u
.pfd
.s
!= NULL
);
2692 pfd_close(c
->u
.pfd
.s
);
2695 c
->closes
|= closetype
;
2696 if (c
->closes
== 3) {
2697 del234(ssh_channels
, c
);
2701 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
2702 /* Data sent down one of our channels. */
2703 int i
= GET_32BIT(pktin
.body
);
2704 int len
= GET_32BIT(pktin
.body
+ 4);
2705 unsigned char *p
= pktin
.body
+ 8;
2706 struct ssh_channel
*c
;
2707 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2711 x11_send(c
->u
.x11
.s
, p
, len
);
2714 pfd_send(c
->u
.pfd
.s
, p
, len
);
2717 /* Data for an agent message. Buffer it. */
2719 if (c
->u
.a
.lensofar
< 4) {
2720 int l
= min(4 - c
->u
.a
.lensofar
, len
);
2721 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
2725 c
->u
.a
.lensofar
+= l
;
2727 if (c
->u
.a
.lensofar
== 4) {
2729 4 + GET_32BIT(c
->u
.a
.msglen
);
2730 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
2731 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
2733 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
2735 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
2737 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
2741 c
->u
.a
.lensofar
+= l
;
2743 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
2744 void *reply
, *sentreply
;
2746 agent_query(c
->u
.a
.message
,
2747 c
->u
.a
.totallen
, &reply
,
2752 /* Fake SSH_AGENT_FAILURE. */
2753 sentreply
= "\0\0\0\1\5";
2756 send_packet(SSH1_MSG_CHANNEL_DATA
,
2757 PKT_INT
, c
->remoteid
,
2759 PKT_DATA
, sentreply
, replylen
,
2763 sfree(c
->u
.a
.message
);
2764 c
->u
.a
.lensofar
= 0;
2770 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2771 /* may be from EXEC_SHELL on some servers */
2772 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2773 /* may be from EXEC_SHELL on some servers
2774 * if no pty is available or in other odd cases. Ignore */
2775 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
2776 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
2778 bombout(("Strange packet received: type %d", pktin
.type
));
2783 int len
= min(inlen
, 512);
2784 send_packet(SSH1_CMSG_STDIN_DATA
,
2785 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
2796 * Utility routine for decoding comma-separated strings in KEXINIT.
2798 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
2800 int needlen
= strlen(needle
);
2803 * Is it at the start of the string?
2805 if (haylen
>= needlen
&& /* haystack is long enough */
2806 !memcmp(needle
, haystack
, needlen
) && /* initial match */
2807 (haylen
== needlen
|| haystack
[needlen
] == ',')
2808 /* either , or EOS follows */
2812 * If not, search for the next comma and resume after that.
2813 * If no comma found, terminate.
2815 while (haylen
> 0 && *haystack
!= ',')
2816 haylen
--, haystack
++;
2819 haylen
--, haystack
++; /* skip over comma itself */
2824 * SSH2 key creation method.
2826 static void ssh2_mkkey(Bignum K
, char *H
, char *sessid
, char chr
,
2830 /* First 20 bytes. */
2833 SHA_Bytes(&s
, H
, 20);
2834 SHA_Bytes(&s
, &chr
, 1);
2835 SHA_Bytes(&s
, sessid
, 20);
2836 SHA_Final(&s
, keyspace
);
2837 /* Next 20 bytes. */
2840 SHA_Bytes(&s
, H
, 20);
2841 SHA_Bytes(&s
, keyspace
, 20);
2842 SHA_Final(&s
, keyspace
+ 20);
2846 * Handle the SSH2 transport layer.
2848 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
2850 static int i
, j
, len
, nbits
, pbits
;
2852 static Bignum p
, g
, e
, f
, K
;
2853 static int kex_init_value
, kex_reply_value
;
2854 static const struct ssh_mac
**maclist
;
2856 static const struct ssh2_cipher
*cscipher_tobe
= NULL
;
2857 static const struct ssh2_cipher
*sccipher_tobe
= NULL
;
2858 static const struct ssh_mac
*csmac_tobe
= NULL
;
2859 static const struct ssh_mac
*scmac_tobe
= NULL
;
2860 static const struct ssh_compress
*cscomp_tobe
= NULL
;
2861 static const struct ssh_compress
*sccomp_tobe
= NULL
;
2862 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
2863 static int hostkeylen
, siglen
;
2864 static void *hkey
; /* actual host key */
2865 static unsigned char exchange_hash
[20];
2866 static unsigned char keyspace
[40];
2867 static const struct ssh2_ciphers
*preferred_cipher
;
2868 static const struct ssh_compress
*preferred_comp
;
2869 static int first_kex
;
2876 * Set up the preferred cipher and compression.
2878 if (cfg
.cipher
== CIPHER_BLOWFISH
) {
2879 preferred_cipher
= &ssh2_blowfish
;
2880 } else if (cfg
.cipher
== CIPHER_DES
) {
2881 logevent("Single DES not supported in SSH2; using 3DES");
2882 preferred_cipher
= &ssh2_3des
;
2883 } else if (cfg
.cipher
== CIPHER_3DES
) {
2884 preferred_cipher
= &ssh2_3des
;
2885 } else if (cfg
.cipher
== CIPHER_AES
) {
2886 preferred_cipher
= &ssh2_aes
;
2888 /* Shouldn't happen, but we do want to initialise to _something_. */
2889 preferred_cipher
= &ssh2_3des
;
2891 if (cfg
.compression
)
2892 preferred_comp
= &ssh_zlib
;
2894 preferred_comp
= &ssh_comp_none
;
2897 * Be prepared to work around the buggy MAC problem.
2899 if (cfg
.buggymac
|| (ssh_remote_bugs
& BUG_SSH2_HMAC
))
2900 maclist
= buggymacs
, nmacs
= lenof(buggymacs
);
2902 maclist
= macs
, nmacs
= lenof(macs
);
2906 * Construct and send our key exchange packet.
2908 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
2909 for (i
= 0; i
< 16; i
++)
2910 ssh2_pkt_addbyte((unsigned char) random_byte());
2911 /* List key exchange algorithms. */
2912 ssh2_pkt_addstring_start();
2913 for (i
= 0; i
< lenof(kex_algs
); i
++) {
2914 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
2915 if (i
< lenof(kex_algs
) - 1)
2916 ssh2_pkt_addstring_str(",");
2918 /* List server host key algorithms. */
2919 ssh2_pkt_addstring_start();
2920 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
2921 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
2922 if (i
< lenof(hostkey_algs
) - 1)
2923 ssh2_pkt_addstring_str(",");
2925 /* List client->server encryption algorithms. */
2926 ssh2_pkt_addstring_start();
2927 for (i
= 0; i
< lenof(ciphers
) + 1; i
++) {
2928 const struct ssh2_ciphers
*c
=
2929 i
== 0 ? preferred_cipher
: ciphers
[i
- 1];
2930 for (j
= 0; j
< c
->nciphers
; j
++) {
2931 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
2932 if (i
< lenof(ciphers
) || j
< c
->nciphers
- 1)
2933 ssh2_pkt_addstring_str(",");
2936 /* List server->client encryption algorithms. */
2937 ssh2_pkt_addstring_start();
2938 for (i
= 0; i
< lenof(ciphers
) + 1; i
++) {
2939 const struct ssh2_ciphers
*c
=
2940 i
== 0 ? preferred_cipher
: ciphers
[i
- 1];
2941 for (j
= 0; j
< c
->nciphers
; j
++) {
2942 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
2943 if (i
< lenof(ciphers
) || j
< c
->nciphers
- 1)
2944 ssh2_pkt_addstring_str(",");
2947 /* List client->server MAC algorithms. */
2948 ssh2_pkt_addstring_start();
2949 for (i
= 0; i
< nmacs
; i
++) {
2950 ssh2_pkt_addstring_str(maclist
[i
]->name
);
2952 ssh2_pkt_addstring_str(",");
2954 /* List server->client MAC algorithms. */
2955 ssh2_pkt_addstring_start();
2956 for (i
= 0; i
< nmacs
; i
++) {
2957 ssh2_pkt_addstring_str(maclist
[i
]->name
);
2959 ssh2_pkt_addstring_str(",");
2961 /* List client->server compression algorithms. */
2962 ssh2_pkt_addstring_start();
2963 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
2964 const struct ssh_compress
*c
=
2965 i
== 0 ? preferred_comp
: compressions
[i
- 1];
2966 ssh2_pkt_addstring_str(c
->name
);
2967 if (i
< lenof(compressions
))
2968 ssh2_pkt_addstring_str(",");
2970 /* List server->client compression algorithms. */
2971 ssh2_pkt_addstring_start();
2972 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
2973 const struct ssh_compress
*c
=
2974 i
== 0 ? preferred_comp
: compressions
[i
- 1];
2975 ssh2_pkt_addstring_str(c
->name
);
2976 if (i
< lenof(compressions
))
2977 ssh2_pkt_addstring_str(",");
2979 /* List client->server languages. Empty list. */
2980 ssh2_pkt_addstring_start();
2981 /* List server->client languages. Empty list. */
2982 ssh2_pkt_addstring_start();
2983 /* First KEX packet does _not_ follow, because we're not that brave. */
2984 ssh2_pkt_addbool(FALSE
);
2986 ssh2_pkt_adduint32(0);
2988 exhash
= exhashbase
;
2989 sha_string(&exhash
, pktout
.data
+ 5, pktout
.length
- 5);
2995 sha_string(&exhash
, pktin
.data
+ 5, pktin
.length
- 5);
2998 * Now examine the other side's KEXINIT to see what we're up
3001 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
3002 bombout(("expected key exchange packet from server"));
3007 cscipher_tobe
= NULL
;
3008 sccipher_tobe
= NULL
;
3013 pktin
.savedpos
+= 16; /* skip garbage cookie */
3014 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
3015 for (i
= 0; i
< lenof(kex_algs
); i
++) {
3016 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
3021 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
3022 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
3023 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
3024 hostkey
= hostkey_algs
[i
];
3028 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
3029 for (i
= 0; i
< lenof(ciphers
) + 1; i
++) {
3030 const struct ssh2_ciphers
*c
=
3031 i
== 0 ? preferred_cipher
: ciphers
[i
- 1];
3032 for (j
= 0; j
< c
->nciphers
; j
++) {
3033 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3034 cscipher_tobe
= c
->list
[j
];
3041 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
3042 for (i
= 0; i
< lenof(ciphers
) + 1; i
++) {
3043 const struct ssh2_ciphers
*c
=
3044 i
== 0 ? preferred_cipher
: ciphers
[i
- 1];
3045 for (j
= 0; j
< c
->nciphers
; j
++) {
3046 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3047 sccipher_tobe
= c
->list
[j
];
3054 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
3055 for (i
= 0; i
< nmacs
; i
++) {
3056 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3057 csmac_tobe
= maclist
[i
];
3061 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
3062 for (i
= 0; i
< nmacs
; i
++) {
3063 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3064 scmac_tobe
= maclist
[i
];
3068 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
3069 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3070 const struct ssh_compress
*c
=
3071 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3072 if (in_commasep_string(c
->name
, str
, len
)) {
3077 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
3078 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3079 const struct ssh_compress
*c
=
3080 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3081 if (in_commasep_string(c
->name
, str
, len
)) {
3088 * Work out the number of bits of key we will need from the key
3089 * exchange. We start with the maximum key length of either
3095 csbits
= cscipher_tobe
->keylen
;
3096 scbits
= sccipher_tobe
->keylen
;
3097 nbits
= (csbits
> scbits ? csbits
: scbits
);
3099 /* The keys only have 160-bit entropy, since they're based on
3100 * a SHA-1 hash. So cap the key size at 160 bits. */
3105 * If we're doing Diffie-Hellman group exchange, start by
3106 * requesting a group.
3108 if (kex
== &ssh_diffiehellman_gex
) {
3109 logevent("Doing Diffie-Hellman group exchange");
3111 * Work out how big a DH group we will need to allow that
3114 pbits
= 512 << ((nbits
- 1) / 64);
3115 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
3116 ssh2_pkt_adduint32(pbits
);
3120 if (pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
3121 bombout(("expected key exchange group packet from server"));
3124 p
= ssh2_pkt_getmp();
3125 g
= ssh2_pkt_getmp();
3126 dh_setup_group(p
, g
);
3127 kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
3128 kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
3131 kex_init_value
= SSH2_MSG_KEXDH_INIT
;
3132 kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
3135 logevent("Doing Diffie-Hellman key exchange");
3137 * Now generate and send e for Diffie-Hellman.
3139 e
= dh_create_e(nbits
* 2);
3140 ssh2_pkt_init(kex_init_value
);
3145 if (pktin
.type
!= kex_reply_value
) {
3146 bombout(("expected key exchange reply packet from server"));
3149 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
3150 f
= ssh2_pkt_getmp();
3151 ssh2_pkt_getstring(&sigdata
, &siglen
);
3155 sha_string(&exhash
, hostkeydata
, hostkeylen
);
3156 if (kex
== &ssh_diffiehellman_gex
) {
3157 sha_uint32(&exhash
, pbits
);
3158 sha_mpint(&exhash
, p
);
3159 sha_mpint(&exhash
, g
);
3161 sha_mpint(&exhash
, e
);
3162 sha_mpint(&exhash
, f
);
3163 sha_mpint(&exhash
, K
);
3164 SHA_Final(&exhash
, exchange_hash
);
3169 debug(("Exchange hash is:\n"));
3170 dmemdump(exchange_hash
, 20);
3173 hkey
= hostkey
->newkey(hostkeydata
, hostkeylen
);
3175 !hostkey
->verifysig(hkey
, sigdata
, siglen
, exchange_hash
, 20)) {
3176 bombout(("Server's host key did not match the signature supplied"));
3181 * Expect SSH2_MSG_NEWKEYS from server.
3184 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
3185 bombout(("expected new-keys packet from server"));
3190 * Authenticate remote host: verify host key. (We've already
3191 * checked the signature of the exchange hash.)
3193 keystr
= hostkey
->fmtkey(hkey
);
3194 fingerprint
= hostkey
->fingerprint(hkey
);
3195 verify_ssh_host_key(savedhost
, savedport
, hostkey
->keytype
,
3196 keystr
, fingerprint
);
3197 if (first_kex
) { /* don't bother logging this in rekeys */
3198 logevent("Host key fingerprint is:");
3199 logevent(fingerprint
);
3203 hostkey
->freekey(hkey
);
3206 * Send SSH2_MSG_NEWKEYS.
3208 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
3212 * Create and initialise session keys.
3214 cscipher
= cscipher_tobe
;
3215 sccipher
= sccipher_tobe
;
3218 cscomp
= cscomp_tobe
;
3219 sccomp
= sccomp_tobe
;
3220 cscomp
->compress_init();
3221 sccomp
->decompress_init();
3223 * Set IVs after keys. Here we use the exchange hash from the
3224 * _first_ key exchange.
3227 memcpy(ssh2_session_id
, exchange_hash
, sizeof(exchange_hash
));
3228 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'C', keyspace
);
3229 cscipher
->setcskey(keyspace
);
3230 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'D', keyspace
);
3231 sccipher
->setsckey(keyspace
);
3232 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'A', keyspace
);
3233 cscipher
->setcsiv(keyspace
);
3234 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'B', keyspace
);
3235 sccipher
->setsciv(keyspace
);
3236 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'E', keyspace
);
3237 csmac
->setcskey(keyspace
);
3238 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'F', keyspace
);
3239 scmac
->setsckey(keyspace
);
3242 * If this is the first key exchange phase, we must pass the
3243 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
3244 * wants to see it but because it will need time to initialise
3245 * itself before it sees an actual packet. In subsequent key
3246 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
3247 * it would only confuse the layer above.
3255 * Now we're encrypting. Begin returning 1 to the protocol main
3256 * function so that other things can run on top of the
3257 * transport. If we ever see a KEXINIT, we must go back to the
3260 while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
)) {
3263 logevent("Server initiated key re-exchange");
3264 goto begin_key_exchange
;
3270 * Add data to an SSH2 channel output buffer.
3272 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
3275 if (c
->v2
.outbufsize
< c
->v2
.outbuflen
+ len
) {
3276 c
->v2
.outbufsize
= c
->v2
.outbuflen
+ len
+ 1024;
3277 c
->v2
.outbuffer
= srealloc(c
->v2
.outbuffer
, c
->v2
.outbufsize
);
3279 memcpy(c
->v2
.outbuffer
+ c
->v2
.outbuflen
, buf
, len
);
3280 c
->v2
.outbuflen
+= len
;
3284 * Attempt to send data on an SSH2 channel.
3286 static void ssh2_try_send(struct ssh_channel
*c
)
3288 while (c
->v2
.remwindow
> 0 && c
->v2
.outbuflen
> 0) {
3289 unsigned len
= c
->v2
.remwindow
;
3290 if (len
> c
->v2
.outbuflen
)
3291 len
= c
->v2
.outbuflen
;
3292 if (len
> c
->v2
.remmaxpkt
)
3293 len
= c
->v2
.remmaxpkt
;
3294 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
3295 ssh2_pkt_adduint32(c
->remoteid
);
3296 ssh2_pkt_addstring_start();
3297 ssh2_pkt_addstring_data(c
->v2
.outbuffer
, len
);
3299 c
->v2
.outbuflen
-= len
;
3300 memmove(c
->v2
.outbuffer
, c
->v2
.outbuffer
+ len
, c
->v2
.outbuflen
);
3301 c
->v2
.remwindow
-= len
;
3306 * Handle the SSH2 userauth and connection layers.
3308 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
3311 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
,
3313 AUTH_KEYBOARD_INTERACTIVE
3317 AUTH_TYPE_PUBLICKEY
,
3318 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
3319 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
3321 AUTH_TYPE_KEYBOARD_INTERACTIVE
3323 static int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
3324 static int tried_pubkey_config
, tried_agent
, tried_keyb_inter
;
3325 static int we_are_in
;
3326 static int num_prompts
, echo
;
3327 static char username
[100];
3328 static char pwprompt
[200];
3329 static char password
[100];
3334 * Request userauth protocol, and await a response to it.
3336 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
3337 ssh2_pkt_addstring("ssh-userauth");
3339 crWaitUntilV(ispkt
);
3340 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
3341 bombout(("Server refused user authentication protocol"));
3346 * We repeat this whole loop, including the username prompt,
3347 * until we manage a successful authentication. If the user
3348 * types the wrong _password_, they are sent back to the
3349 * beginning to try another username. (If they specify a
3350 * username in the config, they are never asked, even if they
3351 * do give a wrong password.)
3353 * I think this best serves the needs of
3355 * - the people who have no configuration, no keys, and just
3356 * want to try repeated (username,password) pairs until they
3357 * type both correctly
3359 * - people who have keys and configuration but occasionally
3360 * need to fall back to passwords
3362 * - people with a key held in Pageant, who might not have
3363 * logged in to a particular machine before; so they want to
3364 * type a username, and then _either_ their key will be
3365 * accepted, _or_ they will type a password. If they mistype
3366 * the username they will want to be able to get back and
3377 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
3379 if (!ssh_get_line("login as: ",
3380 username
, sizeof(username
), FALSE
)) {
3382 * get_line failed to get a username.
3385 logevent("No username provided. Abandoning session.");
3386 ssh_state
= SSH_STATE_CLOSED
;
3390 c_write_str("login as: ");
3393 crWaitUntilV(!ispkt
);
3395 switch (c
= *in
++) {
3404 c_write_str("\b \b");
3411 c_write_str("\b \b");
3421 if (((c
>= ' ' && c
<= '~') ||
3422 ((unsigned char) c
>= 160))
3423 && pos
< sizeof(username
)-1) {
3424 username
[pos
++] = c
;
3431 c_write_str("\r\n");
3432 username
[strcspn(username
, "\n\r")] = '\0';
3435 strncpy(username
, cfg
.username
, 99);
3436 username
[99] = '\0';
3437 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
3438 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
3444 * Send an authentication request using method "none": (a)
3445 * just in case it succeeds, and (b) so that we know what
3446 * authentication methods we can usefully try next.
3448 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3449 ssh2_pkt_addstring(username
);
3450 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3451 ssh2_pkt_addstring("none"); /* method */
3453 type
= AUTH_TYPE_NONE
;
3457 tried_pubkey_config
= FALSE
;
3458 tried_agent
= FALSE
;
3462 * Wait for the result of the last authentication request.
3465 crWaitUntilV(ispkt
);
3466 while (pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
3470 * Don't show the banner if we're operating in
3471 * non-verbose non-interactive mode. (It's probably
3472 * a script, which means nobody will read the
3473 * banner _anyway_, and moreover the printing of
3474 * the banner will screw up processing on the
3475 * output of (say) plink.)
3477 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
3478 ssh2_pkt_getstring(&banner
, &size
);
3480 c_write_untrusted(banner
, size
);
3482 crWaitUntilV(ispkt
);
3484 if (pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
3485 logevent("Access granted");
3490 if (pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
3492 ("Strange packet received during authentication: type %d",
3500 * OK, we're now sitting on a USERAUTH_FAILURE message, so
3501 * we can look at the string in it and know what we can
3502 * helpfully try next.
3507 ssh2_pkt_getstring(&methods
, &methlen
);
3508 if (!ssh2_pkt_getbool()) {
3510 * We have received an unequivocal Access
3511 * Denied. This can translate to a variety of
3514 * - if we'd just tried "none" authentication,
3515 * it's not worth printing anything at all
3517 * - if we'd just tried a public key _offer_,
3518 * the message should be "Server refused our
3519 * key" (or no message at all if the key
3520 * came from Pageant)
3522 * - if we'd just tried anything else, the
3523 * message really should be "Access denied".
3525 * Additionally, if we'd just tried password
3526 * authentication, we should break out of this
3527 * whole loop so as to go back to the username
3530 if (type
== AUTH_TYPE_NONE
) {
3532 } else if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
3533 type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
3534 if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
3535 c_write_str("Server refused our key\r\n");
3536 logevent("Server refused public key");
3538 c_write_str("Access denied\r\n");
3539 logevent("Access denied");
3540 if (type
== AUTH_TYPE_PASSWORD
) {
3546 c_write_str("Further authentication required\r\n");
3547 logevent("Further authentication required");
3551 in_commasep_string("publickey", methods
, methlen
);
3553 in_commasep_string("password", methods
, methlen
);
3555 in_commasep_string("password", methods
, methlen
);
3557 in_commasep_string("keyboard-interactive", methods
, methlen
);
3562 if (!method
&& can_keyb_inter
&& !tried_keyb_inter
) {
3563 method
= AUTH_KEYBOARD_INTERACTIVE
;
3564 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
3565 tried_keyb_inter
= TRUE
;
3567 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3568 ssh2_pkt_addstring(username
);
3569 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3570 ssh2_pkt_addstring("keyboard-interactive"); /* method */
3571 ssh2_pkt_addstring(""); /* lang */
3572 ssh2_pkt_addstring("");
3575 crWaitUntilV(ispkt
);
3576 if (pktin
.type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
3577 if (pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
)
3579 logevent("Keyboard-interactive authentication refused");
3580 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
3584 /* We've got packet with that "interactive" info
3585 dump banners, and set its prompt as ours */
3587 char *name
, *inst
, *lang
, *prompt
;
3588 int name_len
, inst_len
, lang_len
, prompt_len
;
3589 ssh2_pkt_getstring(&name
, &name_len
);
3590 ssh2_pkt_getstring(&inst
, &inst_len
);
3591 ssh2_pkt_getstring(&lang
, &lang_len
);
3593 c_write_untrusted(name
, name_len
);
3595 c_write_untrusted(inst
, inst_len
);
3596 num_prompts
= ssh2_pkt_getuint32();
3598 ssh2_pkt_getstring(&prompt
, &prompt_len
);
3599 strncpy(pwprompt
, prompt
, sizeof(pwprompt
));
3602 echo
= ssh2_pkt_getbool();
3606 if (!method
&& can_pubkey
&& agent_exists() && !tried_agent
) {
3608 * Attempt public-key authentication using Pageant.
3610 static unsigned char request
[5], *response
, *p
;
3611 static int responselen
;
3612 static int i
, nkeys
;
3613 static int authed
= FALSE
;
3618 logevent("Pageant is running. Requesting keys.");
3620 /* Request the keys held by the agent. */
3621 PUT_32BIT(request
, 1);
3622 request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
3623 agent_query(request
, 5, &r
, &responselen
);
3624 response
= (unsigned char *) r
;
3625 if (response
&& responselen
>= 5 &&
3626 response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
3628 nkeys
= GET_32BIT(p
);
3632 sprintf(buf
, "Pageant has %d SSH2 keys", nkeys
);
3635 for (i
= 0; i
< nkeys
; i
++) {
3636 static char *pkblob
, *alg
, *commentp
;
3637 static int pklen
, alglen
, commentlen
;
3638 static int siglen
, retlen
, len
;
3639 static char *q
, *agentreq
, *ret
;
3644 sprintf(buf
, "Trying Pageant key #%d", i
);
3647 pklen
= GET_32BIT(p
);
3651 alglen
= GET_32BIT(pkblob
);
3653 commentlen
= GET_32BIT(p
);
3657 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3658 ssh2_pkt_addstring(username
);
3659 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3660 ssh2_pkt_addstring("publickey"); /* method */
3661 ssh2_pkt_addbool(FALSE
); /* no signature included */
3662 ssh2_pkt_addstring_start();
3663 ssh2_pkt_addstring_data(alg
, alglen
);
3664 ssh2_pkt_addstring_start();
3665 ssh2_pkt_addstring_data(pkblob
, pklen
);
3668 crWaitUntilV(ispkt
);
3669 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3670 logevent("Key refused");
3674 if (flags
& FLAG_VERBOSE
) {
3676 ("Authenticating with public key \"");
3677 c_write(commentp
, commentlen
);
3678 c_write_str("\" from agent\r\n");
3682 * Server is willing to accept the key.
3683 * Construct a SIGN_REQUEST.
3685 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3686 ssh2_pkt_addstring(username
);
3687 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3688 ssh2_pkt_addstring("publickey"); /* method */
3689 ssh2_pkt_addbool(TRUE
);
3690 ssh2_pkt_addstring_start();
3691 ssh2_pkt_addstring_data(alg
, alglen
);
3692 ssh2_pkt_addstring_start();
3693 ssh2_pkt_addstring_data(pkblob
, pklen
);
3695 siglen
= pktout
.length
- 5 + 4 + 20;
3696 len
= 1; /* message type */
3697 len
+= 4 + pklen
; /* key blob */
3698 len
+= 4 + siglen
; /* data to sign */
3699 len
+= 4; /* flags */
3700 agentreq
= smalloc(4 + len
);
3701 PUT_32BIT(agentreq
, len
);
3703 *q
++ = SSH2_AGENTC_SIGN_REQUEST
;
3704 PUT_32BIT(q
, pklen
);
3706 memcpy(q
, pkblob
, pklen
);
3708 PUT_32BIT(q
, siglen
);
3710 /* Now the data to be signed... */
3713 memcpy(q
, ssh2_session_id
, 20);
3715 memcpy(q
, pktout
.data
+ 5, pktout
.length
- 5);
3716 q
+= pktout
.length
- 5;
3717 /* And finally the (zero) flags word. */
3719 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
3723 if (ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
3724 logevent("Sending Pageant's response");
3725 ssh2_pkt_addstring_start();
3726 ssh2_pkt_addstring_data(ret
+ 9,
3734 ("Pageant failed to answer challenge");
3744 if (!method
&& can_pubkey
&& *cfg
.keyfile
3745 && !tried_pubkey_config
) {
3746 unsigned char *pub_blob
;
3747 char *algorithm
, *comment
;
3750 tried_pubkey_config
= TRUE
;
3753 * Try the public key supplied in the configuration.
3755 * First, offer the public blob to see if the server is
3756 * willing to accept it.
3758 pub_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, &algorithm
,
3761 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3762 ssh2_pkt_addstring(username
);
3763 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3764 ssh2_pkt_addstring("publickey"); /* method */
3765 ssh2_pkt_addbool(FALSE
); /* no signature included */
3766 ssh2_pkt_addstring(algorithm
);
3767 ssh2_pkt_addstring_start();
3768 ssh2_pkt_addstring_data(pub_blob
, pub_blob_len
);
3770 logevent("Offered public key"); /* FIXME */
3772 crWaitUntilV(ispkt
);
3773 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3775 type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
3776 continue; /* key refused; give up on it */
3779 logevent("Offer of public key accepted");
3781 * Actually attempt a serious authentication using
3784 if (ssh2_userkey_encrypted(cfg
.keyfile
, &comment
)) {
3786 "Passphrase for key \"%.100s\": ",
3792 c_write_str("Authenticating with public key \"");
3793 c_write_str(comment
);
3794 c_write_str("\"\r\n");
3795 method
= AUTH_PUBLICKEY_FILE
;
3799 if (!method
&& can_passwd
) {
3800 method
= AUTH_PASSWORD
;
3801 sprintf(pwprompt
, "%.90s@%.90s's password: ", username
,
3808 if (!ssh_get_line(pwprompt
, password
,
3809 sizeof(password
), TRUE
)) {
3811 * get_line failed to get a password (for
3812 * example because one was supplied on the
3813 * command line which has already failed to
3816 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3817 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
3819 ("No more passwords available to try");
3820 ssh2_pkt_addstring("en"); /* language tag */
3822 connection_fatal("Unable to authenticate");
3823 ssh_state
= SSH_STATE_CLOSED
;
3830 c_write_untrusted(pwprompt
, strlen(pwprompt
));
3835 crWaitUntilV(!ispkt
);
3837 switch (c
= *in
++) {
3858 if (pos
< sizeof(password
)-1)
3859 password
[pos
++] = c
;
3863 c_write_str("\r\n");
3867 if (method
== AUTH_PUBLICKEY_FILE
) {
3869 * We have our passphrase. Now try the actual authentication.
3871 struct ssh2_userkey
*key
;
3873 key
= ssh2_load_userkey(cfg
.keyfile
, password
);
3874 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
3875 if (key
== SSH2_WRONG_PASSPHRASE
) {
3876 c_write_str("Wrong passphrase\r\n");
3877 tried_pubkey_config
= FALSE
;
3879 c_write_str("Unable to load private key\r\n");
3880 tried_pubkey_config
= TRUE
;
3882 /* Send a spurious AUTH_NONE to return to the top. */
3883 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3884 ssh2_pkt_addstring(username
);
3885 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3886 ssh2_pkt_addstring("none"); /* method */
3888 type
= AUTH_TYPE_NONE
;
3890 unsigned char *blob
, *sigdata
;
3891 int blob_len
, sigdata_len
;
3894 * We have loaded the private key and the server
3895 * has announced that it's willing to accept it.
3896 * Hallelujah. Generate a signature and send it.
3898 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3899 ssh2_pkt_addstring(username
);
3900 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3901 ssh2_pkt_addstring("publickey"); /* method */
3902 ssh2_pkt_addbool(TRUE
);
3903 ssh2_pkt_addstring(key
->alg
->name
);
3904 blob
= key
->alg
->public_blob(key
->data
, &blob_len
);
3905 ssh2_pkt_addstring_start();
3906 ssh2_pkt_addstring_data(blob
, blob_len
);
3910 * The data to be signed is:
3914 * followed by everything so far placed in the
3917 sigdata_len
= pktout
.length
- 5 + 4 + 20;
3918 sigdata
= smalloc(sigdata_len
);
3919 PUT_32BIT(sigdata
, 20);
3920 memcpy(sigdata
+ 4, ssh2_session_id
, 20);
3921 memcpy(sigdata
+ 24, pktout
.data
+ 5,
3924 key
->alg
->sign(key
->data
, sigdata
, sigdata_len
,
3926 ssh2_pkt_addstring_start();
3927 ssh2_pkt_addstring_data(blob
, blob_len
);
3932 type
= AUTH_TYPE_PUBLICKEY
;
3934 } else if (method
== AUTH_PASSWORD
) {
3936 * We send the password packet lumped tightly together with
3937 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
3938 * string long enough to make the total length of the two
3939 * packets constant. This should ensure that a passive
3940 * listener doing traffic analyis can't work out the length
3943 * For this to work, we need an assumption about the
3944 * maximum length of the password packet. I think 256 is
3945 * pretty conservative. Anyone using a password longer than
3946 * that probably doesn't have much to worry about from
3947 * people who find out how long their password is!
3949 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3950 ssh2_pkt_addstring(username
);
3951 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3952 ssh2_pkt_addstring("password");
3953 ssh2_pkt_addbool(FALSE
);
3954 ssh2_pkt_addstring(password
);
3957 * We'll include a string that's an exact multiple of the
3958 * cipher block size. If the cipher is NULL for some
3959 * reason, we don't do this trick at all because we gain
3965 stringlen
= (256 - deferred_len
);
3966 stringlen
+= cscipher
->blksize
- 1;
3967 stringlen
-= (stringlen
% cscipher
->blksize
);
3970 * Temporarily disable actual compression,
3971 * so we can guarantee to get this string
3972 * exactly the length we want it. The
3973 * compression-disabling routine should
3974 * return an integer indicating how many
3975 * bytes we should adjust our string length
3978 stringlen
-= cscomp
->disable_compression();
3980 ssh2_pkt_init(SSH2_MSG_IGNORE
);
3981 ssh2_pkt_addstring_start();
3982 for (i
= 0; i
< stringlen
; i
++) {
3983 char c
= (char) random_byte();
3984 ssh2_pkt_addstring_data(&c
, 1);
3988 ssh_pkt_defersend();
3989 logevent("Sent password");
3990 type
= AUTH_TYPE_PASSWORD
;
3991 } else if (method
== AUTH_KEYBOARD_INTERACTIVE
) {
3992 ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE
);
3993 ssh2_pkt_adduint32(num_prompts
);
3994 ssh2_pkt_addstring(password
);
3995 memset(password
, 0, sizeof(password
));
3997 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
4000 ("No supported authentication methods left to try!\r\n");
4002 ("No supported authentications offered. Disconnecting");
4003 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4004 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4006 ("No supported authentication methods available");
4007 ssh2_pkt_addstring("en"); /* language tag */
4009 ssh_state
= SSH_STATE_CLOSED
;
4013 } while (!we_are_in
);
4016 * Now we're authenticated for the connection protocol. The
4017 * connection protocol will automatically have started at this
4018 * point; there's no need to send SERVICE_REQUEST.
4022 * So now create a channel with a session in it.
4024 ssh_channels
= newtree234(ssh_channelcmp
);
4025 mainchan
= smalloc(sizeof(struct ssh_channel
));
4026 mainchan
->localid
= alloc_channel_id();
4027 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
4028 ssh2_pkt_addstring("session");
4029 ssh2_pkt_adduint32(mainchan
->localid
);
4030 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
4031 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
4033 crWaitUntilV(ispkt
);
4034 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
4035 bombout(("Server refused to open a session"));
4037 /* FIXME: error data comes back in FAILURE packet */
4039 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
4040 bombout(("Server's channel confirmation cited wrong channel"));
4043 mainchan
->remoteid
= ssh2_pkt_getuint32();
4044 mainchan
->type
= CHAN_MAINSESSION
;
4045 mainchan
->closes
= 0;
4046 mainchan
->v2
.remwindow
= ssh2_pkt_getuint32();
4047 mainchan
->v2
.remmaxpkt
= ssh2_pkt_getuint32();
4048 mainchan
->v2
.outbuffer
= NULL
;
4049 mainchan
->v2
.outbuflen
= mainchan
->v2
.outbufsize
= 0;
4050 add234(ssh_channels
, mainchan
);
4051 logevent("Opened channel for session");
4054 * Potentially enable X11 forwarding.
4056 if (cfg
.x11_forward
) {
4057 char proto
[20], data
[64];
4058 logevent("Requesting X11 forwarding");
4059 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
4060 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4061 ssh2_pkt_adduint32(mainchan
->remoteid
);
4062 ssh2_pkt_addstring("x11-req");
4063 ssh2_pkt_addbool(1); /* want reply */
4064 ssh2_pkt_addbool(0); /* many connections */
4065 ssh2_pkt_addstring(proto
);
4066 ssh2_pkt_addstring(data
);
4067 ssh2_pkt_adduint32(0); /* screen number */
4071 crWaitUntilV(ispkt
);
4072 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4073 unsigned i
= ssh2_pkt_getuint32();
4074 struct ssh_channel
*c
;
4075 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4077 continue; /* nonexistent channel */
4078 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
4080 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4082 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4083 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4084 bombout(("Server got confused by X11 forwarding request"));
4087 logevent("X11 forwarding refused");
4089 logevent("X11 forwarding enabled");
4090 ssh_X11_fwd_enabled
= TRUE
;
4095 * Enable port forwardings.
4098 static char *e
; /* preserve across crReturn */
4102 char sports
[256], dports
[256], host
[256];
4105 ssh_rportfwds
= newtree234(ssh_rportcmp_ssh2
);
4106 /* Add port forwardings. */
4111 while (*e
&& *e
!= '\t')
4117 while (*e
&& *e
!= ':')
4127 dport
= atoi(dports
);
4128 sport
= atoi(sports
);
4129 if (sport
&& dport
) {
4131 pfd_addforward(host
, dport
, sport
);
4132 sprintf(buf
, "Local port %d forwarding to %s:%d",
4133 sport
, host
, dport
);
4136 struct ssh_rportfwd
*pf
;
4137 pf
= smalloc(sizeof(*pf
));
4138 strcpy(pf
->dhost
, host
);
4141 if (add234(ssh_rportfwds
, pf
) != pf
) {
4143 "Duplicate remote port forwarding to %s:%s",
4148 sprintf(buf
, "Requesting remote port %d (forwarded to %s:%d)",
4149 sport
, host
, dport
);
4151 ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST
);
4152 ssh2_pkt_addstring("tcpip-forward");
4153 ssh2_pkt_addbool(1);/* want reply */
4154 ssh2_pkt_addstring("127.0.0.1");
4155 ssh2_pkt_adduint32(sport
);
4159 crWaitUntilV(ispkt
);
4160 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4161 unsigned i
= ssh2_pkt_getuint32();
4162 struct ssh_channel
*c
;
4163 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4165 continue;/* nonexistent channel */
4166 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
4168 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4170 if (pktin
.type
!= SSH2_MSG_REQUEST_SUCCESS
) {
4171 if (pktin
.type
!= SSH2_MSG_REQUEST_FAILURE
) {
4172 bombout(("Server got confused by port forwarding request"));
4175 logevent("Server refused this port forwarding");
4177 logevent("Remote port forwarding enabled");
4186 * Potentially enable agent forwarding.
4188 if (cfg
.agentfwd
&& agent_exists()) {
4189 logevent("Requesting OpenSSH-style agent forwarding");
4190 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4191 ssh2_pkt_adduint32(mainchan
->remoteid
);
4192 ssh2_pkt_addstring("auth-agent-req@openssh.com");
4193 ssh2_pkt_addbool(1); /* want reply */
4197 crWaitUntilV(ispkt
);
4198 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4199 unsigned i
= ssh2_pkt_getuint32();
4200 struct ssh_channel
*c
;
4201 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4203 continue; /* nonexistent channel */
4204 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
4206 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4208 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4209 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4211 ("Server got confused by agent forwarding request"));
4214 logevent("Agent forwarding refused");
4216 logevent("Agent forwarding enabled");
4217 ssh_agentfwd_enabled
= TRUE
;
4222 * Now allocate a pty for the session.
4225 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4226 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
4227 ssh2_pkt_addstring("pty-req");
4228 ssh2_pkt_addbool(1); /* want reply */
4229 ssh2_pkt_addstring(cfg
.termtype
);
4230 ssh2_pkt_adduint32(cols
);
4231 ssh2_pkt_adduint32(rows
);
4232 ssh2_pkt_adduint32(0); /* pixel width */
4233 ssh2_pkt_adduint32(0); /* pixel height */
4234 ssh2_pkt_addstring_start();
4235 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
4237 ssh_state
= SSH_STATE_INTERMED
;
4240 crWaitUntilV(ispkt
);
4241 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4242 unsigned i
= ssh2_pkt_getuint32();
4243 struct ssh_channel
*c
;
4244 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4246 continue; /* nonexistent channel */
4247 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
4249 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4251 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4252 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4253 bombout(("Server got confused by pty request"));
4256 c_write_str("Server refused to allocate pty\r\n");
4257 ssh_editing
= ssh_echoing
= 1;
4259 logevent("Allocated pty");
4262 ssh_editing
= ssh_echoing
= 1;
4266 * Start a shell or a remote command.
4268 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4269 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
4270 if (cfg
.ssh_subsys
) {
4271 ssh2_pkt_addstring("subsystem");
4272 ssh2_pkt_addbool(1); /* want reply */
4273 ssh2_pkt_addstring(cfg
.remote_cmd_ptr
);
4274 } else if (*cfg
.remote_cmd_ptr
) {
4275 ssh2_pkt_addstring("exec");
4276 ssh2_pkt_addbool(1); /* want reply */
4277 ssh2_pkt_addstring(cfg
.remote_cmd_ptr
);
4279 ssh2_pkt_addstring("shell");
4280 ssh2_pkt_addbool(1); /* want reply */
4284 crWaitUntilV(ispkt
);
4285 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4286 unsigned i
= ssh2_pkt_getuint32();
4287 struct ssh_channel
*c
;
4288 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4290 continue; /* nonexistent channel */
4291 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
4293 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4294 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4295 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4296 bombout(("Server got confused by shell/command request"));
4299 bombout(("Server refused to start a shell/command"));
4302 logevent("Started a shell/command");
4305 ssh_state
= SSH_STATE_SESSION
;
4309 ssh_special(TS_EOF
);
4314 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
4317 static int try_send
;
4321 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
4322 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
4325 unsigned i
= ssh2_pkt_getuint32();
4326 struct ssh_channel
*c
;
4327 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4329 continue; /* nonexistent channel */
4330 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
4331 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
4332 continue; /* extended but not stderr */
4333 ssh2_pkt_getstring(&data
, &length
);
4336 case CHAN_MAINSESSION
:
4337 from_backend(pktin
.type
==
4338 SSH2_MSG_CHANNEL_EXTENDED_DATA
, data
,
4342 x11_send(c
->u
.x11
.s
, data
, length
);
4345 pfd_send(c
->u
.pfd
.s
, data
, length
);
4348 while (length
> 0) {
4349 if (c
->u
.a
.lensofar
< 4) {
4350 int l
= min(4 - c
->u
.a
.lensofar
, length
);
4351 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
4355 c
->u
.a
.lensofar
+= l
;
4357 if (c
->u
.a
.lensofar
== 4) {
4359 4 + GET_32BIT(c
->u
.a
.msglen
);
4360 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
4361 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
4363 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
4365 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
4367 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
4371 c
->u
.a
.lensofar
+= l
;
4373 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
4374 void *reply
, *sentreply
;
4376 agent_query(c
->u
.a
.message
,
4377 c
->u
.a
.totallen
, &reply
,
4382 /* Fake SSH_AGENT_FAILURE. */
4383 sentreply
= "\0\0\0\1\5";
4386 ssh2_add_channel_data(c
, sentreply
,
4391 sfree(c
->u
.a
.message
);
4392 c
->u
.a
.lensofar
= 0;
4398 * Enlarge the window again at the remote
4399 * side, just in case it ever runs down and
4400 * they fail to send us any more data.
4402 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4403 ssh2_pkt_adduint32(c
->remoteid
);
4404 ssh2_pkt_adduint32(length
);
4407 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
4408 ssh_state
= SSH_STATE_CLOSED
;
4409 logevent("Received disconnect message");
4411 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
4412 continue; /* exit status et al; ignore (FIXME?) */
4413 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
4414 unsigned i
= ssh2_pkt_getuint32();
4415 struct ssh_channel
*c
;
4417 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4419 continue; /* nonexistent channel */
4421 if (c
->type
== CHAN_X11
) {
4423 * Remote EOF on an X11 channel means we should
4424 * wrap up and close the channel ourselves.
4426 x11_close(c
->u
.x11
.s
);
4428 } else if (c
->type
== CHAN_AGENT
) {
4430 } else if (c
->type
== CHAN_SOCKDATA
) {
4431 pfd_close(c
->u
.pfd
.s
);
4434 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
4435 unsigned i
= ssh2_pkt_getuint32();
4436 struct ssh_channel
*c
;
4438 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4440 continue; /* nonexistent channel */
4441 if (c
->closes
== 0) {
4442 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
4443 ssh2_pkt_adduint32(c
->remoteid
);
4446 /* Do pre-close processing on the channel. */
4448 case CHAN_MAINSESSION
:
4449 break; /* nothing to see here, move along */
4457 del234(ssh_channels
, c
);
4458 sfree(c
->v2
.outbuffer
);
4462 * See if that was the last channel left open.
4464 if (count234(ssh_channels
) == 0) {
4465 logevent("All channels closed. Disconnecting");
4466 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4467 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4468 ssh2_pkt_addstring("All open channels closed");
4469 ssh2_pkt_addstring("en"); /* language tag */
4471 ssh_state
= SSH_STATE_CLOSED
;
4474 continue; /* remote sends close; ignore (FIXME) */
4475 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4476 unsigned i
= ssh2_pkt_getuint32();
4477 struct ssh_channel
*c
;
4478 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4480 continue; /* nonexistent channel */
4481 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
4483 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
4484 unsigned i
= ssh2_pkt_getuint32();
4485 struct ssh_channel
*c
;
4486 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4488 continue; /* nonexistent channel */
4489 if (c
->type
!= CHAN_SOCKDATA_DORMANT
)
4490 continue; /* dunno why they're confirming this */
4491 c
->remoteid
= ssh2_pkt_getuint32();
4492 c
->type
= CHAN_SOCKDATA
;
4494 c
->v2
.remwindow
= ssh2_pkt_getuint32();
4495 c
->v2
.remmaxpkt
= ssh2_pkt_getuint32();
4496 c
->v2
.outbuffer
= NULL
;
4497 c
->v2
.outbuflen
= c
->v2
.outbufsize
= 0;
4498 pfd_confirm(c
->u
.pfd
.s
);
4499 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
4503 struct ssh_channel
*c
;
4504 unsigned remid
, winsize
, pktsize
;
4505 ssh2_pkt_getstring(&type
, &typelen
);
4506 c
= smalloc(sizeof(struct ssh_channel
));
4508 remid
= ssh2_pkt_getuint32();
4509 winsize
= ssh2_pkt_getuint32();
4510 pktsize
= ssh2_pkt_getuint32();
4512 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
4513 if (!ssh_X11_fwd_enabled
)
4514 error
= "X11 forwarding is not enabled";
4515 else if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) !=
4517 error
= "Unable to open an X11 connection";
4521 } else if (typelen
== 15 &&
4522 !memcmp(type
, "forwarded-tcpip", 15)) {
4523 struct ssh_rportfwd pf
, *realpf
;
4526 ssh2_pkt_getstring(&dummy
, &dummylen
);/* skip address */
4527 pf
.sport
= ssh2_pkt_getuint32();
4528 realpf
= find234(ssh_rportfwds
, &pf
, NULL
);
4529 if (realpf
== NULL
) {
4530 error
= "Remote port is not recognised";
4532 char *e
= pfd_newconnect(&c
->u
.pfd
.s
, realpf
->dhost
,
4535 sprintf(buf
, "Received remote port open request for %s:%d",
4536 realpf
->dhost
, realpf
->dport
);
4539 sprintf(buf
, "Port open failed: %s", e
);
4541 error
= "Port open failed";
4543 logevent("Forwarded port opened successfully");
4544 c
->type
= CHAN_SOCKDATA
;
4547 } else if (typelen
== 22 &&
4548 !memcmp(type
, "auth-agent@openssh.com", 3)) {
4549 if (!ssh_agentfwd_enabled
)
4550 error
= "Agent forwarding is not enabled";
4552 c
->type
= CHAN_AGENT
; /* identify channel type */
4553 c
->u
.a
.lensofar
= 0;
4556 error
= "Unsupported channel type requested";
4559 c
->remoteid
= remid
;
4561 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
4562 ssh2_pkt_adduint32(c
->remoteid
);
4563 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED
);
4564 ssh2_pkt_addstring(error
);
4565 ssh2_pkt_addstring("en"); /* language tag */
4569 c
->localid
= alloc_channel_id();
4571 c
->v2
.remwindow
= winsize
;
4572 c
->v2
.remmaxpkt
= pktsize
;
4573 c
->v2
.outbuffer
= NULL
;
4574 c
->v2
.outbuflen
= c
->v2
.outbufsize
= 0;
4575 add234(ssh_channels
, c
);
4576 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
4577 ssh2_pkt_adduint32(c
->remoteid
);
4578 ssh2_pkt_adduint32(c
->localid
);
4579 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
4580 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
4584 bombout(("Strange packet received: type %d", pktin
.type
));
4589 * We have spare data. Add it to the channel buffer.
4591 ssh2_add_channel_data(mainchan
, in
, inlen
);
4596 struct ssh_channel
*c
;
4598 * Try to send data on all channels if we can.
4600 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++)
4609 * Handle the top-level SSH2 protocol.
4611 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
4613 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
4615 do_ssh2_authconn(in
, inlen
, ispkt
);
4619 * Called to set up the connection.
4621 * Returns an error message, or NULL on success.
4623 static char *ssh_init(char *host
, int port
, char **realhost
)
4628 if (crypto_startup() == 0)
4629 return "Microsoft high encryption pack not installed!";
4636 p
= connect_to_host(host
, port
, realhost
);
4644 * Called to send data down the Telnet connection.
4646 static void ssh_send(char *buf
, int len
)
4648 if (s
== NULL
|| ssh_protocol
== NULL
)
4651 ssh_protocol(buf
, len
, 0);
4655 * Called to set the size of the window from SSH's POV.
4657 static void ssh_size(void)
4659 switch (ssh_state
) {
4660 case SSH_STATE_BEFORE_SIZE
:
4661 case SSH_STATE_PREPACKET
:
4662 case SSH_STATE_CLOSED
:
4663 break; /* do nothing */
4664 case SSH_STATE_INTERMED
:
4665 size_needed
= TRUE
; /* buffer for later */
4667 case SSH_STATE_SESSION
:
4669 if (ssh_version
== 1) {
4670 send_packet(SSH1_CMSG_WINDOW_SIZE
,
4671 PKT_INT
, rows
, PKT_INT
, cols
,
4672 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
4674 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4675 ssh2_pkt_adduint32(mainchan
->remoteid
);
4676 ssh2_pkt_addstring("window-change");
4677 ssh2_pkt_addbool(0);
4678 ssh2_pkt_adduint32(cols
);
4679 ssh2_pkt_adduint32(rows
);
4680 ssh2_pkt_adduint32(0);
4681 ssh2_pkt_adduint32(0);
4690 * Send Telnet special codes. TS_EOF is useful for `plink', so you
4691 * can send an EOF and collect resulting output (e.g. `plink
4694 static void ssh_special(Telnet_Special code
)
4696 if (code
== TS_EOF
) {
4697 if (ssh_state
!= SSH_STATE_SESSION
) {
4699 * Buffer the EOF in case we are pre-SESSION, so we can
4700 * send it as soon as we reach SESSION.
4706 if (ssh_version
== 1) {
4707 send_packet(SSH1_CMSG_EOF
, PKT_END
);
4709 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
4710 ssh2_pkt_adduint32(mainchan
->remoteid
);
4713 logevent("Sent EOF message");
4714 } else if (code
== TS_PING
) {
4715 if (ssh_state
== SSH_STATE_CLOSED
4716 || ssh_state
== SSH_STATE_PREPACKET
) return;
4717 if (ssh_version
== 1) {
4718 send_packet(SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
4720 ssh2_pkt_init(SSH2_MSG_IGNORE
);
4721 ssh2_pkt_addstring_start();
4729 void *new_sock_channel(Socket s
)
4731 struct ssh_channel
*c
;
4732 c
= smalloc(sizeof(struct ssh_channel
));
4735 c
->remoteid
= -1; /* to be set when open confirmed */
4736 c
->localid
= alloc_channel_id();
4738 c
->type
= CHAN_SOCKDATA_DORMANT
;/* identify channel type */
4740 add234(ssh_channels
, c
);
4745 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
4747 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
4750 sprintf(buf
, "Opening forwarded connection to %.512s:%d", hostname
, port
);
4753 if (ssh_version
== 1) {
4754 send_packet(SSH1_MSG_PORT_OPEN
,
4755 PKT_INT
, c
->localid
,
4758 //PKT_STR, <org:orgport>,
4761 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
4762 ssh2_pkt_addstring("direct-tcpip");
4763 ssh2_pkt_adduint32(c
->localid
);
4764 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
4765 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
4766 ssh2_pkt_addstring(hostname
);
4767 ssh2_pkt_adduint32(port
);
4769 * We make up values for the originator data; partly it's
4770 * too much hassle to keep track, and partly I'm not
4771 * convinced the server should be told details like that
4772 * about my local network configuration.
4774 ssh2_pkt_addstring("client-side-connection");
4775 ssh2_pkt_adduint32(0);
4781 static Socket
ssh_socket(void)
4786 static int ssh_sendok(void)
4791 static int ssh_ldisc(int option
)
4793 if (option
== LD_ECHO
)
4795 if (option
== LD_EDIT
)
4800 Backend ssh_backend
= {