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 */
278 * 2-3-4 tree storing channels.
281 unsigned remoteid
, localid
;
284 struct ssh2_data_channel
{
285 unsigned char *outbuffer
;
286 unsigned outbuflen
, outbufsize
;
287 unsigned remwindow
, remmaxpkt
;
290 struct ssh_agent_channel
{
291 unsigned char *message
;
292 unsigned char msglen
[4];
293 int lensofar
, totallen
;
295 struct ssh_x11_channel
{
298 struct ssh_pfd_channel
{
305 * 2-3-4 tree storing remote->local port forwardings (so we can
306 * reject any attempt to open a port we didn't explicitly ask to
309 struct ssh_rportfwd
{
323 static SHA_State exhash
, exhashbase
;
325 static Socket s
= NULL
;
327 static unsigned char session_key
[32];
328 static int ssh1_compressing
;
329 static int ssh1_remote_protoflags
;
330 static int ssh1_local_protoflags
;
331 static int ssh_agentfwd_enabled
;
332 static int ssh_X11_fwd_enabled
;
333 static int ssh_remote_bugs
;
334 static const struct ssh_cipher
*cipher
= NULL
;
335 static const struct ssh2_cipher
*cscipher
= NULL
;
336 static const struct ssh2_cipher
*sccipher
= NULL
;
337 static const struct ssh_mac
*csmac
= NULL
;
338 static const struct ssh_mac
*scmac
= NULL
;
339 static const struct ssh_compress
*cscomp
= NULL
;
340 static const struct ssh_compress
*sccomp
= NULL
;
341 static const struct ssh_kex
*kex
= NULL
;
342 static const struct ssh_signkey
*hostkey
= NULL
;
343 static unsigned char ssh2_session_id
[20];
344 int (*ssh_get_line
) (const char *prompt
, char *str
, int maxlen
,
347 static char *savedhost
;
348 static int savedport
;
349 static int ssh_send_ok
;
350 static int ssh_echoing
, ssh_editing
;
352 static tree234
*ssh_channels
; /* indexed by local id */
353 static struct ssh_channel
*mainchan
; /* primary session channel */
355 static tree234
*ssh_rportfwds
;
359 SSH_STATE_BEFORE_SIZE
,
363 } ssh_state
= SSH_STATE_PREPACKET
;
365 static int size_needed
= FALSE
, eof_needed
= FALSE
;
367 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
368 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
369 static unsigned char *deferred_send_data
= NULL
;
370 static int deferred_len
= 0, deferred_size
= 0;
372 static int ssh_version
;
373 static void (*ssh_protocol
) (unsigned char *in
, int inlen
, int ispkt
);
374 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
375 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
376 static void ssh_size(void);
377 static void ssh_special(Telnet_Special
);
378 static void ssh2_try_send(struct ssh_channel
*c
);
379 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
382 static int (*s_rdpkt
) (unsigned char **data
, int *datalen
);
384 static struct rdpkt1_state_tag
{
385 long len
, pad
, biglen
, to_read
;
386 unsigned long realcrc
, gotcrc
;
392 static struct rdpkt2_state_tag
{
393 long len
, pad
, payload
, packetlen
, maclen
;
396 unsigned long incoming_sequence
;
399 static int ssh_channelcmp(void *av
, void *bv
)
401 struct ssh_channel
*a
= (struct ssh_channel
*) av
;
402 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
403 if (a
->localid
< b
->localid
)
405 if (a
->localid
> b
->localid
)
409 static int ssh_channelfind(void *av
, void *bv
)
411 unsigned *a
= (unsigned *) av
;
412 struct ssh_channel
*b
= (struct ssh_channel
*) bv
;
420 static int ssh_rportcmp(void *av
, void *bv
)
422 struct ssh_rportfwd
*a
= (struct ssh_rportfwd
*) av
;
423 struct ssh_rportfwd
*b
= (struct ssh_rportfwd
*) bv
;
425 if ( (i
= strcmp(a
->host
, b
->host
)) != 0)
426 return i
< 0 ?
-1 : +1;
427 if (a
->port
> b
->port
)
432 static int alloc_channel_id(void)
434 const unsigned CHANNEL_NUMBER_OFFSET
= 256;
435 unsigned low
, high
, mid
;
437 struct ssh_channel
*c
;
440 * First-fit allocation of channel numbers: always pick the
441 * lowest unused one. To do this, binary-search using the
442 * counted B-tree to find the largest channel ID which is in a
443 * contiguous sequence from the beginning. (Precisely
444 * everything in that sequence must have ID equal to its tree
445 * index plus CHANNEL_NUMBER_OFFSET.)
447 tsize
= count234(ssh_channels
);
451 while (high
- low
> 1) {
452 mid
= (high
+ low
) / 2;
453 c
= index234(ssh_channels
, mid
);
454 if (c
->localid
== mid
+ CHANNEL_NUMBER_OFFSET
)
455 low
= mid
; /* this one is fine */
457 high
= mid
; /* this one is past it */
460 * Now low points to either -1, or the tree index of the
461 * largest ID in the initial sequence.
464 unsigned i
= low
+ 1 + CHANNEL_NUMBER_OFFSET
;
465 assert(NULL
== find234(ssh_channels
, &i
, ssh_channelfind
));
467 return low
+ 1 + CHANNEL_NUMBER_OFFSET
;
470 static void c_write(char *buf
, int len
)
472 if ((flags
& FLAG_STDERR
)) {
474 for (i
= 0; i
< len
; i
++)
476 fputc(buf
[i
], stderr
);
479 from_backend(1, buf
, len
);
482 static void c_write_untrusted(char *buf
, int len
)
485 for (i
= 0; i
< len
; i
++) {
488 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
493 static void c_write_str(char *buf
)
495 c_write(buf
, strlen(buf
));
499 * Collect incoming data in the incoming packet buffer.
500 * Decipher and verify the packet when it is completely read.
501 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
502 * Update the *data and *datalen variables.
503 * Return the additional nr of bytes needed, or 0 when
504 * a complete packet is available.
506 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
508 struct rdpkt1_state_tag
*st
= &rdpkt1_state
;
517 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
518 while ((*datalen
) == 0)
520 st
->len
= (st
->len
<< 8) + **data
;
521 (*data
)++, (*datalen
)--;
525 if (st
->len
== 0x52656d6f) { /* "Remo"te server has closed ... */
526 st
->len
= 0x300; /* big enough to carry to end */
530 st
->pad
= 8 - (st
->len
% 8);
531 st
->biglen
= st
->len
+ st
->pad
;
532 pktin
.length
= st
->len
- 5;
534 if (pktin
.maxlen
< st
->biglen
) {
535 pktin
.maxlen
= st
->biglen
;
536 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->biglen
+ APIEXTRA
) :
537 srealloc(pktin
.data
, st
->biglen
+ APIEXTRA
));
539 fatalbox("Out of memory");
542 st
->to_read
= st
->biglen
;
544 while (st
->to_read
> 0) {
545 st
->chunk
= st
->to_read
;
546 while ((*datalen
) == 0)
547 crReturn(st
->to_read
);
548 if (st
->chunk
> (*datalen
))
549 st
->chunk
= (*datalen
);
550 memcpy(st
->p
, *data
, st
->chunk
);
552 *datalen
-= st
->chunk
;
554 st
->to_read
-= st
->chunk
;
558 cipher
->decrypt(pktin
.data
, st
->biglen
);
560 debug(("Got packet len=%d pad=%d\n", st
->len
, st
->pad
));
561 dmemdump(pktin
.data
, st
->biglen
);
564 st
->realcrc
= crc32(pktin
.data
, st
->biglen
- 4);
565 st
->gotcrc
= GET_32BIT(pktin
.data
+ st
->biglen
- 4);
566 if (st
->gotcrc
!= st
->realcrc
) {
567 bombout(("Incorrect CRC received on packet"));
571 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
573 if (ssh1_compressing
) {
574 unsigned char *decompblk
;
577 debug(("Packet payload pre-decompression:\n"));
578 dmemdump(pktin
.body
- 1, pktin
.length
+ 1);
580 zlib_decompress_block(pktin
.body
- 1, pktin
.length
+ 1,
581 &decompblk
, &decomplen
);
583 if (pktin
.maxlen
< st
->pad
+ decomplen
) {
584 pktin
.maxlen
= st
->pad
+ decomplen
;
585 pktin
.data
= srealloc(pktin
.data
, pktin
.maxlen
+ APIEXTRA
);
586 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
588 fatalbox("Out of memory");
591 memcpy(pktin
.body
- 1, decompblk
, decomplen
);
593 pktin
.length
= decomplen
- 1;
595 debug(("Packet payload post-decompression:\n"));
596 dmemdump(pktin
.body
- 1, pktin
.length
+ 1);
600 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
601 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
602 pktin
.type
== SSH1_MSG_DEBUG
||
603 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
604 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
605 long strlen
= GET_32BIT(pktin
.body
);
606 if (strlen
+ 4 != pktin
.length
) {
607 bombout(("Received data packet with bogus string length"));
612 pktin
.type
= pktin
.body
[-1];
614 if (pktin
.type
== SSH1_MSG_DEBUG
) {
615 /* log debug message */
617 int strlen
= GET_32BIT(pktin
.body
);
618 strcpy(buf
, "Remote: ");
621 memcpy(buf
+ 8, pktin
.body
+ 4, strlen
);
622 buf
[8 + strlen
] = '\0';
625 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
630 if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
631 /* log reason code in disconnect message */
633 unsigned msglen
= GET_32BIT(pktin
.body
);
635 strcpy(buf
, "Remote sent disconnect: ");
636 nowlen
= strlen(buf
);
637 if (msglen
> sizeof(buf
) - nowlen
- 1)
638 msglen
= sizeof(buf
) - nowlen
- 1;
639 memcpy(buf
+ nowlen
, pktin
.body
+ 4, msglen
);
640 buf
[nowlen
+ msglen
] = '\0';
647 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
649 struct rdpkt2_state_tag
*st
= &rdpkt2_state
;
657 st
->cipherblk
= sccipher
->blksize
;
660 if (st
->cipherblk
< 8)
663 if (pktin
.maxlen
< st
->cipherblk
) {
664 pktin
.maxlen
= st
->cipherblk
;
667 NULL ?
smalloc(st
->cipherblk
+
668 APIEXTRA
) : srealloc(pktin
.data
,
672 fatalbox("Out of memory");
676 * Acquire and decrypt the first block of the packet. This will
677 * contain the length and padding details.
679 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
680 while ((*datalen
) == 0)
681 crReturn(st
->cipherblk
- st
->i
);
682 pktin
.data
[st
->i
] = *(*data
)++;
686 if (!memcmp(pktin
.data
, "Remo", 4)) { /* "Remo"te server has closed ... */
691 sccipher
->decrypt(pktin
.data
, st
->cipherblk
);
694 * Now get the length and padding figures.
696 st
->len
= GET_32BIT(pktin
.data
);
697 st
->pad
= pktin
.data
[4];
700 * This enables us to deduce the payload length.
702 st
->payload
= st
->len
- st
->pad
- 1;
704 pktin
.length
= st
->payload
+ 5;
707 * So now we can work out the total packet length.
709 st
->packetlen
= st
->len
+ 4;
710 st
->maclen
= scmac ? scmac
->len
: 0;
713 * Adjust memory allocation if packet is too big.
715 if (pktin
.maxlen
< st
->packetlen
+ st
->maclen
) {
716 pktin
.maxlen
= st
->packetlen
+ st
->maclen
;
719 NULL ?
smalloc(pktin
.maxlen
+ APIEXTRA
) : srealloc(pktin
.data
,
724 fatalbox("Out of memory");
728 * Read and decrypt the remainder of the packet.
730 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
;
732 while ((*datalen
) == 0)
733 crReturn(st
->packetlen
+ st
->maclen
- st
->i
);
734 pktin
.data
[st
->i
] = *(*data
)++;
737 /* Decrypt everything _except_ the MAC. */
739 sccipher
->decrypt(pktin
.data
+ st
->cipherblk
,
740 st
->packetlen
- st
->cipherblk
);
743 debug(("Got packet len=%d pad=%d\n", st
->len
, st
->pad
));
744 dmemdump(pktin
.data
, st
->packetlen
);
751 && !scmac
->verify(pktin
.data
, st
->len
+ 4,
752 st
->incoming_sequence
)) {
753 bombout(("Incorrect MAC received on packet"));
756 st
->incoming_sequence
++; /* whether or not we MACed */
759 * Decompress packet payload.
762 unsigned char *newpayload
;
764 if (sccomp
&& sccomp
->decompress(pktin
.data
+ 5, pktin
.length
- 5,
765 &newpayload
, &newlen
)) {
766 if (pktin
.maxlen
< newlen
+ 5) {
767 pktin
.maxlen
= newlen
+ 5;
770 NULL ?
smalloc(pktin
.maxlen
+
771 APIEXTRA
) : srealloc(pktin
.data
,
775 fatalbox("Out of memory");
777 pktin
.length
= 5 + newlen
;
778 memcpy(pktin
.data
+ 5, newpayload
, newlen
);
780 debug(("Post-decompression payload:\n"));
781 dmemdump(pktin
.data
+ 5, newlen
);
789 pktin
.type
= pktin
.data
[5];
791 if (pktin
.type
== SSH2_MSG_IGNORE
|| pktin
.type
== SSH2_MSG_DEBUG
)
792 goto next_packet
; /* FIXME: print DEBUG message */
794 if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
795 /* log reason code in disconnect message */
797 int reason
= GET_32BIT(pktin
.data
+ 6);
798 unsigned msglen
= GET_32BIT(pktin
.data
+ 10);
800 if (reason
> 0 && reason
< lenof(ssh2_disconnect_reasons
)) {
801 sprintf(buf
, "Received disconnect message (%s)",
802 ssh2_disconnect_reasons
[reason
]);
804 sprintf(buf
, "Received disconnect message (unknown type %d)",
808 strcpy(buf
, "Disconnection message text: ");
809 nowlen
= strlen(buf
);
810 if (msglen
> sizeof(buf
) - nowlen
- 1)
811 msglen
= sizeof(buf
) - nowlen
- 1;
812 memcpy(buf
+ nowlen
, pktin
.data
+ 14, msglen
);
813 buf
[nowlen
+ msglen
] = '\0';
820 static void ssh1_pktout_size(int len
)
824 len
+= 5; /* type and CRC */
828 pktout
.length
= len
- 5;
829 if (pktout
.maxlen
< biglen
) {
830 pktout
.maxlen
= biglen
;
832 /* Allocate enough buffer space for extra block
833 * for MS CryptEncrypt() */
834 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+ 12) :
835 srealloc(pktout
.data
, biglen
+ 12));
837 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+ 4) :
838 srealloc(pktout
.data
, biglen
+ 4));
841 fatalbox("Out of memory");
843 pktout
.body
= pktout
.data
+ 4 + pad
+ 1;
846 static void s_wrpkt_start(int type
, int len
)
848 ssh1_pktout_size(len
);
852 static int s_wrpkt_prepare(void)
854 int pad
, len
, biglen
, i
;
857 pktout
.body
[-1] = pktout
.type
;
860 debug(("Packet payload pre-compression:\n"));
861 dmemdump(pktout
.body
- 1, pktout
.length
+ 1);
864 if (ssh1_compressing
) {
865 unsigned char *compblk
;
867 zlib_compress_block(pktout
.body
- 1, pktout
.length
+ 1,
869 ssh1_pktout_size(complen
- 1);
870 memcpy(pktout
.body
- 1, compblk
, complen
);
873 debug(("Packet payload post-compression:\n"));
874 dmemdump(pktout
.body
- 1, pktout
.length
+ 1);
878 len
= pktout
.length
+ 5; /* type and CRC */
882 for (i
= 0; i
< pad
; i
++)
883 pktout
.data
[i
+ 4] = random_byte();
884 crc
= crc32(pktout
.data
+ 4, biglen
- 4);
885 PUT_32BIT(pktout
.data
+ biglen
, crc
);
886 PUT_32BIT(pktout
.data
, len
);
889 debug(("Sending packet len=%d\n", biglen
+ 4));
890 dmemdump(pktout
.data
, biglen
+ 4);
893 cipher
->encrypt(pktout
.data
+ 4, biglen
);
898 static void s_wrpkt(void)
901 len
= s_wrpkt_prepare();
902 sk_write(s
, pktout
.data
, len
);
905 static void s_wrpkt_defer(void)
908 len
= s_wrpkt_prepare();
909 if (deferred_len
+ len
> deferred_size
) {
910 deferred_size
= deferred_len
+ len
+ 128;
911 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
913 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
918 * Construct a packet with the specified contents.
920 static void construct_packet(int pkttype
, va_list ap1
, va_list ap2
)
922 unsigned char *p
, *argp
, argchar
;
923 unsigned long argint
;
924 int pktlen
, argtype
, arglen
;
928 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
931 (void) va_arg(ap1
, int);
935 (void) va_arg(ap1
, char);
939 (void) va_arg(ap1
, unsigned char *);
940 arglen
= va_arg(ap1
, int);
944 argp
= va_arg(ap1
, unsigned char *);
945 arglen
= strlen(argp
);
946 pktlen
+= 4 + arglen
;
949 bn
= va_arg(ap1
, Bignum
);
950 pktlen
+= ssh1_bignum_length(bn
);
957 s_wrpkt_start(pkttype
, pktlen
);
960 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
963 argint
= va_arg(ap2
, int);
964 PUT_32BIT(p
, argint
);
968 argchar
= va_arg(ap2
, unsigned char);
973 argp
= va_arg(ap2
, unsigned char *);
974 arglen
= va_arg(ap2
, int);
975 memcpy(p
, argp
, arglen
);
979 argp
= va_arg(ap2
, unsigned char *);
980 arglen
= strlen(argp
);
981 PUT_32BIT(p
, arglen
);
982 memcpy(p
+ 4, argp
, arglen
);
986 bn
= va_arg(ap2
, Bignum
);
987 p
+= ssh1_write_bignum(p
, bn
);
993 static void send_packet(int pkttype
, ...)
996 va_start(ap1
, pkttype
);
997 va_start(ap2
, pkttype
);
998 construct_packet(pkttype
, ap1
, ap2
);
1002 static void defer_packet(int pkttype
, ...)
1005 va_start(ap1
, pkttype
);
1006 va_start(ap2
, pkttype
);
1007 construct_packet(pkttype
, ap1
, ap2
);
1011 static int ssh_versioncmp(char *a
, char *b
)
1014 unsigned long av
, bv
;
1016 av
= strtoul(a
, &ae
, 10);
1017 bv
= strtoul(b
, &be
, 10);
1019 return (av
< bv ?
-1 : +1);
1024 av
= strtoul(ae
, &ae
, 10);
1025 bv
= strtoul(be
, &be
, 10);
1027 return (av
< bv ?
-1 : +1);
1033 * Utility routines for putting an SSH-protocol `string' and
1034 * `uint32' into a SHA state.
1037 static void sha_string(SHA_State
* s
, void *str
, int len
)
1039 unsigned char lenblk
[4];
1040 PUT_32BIT(lenblk
, len
);
1041 SHA_Bytes(s
, lenblk
, 4);
1042 SHA_Bytes(s
, str
, len
);
1045 static void sha_uint32(SHA_State
* s
, unsigned i
)
1047 unsigned char intblk
[4];
1048 PUT_32BIT(intblk
, i
);
1049 SHA_Bytes(s
, intblk
, 4);
1053 * SSH2 packet construction functions.
1055 static void ssh2_pkt_ensure(int length
)
1057 if (pktout
.maxlen
< length
) {
1058 pktout
.maxlen
= length
+ 256;
1061 NULL ?
smalloc(pktout
.maxlen
+
1062 APIEXTRA
) : srealloc(pktout
.data
,
1066 fatalbox("Out of memory");
1069 static void ssh2_pkt_adddata(void *data
, int len
)
1071 pktout
.length
+= len
;
1072 ssh2_pkt_ensure(pktout
.length
);
1073 memcpy(pktout
.data
+ pktout
.length
- len
, data
, len
);
1075 static void ssh2_pkt_addbyte(unsigned char byte
)
1077 ssh2_pkt_adddata(&byte
, 1);
1079 static void ssh2_pkt_init(int pkt_type
)
1082 ssh2_pkt_addbyte((unsigned char) pkt_type
);
1084 static void ssh2_pkt_addbool(unsigned char value
)
1086 ssh2_pkt_adddata(&value
, 1);
1088 static void ssh2_pkt_adduint32(unsigned long value
)
1091 PUT_32BIT(x
, value
);
1092 ssh2_pkt_adddata(x
, 4);
1094 static void ssh2_pkt_addstring_start(void)
1096 ssh2_pkt_adduint32(0);
1097 pktout
.savedpos
= pktout
.length
;
1099 static void ssh2_pkt_addstring_str(char *data
)
1101 ssh2_pkt_adddata(data
, strlen(data
));
1102 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1103 pktout
.length
- pktout
.savedpos
);
1105 static void ssh2_pkt_addstring_data(char *data
, int len
)
1107 ssh2_pkt_adddata(data
, len
);
1108 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
1109 pktout
.length
- pktout
.savedpos
);
1111 static void ssh2_pkt_addstring(char *data
)
1113 ssh2_pkt_addstring_start();
1114 ssh2_pkt_addstring_str(data
);
1116 static char *ssh2_mpint_fmt(Bignum b
, int *len
)
1119 int i
, n
= (bignum_bitcount(b
) + 7) / 8;
1122 fatalbox("out of memory");
1124 for (i
= 1; i
<= n
; i
++)
1125 p
[i
] = bignum_byte(b
, n
- i
);
1127 while (i
<= n
&& p
[i
] == 0 && (p
[i
+ 1] & 0x80) == 0)
1129 memmove(p
, p
+ i
, n
+ 1 - i
);
1133 static void ssh2_pkt_addmp(Bignum b
)
1137 p
= ssh2_mpint_fmt(b
, &len
);
1138 ssh2_pkt_addstring_start();
1139 ssh2_pkt_addstring_data(p
, len
);
1144 * Construct an SSH2 final-form packet: compress it, encrypt it,
1145 * put the MAC on it. Final packet, ready to be sent, is stored in
1146 * pktout.data. Total length is returned.
1148 static int ssh2_pkt_construct(void)
1150 int cipherblk
, maclen
, padding
, i
;
1151 static unsigned long outgoing_sequence
= 0;
1154 * Compress packet payload.
1157 debug(("Pre-compression payload:\n"));
1158 dmemdump(pktout
.data
+ 5, pktout
.length
- 5);
1161 unsigned char *newpayload
;
1163 if (cscomp
&& cscomp
->compress(pktout
.data
+ 5, pktout
.length
- 5,
1164 &newpayload
, &newlen
)) {
1166 ssh2_pkt_adddata(newpayload
, newlen
);
1172 * Add padding. At least four bytes, and must also bring total
1173 * length (minus MAC) up to a multiple of the block size.
1175 cipherblk
= cscipher ? cscipher
->blksize
: 8; /* block size */
1176 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
1179 (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
1180 maclen
= csmac ? csmac
->len
: 0;
1181 ssh2_pkt_ensure(pktout
.length
+ padding
+ maclen
);
1182 pktout
.data
[4] = padding
;
1183 for (i
= 0; i
< padding
; i
++)
1184 pktout
.data
[pktout
.length
+ i
] = random_byte();
1185 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
1187 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
1189 outgoing_sequence
++; /* whether or not we MACed */
1192 debug(("Sending packet len=%d\n", pktout
.length
+ padding
));
1193 dmemdump(pktout
.data
, pktout
.length
+ padding
);
1197 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
1199 /* Ready-to-send packet starts at pktout.data. We return length. */
1200 return pktout
.length
+ padding
+ maclen
;
1204 * Construct and send an SSH2 packet immediately.
1206 static void ssh2_pkt_send(void)
1208 int len
= ssh2_pkt_construct();
1209 sk_write(s
, pktout
.data
, len
);
1213 * Construct an SSH2 packet and add it to a deferred data block.
1214 * Useful for sending multiple packets in a single sk_write() call,
1215 * to prevent a traffic-analysing listener from being able to work
1216 * out the length of any particular packet (such as the password
1219 * Note that because SSH2 sequence-numbers its packets, this can
1220 * NOT be used as an m4-style `defer' allowing packets to be
1221 * constructed in one order and sent in another.
1223 static void ssh2_pkt_defer(void)
1225 int len
= ssh2_pkt_construct();
1226 if (deferred_len
+ len
> deferred_size
) {
1227 deferred_size
= deferred_len
+ len
+ 128;
1228 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1230 memcpy(deferred_send_data
+ deferred_len
, pktout
.data
, len
);
1231 deferred_len
+= len
;
1235 * Send the whole deferred data block constructed by
1236 * ssh2_pkt_defer() or SSH1's defer_packet().
1238 static void ssh_pkt_defersend(void)
1240 sk_write(s
, deferred_send_data
, deferred_len
);
1241 deferred_len
= deferred_size
= 0;
1242 sfree(deferred_send_data
);
1243 deferred_send_data
= NULL
;
1247 void bndebug(char *string
, Bignum b
)
1251 p
= ssh2_mpint_fmt(b
, &len
);
1252 debug(("%s", string
));
1253 for (i
= 0; i
< len
; i
++)
1254 debug((" %02x", p
[i
]));
1260 static void sha_mpint(SHA_State
* s
, Bignum b
)
1264 p
= ssh2_mpint_fmt(b
, &len
);
1265 sha_string(s
, p
, len
);
1270 * SSH2 packet decode functions.
1272 static unsigned long ssh2_pkt_getuint32(void)
1274 unsigned long value
;
1275 if (pktin
.length
- pktin
.savedpos
< 4)
1276 return 0; /* arrgh, no way to decline (FIXME?) */
1277 value
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1278 pktin
.savedpos
+= 4;
1281 static int ssh2_pkt_getbool(void)
1283 unsigned long value
;
1284 if (pktin
.length
- pktin
.savedpos
< 1)
1285 return 0; /* arrgh, no way to decline (FIXME?) */
1286 value
= pktin
.data
[pktin
.savedpos
] != 0;
1290 static void ssh2_pkt_getstring(char **p
, int *length
)
1293 if (pktin
.length
- pktin
.savedpos
< 4)
1295 *length
= GET_32BIT(pktin
.data
+ pktin
.savedpos
);
1296 pktin
.savedpos
+= 4;
1297 if (pktin
.length
- pktin
.savedpos
< *length
)
1299 *p
= pktin
.data
+ pktin
.savedpos
;
1300 pktin
.savedpos
+= *length
;
1302 static Bignum
ssh2_pkt_getmp(void)
1308 ssh2_pkt_getstring(&p
, &length
);
1312 bombout(("internal error: Can't handle negative mpints"));
1315 b
= bignum_from_bytes(p
, length
);
1320 * Examine the remote side's version string and compare it against
1321 * a list of known buggy implementations.
1323 static void ssh_detect_bugs(char *vstring
)
1325 char *imp
; /* pointer to implementation part */
1327 imp
+= strcspn(imp
, "-");
1330 imp
+= strcspn(imp
, "-");
1334 ssh_remote_bugs
= 0;
1336 if (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
1337 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
1338 !strcmp(imp
, "1.2.22")) {
1340 * These versions don't support SSH1_MSG_IGNORE, so we have
1341 * to use a different defence against password length
1344 ssh_remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
1345 logevent("We believe remote version has SSH1 ignore bug");
1348 if (!strncmp(imp
, "2.1.0", 5) || !strncmp(imp
, "2.0.", 4) ||
1349 !strncmp(imp
, "2.2.0", 5) || !strncmp(imp
, "2.3.0", 5) ||
1350 !strncmp(imp
, "2.1 ", 4)) {
1352 * These versions have the HMAC bug.
1354 ssh_remote_bugs
|= BUG_SSH2_HMAC
;
1355 logevent("We believe remote version has SSH2 HMAC bug");
1359 static int do_ssh_init(unsigned char c
)
1362 static char version
[10];
1363 static char *vstring
;
1364 static int vstrsize
;
1370 /* Search for the string "SSH-" in the input. */
1373 static const int transS
[] = { 1, 2, 2, 1 };
1374 static const int transH
[] = { 0, 0, 3, 0 };
1375 static const int transminus
[] = { 0, 0, 0, -1 };
1386 crReturn(1); /* get another character */
1389 vstring
= smalloc(16);
1391 strcpy(vstring
, "SSH-");
1395 crReturn(1); /* get another char */
1396 if (vslen
>= vstrsize
- 1) {
1398 vstring
= srealloc(vstring
, vstrsize
);
1400 vstring
[vslen
++] = c
;
1405 } else if (i
< sizeof(version
) - 1)
1407 } else if (c
== '\n')
1411 ssh_agentfwd_enabled
= FALSE
;
1412 rdpkt2_state
.incoming_sequence
= 0;
1415 vlog
= smalloc(20 + vslen
);
1416 sprintf(vlog
, "Server version: %s", vstring
);
1417 ssh_detect_bugs(vstring
);
1418 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1423 * Server version "1.99" means we can choose whether we use v1
1424 * or v2 protocol. Choice is based on cfg.sshprot.
1426 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1428 * This is a v2 server. Begin v2 protocol.
1430 char verstring
[80], vlog
[100];
1431 sprintf(verstring
, "SSH-2.0-%s", sshver
);
1432 SHA_Init(&exhashbase
);
1434 * Hash our version string and their version string.
1436 sha_string(&exhashbase
, verstring
, strlen(verstring
));
1437 sha_string(&exhashbase
, vstring
, strcspn(vstring
, "\r\n"));
1438 sprintf(vlog
, "We claim version: %s", verstring
);
1440 strcat(verstring
, "\n");
1441 logevent("Using SSH protocol version 2");
1442 sk_write(s
, verstring
, strlen(verstring
));
1443 ssh_protocol
= ssh2_protocol
;
1445 s_rdpkt
= ssh2_rdpkt
;
1448 * This is a v1 server. Begin v1 protocol.
1450 char verstring
[80], vlog
[100];
1451 sprintf(verstring
, "SSH-%s-%s",
1452 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"),
1454 sprintf(vlog
, "We claim version: %s", verstring
);
1456 strcat(verstring
, "\n");
1457 logevent("Using SSH protocol version 1");
1458 sk_write(s
, verstring
, strlen(verstring
));
1459 ssh_protocol
= ssh1_protocol
;
1461 s_rdpkt
= ssh1_rdpkt
;
1463 ssh_state
= SSH_STATE_BEFORE_SIZE
;
1470 static void ssh_gotdata(unsigned char *data
, int datalen
)
1475 * To begin with, feed the characters one by one to the
1476 * protocol initialisation / selection function do_ssh_init().
1477 * When that returns 0, we're done with the initial greeting
1478 * exchange and can move on to packet discipline.
1483 crReturnV
; /* more data please */
1484 ret
= do_ssh_init(*data
);
1492 * We emerge from that loop when the initial negotiation is
1493 * over and we have selected an s_rdpkt function. Now pass
1494 * everything to s_rdpkt, and then pass the resulting packets
1495 * to the proper protocol handler.
1500 while (datalen
> 0) {
1501 if (s_rdpkt(&data
, &datalen
) == 0) {
1502 ssh_protocol(NULL
, 0, 1);
1503 if (ssh_state
== SSH_STATE_CLOSED
) {
1513 static int ssh_closing(Plug plug
, char *error_msg
, int error_code
,
1516 ssh_state
= SSH_STATE_CLOSED
;
1522 /* A socket error has occurred. */
1523 connection_fatal(error_msg
);
1525 /* Otherwise, the remote side closed the connection normally. */
1530 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
)
1532 ssh_gotdata(data
, len
);
1533 if (ssh_state
== SSH_STATE_CLOSED
) {
1544 * Connect to specified host and port.
1545 * Returns an error message, or NULL on success.
1546 * Also places the canonical host name into `realhost'. It must be
1547 * freed by the caller.
1549 static char *connect_to_host(char *host
, int port
, char **realhost
)
1551 static struct plug_function_table fn_table
= {
1554 }, *fn_table_ptr
= &fn_table
;
1563 savedhost
= smalloc(1 + strlen(host
));
1565 fatalbox("Out of memory");
1566 strcpy(savedhost
, host
);
1569 port
= 22; /* default ssh port */
1582 addr
= sk_namelookup(host
, realhost
);
1583 if ((err
= sk_addr_error(addr
)))
1587 *realhost
= strdup(FWhost
);
1593 s
= sk_new(addr
, port
, 0, 1, &fn_table_ptr
);
1594 if ((err
= sk_socket_error(s
)))
1598 sk_write(s
, "connect ", 8);
1599 sk_write(s
, FWhost
, strlen(FWhost
));
1602 sprintf(buf
, " %d\n", FWport
);
1603 sk_write(s
, buf
, strlen(buf
));
1611 * Handle the key exchange and user authentication phases.
1613 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1617 static unsigned char *rsabuf
, *keystr1
, *keystr2
;
1618 unsigned char cookie
[8];
1619 struct RSAKey servkey
, hostkey
;
1620 struct MD5Context md5c
;
1621 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1622 static int tried_publickey
;
1623 static unsigned char session_id
[16];
1624 static int cipher_type
;
1625 static char username
[100];
1632 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1633 bombout(("Public key packet not received"));
1637 logevent("Received public keys");
1639 memcpy(cookie
, pktin
.body
, 8);
1641 i
= makekey(pktin
.body
+ 8, &servkey
, &keystr1
, 0);
1642 j
= makekey(pktin
.body
+ 8 + i
, &hostkey
, &keystr2
, 0);
1645 * Log the host key fingerprint.
1649 logevent("Host key fingerprint is:");
1650 strcpy(logmsg
, " ");
1651 hostkey
.comment
= NULL
;
1652 rsa_fingerprint(logmsg
+ strlen(logmsg
),
1653 sizeof(logmsg
) - strlen(logmsg
), &hostkey
);
1657 ssh1_remote_protoflags
= GET_32BIT(pktin
.body
+ 8 + i
+ j
);
1658 supported_ciphers_mask
= GET_32BIT(pktin
.body
+ 12 + i
+ j
);
1659 supported_auths_mask
= GET_32BIT(pktin
.body
+ 16 + i
+ j
);
1661 ssh1_local_protoflags
=
1662 ssh1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
1663 ssh1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
1666 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1667 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1668 MD5Update(&md5c
, pktin
.body
, 8);
1669 MD5Final(session_id
, &md5c
);
1671 for (i
= 0; i
< 32; i
++)
1672 session_key
[i
] = random_byte();
1674 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1676 rsabuf
= smalloc(len
);
1678 fatalbox("Out of memory");
1681 * Verify the host key.
1685 * First format the key into a string.
1687 int len
= rsastr_len(&hostkey
);
1688 char fingerprint
[100];
1689 char *keystr
= smalloc(len
);
1691 fatalbox("Out of memory");
1692 rsastr_fmt(keystr
, &hostkey
);
1693 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
1694 verify_ssh_host_key(savedhost
, savedport
, "rsa", keystr
,
1699 for (i
= 0; i
< 32; i
++) {
1700 rsabuf
[i
] = session_key
[i
];
1702 rsabuf
[i
] ^= session_id
[i
];
1705 if (hostkey
.bytes
> servkey
.bytes
) {
1706 rsaencrypt(rsabuf
, 32, &servkey
);
1707 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1709 rsaencrypt(rsabuf
, 32, &hostkey
);
1710 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1713 logevent("Encrypted session key");
1715 switch (cfg
.cipher
) {
1716 case CIPHER_BLOWFISH
:
1717 cipher_type
= SSH_CIPHER_BLOWFISH
;
1720 cipher_type
= SSH_CIPHER_DES
;
1723 cipher_type
= SSH_CIPHER_3DES
;
1726 c_write_str("AES not supported in SSH1, falling back to 3DES\r\n");
1727 cipher_type
= SSH_CIPHER_3DES
;
1730 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1732 ("Selected cipher not supported, falling back to 3DES\r\n");
1733 cipher_type
= SSH_CIPHER_3DES
;
1734 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1735 bombout(("Server violates SSH 1 protocol by "
1736 "not supporting 3DES encryption"));
1740 switch (cipher_type
) {
1741 case SSH_CIPHER_3DES
:
1742 logevent("Using 3DES encryption");
1744 case SSH_CIPHER_DES
:
1745 logevent("Using single-DES encryption");
1747 case SSH_CIPHER_BLOWFISH
:
1748 logevent("Using Blowfish encryption");
1752 send_packet(SSH1_CMSG_SESSION_KEY
,
1753 PKT_CHAR
, cipher_type
,
1754 PKT_DATA
, cookie
, 8,
1755 PKT_CHAR
, (len
* 8) >> 8, PKT_CHAR
, (len
* 8) & 0xFF,
1756 PKT_DATA
, rsabuf
, len
,
1757 PKT_INT
, ssh1_local_protoflags
, PKT_END
);
1759 logevent("Trying to enable encryption...");
1763 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
1764 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
: &ssh_3des
;
1765 cipher
->sesskey(session_key
);
1769 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1770 bombout(("Encryption not successfully enabled"));
1774 logevent("Successfully started encryption");
1780 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
1782 if (!ssh_get_line("login as: ",
1783 username
, sizeof(username
), FALSE
)) {
1785 * get_line failed to get a username.
1788 logevent("No username provided. Abandoning session.");
1789 ssh_state
= SSH_STATE_CLOSED
;
1793 c_write_str("login as: ");
1796 crWaitUntil(!ispkt
);
1798 switch (c
= *in
++) {
1807 c_write_str("\b \b");
1814 c_write_str("\b \b");
1824 if (((c
>= ' ' && c
<= '~') ||
1825 ((unsigned char) c
>= 160))
1826 && pos
< sizeof(username
)-1) {
1827 username
[pos
++] = c
;
1833 c_write_str("\r\n");
1834 username
[strcspn(username
, "\n\r")] = '\0';
1837 strncpy(username
, cfg
.username
, 99);
1838 username
[99] = '\0';
1841 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
1843 char userlog
[22 + sizeof(username
)];
1844 sprintf(userlog
, "Sent username \"%s\"", username
);
1846 if (flags
& FLAG_INTERACTIVE
&&
1847 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
1848 strcat(userlog
, "\r\n");
1849 c_write_str(userlog
);
1856 tried_publickey
= 0;
1858 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
1859 static char password
[100];
1860 static char prompt
[200];
1863 static int pwpkt_type
;
1865 * Show password prompt, having first obtained it via a TIS
1866 * or CryptoCard exchange if we're doing TIS or CryptoCard
1869 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
1870 if (agent_exists()) {
1872 * Attempt RSA authentication using Pageant.
1874 static unsigned char request
[5], *response
, *p
;
1875 static int responselen
;
1876 static int i
, nkeys
;
1877 static int authed
= FALSE
;
1880 logevent("Pageant is running. Requesting keys.");
1882 /* Request the keys held by the agent. */
1883 PUT_32BIT(request
, 1);
1884 request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
1885 agent_query(request
, 5, &r
, &responselen
);
1886 response
= (unsigned char *) r
;
1887 if (response
&& responselen
>= 5 &&
1888 response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
1890 nkeys
= GET_32BIT(p
);
1894 sprintf(buf
, "Pageant has %d SSH1 keys", nkeys
);
1897 for (i
= 0; i
< nkeys
; i
++) {
1898 static struct RSAKey key
;
1899 static Bignum challenge
;
1900 static char *commentp
;
1901 static int commentlen
;
1905 sprintf(buf
, "Trying Pageant key #%d", i
);
1909 p
+= ssh1_read_bignum(p
, &key
.exponent
);
1910 p
+= ssh1_read_bignum(p
, &key
.modulus
);
1911 commentlen
= GET_32BIT(p
);
1915 send_packet(SSH1_CMSG_AUTH_RSA
,
1916 PKT_BIGNUM
, key
.modulus
, PKT_END
);
1918 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1919 logevent("Key refused");
1922 logevent("Received RSA challenge");
1923 ssh1_read_bignum(pktin
.body
, &challenge
);
1925 char *agentreq
, *q
, *ret
;
1928 len
= 1 + 4; /* message type, bit count */
1929 len
+= ssh1_bignum_length(key
.exponent
);
1930 len
+= ssh1_bignum_length(key
.modulus
);
1931 len
+= ssh1_bignum_length(challenge
);
1932 len
+= 16; /* session id */
1933 len
+= 4; /* response format */
1934 agentreq
= smalloc(4 + len
);
1935 PUT_32BIT(agentreq
, len
);
1937 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
1938 PUT_32BIT(q
, bignum_bitcount(key
.modulus
));
1940 q
+= ssh1_write_bignum(q
, key
.exponent
);
1941 q
+= ssh1_write_bignum(q
, key
.modulus
);
1942 q
+= ssh1_write_bignum(q
, challenge
);
1943 memcpy(q
, session_id
, 16);
1945 PUT_32BIT(q
, 1); /* response format */
1946 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
1950 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
1951 logevent("Sending Pageant's response");
1952 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1953 PKT_DATA
, ret
+ 5, 16,
1957 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1959 ("Pageant's response accepted");
1960 if (flags
& FLAG_VERBOSE
) {
1962 ("Authenticated using RSA key \"");
1963 c_write(commentp
, commentlen
);
1964 c_write_str("\" from agent\r\n");
1969 ("Pageant's response not accepted");
1972 ("Pageant failed to answer challenge");
1976 logevent("No reply received from Pageant");
1979 freebn(key
.exponent
);
1980 freebn(key
.modulus
);
1989 if (*cfg
.keyfile
&& !tried_publickey
)
1990 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
1992 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1994 (supported_auths_mask
& (1 << SSH1_AUTH_TIS
))) {
1995 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
1996 logevent("Requested TIS authentication");
1997 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
1999 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
2000 logevent("TIS authentication declined");
2001 if (flags
& FLAG_INTERACTIVE
)
2002 c_write_str("TIS authentication refused.\r\n");
2004 int challengelen
= ((pktin
.body
[0] << 24) |
2005 (pktin
.body
[1] << 16) |
2006 (pktin
.body
[2] << 8) |
2008 logevent("Received TIS challenge");
2009 if (challengelen
> sizeof(prompt
) - 1)
2010 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2011 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2012 prompt
[challengelen
] = '\0';
2015 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
2017 (supported_auths_mask
& (1 << SSH1_AUTH_CCARD
))) {
2018 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
2019 logevent("Requested CryptoCard authentication");
2020 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
2022 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
2023 logevent("CryptoCard authentication declined");
2024 c_write_str("CryptoCard authentication refused.\r\n");
2026 int challengelen
= ((pktin
.body
[0] << 24) |
2027 (pktin
.body
[1] << 16) |
2028 (pktin
.body
[2] << 8) |
2030 logevent("Received CryptoCard challenge");
2031 if (challengelen
> sizeof(prompt
) - 1)
2032 challengelen
= sizeof(prompt
) - 1; /* prevent overrun */
2033 memcpy(prompt
, pktin
.body
+ 4, challengelen
);
2034 strncpy(prompt
+ challengelen
, "\r\nResponse : ",
2035 sizeof(prompt
) - challengelen
);
2036 prompt
[sizeof(prompt
) - 1] = '\0';
2039 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2040 sprintf(prompt
, "%.90s@%.90s's password: ",
2041 username
, savedhost
);
2043 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2044 char *comment
= NULL
;
2045 if (flags
& FLAG_VERBOSE
)
2046 c_write_str("Trying public key authentication.\r\n");
2047 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
2048 if (flags
& FLAG_VERBOSE
)
2049 c_write_str("No passphrase required.\r\n");
2052 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
2057 if (!ssh_get_line(prompt
, password
, sizeof(password
), TRUE
)) {
2059 * get_line failed to get a password (for example
2060 * because one was supplied on the command line
2061 * which has already failed to work). Terminate.
2063 send_packet(SSH1_MSG_DISCONNECT
,
2064 PKT_STR
, "No more passwords available to try",
2066 connection_fatal("Unable to authenticate");
2067 ssh_state
= SSH_STATE_CLOSED
;
2071 c_write_str(prompt
);
2075 crWaitUntil(!ispkt
);
2077 switch (c
= *in
++) {
2098 if (pos
< sizeof(password
)-1)
2099 password
[pos
++] = c
;
2103 c_write_str("\r\n");
2107 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
2109 * Try public key authentication with the specified
2112 static struct RSAKey pubkey
;
2113 static Bignum challenge
, response
;
2115 static unsigned char buffer
[32];
2117 tried_publickey
= 1;
2118 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
2120 c_write_str("Couldn't load public key from ");
2121 c_write_str(cfg
.keyfile
);
2122 c_write_str(".\r\n");
2123 continue; /* go and try password */
2126 c_write_str("Wrong passphrase.\r\n");
2127 tried_publickey
= 0;
2128 continue; /* try again */
2132 * Send a public key attempt.
2134 send_packet(SSH1_CMSG_AUTH_RSA
,
2135 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
2138 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2139 c_write_str("Server refused our public key.\r\n");
2140 continue; /* go and try password */
2142 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
2143 bombout(("Bizarre response to offer of public key"));
2146 ssh1_read_bignum(pktin
.body
, &challenge
);
2147 response
= rsadecrypt(challenge
, &pubkey
);
2148 freebn(pubkey
.private_exponent
); /* burn the evidence */
2150 for (i
= 0; i
< 32; i
++) {
2151 buffer
[i
] = bignum_byte(response
, 31 - i
);
2155 MD5Update(&md5c
, buffer
, 32);
2156 MD5Update(&md5c
, session_id
, 16);
2157 MD5Final(buffer
, &md5c
);
2159 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
2160 PKT_DATA
, buffer
, 16, PKT_END
);
2163 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2164 if (flags
& FLAG_VERBOSE
)
2166 ("Failed to authenticate with our public key.\r\n");
2167 continue; /* go and try password */
2168 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2170 ("Bizarre response to RSA authentication response"));
2174 break; /* we're through! */
2176 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
2178 * Defence against traffic analysis: we send a
2179 * whole bunch of packets containing strings of
2180 * different lengths. One of these strings is the
2181 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2182 * The others are all random data in
2183 * SSH1_MSG_IGNORE packets. This way a passive
2184 * listener can't tell which is the password, and
2185 * hence can't deduce the password length.
2187 * Anybody with a password length greater than 16
2188 * bytes is going to have enough entropy in their
2189 * password that a listener won't find it _that_
2190 * much help to know how long it is. So what we'll
2193 * - if password length < 16, we send 15 packets
2194 * containing string lengths 1 through 15
2196 * - otherwise, we let N be the nearest multiple
2197 * of 8 below the password length, and send 8
2198 * packets containing string lengths N through
2199 * N+7. This won't obscure the order of
2200 * magnitude of the password length, but it will
2201 * introduce a bit of extra uncertainty.
2203 * A few servers (the old 1.2.18 through 1.2.22)
2204 * can't deal with SSH1_MSG_IGNORE. For these
2205 * servers, we need an alternative defence. We make
2206 * use of the fact that the password is interpreted
2207 * as a C string: so we can append a NUL, then some
2210 if (ssh_remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
) {
2215 len
= strlen(password
);
2216 if (len
< sizeof(string
)) {
2218 strcpy(string
, password
);
2219 len
++; /* cover the zero byte */
2220 while (len
< sizeof(string
)) {
2221 string
[len
++] = (char) random_byte();
2226 send_packet(pwpkt_type
, PKT_INT
, len
,
2227 PKT_DATA
, s
, len
, PKT_END
);
2229 int bottom
, top
, pwlen
, i
;
2232 pwlen
= strlen(password
);
2234 bottom
= 0; /* zero length passwords are OK! :-) */
2237 bottom
= pwlen
& ~7;
2241 assert(pwlen
>= bottom
&& pwlen
<= top
);
2243 randomstr
= smalloc(top
+ 1);
2245 for (i
= bottom
; i
<= top
; i
++) {
2247 defer_packet(pwpkt_type
, PKT_STR
, password
,
2250 for (j
= 0; j
< i
; j
++) {
2252 randomstr
[j
] = random_byte();
2253 } while (randomstr
[j
] == '\0');
2255 randomstr
[i
] = '\0';
2256 defer_packet(SSH1_MSG_IGNORE
,
2257 PKT_STR
, randomstr
, PKT_END
);
2260 ssh_pkt_defersend();
2263 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
2266 logevent("Sent password");
2267 memset(password
, 0, strlen(password
));
2269 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2270 if (flags
& FLAG_VERBOSE
)
2271 c_write_str("Access denied\r\n");
2272 logevent("Authentication refused");
2273 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2274 logevent("Received disconnect request");
2275 ssh_state
= SSH_STATE_CLOSED
;
2277 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2278 bombout(("Strange packet received, type %d", pktin
.type
));
2283 logevent("Authentication successful");
2288 void sshfwd_close(struct ssh_channel
*c
)
2290 if (c
&& !c
->closes
) {
2291 if (ssh_version
== 1) {
2292 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
,
2295 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2296 ssh2_pkt_adduint32(c
->remoteid
);
2300 if (c
->type
== CHAN_X11
) {
2302 logevent("Forwarded X11 connection terminated");
2303 } else if (c
->type
== CHAN_SOCKDATA
) {
2305 logevent("Forwarded port closed");
2310 void sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
)
2312 if (ssh_version
== 1) {
2313 send_packet(SSH1_MSG_CHANNEL_DATA
,
2314 PKT_INT
, c
->remoteid
,
2315 PKT_INT
, len
, PKT_DATA
, buf
, len
, PKT_END
);
2317 ssh2_add_channel_data(c
, buf
, len
);
2322 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
)
2328 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
2331 if (ssh_state
== SSH_STATE_CLOSED
)
2334 if (cfg
.agentfwd
&& agent_exists()) {
2335 logevent("Requesting agent forwarding");
2336 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
2340 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2341 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2342 bombout(("Protocol confusion"));
2344 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2345 logevent("Agent forwarding refused");
2347 logevent("Agent forwarding enabled");
2348 ssh_agentfwd_enabled
= TRUE
;
2352 if (cfg
.x11_forward
) {
2353 char proto
[20], data
[64];
2354 logevent("Requesting X11 forwarding");
2355 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
2356 if (ssh1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
2357 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2358 PKT_STR
, proto
, PKT_STR
, data
,
2359 PKT_INT
, 0, PKT_END
);
2361 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2362 PKT_STR
, proto
, PKT_STR
, data
, PKT_END
);
2367 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2368 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2369 bombout(("Protocol confusion"));
2371 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2372 logevent("X11 forwarding refused");
2374 logevent("X11 forwarding enabled");
2375 ssh_X11_fwd_enabled
= TRUE
;
2383 char sports
[256], dports
[256], host
[256];
2386 ssh_rportfwds
= newtree234(ssh_rportcmp
);
2387 /* Add port forwardings. */
2392 while (*e
&& *e
!= '\t')
2398 while (*e
&& *e
!= ':')
2408 dport
= atoi(dports
);
2409 sport
= atoi(sports
);
2410 if (sport
&& dport
) {
2412 pfd_addforward(host
, dport
, sport
);
2413 sprintf(buf
, "Local port %d forwarding to %s:%d",
2414 sport
, host
, dport
);
2417 struct ssh_rportfwd
*pf
;
2418 pf
= smalloc(sizeof(*pf
));
2419 strcpy(pf
->host
, host
);
2421 if (add234(ssh_rportfwds
, pf
) != pf
) {
2423 "Duplicate remote port forwarding to %s:%s",
2427 sprintf(buf
, "Requesting remote port %d forward to %s:%d",
2428 sport
, host
, dport
);
2430 send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST
,
2442 send_packet(SSH1_CMSG_REQUEST_PTY
,
2443 PKT_STR
, cfg
.termtype
,
2444 PKT_INT
, rows
, PKT_INT
, cols
,
2445 PKT_INT
, 0, PKT_INT
, 0, PKT_CHAR
, 0, PKT_END
);
2446 ssh_state
= SSH_STATE_INTERMED
;
2450 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2451 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2452 bombout(("Protocol confusion"));
2454 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2455 c_write_str("Server refused to allocate pty\r\n");
2456 ssh_editing
= ssh_echoing
= 1;
2458 logevent("Allocated pty");
2460 ssh_editing
= ssh_echoing
= 1;
2463 if (cfg
.compression
) {
2464 send_packet(SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
2468 if (pktin
.type
!= SSH1_SMSG_SUCCESS
2469 && pktin
.type
!= SSH1_SMSG_FAILURE
) {
2470 bombout(("Protocol confusion"));
2472 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2473 c_write_str("Server refused to compress\r\n");
2475 logevent("Started compression");
2476 ssh1_compressing
= TRUE
;
2477 zlib_compress_init();
2478 zlib_decompress_init();
2481 if (*cfg
.remote_cmd_ptr
)
2482 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cfg
.remote_cmd_ptr
,
2485 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
2486 logevent("Started session");
2488 ssh_state
= SSH_STATE_SESSION
;
2492 ssh_special(TS_EOF
);
2494 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
2496 ssh_channels
= newtree234(ssh_channelcmp
);
2500 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
2501 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
2502 long len
= GET_32BIT(pktin
.body
);
2503 from_backend(pktin
.type
== SSH1_SMSG_STDERR_DATA
,
2504 pktin
.body
+ 4, len
);
2505 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2506 ssh_state
= SSH_STATE_CLOSED
;
2507 logevent("Received disconnect request");
2509 } else if (pktin
.type
== SSH1_SMSG_X11_OPEN
) {
2510 /* Remote side is trying to open a channel to talk to our
2511 * X-Server. Give them back a local channel number. */
2512 struct ssh_channel
*c
;
2514 logevent("Received X11 connect request");
2515 /* Refuse if X11 forwarding is disabled. */
2516 if (!ssh_X11_fwd_enabled
) {
2517 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2518 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2519 logevent("Rejected X11 connect request");
2521 c
= smalloc(sizeof(struct ssh_channel
));
2523 if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
2524 logevent("opening X11 forward connection failed");
2526 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2527 PKT_INT
, GET_32BIT(pktin
.body
),
2531 ("opening X11 forward connection succeeded");
2532 c
->remoteid
= GET_32BIT(pktin
.body
);
2533 c
->localid
= alloc_channel_id();
2535 c
->type
= CHAN_X11
; /* identify channel type */
2536 add234(ssh_channels
, c
);
2537 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2538 PKT_INT
, c
->remoteid
, PKT_INT
,
2539 c
->localid
, PKT_END
);
2540 logevent("Opened X11 forward channel");
2543 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
2544 /* Remote side is trying to open a channel to talk to our
2545 * agent. Give them back a local channel number. */
2546 struct ssh_channel
*c
;
2548 /* Refuse if agent forwarding is disabled. */
2549 if (!ssh_agentfwd_enabled
) {
2550 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2551 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2553 c
= smalloc(sizeof(struct ssh_channel
));
2554 c
->remoteid
= GET_32BIT(pktin
.body
);
2555 c
->localid
= alloc_channel_id();
2557 c
->type
= CHAN_AGENT
; /* identify channel type */
2558 c
->u
.a
.lensofar
= 0;
2559 add234(ssh_channels
, c
);
2560 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2561 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2564 } else if (pktin
.type
== SSH1_MSG_PORT_OPEN
) {
2565 /* Remote side is trying to open a channel to talk to a
2566 * forwarded port. Give them back a local channel number. */
2567 struct ssh_channel
*c
;
2568 struct ssh_rportfwd pf
;
2570 char host
[256], buf
[1024];
2572 c
= smalloc(sizeof(struct ssh_channel
));
2574 hostsize
= GET_32BIT(pktin
.body
+4);
2575 for(h
= host
, p
= pktin
.body
+8; hostsize
!= 0; hostsize
--) {
2576 if (h
+1 < host
+sizeof(host
))
2581 port
= GET_32BIT(p
);
2583 strcpy(pf
.host
, host
);
2586 if (find234(ssh_rportfwds
, &pf
, NULL
) == NULL
) {
2587 sprintf(buf
, "Rejected remote port open request for %s:%d",
2590 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2591 PKT_INT
, GET_32BIT(pktin
.body
), PKT_END
);
2593 sprintf(buf
, "Received remote port open request for %s:%d",
2596 e
= pfd_newconnect(&c
->u
.pfd
.s
, host
, port
, c
);
2599 sprintf(buf
, "Port open failed: %s", e
);
2602 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2603 PKT_INT
, GET_32BIT(pktin
.body
),
2606 c
->remoteid
= GET_32BIT(pktin
.body
);
2607 c
->localid
= alloc_channel_id();
2609 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
2610 add234(ssh_channels
, c
);
2611 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2612 PKT_INT
, c
->remoteid
, PKT_INT
,
2613 c
->localid
, PKT_END
);
2614 logevent("Forwarded port opened successfully");
2618 } else if (pktin
.type
== SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
) {
2619 unsigned int remoteid
= GET_32BIT(pktin
.body
);
2620 unsigned int localid
= GET_32BIT(pktin
.body
+4);
2621 struct ssh_channel
*c
;
2623 c
= find234(ssh_channels
, &remoteid
, ssh_channelfind
);
2625 c
->remoteid
= localid
;
2626 pfd_confirm(c
->u
.pfd
.s
);
2631 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
2632 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
2633 /* Remote side closes a channel. */
2634 unsigned i
= GET_32BIT(pktin
.body
);
2635 struct ssh_channel
*c
;
2636 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2640 (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
2641 if (!(c
->closes
& closetype
))
2642 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
,
2644 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
2645 logevent("Forwarded X11 connection terminated");
2646 assert(c
->u
.x11
.s
!= NULL
);
2647 x11_close(c
->u
.x11
.s
);
2650 if ((c
->closes
== 0) && (c
->type
== CHAN_SOCKDATA
)) {
2651 logevent("Forwarded port closed");
2652 assert(c
->u
.pfd
.s
!= NULL
);
2653 pfd_close(c
->u
.pfd
.s
);
2656 c
->closes
|= closetype
;
2657 if (c
->closes
== 3) {
2658 del234(ssh_channels
, c
);
2662 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
2663 /* Data sent down one of our channels. */
2664 int i
= GET_32BIT(pktin
.body
);
2665 int len
= GET_32BIT(pktin
.body
+ 4);
2666 unsigned char *p
= pktin
.body
+ 8;
2667 struct ssh_channel
*c
;
2668 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2672 x11_send(c
->u
.x11
.s
, p
, len
);
2675 pfd_send(c
->u
.pfd
.s
, p
, len
);
2678 /* Data for an agent message. Buffer it. */
2680 if (c
->u
.a
.lensofar
< 4) {
2681 int l
= min(4 - c
->u
.a
.lensofar
, len
);
2682 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
,
2686 c
->u
.a
.lensofar
+= l
;
2688 if (c
->u
.a
.lensofar
== 4) {
2690 4 + GET_32BIT(c
->u
.a
.msglen
);
2691 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
2692 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
2694 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
2696 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
2698 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
,
2702 c
->u
.a
.lensofar
+= l
;
2704 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
2705 void *reply
, *sentreply
;
2707 agent_query(c
->u
.a
.message
,
2708 c
->u
.a
.totallen
, &reply
,
2713 /* Fake SSH_AGENT_FAILURE. */
2714 sentreply
= "\0\0\0\1\5";
2717 send_packet(SSH1_MSG_CHANNEL_DATA
,
2718 PKT_INT
, c
->remoteid
,
2720 PKT_DATA
, sentreply
, replylen
,
2724 sfree(c
->u
.a
.message
);
2725 c
->u
.a
.lensofar
= 0;
2731 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2732 /* may be from EXEC_SHELL on some servers */
2733 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2734 /* may be from EXEC_SHELL on some servers
2735 * if no pty is available or in other odd cases. Ignore */
2736 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
2737 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
2739 bombout(("Strange packet received: type %d", pktin
.type
));
2744 int len
= min(inlen
, 512);
2745 send_packet(SSH1_CMSG_STDIN_DATA
,
2746 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
2757 * Utility routine for decoding comma-separated strings in KEXINIT.
2759 static int in_commasep_string(char *needle
, char *haystack
, int haylen
)
2761 int needlen
= strlen(needle
);
2764 * Is it at the start of the string?
2766 if (haylen
>= needlen
&& /* haystack is long enough */
2767 !memcmp(needle
, haystack
, needlen
) && /* initial match */
2768 (haylen
== needlen
|| haystack
[needlen
] == ',')
2769 /* either , or EOS follows */
2773 * If not, search for the next comma and resume after that.
2774 * If no comma found, terminate.
2776 while (haylen
> 0 && *haystack
!= ',')
2777 haylen
--, haystack
++;
2780 haylen
--, haystack
++; /* skip over comma itself */
2785 * SSH2 key creation method.
2787 static void ssh2_mkkey(Bignum K
, char *H
, char *sessid
, char chr
,
2791 /* First 20 bytes. */
2794 SHA_Bytes(&s
, H
, 20);
2795 SHA_Bytes(&s
, &chr
, 1);
2796 SHA_Bytes(&s
, sessid
, 20);
2797 SHA_Final(&s
, keyspace
);
2798 /* Next 20 bytes. */
2801 SHA_Bytes(&s
, H
, 20);
2802 SHA_Bytes(&s
, keyspace
, 20);
2803 SHA_Final(&s
, keyspace
+ 20);
2807 * Handle the SSH2 transport layer.
2809 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
2811 static int i
, j
, len
, nbits
, pbits
;
2813 static Bignum p
, g
, e
, f
, K
;
2814 static int kex_init_value
, kex_reply_value
;
2815 static const struct ssh_mac
**maclist
;
2817 static const struct ssh2_cipher
*cscipher_tobe
= NULL
;
2818 static const struct ssh2_cipher
*sccipher_tobe
= NULL
;
2819 static const struct ssh_mac
*csmac_tobe
= NULL
;
2820 static const struct ssh_mac
*scmac_tobe
= NULL
;
2821 static const struct ssh_compress
*cscomp_tobe
= NULL
;
2822 static const struct ssh_compress
*sccomp_tobe
= NULL
;
2823 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
2824 static int hostkeylen
, siglen
;
2825 static void *hkey
; /* actual host key */
2826 static unsigned char exchange_hash
[20];
2827 static unsigned char keyspace
[40];
2828 static const struct ssh2_ciphers
*preferred_cipher
;
2829 static const struct ssh_compress
*preferred_comp
;
2830 static int first_kex
;
2837 * Set up the preferred cipher and compression.
2839 if (cfg
.cipher
== CIPHER_BLOWFISH
) {
2840 preferred_cipher
= &ssh2_blowfish
;
2841 } else if (cfg
.cipher
== CIPHER_DES
) {
2842 logevent("Single DES not supported in SSH2; using 3DES");
2843 preferred_cipher
= &ssh2_3des
;
2844 } else if (cfg
.cipher
== CIPHER_3DES
) {
2845 preferred_cipher
= &ssh2_3des
;
2846 } else if (cfg
.cipher
== CIPHER_AES
) {
2847 preferred_cipher
= &ssh2_aes
;
2849 /* Shouldn't happen, but we do want to initialise to _something_. */
2850 preferred_cipher
= &ssh2_3des
;
2852 if (cfg
.compression
)
2853 preferred_comp
= &ssh_zlib
;
2855 preferred_comp
= &ssh_comp_none
;
2858 * Be prepared to work around the buggy MAC problem.
2860 if (cfg
.buggymac
|| (ssh_remote_bugs
& BUG_SSH2_HMAC
))
2861 maclist
= buggymacs
, nmacs
= lenof(buggymacs
);
2863 maclist
= macs
, nmacs
= lenof(macs
);
2867 * Construct and send our key exchange packet.
2869 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
2870 for (i
= 0; i
< 16; i
++)
2871 ssh2_pkt_addbyte((unsigned char) random_byte());
2872 /* List key exchange algorithms. */
2873 ssh2_pkt_addstring_start();
2874 for (i
= 0; i
< lenof(kex_algs
); i
++) {
2875 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
2876 if (i
< lenof(kex_algs
) - 1)
2877 ssh2_pkt_addstring_str(",");
2879 /* List server host key algorithms. */
2880 ssh2_pkt_addstring_start();
2881 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
2882 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
2883 if (i
< lenof(hostkey_algs
) - 1)
2884 ssh2_pkt_addstring_str(",");
2886 /* List client->server encryption algorithms. */
2887 ssh2_pkt_addstring_start();
2888 for (i
= 0; i
< lenof(ciphers
) + 1; i
++) {
2889 const struct ssh2_ciphers
*c
=
2890 i
== 0 ? preferred_cipher
: ciphers
[i
- 1];
2891 for (j
= 0; j
< c
->nciphers
; j
++) {
2892 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
2893 if (i
< lenof(ciphers
) || j
< c
->nciphers
- 1)
2894 ssh2_pkt_addstring_str(",");
2897 /* List server->client encryption algorithms. */
2898 ssh2_pkt_addstring_start();
2899 for (i
= 0; i
< lenof(ciphers
) + 1; i
++) {
2900 const struct ssh2_ciphers
*c
=
2901 i
== 0 ? preferred_cipher
: ciphers
[i
- 1];
2902 for (j
= 0; j
< c
->nciphers
; j
++) {
2903 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
2904 if (i
< lenof(ciphers
) || j
< c
->nciphers
- 1)
2905 ssh2_pkt_addstring_str(",");
2908 /* List client->server MAC algorithms. */
2909 ssh2_pkt_addstring_start();
2910 for (i
= 0; i
< nmacs
; i
++) {
2911 ssh2_pkt_addstring_str(maclist
[i
]->name
);
2913 ssh2_pkt_addstring_str(",");
2915 /* List server->client MAC algorithms. */
2916 ssh2_pkt_addstring_start();
2917 for (i
= 0; i
< nmacs
; i
++) {
2918 ssh2_pkt_addstring_str(maclist
[i
]->name
);
2920 ssh2_pkt_addstring_str(",");
2922 /* List client->server compression algorithms. */
2923 ssh2_pkt_addstring_start();
2924 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
2925 const struct ssh_compress
*c
=
2926 i
== 0 ? preferred_comp
: compressions
[i
- 1];
2927 ssh2_pkt_addstring_str(c
->name
);
2928 if (i
< lenof(compressions
))
2929 ssh2_pkt_addstring_str(",");
2931 /* List server->client compression algorithms. */
2932 ssh2_pkt_addstring_start();
2933 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
2934 const struct ssh_compress
*c
=
2935 i
== 0 ? preferred_comp
: compressions
[i
- 1];
2936 ssh2_pkt_addstring_str(c
->name
);
2937 if (i
< lenof(compressions
))
2938 ssh2_pkt_addstring_str(",");
2940 /* List client->server languages. Empty list. */
2941 ssh2_pkt_addstring_start();
2942 /* List server->client languages. Empty list. */
2943 ssh2_pkt_addstring_start();
2944 /* First KEX packet does _not_ follow, because we're not that brave. */
2945 ssh2_pkt_addbool(FALSE
);
2947 ssh2_pkt_adduint32(0);
2949 exhash
= exhashbase
;
2950 sha_string(&exhash
, pktout
.data
+ 5, pktout
.length
- 5);
2956 sha_string(&exhash
, pktin
.data
+ 5, pktin
.length
- 5);
2959 * Now examine the other side's KEXINIT to see what we're up
2962 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
2963 bombout(("expected key exchange packet from server"));
2968 cscipher_tobe
= NULL
;
2969 sccipher_tobe
= NULL
;
2974 pktin
.savedpos
+= 16; /* skip garbage cookie */
2975 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
2976 for (i
= 0; i
< lenof(kex_algs
); i
++) {
2977 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
2982 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
2983 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
2984 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
2985 hostkey
= hostkey_algs
[i
];
2989 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
2990 for (i
= 0; i
< lenof(ciphers
) + 1; i
++) {
2991 const struct ssh2_ciphers
*c
=
2992 i
== 0 ? preferred_cipher
: ciphers
[i
- 1];
2993 for (j
= 0; j
< c
->nciphers
; j
++) {
2994 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
2995 cscipher_tobe
= c
->list
[j
];
3002 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
3003 for (i
= 0; i
< lenof(ciphers
) + 1; i
++) {
3004 const struct ssh2_ciphers
*c
=
3005 i
== 0 ? preferred_cipher
: ciphers
[i
- 1];
3006 for (j
= 0; j
< c
->nciphers
; j
++) {
3007 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
3008 sccipher_tobe
= c
->list
[j
];
3015 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
3016 for (i
= 0; i
< nmacs
; i
++) {
3017 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3018 csmac_tobe
= maclist
[i
];
3022 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
3023 for (i
= 0; i
< nmacs
; i
++) {
3024 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
3025 scmac_tobe
= maclist
[i
];
3029 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
3030 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3031 const struct ssh_compress
*c
=
3032 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3033 if (in_commasep_string(c
->name
, str
, len
)) {
3038 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
3039 for (i
= 0; i
< lenof(compressions
) + 1; i
++) {
3040 const struct ssh_compress
*c
=
3041 i
== 0 ? preferred_comp
: compressions
[i
- 1];
3042 if (in_commasep_string(c
->name
, str
, len
)) {
3049 * Work out the number of bits of key we will need from the key
3050 * exchange. We start with the maximum key length of either
3056 csbits
= cscipher_tobe
->keylen
;
3057 scbits
= sccipher_tobe
->keylen
;
3058 nbits
= (csbits
> scbits ? csbits
: scbits
);
3060 /* The keys only have 160-bit entropy, since they're based on
3061 * a SHA-1 hash. So cap the key size at 160 bits. */
3066 * If we're doing Diffie-Hellman group exchange, start by
3067 * requesting a group.
3069 if (kex
== &ssh_diffiehellman_gex
) {
3070 logevent("Doing Diffie-Hellman group exchange");
3072 * Work out how big a DH group we will need to allow that
3075 pbits
= 512 << ((nbits
- 1) / 64);
3076 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
3077 ssh2_pkt_adduint32(pbits
);
3081 if (pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
3082 bombout(("expected key exchange group packet from server"));
3085 p
= ssh2_pkt_getmp();
3086 g
= ssh2_pkt_getmp();
3087 dh_setup_group(p
, g
);
3088 kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
3089 kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
3092 kex_init_value
= SSH2_MSG_KEXDH_INIT
;
3093 kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
3096 logevent("Doing Diffie-Hellman key exchange");
3098 * Now generate and send e for Diffie-Hellman.
3100 e
= dh_create_e(nbits
* 2);
3101 ssh2_pkt_init(kex_init_value
);
3106 if (pktin
.type
!= kex_reply_value
) {
3107 bombout(("expected key exchange reply packet from server"));
3110 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
3111 f
= ssh2_pkt_getmp();
3112 ssh2_pkt_getstring(&sigdata
, &siglen
);
3116 sha_string(&exhash
, hostkeydata
, hostkeylen
);
3117 if (kex
== &ssh_diffiehellman_gex
) {
3118 sha_uint32(&exhash
, pbits
);
3119 sha_mpint(&exhash
, p
);
3120 sha_mpint(&exhash
, g
);
3122 sha_mpint(&exhash
, e
);
3123 sha_mpint(&exhash
, f
);
3124 sha_mpint(&exhash
, K
);
3125 SHA_Final(&exhash
, exchange_hash
);
3130 debug(("Exchange hash is:\n"));
3131 dmemdump(exchange_hash
, 20);
3134 hkey
= hostkey
->newkey(hostkeydata
, hostkeylen
);
3136 !hostkey
->verifysig(hkey
, sigdata
, siglen
, exchange_hash
, 20)) {
3137 bombout(("Server's host key did not match the signature supplied"));
3142 * Expect SSH2_MSG_NEWKEYS from server.
3145 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
3146 bombout(("expected new-keys packet from server"));
3151 * Authenticate remote host: verify host key. (We've already
3152 * checked the signature of the exchange hash.)
3154 keystr
= hostkey
->fmtkey(hkey
);
3155 fingerprint
= hostkey
->fingerprint(hkey
);
3156 verify_ssh_host_key(savedhost
, savedport
, hostkey
->keytype
,
3157 keystr
, fingerprint
);
3158 if (first_kex
) { /* don't bother logging this in rekeys */
3159 logevent("Host key fingerprint is:");
3160 logevent(fingerprint
);
3164 hostkey
->freekey(hkey
);
3167 * Send SSH2_MSG_NEWKEYS.
3169 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
3173 * Create and initialise session keys.
3175 cscipher
= cscipher_tobe
;
3176 sccipher
= sccipher_tobe
;
3179 cscomp
= cscomp_tobe
;
3180 sccomp
= sccomp_tobe
;
3181 cscomp
->compress_init();
3182 sccomp
->decompress_init();
3184 * Set IVs after keys. Here we use the exchange hash from the
3185 * _first_ key exchange.
3188 memcpy(ssh2_session_id
, exchange_hash
, sizeof(exchange_hash
));
3189 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'C', keyspace
);
3190 cscipher
->setcskey(keyspace
);
3191 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'D', keyspace
);
3192 sccipher
->setsckey(keyspace
);
3193 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'A', keyspace
);
3194 cscipher
->setcsiv(keyspace
);
3195 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'B', keyspace
);
3196 sccipher
->setsciv(keyspace
);
3197 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'E', keyspace
);
3198 csmac
->setcskey(keyspace
);
3199 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'F', keyspace
);
3200 scmac
->setsckey(keyspace
);
3203 * If this is the first key exchange phase, we must pass the
3204 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
3205 * wants to see it but because it will need time to initialise
3206 * itself before it sees an actual packet. In subsequent key
3207 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
3208 * it would only confuse the layer above.
3216 * Now we're encrypting. Begin returning 1 to the protocol main
3217 * function so that other things can run on top of the
3218 * transport. If we ever see a KEXINIT, we must go back to the
3221 while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
)) {
3224 logevent("Server initiated key re-exchange");
3225 goto begin_key_exchange
;
3231 * Add data to an SSH2 channel output buffer.
3233 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
,
3236 if (c
->v2
.outbufsize
< c
->v2
.outbuflen
+ len
) {
3237 c
->v2
.outbufsize
= c
->v2
.outbuflen
+ len
+ 1024;
3238 c
->v2
.outbuffer
= srealloc(c
->v2
.outbuffer
, c
->v2
.outbufsize
);
3240 memcpy(c
->v2
.outbuffer
+ c
->v2
.outbuflen
, buf
, len
);
3241 c
->v2
.outbuflen
+= len
;
3245 * Attempt to send data on an SSH2 channel.
3247 static void ssh2_try_send(struct ssh_channel
*c
)
3249 while (c
->v2
.remwindow
> 0 && c
->v2
.outbuflen
> 0) {
3250 unsigned len
= c
->v2
.remwindow
;
3251 if (len
> c
->v2
.outbuflen
)
3252 len
= c
->v2
.outbuflen
;
3253 if (len
> c
->v2
.remmaxpkt
)
3254 len
= c
->v2
.remmaxpkt
;
3255 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
3256 ssh2_pkt_adduint32(c
->remoteid
);
3257 ssh2_pkt_addstring_start();
3258 ssh2_pkt_addstring_data(c
->v2
.outbuffer
, len
);
3260 c
->v2
.outbuflen
-= len
;
3261 memmove(c
->v2
.outbuffer
, c
->v2
.outbuffer
+ len
, c
->v2
.outbuflen
);
3262 c
->v2
.remwindow
-= len
;
3267 * Handle the SSH2 userauth and connection layers.
3269 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
3272 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
,
3274 AUTH_KEYBOARD_INTERACTIVE
3278 AUTH_TYPE_PUBLICKEY
,
3279 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
3280 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
3282 AUTH_TYPE_KEYBOARD_INTERACTIVE
3284 static int gotit
, need_pw
, can_pubkey
, can_passwd
, can_keyb_inter
;
3285 static int tried_pubkey_config
, tried_agent
, tried_keyb_inter
;
3286 static int we_are_in
;
3287 static int num_prompts
, echo
;
3288 static char username
[100];
3289 static char pwprompt
[200];
3290 static char password
[100];
3295 * Request userauth protocol, and await a response to it.
3297 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
3298 ssh2_pkt_addstring("ssh-userauth");
3300 crWaitUntilV(ispkt
);
3301 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
3302 bombout(("Server refused user authentication protocol"));
3307 * We repeat this whole loop, including the username prompt,
3308 * until we manage a successful authentication. If the user
3309 * types the wrong _password_, they are sent back to the
3310 * beginning to try another username. (If they specify a
3311 * username in the config, they are never asked, even if they
3312 * do give a wrong password.)
3314 * I think this best serves the needs of
3316 * - the people who have no configuration, no keys, and just
3317 * want to try repeated (username,password) pairs until they
3318 * type both correctly
3320 * - people who have keys and configuration but occasionally
3321 * need to fall back to passwords
3323 * - people with a key held in Pageant, who might not have
3324 * logged in to a particular machine before; so they want to
3325 * type a username, and then _either_ their key will be
3326 * accepted, _or_ they will type a password. If they mistype
3327 * the username they will want to be able to get back and
3338 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
3340 if (!ssh_get_line("login as: ",
3341 username
, sizeof(username
), FALSE
)) {
3343 * get_line failed to get a username.
3346 logevent("No username provided. Abandoning session.");
3347 ssh_state
= SSH_STATE_CLOSED
;
3351 c_write_str("login as: ");
3354 crWaitUntilV(!ispkt
);
3356 switch (c
= *in
++) {
3365 c_write_str("\b \b");
3372 c_write_str("\b \b");
3382 if (((c
>= ' ' && c
<= '~') ||
3383 ((unsigned char) c
>= 160))
3384 && pos
< sizeof(username
)-1) {
3385 username
[pos
++] = c
;
3392 c_write_str("\r\n");
3393 username
[strcspn(username
, "\n\r")] = '\0';
3396 strncpy(username
, cfg
.username
, 99);
3397 username
[99] = '\0';
3398 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
3399 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
3405 * Send an authentication request using method "none": (a)
3406 * just in case it succeeds, and (b) so that we know what
3407 * authentication methods we can usefully try next.
3409 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3410 ssh2_pkt_addstring(username
);
3411 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3412 ssh2_pkt_addstring("none"); /* method */
3414 type
= AUTH_TYPE_NONE
;
3418 tried_pubkey_config
= FALSE
;
3419 tried_agent
= FALSE
;
3423 * Wait for the result of the last authentication request.
3426 crWaitUntilV(ispkt
);
3427 while (pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
3431 * Don't show the banner if we're operating in
3432 * non-verbose non-interactive mode. (It's probably
3433 * a script, which means nobody will read the
3434 * banner _anyway_, and moreover the printing of
3435 * the banner will screw up processing on the
3436 * output of (say) plink.)
3438 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
3439 ssh2_pkt_getstring(&banner
, &size
);
3441 c_write_untrusted(banner
, size
);
3443 crWaitUntilV(ispkt
);
3445 if (pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
3446 logevent("Access granted");
3451 if (pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
3453 ("Strange packet received during authentication: type %d",
3461 * OK, we're now sitting on a USERAUTH_FAILURE message, so
3462 * we can look at the string in it and know what we can
3463 * helpfully try next.
3468 ssh2_pkt_getstring(&methods
, &methlen
);
3469 if (!ssh2_pkt_getbool()) {
3471 * We have received an unequivocal Access
3472 * Denied. This can translate to a variety of
3475 * - if we'd just tried "none" authentication,
3476 * it's not worth printing anything at all
3478 * - if we'd just tried a public key _offer_,
3479 * the message should be "Server refused our
3480 * key" (or no message at all if the key
3481 * came from Pageant)
3483 * - if we'd just tried anything else, the
3484 * message really should be "Access denied".
3486 * Additionally, if we'd just tried password
3487 * authentication, we should break out of this
3488 * whole loop so as to go back to the username
3491 if (type
== AUTH_TYPE_NONE
) {
3493 } else if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
3494 type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
3495 if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
3496 c_write_str("Server refused our key\r\n");
3497 logevent("Server refused public key");
3499 c_write_str("Access denied\r\n");
3500 logevent("Access denied");
3501 if (type
== AUTH_TYPE_PASSWORD
) {
3507 c_write_str("Further authentication required\r\n");
3508 logevent("Further authentication required");
3512 in_commasep_string("publickey", methods
, methlen
);
3514 in_commasep_string("password", methods
, methlen
);
3516 in_commasep_string("password", methods
, methlen
);
3518 in_commasep_string("keyboard-interactive", methods
, methlen
);
3523 if (!method
&& can_keyb_inter
&& !tried_keyb_inter
) {
3524 method
= AUTH_KEYBOARD_INTERACTIVE
;
3525 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
3526 tried_keyb_inter
= TRUE
;
3528 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3529 ssh2_pkt_addstring(username
);
3530 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3531 ssh2_pkt_addstring("keyboard-interactive"); /* method */
3532 ssh2_pkt_addstring(""); /* lang */
3533 ssh2_pkt_addstring("");
3536 crWaitUntilV(ispkt
);
3537 if (pktin
.type
!= SSH2_MSG_USERAUTH_INFO_REQUEST
) {
3538 if (pktin
.type
== SSH2_MSG_USERAUTH_FAILURE
)
3540 logevent("Keyboard-interactive authentication refused");
3541 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
3545 /* We've got packet with that "interactive" info
3546 dump banners, and set its prompt as ours */
3548 char *name
, *inst
, *lang
, *prompt
;
3549 int name_len
, inst_len
, lang_len
, prompt_len
;
3550 ssh2_pkt_getstring(&name
, &name_len
);
3551 ssh2_pkt_getstring(&inst
, &inst_len
);
3552 ssh2_pkt_getstring(&lang
, &lang_len
);
3554 c_write_untrusted(name
, name_len
);
3556 c_write_untrusted(inst
, inst_len
);
3557 num_prompts
= ssh2_pkt_getuint32();
3559 ssh2_pkt_getstring(&prompt
, &prompt_len
);
3560 strncpy(pwprompt
, prompt
, sizeof(pwprompt
));
3563 echo
= ssh2_pkt_getbool();
3567 if (!method
&& can_pubkey
&& agent_exists() && !tried_agent
) {
3569 * Attempt public-key authentication using Pageant.
3571 static unsigned char request
[5], *response
, *p
;
3572 static int responselen
;
3573 static int i
, nkeys
;
3574 static int authed
= FALSE
;
3579 logevent("Pageant is running. Requesting keys.");
3581 /* Request the keys held by the agent. */
3582 PUT_32BIT(request
, 1);
3583 request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
3584 agent_query(request
, 5, &r
, &responselen
);
3585 response
= (unsigned char *) r
;
3586 if (response
&& responselen
>= 5 &&
3587 response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
3589 nkeys
= GET_32BIT(p
);
3593 sprintf(buf
, "Pageant has %d SSH2 keys", nkeys
);
3596 for (i
= 0; i
< nkeys
; i
++) {
3597 static char *pkblob
, *alg
, *commentp
;
3598 static int pklen
, alglen
, commentlen
;
3599 static int siglen
, retlen
, len
;
3600 static char *q
, *agentreq
, *ret
;
3605 sprintf(buf
, "Trying Pageant key #%d", i
);
3608 pklen
= GET_32BIT(p
);
3612 alglen
= GET_32BIT(pkblob
);
3614 commentlen
= GET_32BIT(p
);
3618 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3619 ssh2_pkt_addstring(username
);
3620 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3621 ssh2_pkt_addstring("publickey"); /* method */
3622 ssh2_pkt_addbool(FALSE
); /* no signature included */
3623 ssh2_pkt_addstring_start();
3624 ssh2_pkt_addstring_data(alg
, alglen
);
3625 ssh2_pkt_addstring_start();
3626 ssh2_pkt_addstring_data(pkblob
, pklen
);
3629 crWaitUntilV(ispkt
);
3630 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3631 logevent("Key refused");
3635 if (flags
& FLAG_VERBOSE
) {
3637 ("Authenticating with public key \"");
3638 c_write(commentp
, commentlen
);
3639 c_write_str("\" from agent\r\n");
3643 * Server is willing to accept the key.
3644 * Construct a SIGN_REQUEST.
3646 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3647 ssh2_pkt_addstring(username
);
3648 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3649 ssh2_pkt_addstring("publickey"); /* method */
3650 ssh2_pkt_addbool(TRUE
);
3651 ssh2_pkt_addstring_start();
3652 ssh2_pkt_addstring_data(alg
, alglen
);
3653 ssh2_pkt_addstring_start();
3654 ssh2_pkt_addstring_data(pkblob
, pklen
);
3656 siglen
= pktout
.length
- 5 + 4 + 20;
3657 len
= 1; /* message type */
3658 len
+= 4 + pklen
; /* key blob */
3659 len
+= 4 + siglen
; /* data to sign */
3660 len
+= 4; /* flags */
3661 agentreq
= smalloc(4 + len
);
3662 PUT_32BIT(agentreq
, len
);
3664 *q
++ = SSH2_AGENTC_SIGN_REQUEST
;
3665 PUT_32BIT(q
, pklen
);
3667 memcpy(q
, pkblob
, pklen
);
3669 PUT_32BIT(q
, siglen
);
3671 /* Now the data to be signed... */
3674 memcpy(q
, ssh2_session_id
, 20);
3676 memcpy(q
, pktout
.data
+ 5, pktout
.length
- 5);
3677 q
+= pktout
.length
- 5;
3678 /* And finally the (zero) flags word. */
3680 agent_query(agentreq
, len
+ 4, &vret
, &retlen
);
3684 if (ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
3685 logevent("Sending Pageant's response");
3686 ssh2_pkt_addstring_start();
3687 ssh2_pkt_addstring_data(ret
+ 9,
3695 ("Pageant failed to answer challenge");
3705 if (!method
&& can_pubkey
&& *cfg
.keyfile
3706 && !tried_pubkey_config
) {
3707 unsigned char *pub_blob
;
3708 char *algorithm
, *comment
;
3711 tried_pubkey_config
= TRUE
;
3714 * Try the public key supplied in the configuration.
3716 * First, offer the public blob to see if the server is
3717 * willing to accept it.
3719 pub_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, &algorithm
,
3722 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3723 ssh2_pkt_addstring(username
);
3724 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3725 ssh2_pkt_addstring("publickey"); /* method */
3726 ssh2_pkt_addbool(FALSE
); /* no signature included */
3727 ssh2_pkt_addstring(algorithm
);
3728 ssh2_pkt_addstring_start();
3729 ssh2_pkt_addstring_data(pub_blob
, pub_blob_len
);
3731 logevent("Offered public key"); /* FIXME */
3733 crWaitUntilV(ispkt
);
3734 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3736 type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
3737 continue; /* key refused; give up on it */
3740 logevent("Offer of public key accepted");
3742 * Actually attempt a serious authentication using
3745 if (ssh2_userkey_encrypted(cfg
.keyfile
, &comment
)) {
3747 "Passphrase for key \"%.100s\": ",
3753 c_write_str("Authenticating with public key \"");
3754 c_write_str(comment
);
3755 c_write_str("\"\r\n");
3756 method
= AUTH_PUBLICKEY_FILE
;
3760 if (!method
&& can_passwd
) {
3761 method
= AUTH_PASSWORD
;
3762 sprintf(pwprompt
, "%.90s@%.90s's password: ", username
,
3769 if (!ssh_get_line(pwprompt
, password
,
3770 sizeof(password
), TRUE
)) {
3772 * get_line failed to get a password (for
3773 * example because one was supplied on the
3774 * command line which has already failed to
3777 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3778 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
3780 ("No more passwords available to try");
3781 ssh2_pkt_addstring("en"); /* language tag */
3783 connection_fatal("Unable to authenticate");
3784 ssh_state
= SSH_STATE_CLOSED
;
3791 c_write_untrusted(pwprompt
, strlen(pwprompt
));
3796 crWaitUntilV(!ispkt
);
3798 switch (c
= *in
++) {
3819 if (pos
< sizeof(password
)-1)
3820 password
[pos
++] = c
;
3824 c_write_str("\r\n");
3828 if (method
== AUTH_PUBLICKEY_FILE
) {
3830 * We have our passphrase. Now try the actual authentication.
3832 struct ssh2_userkey
*key
;
3834 key
= ssh2_load_userkey(cfg
.keyfile
, password
);
3835 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
3836 if (key
== SSH2_WRONG_PASSPHRASE
) {
3837 c_write_str("Wrong passphrase\r\n");
3838 tried_pubkey_config
= FALSE
;
3840 c_write_str("Unable to load private key\r\n");
3841 tried_pubkey_config
= TRUE
;
3843 /* Send a spurious AUTH_NONE to return to the top. */
3844 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3845 ssh2_pkt_addstring(username
);
3846 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3847 ssh2_pkt_addstring("none"); /* method */
3849 type
= AUTH_TYPE_NONE
;
3851 unsigned char *blob
, *sigdata
;
3852 int blob_len
, sigdata_len
;
3855 * We have loaded the private key and the server
3856 * has announced that it's willing to accept it.
3857 * Hallelujah. Generate a signature and send it.
3859 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3860 ssh2_pkt_addstring(username
);
3861 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3862 ssh2_pkt_addstring("publickey"); /* method */
3863 ssh2_pkt_addbool(TRUE
);
3864 ssh2_pkt_addstring(key
->alg
->name
);
3865 blob
= key
->alg
->public_blob(key
->data
, &blob_len
);
3866 ssh2_pkt_addstring_start();
3867 ssh2_pkt_addstring_data(blob
, blob_len
);
3871 * The data to be signed is:
3875 * followed by everything so far placed in the
3878 sigdata_len
= pktout
.length
- 5 + 4 + 20;
3879 sigdata
= smalloc(sigdata_len
);
3880 PUT_32BIT(sigdata
, 20);
3881 memcpy(sigdata
+ 4, ssh2_session_id
, 20);
3882 memcpy(sigdata
+ 24, pktout
.data
+ 5,
3885 key
->alg
->sign(key
->data
, sigdata
, sigdata_len
,
3887 ssh2_pkt_addstring_start();
3888 ssh2_pkt_addstring_data(blob
, blob_len
);
3893 type
= AUTH_TYPE_PUBLICKEY
;
3895 } else if (method
== AUTH_PASSWORD
) {
3897 * We send the password packet lumped tightly together with
3898 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
3899 * string long enough to make the total length of the two
3900 * packets constant. This should ensure that a passive
3901 * listener doing traffic analyis can't work out the length
3904 * For this to work, we need an assumption about the
3905 * maximum length of the password packet. I think 256 is
3906 * pretty conservative. Anyone using a password longer than
3907 * that probably doesn't have much to worry about from
3908 * people who find out how long their password is!
3910 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3911 ssh2_pkt_addstring(username
);
3912 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3913 ssh2_pkt_addstring("password");
3914 ssh2_pkt_addbool(FALSE
);
3915 ssh2_pkt_addstring(password
);
3918 * We'll include a string that's an exact multiple of the
3919 * cipher block size. If the cipher is NULL for some
3920 * reason, we don't do this trick at all because we gain
3926 stringlen
= (256 - deferred_len
);
3927 stringlen
+= cscipher
->blksize
- 1;
3928 stringlen
-= (stringlen
% cscipher
->blksize
);
3931 * Temporarily disable actual compression,
3932 * so we can guarantee to get this string
3933 * exactly the length we want it. The
3934 * compression-disabling routine should
3935 * return an integer indicating how many
3936 * bytes we should adjust our string length
3939 stringlen
-= cscomp
->disable_compression();
3941 ssh2_pkt_init(SSH2_MSG_IGNORE
);
3942 ssh2_pkt_addstring_start();
3943 for (i
= 0; i
< stringlen
; i
++) {
3944 char c
= (char) random_byte();
3945 ssh2_pkt_addstring_data(&c
, 1);
3949 ssh_pkt_defersend();
3950 logevent("Sent password");
3951 type
= AUTH_TYPE_PASSWORD
;
3952 } else if (method
== AUTH_KEYBOARD_INTERACTIVE
) {
3953 ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE
);
3954 ssh2_pkt_adduint32(num_prompts
);
3955 ssh2_pkt_addstring(password
);
3956 memset(password
, 0, sizeof(password
));
3958 type
= AUTH_TYPE_KEYBOARD_INTERACTIVE
;
3961 ("No supported authentication methods left to try!\r\n");
3963 ("No supported authentications offered. Disconnecting");
3964 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3965 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
3967 ("No supported authentication methods available");
3968 ssh2_pkt_addstring("en"); /* language tag */
3970 ssh_state
= SSH_STATE_CLOSED
;
3974 } while (!we_are_in
);
3977 * Now we're authenticated for the connection protocol. The
3978 * connection protocol will automatically have started at this
3979 * point; there's no need to send SERVICE_REQUEST.
3983 * So now create a channel with a session in it.
3985 ssh_channels
= newtree234(ssh_channelcmp
);
3986 mainchan
= smalloc(sizeof(struct ssh_channel
));
3987 mainchan
->localid
= alloc_channel_id();
3988 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
3989 ssh2_pkt_addstring("session");
3990 ssh2_pkt_adduint32(mainchan
->localid
);
3991 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
3992 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
3994 crWaitUntilV(ispkt
);
3995 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
3996 bombout(("Server refused to open a session"));
3998 /* FIXME: error data comes back in FAILURE packet */
4000 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
4001 bombout(("Server's channel confirmation cited wrong channel"));
4004 mainchan
->remoteid
= ssh2_pkt_getuint32();
4005 mainchan
->type
= CHAN_MAINSESSION
;
4006 mainchan
->closes
= 0;
4007 mainchan
->v2
.remwindow
= ssh2_pkt_getuint32();
4008 mainchan
->v2
.remmaxpkt
= ssh2_pkt_getuint32();
4009 mainchan
->v2
.outbuffer
= NULL
;
4010 mainchan
->v2
.outbuflen
= mainchan
->v2
.outbufsize
= 0;
4011 add234(ssh_channels
, mainchan
);
4012 logevent("Opened channel for session");
4015 * Potentially enable X11 forwarding.
4017 if (cfg
.x11_forward
) {
4018 char proto
[20], data
[64];
4019 logevent("Requesting X11 forwarding");
4020 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
4021 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4022 ssh2_pkt_adduint32(mainchan
->remoteid
);
4023 ssh2_pkt_addstring("x11-req");
4024 ssh2_pkt_addbool(1); /* want reply */
4025 ssh2_pkt_addbool(0); /* many connections */
4026 ssh2_pkt_addstring(proto
);
4027 ssh2_pkt_addstring(data
);
4028 ssh2_pkt_adduint32(0); /* screen number */
4032 crWaitUntilV(ispkt
);
4033 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4034 unsigned i
= ssh2_pkt_getuint32();
4035 struct ssh_channel
*c
;
4036 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4038 continue; /* nonexistent channel */
4039 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
4041 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4043 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4044 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4045 bombout(("Server got confused by X11 forwarding request"));
4048 logevent("X11 forwarding refused");
4050 logevent("X11 forwarding enabled");
4051 ssh_X11_fwd_enabled
= TRUE
;
4056 * Potentially enable agent forwarding.
4058 if (cfg
.agentfwd
&& agent_exists()) {
4059 logevent("Requesting OpenSSH-style agent forwarding");
4060 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4061 ssh2_pkt_adduint32(mainchan
->remoteid
);
4062 ssh2_pkt_addstring("auth-agent-req@openssh.com");
4063 ssh2_pkt_addbool(1); /* want reply */
4067 crWaitUntilV(ispkt
);
4068 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4069 unsigned i
= ssh2_pkt_getuint32();
4070 struct ssh_channel
*c
;
4071 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4073 continue; /* nonexistent channel */
4074 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
4076 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4078 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4079 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4081 ("Server got confused by agent forwarding request"));
4084 logevent("Agent forwarding refused");
4086 logevent("Agent forwarding enabled");
4087 ssh_agentfwd_enabled
= TRUE
;
4092 * Now allocate a pty for the session.
4095 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4096 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
4097 ssh2_pkt_addstring("pty-req");
4098 ssh2_pkt_addbool(1); /* want reply */
4099 ssh2_pkt_addstring(cfg
.termtype
);
4100 ssh2_pkt_adduint32(cols
);
4101 ssh2_pkt_adduint32(rows
);
4102 ssh2_pkt_adduint32(0); /* pixel width */
4103 ssh2_pkt_adduint32(0); /* pixel height */
4104 ssh2_pkt_addstring_start();
4105 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
4107 ssh_state
= SSH_STATE_INTERMED
;
4110 crWaitUntilV(ispkt
);
4111 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4112 unsigned i
= ssh2_pkt_getuint32();
4113 struct ssh_channel
*c
;
4114 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4116 continue; /* nonexistent channel */
4117 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
4119 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4121 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4122 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4123 bombout(("Server got confused by pty request"));
4126 c_write_str("Server refused to allocate pty\r\n");
4127 ssh_editing
= ssh_echoing
= 1;
4129 logevent("Allocated pty");
4132 ssh_editing
= ssh_echoing
= 1;
4136 * Start a shell or a remote command.
4138 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4139 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
4140 if (cfg
.ssh_subsys
) {
4141 ssh2_pkt_addstring("subsystem");
4142 ssh2_pkt_addbool(1); /* want reply */
4143 ssh2_pkt_addstring(cfg
.remote_cmd_ptr
);
4144 } else if (*cfg
.remote_cmd_ptr
) {
4145 ssh2_pkt_addstring("exec");
4146 ssh2_pkt_addbool(1); /* want reply */
4147 ssh2_pkt_addstring(cfg
.remote_cmd_ptr
);
4149 ssh2_pkt_addstring("shell");
4150 ssh2_pkt_addbool(1); /* want reply */
4154 crWaitUntilV(ispkt
);
4155 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4156 unsigned i
= ssh2_pkt_getuint32();
4157 struct ssh_channel
*c
;
4158 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4160 continue; /* nonexistent channel */
4161 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
4163 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4164 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
4165 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
4166 bombout(("Server got confused by shell/command request"));
4169 bombout(("Server refused to start a shell/command"));
4172 logevent("Started a shell/command");
4175 ssh_state
= SSH_STATE_SESSION
;
4179 ssh_special(TS_EOF
);
4184 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
4187 static int try_send
;
4191 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
4192 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
4195 unsigned i
= ssh2_pkt_getuint32();
4196 struct ssh_channel
*c
;
4197 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4199 continue; /* nonexistent channel */
4200 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
4201 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
4202 continue; /* extended but not stderr */
4203 ssh2_pkt_getstring(&data
, &length
);
4206 case CHAN_MAINSESSION
:
4207 from_backend(pktin
.type
==
4208 SSH2_MSG_CHANNEL_EXTENDED_DATA
, data
,
4212 x11_send(c
->u
.x11
.s
, data
, length
);
4215 pfd_send(c
->u
.pfd
.s
, data
, length
);
4218 while (length
> 0) {
4219 if (c
->u
.a
.lensofar
< 4) {
4220 int l
= min(4 - c
->u
.a
.lensofar
, length
);
4221 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
,
4225 c
->u
.a
.lensofar
+= l
;
4227 if (c
->u
.a
.lensofar
== 4) {
4229 4 + GET_32BIT(c
->u
.a
.msglen
);
4230 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
4231 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
4233 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
4235 min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
4237 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
,
4241 c
->u
.a
.lensofar
+= l
;
4243 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
4244 void *reply
, *sentreply
;
4246 agent_query(c
->u
.a
.message
,
4247 c
->u
.a
.totallen
, &reply
,
4252 /* Fake SSH_AGENT_FAILURE. */
4253 sentreply
= "\0\0\0\1\5";
4256 ssh2_add_channel_data(c
, sentreply
,
4261 sfree(c
->u
.a
.message
);
4262 c
->u
.a
.lensofar
= 0;
4268 * Enlarge the window again at the remote
4269 * side, just in case it ever runs down and
4270 * they fail to send us any more data.
4272 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
4273 ssh2_pkt_adduint32(c
->remoteid
);
4274 ssh2_pkt_adduint32(length
);
4277 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
4278 ssh_state
= SSH_STATE_CLOSED
;
4279 logevent("Received disconnect message");
4281 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
4282 continue; /* exit status et al; ignore (FIXME?) */
4283 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
4284 unsigned i
= ssh2_pkt_getuint32();
4285 struct ssh_channel
*c
;
4287 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4289 continue; /* nonexistent channel */
4291 if (c
->type
== CHAN_X11
) {
4293 * Remote EOF on an X11 channel means we should
4294 * wrap up and close the channel ourselves.
4296 x11_close(c
->u
.x11
.s
);
4298 } else if (c
->type
== CHAN_AGENT
) {
4300 } else if (c
->type
== CHAN_SOCKDATA
) {
4301 pfd_close(c
->u
.pfd
.s
);
4304 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
4305 unsigned i
= ssh2_pkt_getuint32();
4306 struct ssh_channel
*c
;
4308 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4310 continue; /* nonexistent channel */
4311 if (c
->closes
== 0) {
4312 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
4313 ssh2_pkt_adduint32(c
->remoteid
);
4316 /* Do pre-close processing on the channel. */
4318 case CHAN_MAINSESSION
:
4319 break; /* nothing to see here, move along */
4327 del234(ssh_channels
, c
);
4328 sfree(c
->v2
.outbuffer
);
4332 * See if that was the last channel left open.
4334 if (count234(ssh_channels
) == 0) {
4335 logevent("All channels closed. Disconnecting");
4336 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
4337 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
4338 ssh2_pkt_addstring("All open channels closed");
4339 ssh2_pkt_addstring("en"); /* language tag */
4341 ssh_state
= SSH_STATE_CLOSED
;
4344 continue; /* remote sends close; ignore (FIXME) */
4345 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
4346 unsigned i
= ssh2_pkt_getuint32();
4347 struct ssh_channel
*c
;
4348 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
4350 continue; /* nonexistent channel */
4351 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
4353 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
4357 struct ssh_channel
*c
;
4358 ssh2_pkt_getstring(&type
, &typelen
);
4359 c
= smalloc(sizeof(struct ssh_channel
));
4361 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
4362 if (!ssh_X11_fwd_enabled
)
4363 error
= "X11 forwarding is not enabled";
4364 else if (x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) !=
4366 error
= "Unable to open an X11 connection";
4370 } else if (typelen
== 22 &&
4371 !memcmp(type
, "auth-agent@openssh.com", 3)) {
4372 if (!ssh_agentfwd_enabled
)
4373 error
= "Agent forwarding is not enabled";
4375 c
->type
= CHAN_AGENT
; /* identify channel type */
4376 c
->u
.a
.lensofar
= 0;
4379 error
= "Unsupported channel type requested";
4382 c
->remoteid
= ssh2_pkt_getuint32();
4384 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
4385 ssh2_pkt_adduint32(c
->remoteid
);
4386 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED
);
4387 ssh2_pkt_addstring(error
);
4388 ssh2_pkt_addstring("en"); /* language tag */
4392 c
->localid
= alloc_channel_id();
4394 c
->v2
.remwindow
= ssh2_pkt_getuint32();
4395 c
->v2
.remmaxpkt
= ssh2_pkt_getuint32();
4396 c
->v2
.outbuffer
= NULL
;
4397 c
->v2
.outbuflen
= c
->v2
.outbufsize
= 0;
4398 add234(ssh_channels
, c
);
4399 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
4400 ssh2_pkt_adduint32(c
->remoteid
);
4401 ssh2_pkt_adduint32(c
->localid
);
4402 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
4403 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
4407 bombout(("Strange packet received: type %d", pktin
.type
));
4412 * We have spare data. Add it to the channel buffer.
4414 ssh2_add_channel_data(mainchan
, in
, inlen
);
4419 struct ssh_channel
*c
;
4421 * Try to send data on all channels if we can.
4423 for (i
= 0; NULL
!= (c
= index234(ssh_channels
, i
)); i
++)
4432 * Handle the top-level SSH2 protocol.
4434 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
4436 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
4438 do_ssh2_authconn(in
, inlen
, ispkt
);
4442 * Called to set up the connection.
4444 * Returns an error message, or NULL on success.
4446 static char *ssh_init(char *host
, int port
, char **realhost
)
4451 if (crypto_startup() == 0)
4452 return "Microsoft high encryption pack not installed!";
4459 p
= connect_to_host(host
, port
, realhost
);
4467 * Called to send data down the Telnet connection.
4469 static void ssh_send(char *buf
, int len
)
4471 if (s
== NULL
|| ssh_protocol
== NULL
)
4474 ssh_protocol(buf
, len
, 0);
4478 * Called to set the size of the window from SSH's POV.
4480 static void ssh_size(void)
4482 switch (ssh_state
) {
4483 case SSH_STATE_BEFORE_SIZE
:
4484 case SSH_STATE_PREPACKET
:
4485 case SSH_STATE_CLOSED
:
4486 break; /* do nothing */
4487 case SSH_STATE_INTERMED
:
4488 size_needed
= TRUE
; /* buffer for later */
4490 case SSH_STATE_SESSION
:
4492 if (ssh_version
== 1) {
4493 send_packet(SSH1_CMSG_WINDOW_SIZE
,
4494 PKT_INT
, rows
, PKT_INT
, cols
,
4495 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
4497 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
4498 ssh2_pkt_adduint32(mainchan
->remoteid
);
4499 ssh2_pkt_addstring("window-change");
4500 ssh2_pkt_addbool(0);
4501 ssh2_pkt_adduint32(cols
);
4502 ssh2_pkt_adduint32(rows
);
4503 ssh2_pkt_adduint32(0);
4504 ssh2_pkt_adduint32(0);
4513 * Send Telnet special codes. TS_EOF is useful for `plink', so you
4514 * can send an EOF and collect resulting output (e.g. `plink
4517 static void ssh_special(Telnet_Special code
)
4519 if (code
== TS_EOF
) {
4520 if (ssh_state
!= SSH_STATE_SESSION
) {
4522 * Buffer the EOF in case we are pre-SESSION, so we can
4523 * send it as soon as we reach SESSION.
4529 if (ssh_version
== 1) {
4530 send_packet(SSH1_CMSG_EOF
, PKT_END
);
4532 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
4533 ssh2_pkt_adduint32(mainchan
->remoteid
);
4536 logevent("Sent EOF message");
4537 } else if (code
== TS_PING
) {
4538 if (ssh_state
== SSH_STATE_CLOSED
4539 || ssh_state
== SSH_STATE_PREPACKET
) return;
4540 if (ssh_version
== 1) {
4541 send_packet(SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
4543 ssh2_pkt_init(SSH2_MSG_IGNORE
);
4544 ssh2_pkt_addstring_start();
4552 void *new_sock_channel(Socket s
)
4554 struct ssh_channel
*c
;
4555 c
= smalloc(sizeof(struct ssh_channel
));
4558 c
->remoteid
= GET_32BIT(pktin
.body
);
4559 c
->localid
= alloc_channel_id();
4561 c
->type
= CHAN_SOCKDATA
; /* identify channel type */
4563 add234(ssh_channels
, c
);
4568 void ssh_send_port_open(void *channel
, char *hostname
, int port
, char *org
)
4570 struct ssh_channel
*c
= (struct ssh_channel
*)channel
;
4573 sprintf(buf
, "Opening forwarded connection to %.512s:%d", hostname
, port
);
4576 send_packet(SSH1_MSG_PORT_OPEN
,
4577 PKT_INT
, c
->localid
,
4585 static Socket
ssh_socket(void)
4590 static int ssh_sendok(void)
4595 static int ssh_ldisc(int option
)
4597 if (option
== LD_ECHO
)
4599 if (option
== LD_EDIT
)
4604 Backend ssh_backend
= {