18 #define logevent(s) { logevent(s); \
19 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
20 fprintf(stderr, "%s\n", s); }
22 #define bombout(msg) ( ssh_state = SSH_STATE_CLOSED, \
23 (s ? sk_close(s), s = NULL : 0), \
24 connection_fatal msg )
26 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
27 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
28 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
29 #define SSH1_CMSG_USER 4 /* 0x4 */
30 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
31 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
32 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
33 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
34 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
35 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
36 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
37 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
38 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
39 #define SSH1_SMSG_FAILURE 15 /* 0xf */
40 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
41 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
42 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
43 #define SSH1_CMSG_EOF 19 /* 0x13 */
44 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
45 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
46 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
47 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
48 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
49 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
50 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
51 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
52 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
53 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
54 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
55 #define SSH1_MSG_IGNORE 32 /* 0x20 */
56 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
57 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
58 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
59 #define SSH1_MSG_DEBUG 36 /* 0x24 */
60 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
61 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
62 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
63 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
64 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
65 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
66 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
68 #define SSH1_AUTH_TIS 5 /* 0x5 */
69 #define SSH1_AUTH_CCARD 16 /* 0x10 */
71 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
72 /* Mask for protoflags we will echo back to server if seen */
73 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
75 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
76 #define SSH2_MSG_IGNORE 2 /* 0x2 */
77 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
78 #define SSH2_MSG_DEBUG 4 /* 0x4 */
79 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
80 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
81 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
82 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
83 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
84 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
85 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
86 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
87 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
88 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
89 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
90 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
91 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
92 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
93 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
94 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
95 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
96 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
97 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
98 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
99 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
100 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
101 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
102 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
103 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
104 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
105 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
106 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
107 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
108 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
110 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
111 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
112 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
113 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
114 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
115 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
116 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
117 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
118 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
119 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
120 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
122 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
123 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
124 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
125 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
127 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
130 * Various remote-bug flags.
132 #define BUG_CHOKES_ON_SSH1_IGNORE 1
133 #define BUG_SSH2_HMAC 2
135 #define GET_32BIT(cp) \
136 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
137 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
138 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
139 ((unsigned long)(unsigned char)(cp)[3]))
141 #define PUT_32BIT(cp, value) { \
142 (cp)[0] = (unsigned char)((value) >> 24); \
143 (cp)[1] = (unsigned char)((value) >> 16); \
144 (cp)[2] = (unsigned char)((value) >> 8); \
145 (cp)[3] = (unsigned char)(value); }
147 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
149 /* Coroutine mechanics for the sillier bits of the code */
150 #define crBegin1 static int crLine = 0;
151 #define crBegin2 switch(crLine) { case 0:;
152 #define crBegin crBegin1; crBegin2;
153 #define crFinish(z) } crLine = 0; return (z)
154 #define crFinishV } crLine = 0; return
155 #define crReturn(z) \
157 crLine=__LINE__; return (z); case __LINE__:;\
161 crLine=__LINE__; return; case __LINE__:;\
163 #define crStop(z) do{ crLine = 0; return (z); }while(0)
164 #define crStopV do{ crLine = 0; return; }while(0)
165 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
166 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
168 extern char *x11_init (Socket
*, char *, void *);
169 extern void x11_close (Socket
);
170 extern void x11_send (Socket
, char *, int);
171 extern void x11_invent_auth(char *, int, char *, int);
174 * Ciphers for SSH2. We miss out single-DES because it isn't
175 * supported; also 3DES and Blowfish are both done differently from
176 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
177 * endianness and different-sized keys.)
179 const static struct ssh2_ciphers
*ciphers
[] = {
185 const static struct ssh_kex
*kex_algs
[] = {
186 &ssh_diffiehellman_gex
,
187 &ssh_diffiehellman
};
189 const static struct ssh_signkey
*hostkey_algs
[] = { &ssh_rsa
, &ssh_dss
};
191 static void nullmac_key(unsigned char *key
) { }
192 static void nullmac_generate(unsigned char *blk
, int len
, unsigned long seq
) { }
193 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
) { return 1; }
194 const static struct ssh_mac ssh_mac_none
= {
195 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
197 const static struct ssh_mac
*macs
[] = {
198 &ssh_sha1
, &ssh_md5
, &ssh_mac_none
};
199 const static struct ssh_mac
*buggymacs
[] = {
200 &ssh_sha1_buggy
, &ssh_md5
, &ssh_mac_none
};
202 static void ssh_comp_none_init(void) { }
203 static int ssh_comp_none_block(unsigned char *block
, int len
,
204 unsigned char **outblock
, int *outlen
) {
207 static int ssh_comp_none_disable(void) { return 0; }
208 const static struct ssh_compress ssh_comp_none
= {
210 ssh_comp_none_init
, ssh_comp_none_block
,
211 ssh_comp_none_init
, ssh_comp_none_block
,
212 ssh_comp_none_disable
214 extern const struct ssh_compress ssh_zlib
;
215 const static struct ssh_compress
*compressions
[] = {
216 &ssh_zlib
, &ssh_comp_none
};
218 enum { /* channel types */
225 * 2-3-4 tree storing channels.
228 unsigned remoteid
, localid
;
231 struct ssh2_data_channel
{
232 unsigned char *outbuffer
;
233 unsigned outbuflen
, outbufsize
;
234 unsigned remwindow
, remmaxpkt
;
237 struct ssh_agent_channel
{
238 unsigned char *message
;
239 unsigned char msglen
[4];
240 int lensofar
, totallen
;
242 struct ssh_x11_channel
{
257 static SHA_State exhash
, exhashbase
;
259 static Socket s
= NULL
;
261 static unsigned char session_key
[32];
262 static int ssh1_compressing
;
263 static int ssh1_remote_protoflags
;
264 static int ssh1_local_protoflags
;
265 static int ssh_agentfwd_enabled
;
266 static int ssh_X11_fwd_enabled
;
267 static int ssh_remote_bugs
;
268 static const struct ssh_cipher
*cipher
= NULL
;
269 static const struct ssh2_cipher
*cscipher
= NULL
;
270 static const struct ssh2_cipher
*sccipher
= NULL
;
271 static const struct ssh_mac
*csmac
= NULL
;
272 static const struct ssh_mac
*scmac
= NULL
;
273 static const struct ssh_compress
*cscomp
= NULL
;
274 static const struct ssh_compress
*sccomp
= NULL
;
275 static const struct ssh_kex
*kex
= NULL
;
276 static const struct ssh_signkey
*hostkey
= NULL
;
277 static unsigned char ssh2_session_id
[20];
278 int (*ssh_get_line
)(const char *prompt
, char *str
, int maxlen
,
281 static char *savedhost
;
282 static int savedport
;
283 static int ssh_send_ok
;
284 static int ssh_echoing
, ssh_editing
;
286 static tree234
*ssh_channels
; /* indexed by local id */
287 static struct ssh_channel
*mainchan
; /* primary session channel */
291 SSH_STATE_BEFORE_SIZE
,
295 } ssh_state
= SSH_STATE_PREPACKET
;
297 static int size_needed
= FALSE
, eof_needed
= FALSE
;
299 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
300 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
301 static unsigned char *deferred_send_data
= NULL
;
302 static int deferred_len
= 0, deferred_size
= 0;
304 static int ssh_version
;
305 static void (*ssh_protocol
)(unsigned char *in
, int inlen
, int ispkt
);
306 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
307 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
308 static void ssh_size(void);
309 static void ssh_special (Telnet_Special
);
310 static void ssh2_try_send(struct ssh_channel
*c
);
311 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
);
313 static int (*s_rdpkt
)(unsigned char **data
, int *datalen
);
315 static struct rdpkt1_state_tag
{
316 long len
, pad
, biglen
, to_read
;
317 unsigned long realcrc
, gotcrc
;
323 static struct rdpkt2_state_tag
{
324 long len
, pad
, payload
, packetlen
, maclen
;
327 unsigned long incoming_sequence
;
330 static int ssh_channelcmp(void *av
, void *bv
) {
331 struct ssh_channel
*a
= (struct ssh_channel
*)av
;
332 struct ssh_channel
*b
= (struct ssh_channel
*)bv
;
333 if (a
->localid
< b
->localid
) return -1;
334 if (a
->localid
> b
->localid
) return +1;
337 static int ssh_channelfind(void *av
, void *bv
) {
338 unsigned *a
= (unsigned *)av
;
339 struct ssh_channel
*b
= (struct ssh_channel
*)bv
;
340 if (*a
< b
->localid
) return -1;
341 if (*a
> b
->localid
) return +1;
345 static void c_write (char *buf
, int len
) {
346 if ((flags
& FLAG_STDERR
)) {
348 for (i
= 0; i
< len
; i
++)
350 fputc(buf
[i
], stderr
);
353 from_backend(1, buf
, len
);
356 static void c_write_untrusted(char *buf
, int len
) {
358 for (i
= 0; i
< len
; i
++) {
361 else if ((buf
[i
] & 0x60) || (buf
[i
] == '\r'))
366 static void c_write_str (char *buf
) {
367 c_write(buf
, strlen(buf
));
371 * Collect incoming data in the incoming packet buffer.
372 * Decipher and verify the packet when it is completely read.
373 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
374 * Update the *data and *datalen variables.
375 * Return the additional nr of bytes needed, or 0 when
376 * a complete packet is available.
378 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
380 struct rdpkt1_state_tag
*st
= &rdpkt1_state
;
389 for (st
->i
= st
->len
= 0; st
->i
< 4; st
->i
++) {
390 while ((*datalen
) == 0)
392 st
->len
= (st
->len
<< 8) + **data
;
393 (*data
)++, (*datalen
)--;
397 if (st
->len
== 0x52656d6f) { /* "Remo"te server has closed ... */
398 st
->len
= 0x300; /* big enough to carry to end */
402 st
->pad
= 8 - (st
->len
% 8);
403 st
->biglen
= st
->len
+ st
->pad
;
404 pktin
.length
= st
->len
- 5;
406 if (pktin
.maxlen
< st
->biglen
) {
407 pktin
.maxlen
= st
->biglen
;
408 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->biglen
+APIEXTRA
) :
409 srealloc(pktin
.data
, st
->biglen
+APIEXTRA
));
411 fatalbox("Out of memory");
414 st
->to_read
= st
->biglen
;
416 while (st
->to_read
> 0) {
417 st
->chunk
= st
->to_read
;
418 while ((*datalen
) == 0)
419 crReturn(st
->to_read
);
420 if (st
->chunk
> (*datalen
))
421 st
->chunk
= (*datalen
);
422 memcpy(st
->p
, *data
, st
->chunk
);
424 *datalen
-= st
->chunk
;
426 st
->to_read
-= st
->chunk
;
430 cipher
->decrypt(pktin
.data
, st
->biglen
);
432 debug(("Got packet len=%d pad=%d\r\n", st
->len
, st
->pad
));
433 for (st
->i
= 0; st
->i
< st
->biglen
; st
->i
++)
434 debug((" %02x", (unsigned char)pktin
.data
[st
->i
]));
438 st
->realcrc
= crc32(pktin
.data
, st
->biglen
-4);
439 st
->gotcrc
= GET_32BIT(pktin
.data
+st
->biglen
-4);
440 if (st
->gotcrc
!= st
->realcrc
) {
441 bombout(("Incorrect CRC received on packet"));
445 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
447 if (ssh1_compressing
) {
448 unsigned char *decompblk
;
453 debug(("Packet payload pre-decompression:\n"));
454 for (i
= -1; i
< pktin
.length
; i
++)
455 debug((" %02x", (unsigned char)pktin
.body
[i
]));
459 zlib_decompress_block(pktin
.body
-1, pktin
.length
+1,
460 &decompblk
, &decomplen
);
462 if (pktin
.maxlen
< st
->pad
+ decomplen
) {
463 pktin
.maxlen
= st
->pad
+ decomplen
;
464 pktin
.data
= srealloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
);
465 pktin
.body
= pktin
.data
+ st
->pad
+ 1;
467 fatalbox("Out of memory");
470 memcpy(pktin
.body
-1, decompblk
, decomplen
);
472 pktin
.length
= decomplen
-1;
476 debug(("Packet payload post-decompression:\n"));
477 for (i
= -1; i
< pktin
.length
; i
++)
478 debug((" %02x", (unsigned char)pktin
.body
[i
]));
484 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
485 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
486 pktin
.type
== SSH1_MSG_DEBUG
||
487 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
488 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
489 long strlen
= GET_32BIT(pktin
.body
);
490 if (strlen
+ 4 != pktin
.length
) {
491 bombout(("Received data packet with bogus string length"));
496 pktin
.type
= pktin
.body
[-1];
498 if (pktin
.type
== SSH1_MSG_DEBUG
) {
499 /* log debug message */
501 int strlen
= GET_32BIT(pktin
.body
);
502 strcpy(buf
, "Remote: ");
503 if (strlen
> 70) strlen
= 70;
504 memcpy(buf
+8, pktin
.body
+4, strlen
);
505 buf
[8+strlen
] = '\0';
508 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
516 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
518 struct rdpkt2_state_tag
*st
= &rdpkt2_state
;
526 st
->cipherblk
= sccipher
->blksize
;
529 if (st
->cipherblk
< 8)
532 if (pktin
.maxlen
< st
->cipherblk
) {
533 pktin
.maxlen
= st
->cipherblk
;
534 pktin
.data
= (pktin
.data
== NULL ?
smalloc(st
->cipherblk
+APIEXTRA
) :
535 srealloc(pktin
.data
, st
->cipherblk
+APIEXTRA
));
537 fatalbox("Out of memory");
541 * Acquire and decrypt the first block of the packet. This will
542 * contain the length and padding details.
544 for (st
->i
= st
->len
= 0; st
->i
< st
->cipherblk
; st
->i
++) {
545 while ((*datalen
) == 0)
546 crReturn(st
->cipherblk
-st
->i
);
547 pktin
.data
[st
->i
] = *(*data
)++;
551 if (!memcmp(pktin
.data
, "Remo", 4)) {/* "Remo"te server has closed ... */
556 sccipher
->decrypt(pktin
.data
, st
->cipherblk
);
559 * Now get the length and padding figures.
561 st
->len
= GET_32BIT(pktin
.data
);
562 st
->pad
= pktin
.data
[4];
565 * This enables us to deduce the payload length.
567 st
->payload
= st
->len
- st
->pad
- 1;
569 pktin
.length
= st
->payload
+ 5;
572 * So now we can work out the total packet length.
574 st
->packetlen
= st
->len
+ 4;
575 st
->maclen
= scmac ? scmac
->len
: 0;
578 * Adjust memory allocation if packet is too big.
580 if (pktin
.maxlen
< st
->packetlen
+st
->maclen
) {
581 pktin
.maxlen
= st
->packetlen
+st
->maclen
;
582 pktin
.data
= (pktin
.data
== NULL ?
smalloc(pktin
.maxlen
+APIEXTRA
) :
583 srealloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
));
585 fatalbox("Out of memory");
589 * Read and decrypt the remainder of the packet.
591 for (st
->i
= st
->cipherblk
; st
->i
< st
->packetlen
+ st
->maclen
; st
->i
++) {
592 while ((*datalen
) == 0)
593 crReturn(st
->packetlen
+ st
->maclen
- st
->i
);
594 pktin
.data
[st
->i
] = *(*data
)++;
597 /* Decrypt everything _except_ the MAC. */
599 sccipher
->decrypt(pktin
.data
+ st
->cipherblk
,
600 st
->packetlen
- st
->cipherblk
);
603 debug(("Got packet len=%d pad=%d\r\n", st
->len
, st
->pad
));
604 for (st
->i
= 0; st
->i
< st
->packetlen
; st
->i
++)
605 debug((" %02x", (unsigned char)pktin
.data
[st
->i
]));
612 if (scmac
&& !scmac
->verify(pktin
.data
, st
->len
+4, st
->incoming_sequence
)) {
613 bombout(("Incorrect MAC received on packet"));
616 st
->incoming_sequence
++; /* whether or not we MACed */
619 * Decompress packet payload.
622 unsigned char *newpayload
;
624 if (sccomp
&& sccomp
->decompress(pktin
.data
+5, pktin
.length
-5,
625 &newpayload
, &newlen
)) {
626 if (pktin
.maxlen
< newlen
+5) {
627 pktin
.maxlen
= newlen
+5;
628 pktin
.data
= (pktin
.data
== NULL ?
smalloc(pktin
.maxlen
+APIEXTRA
) :
629 srealloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
));
631 fatalbox("Out of memory");
633 pktin
.length
= 5 + newlen
;
634 memcpy(pktin
.data
+5, newpayload
, newlen
);
636 debug(("Post-decompression payload:\r\n"));
637 for (st
->i
= 0; st
->i
< newlen
; st
->i
++)
638 debug((" %02x", (unsigned char)pktin
.data
[5+st
->i
]));
647 pktin
.type
= pktin
.data
[5];
649 if (pktin
.type
== SSH2_MSG_IGNORE
|| pktin
.type
== SSH2_MSG_DEBUG
)
650 goto next_packet
; /* FIXME: print DEBUG message */
655 static void ssh1_pktout_size(int len
) {
658 len
+= 5; /* type and CRC */
662 pktout
.length
= len
-5;
663 if (pktout
.maxlen
< biglen
) {
664 pktout
.maxlen
= biglen
;
666 /* Allocate enough buffer space for extra block
667 * for MS CryptEncrypt() */
668 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+12) :
669 srealloc(pktout
.data
, biglen
+12));
671 pktout
.data
= (pktout
.data
== NULL ?
smalloc(biglen
+4) :
672 srealloc(pktout
.data
, biglen
+4));
675 fatalbox("Out of memory");
677 pktout
.body
= pktout
.data
+4+pad
+1;
680 static void s_wrpkt_start(int type
, int len
) {
681 ssh1_pktout_size(len
);
685 static int s_wrpkt_prepare(void) {
686 int pad
, len
, biglen
, i
;
689 pktout
.body
[-1] = pktout
.type
;
692 debug(("Packet payload pre-compression:\n"));
693 for (i
= -1; i
< pktout
.length
; i
++)
694 debug((" %02x", (unsigned char)pktout
.body
[i
]));
698 if (ssh1_compressing
) {
699 unsigned char *compblk
;
701 zlib_compress_block(pktout
.body
-1, pktout
.length
+1,
703 ssh1_pktout_size(complen
-1);
704 memcpy(pktout
.body
-1, compblk
, complen
);
707 debug(("Packet payload post-compression:\n"));
708 for (i
= -1; i
< pktout
.length
; i
++)
709 debug((" %02x", (unsigned char)pktout
.body
[i
]));
714 len
= pktout
.length
+ 5; /* type and CRC */
718 for (i
=0; i
<pad
; i
++)
719 pktout
.data
[i
+4] = random_byte();
720 crc
= crc32(pktout
.data
+4, biglen
-4);
721 PUT_32BIT(pktout
.data
+biglen
, crc
);
722 PUT_32BIT(pktout
.data
, len
);
725 debug(("Sending packet len=%d\r\n", biglen
+4));
726 for (i
= 0; i
< biglen
+4; i
++)
727 debug((" %02x", (unsigned char)pktout
.data
[i
]));
731 cipher
->encrypt(pktout
.data
+4, biglen
);
736 static void s_wrpkt(void) {
738 len
= s_wrpkt_prepare();
739 sk_write(s
, pktout
.data
, len
);
742 static void s_wrpkt_defer(void) {
744 len
= s_wrpkt_prepare();
745 if (deferred_len
+ len
> deferred_size
) {
746 deferred_size
= deferred_len
+ len
+ 128;
747 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
749 memcpy(deferred_send_data
+deferred_len
, pktout
.data
, len
);
754 * Construct a packet with the specified contents.
756 static void construct_packet(int pkttype
, va_list ap1
, va_list ap2
)
758 unsigned char *p
, *argp
, argchar
;
759 unsigned long argint
;
760 int pktlen
, argtype
, arglen
;
764 while ((argtype
= va_arg(ap1
, int)) != PKT_END
) {
767 (void) va_arg(ap1
, int);
771 (void) va_arg(ap1
, char);
775 (void) va_arg(ap1
, unsigned char *);
776 arglen
= va_arg(ap1
, int);
780 argp
= va_arg(ap1
, unsigned char *);
781 arglen
= strlen(argp
);
782 pktlen
+= 4 + arglen
;
785 bn
= va_arg(ap1
, Bignum
);
786 pktlen
+= ssh1_bignum_length(bn
);
793 s_wrpkt_start(pkttype
, pktlen
);
796 while ((argtype
= va_arg(ap2
, int)) != PKT_END
) {
799 argint
= va_arg(ap2
, int);
800 PUT_32BIT(p
, argint
);
804 argchar
= va_arg(ap2
, unsigned char);
809 argp
= va_arg(ap2
, unsigned char *);
810 arglen
= va_arg(ap2
, int);
811 memcpy(p
, argp
, arglen
);
815 argp
= va_arg(ap2
, unsigned char *);
816 arglen
= strlen(argp
);
817 PUT_32BIT(p
, arglen
);
818 memcpy(p
+ 4, argp
, arglen
);
822 bn
= va_arg(ap2
, Bignum
);
823 p
+= ssh1_write_bignum(p
, bn
);
829 static void send_packet(int pkttype
, ...) {
831 va_start(ap1
, pkttype
);
832 va_start(ap2
, pkttype
);
833 construct_packet(pkttype
, ap1
, ap2
);
837 static void defer_packet(int pkttype
, ...) {
839 va_start(ap1
, pkttype
);
840 va_start(ap2
, pkttype
);
841 construct_packet(pkttype
, ap1
, ap2
);
845 static int ssh_versioncmp(char *a
, char *b
) {
847 unsigned long av
, bv
;
849 av
= strtoul(a
, &ae
, 10);
850 bv
= strtoul(b
, &be
, 10);
851 if (av
!= bv
) return (av
< bv ?
-1 : +1);
852 if (*ae
== '.') ae
++;
853 if (*be
== '.') be
++;
854 av
= strtoul(ae
, &ae
, 10);
855 bv
= strtoul(be
, &be
, 10);
856 if (av
!= bv
) return (av
< bv ?
-1 : +1);
862 * Utility routines for putting an SSH-protocol `string' and
863 * `uint32' into a SHA state.
866 static void sha_string(SHA_State
*s
, void *str
, int len
) {
867 unsigned char lenblk
[4];
868 PUT_32BIT(lenblk
, len
);
869 SHA_Bytes(s
, lenblk
, 4);
870 SHA_Bytes(s
, str
, len
);
873 static void sha_uint32(SHA_State
*s
, unsigned i
) {
874 unsigned char intblk
[4];
875 PUT_32BIT(intblk
, i
);
876 SHA_Bytes(s
, intblk
, 4);
880 * SSH2 packet construction functions.
882 static void ssh2_pkt_ensure(int length
) {
883 if (pktout
.maxlen
< length
) {
884 pktout
.maxlen
= length
+ 256;
885 pktout
.data
= (pktout
.data
== NULL ?
smalloc(pktout
.maxlen
+APIEXTRA
) :
886 srealloc(pktout
.data
, pktout
.maxlen
+APIEXTRA
));
888 fatalbox("Out of memory");
891 static void ssh2_pkt_adddata(void *data
, int len
) {
892 pktout
.length
+= len
;
893 ssh2_pkt_ensure(pktout
.length
);
894 memcpy(pktout
.data
+pktout
.length
-len
, data
, len
);
896 static void ssh2_pkt_addbyte(unsigned char byte
) {
897 ssh2_pkt_adddata(&byte
, 1);
899 static void ssh2_pkt_init(int pkt_type
) {
901 ssh2_pkt_addbyte((unsigned char)pkt_type
);
903 static void ssh2_pkt_addbool(unsigned char value
) {
904 ssh2_pkt_adddata(&value
, 1);
906 static void ssh2_pkt_adduint32(unsigned long value
) {
909 ssh2_pkt_adddata(x
, 4);
911 static void ssh2_pkt_addstring_start(void) {
912 ssh2_pkt_adduint32(0);
913 pktout
.savedpos
= pktout
.length
;
915 static void ssh2_pkt_addstring_str(char *data
) {
916 ssh2_pkt_adddata(data
, strlen(data
));
917 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
918 pktout
.length
- pktout
.savedpos
);
920 static void ssh2_pkt_addstring_data(char *data
, int len
) {
921 ssh2_pkt_adddata(data
, len
);
922 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
923 pktout
.length
- pktout
.savedpos
);
925 static void ssh2_pkt_addstring(char *data
) {
926 ssh2_pkt_addstring_start();
927 ssh2_pkt_addstring_str(data
);
929 static char *ssh2_mpint_fmt(Bignum b
, int *len
) {
931 int i
, n
= (ssh1_bignum_bitcount(b
)+7)/8;
934 fatalbox("out of memory");
936 for (i
= 1; i
<= n
; i
++)
937 p
[i
] = bignum_byte(b
, n
-i
);
939 while (i
<= n
&& p
[i
] == 0 && (p
[i
+1] & 0x80) == 0)
941 memmove(p
, p
+i
, n
+1-i
);
945 static void ssh2_pkt_addmp(Bignum b
) {
948 p
= ssh2_mpint_fmt(b
, &len
);
949 ssh2_pkt_addstring_start();
950 ssh2_pkt_addstring_data(p
, len
);
955 * Construct an SSH2 final-form packet: compress it, encrypt it,
956 * put the MAC on it. Final packet, ready to be sent, is stored in
957 * pktout.data. Total length is returned.
959 static int ssh2_pkt_construct(void) {
960 int cipherblk
, maclen
, padding
, i
;
961 static unsigned long outgoing_sequence
= 0;
964 * Compress packet payload.
967 debug(("Pre-compression payload:\r\n"));
968 for (i
= 5; i
< pktout
.length
; i
++)
969 debug((" %02x", (unsigned char)pktout
.data
[i
]));
973 unsigned char *newpayload
;
975 if (cscomp
&& cscomp
->compress(pktout
.data
+5, pktout
.length
-5,
976 &newpayload
, &newlen
)) {
978 ssh2_pkt_adddata(newpayload
, newlen
);
984 * Add padding. At least four bytes, and must also bring total
985 * length (minus MAC) up to a multiple of the block size.
987 cipherblk
= cscipher ? cscipher
->blksize
: 8; /* block size */
988 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
990 padding
+= (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
991 maclen
= csmac ? csmac
->len
: 0;
992 ssh2_pkt_ensure(pktout
.length
+ padding
+ maclen
);
993 pktout
.data
[4] = padding
;
994 for (i
= 0; i
< padding
; i
++)
995 pktout
.data
[pktout
.length
+ i
] = random_byte();
996 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
998 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
1000 outgoing_sequence
++; /* whether or not we MACed */
1003 debug(("Sending packet len=%d\r\n", pktout
.length
+padding
));
1004 for (i
= 0; i
< pktout
.length
+padding
; i
++)
1005 debug((" %02x", (unsigned char)pktout
.data
[i
]));
1010 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
1012 /* Ready-to-send packet starts at pktout.data. We return length. */
1013 return pktout
.length
+ padding
+ maclen
;
1017 * Construct and send an SSH2 packet immediately.
1019 static void ssh2_pkt_send(void) {
1020 int len
= ssh2_pkt_construct();
1021 sk_write(s
, pktout
.data
, len
);
1025 * Construct an SSH2 packet and add it to a deferred data block.
1026 * Useful for sending multiple packets in a single sk_write() call,
1027 * to prevent a traffic-analysing listener from being able to work
1028 * out the length of any particular packet (such as the password
1031 * Note that because SSH2 sequence-numbers its packets, this can
1032 * NOT be used as an m4-style `defer' allowing packets to be
1033 * constructed in one order and sent in another.
1035 static void ssh2_pkt_defer(void) {
1036 int len
= ssh2_pkt_construct();
1037 if (deferred_len
+ len
> deferred_size
) {
1038 deferred_size
= deferred_len
+ len
+ 128;
1039 deferred_send_data
= srealloc(deferred_send_data
, deferred_size
);
1041 memcpy(deferred_send_data
+deferred_len
, pktout
.data
, len
);
1042 deferred_len
+= len
;
1046 * Send the whole deferred data block constructed by
1047 * ssh2_pkt_defer() or SSH1's defer_packet().
1049 static void ssh_pkt_defersend(void) {
1050 sk_write(s
, deferred_send_data
, deferred_len
);
1051 deferred_len
= deferred_size
= 0;
1052 sfree(deferred_send_data
);
1053 deferred_send_data
= NULL
;
1057 void bndebug(char *string
, Bignum b
) {
1060 p
= ssh2_mpint_fmt(b
, &len
);
1061 debug(("%s", string
));
1062 for (i
= 0; i
< len
; i
++)
1063 debug((" %02x", p
[i
]));
1069 static void sha_mpint(SHA_State
*s
, Bignum b
) {
1072 p
= ssh2_mpint_fmt(b
, &len
);
1073 sha_string(s
, p
, len
);
1078 * SSH2 packet decode functions.
1080 static unsigned long ssh2_pkt_getuint32(void) {
1081 unsigned long value
;
1082 if (pktin
.length
- pktin
.savedpos
< 4)
1083 return 0; /* arrgh, no way to decline (FIXME?) */
1084 value
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
1085 pktin
.savedpos
+= 4;
1088 static int ssh2_pkt_getbool(void) {
1089 unsigned long value
;
1090 if (pktin
.length
- pktin
.savedpos
< 1)
1091 return 0; /* arrgh, no way to decline (FIXME?) */
1092 value
= pktin
.data
[pktin
.savedpos
] != 0;
1096 static void ssh2_pkt_getstring(char **p
, int *length
) {
1098 if (pktin
.length
- pktin
.savedpos
< 4)
1100 *length
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
1101 pktin
.savedpos
+= 4;
1102 if (pktin
.length
- pktin
.savedpos
< *length
)
1104 *p
= pktin
.data
+pktin
.savedpos
;
1105 pktin
.savedpos
+= *length
;
1107 static Bignum
ssh2_pkt_getmp(void) {
1112 ssh2_pkt_getstring(&p
, &length
);
1116 bombout(("internal error: Can't handle negative mpints"));
1119 b
= bignum_from_bytes(p
, length
);
1124 * Examine the remote side's version string and compare it against
1125 * a list of known buggy implementations.
1127 static void ssh_detect_bugs(char *vstring
) {
1128 char *imp
; /* pointer to implementation part */
1130 imp
+= strcspn(imp
, "-");
1131 imp
+= strcspn(imp
, "-");
1133 ssh_remote_bugs
= 0;
1135 if (!strcmp(imp
, "1.2.18") || !strcmp(imp
, "1.2.19") ||
1136 !strcmp(imp
, "1.2.20") || !strcmp(imp
, "1.2.21") ||
1137 !strcmp(imp
, "1.2.22")) {
1139 * These versions don't support SSH1_MSG_IGNORE, so we have
1140 * to use a different defence against password length
1143 ssh_remote_bugs
|= BUG_CHOKES_ON_SSH1_IGNORE
;
1144 logevent("We believe remote version has SSH1 ignore bug");
1147 if (!strncmp(imp
, "2.1.0", 5) || !strncmp(imp
, "2.0.", 4) ||
1148 !strncmp(imp
, "2.2.0", 5) || !strncmp(imp
, "2.3.0", 5) ||
1149 !strncmp(imp
, "2.1 ", 4)) {
1151 * These versions have the HMAC bug.
1153 ssh_remote_bugs
|= BUG_SSH2_HMAC
;
1154 logevent("We believe remote version has SSH2 HMAC bug");
1158 static int do_ssh_init(unsigned char c
) {
1160 static char version
[10];
1161 static char *vstring
;
1162 static int vstrsize
;
1168 /* Search for the string "SSH-" in the input. */
1171 static const int transS
[] = { 1, 2, 2, 1 };
1172 static const int transH
[] = { 0, 0, 3, 0 };
1173 static const int transminus
[] = { 0, 0, 0, -1 };
1174 if (c
== 'S') i
= transS
[i
];
1175 else if (c
== 'H') i
= transH
[i
];
1176 else if (c
== '-') i
= transminus
[i
];
1180 crReturn(1); /* get another character */
1183 vstring
= smalloc(16);
1185 strcpy(vstring
, "SSH-");
1189 crReturn(1); /* get another char */
1190 if (vslen
>= vstrsize
-1) {
1192 vstring
= srealloc(vstring
, vstrsize
);
1194 vstring
[vslen
++] = c
;
1199 } else if (i
< sizeof(version
)-1)
1206 ssh_agentfwd_enabled
= FALSE
;
1207 rdpkt2_state
.incoming_sequence
= 0;
1211 vlog
= smalloc(20 + vslen
);
1213 vlog
= smalloc(100);
1214 sprintf(vlog
, "Server version: %s", vstring
);
1215 ssh_detect_bugs(vstring
);
1216 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1220 * Server version "1.99" means we can choose whether we use v1
1221 * or v2 protocol. Choice is based on cfg.sshprot.
1223 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1225 * This is a v2 server. Begin v2 protocol.
1228 sprintf(verstring
, "SSH-2.0-%s", sshver
);
1229 SHA_Init(&exhashbase
);
1231 * Hash our version string and their version string.
1233 sha_string(&exhashbase
, verstring
, strlen(verstring
));
1234 sha_string(&exhashbase
, vstring
, strcspn(vstring
, "\r\n"));
1235 sprintf(vstring
, "%s\n", verstring
);
1236 sprintf(vlog
, "We claim version: %s", verstring
);
1238 logevent("Using SSH protocol version 2");
1239 sk_write(s
, vstring
, strlen(vstring
));
1240 ssh_protocol
= ssh2_protocol
;
1242 s_rdpkt
= ssh2_rdpkt
;
1245 * This is a v1 server. Begin v1 protocol.
1247 sprintf(vstring
, "SSH-%s-%s\n",
1248 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"),
1250 sprintf(vlog
, "We claim version: %s", vstring
);
1251 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1253 logevent("Using SSH protocol version 1");
1254 sk_write(s
, vstring
, strlen(vstring
));
1255 ssh_protocol
= ssh1_protocol
;
1257 s_rdpkt
= ssh1_rdpkt
;
1259 ssh_state
= SSH_STATE_BEFORE_SIZE
;
1267 static void ssh_gotdata(unsigned char *data
, int datalen
)
1272 * To begin with, feed the characters one by one to the
1273 * protocol initialisation / selection function do_ssh_init().
1274 * When that returns 0, we're done with the initial greeting
1275 * exchange and can move on to packet discipline.
1280 crReturnV
; /* more data please */
1281 ret
= do_ssh_init(*data
);
1288 * We emerge from that loop when the initial negotiation is
1289 * over and we have selected an s_rdpkt function. Now pass
1290 * everything to s_rdpkt, and then pass the resulting packets
1291 * to the proper protocol handler.
1296 while (datalen
> 0) {
1297 if ( s_rdpkt(&data
, &datalen
) == 0 ) {
1298 ssh_protocol(NULL
, 0, 1);
1299 if (ssh_state
== SSH_STATE_CLOSED
) {
1309 static int ssh_closing (Plug plug
, char *error_msg
, int error_code
, int calling_back
) {
1310 ssh_state
= SSH_STATE_CLOSED
;
1314 /* A socket error has occurred. */
1315 connection_fatal (error_msg
);
1317 /* Otherwise, the remote side closed the connection normally. */
1322 static int ssh_receive(Plug plug
, int urgent
, char *data
, int len
) {
1323 ssh_gotdata (data
, len
);
1324 if (ssh_state
== SSH_STATE_CLOSED
) {
1335 * Connect to specified host and port.
1336 * Returns an error message, or NULL on success.
1337 * Also places the canonical host name into `realhost'.
1339 static char *connect_to_host(char *host
, int port
, char **realhost
)
1341 static struct plug_function_table fn_table
= {
1344 }, *fn_table_ptr
= &fn_table
;
1353 savedhost
= smalloc(1+strlen(host
));
1355 fatalbox("Out of memory");
1356 strcpy(savedhost
, host
);
1359 port
= 22; /* default ssh port */
1372 addr
= sk_namelookup(host
, realhost
);
1373 if ( (err
= sk_addr_error(addr
)) )
1383 s
= sk_new(addr
, port
, 0, 1, &fn_table_ptr
);
1384 if ( (err
= sk_socket_error(s
)) )
1388 sk_write(s
, "connect ", 8);
1389 sk_write(s
, FWhost
, strlen(FWhost
));
1392 sprintf(buf
, " %d\n", FWport
);
1393 sk_write(s
, buf
, strlen(buf
));
1401 * Handle the key exchange and user authentication phases.
1403 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1406 unsigned char *rsabuf
, *keystr1
, *keystr2
;
1407 unsigned char cookie
[8];
1408 struct RSAKey servkey
, hostkey
;
1409 struct MD5Context md5c
;
1410 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1411 static int tried_publickey
;
1412 static unsigned char session_id
[16];
1414 static char username
[100];
1418 if (!ispkt
) crWaitUntil(ispkt
);
1420 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1421 bombout(("Public key packet not received"));
1425 logevent("Received public keys");
1427 memcpy(cookie
, pktin
.body
, 8);
1429 i
= makekey(pktin
.body
+8, &servkey
, &keystr1
, 0);
1430 j
= makekey(pktin
.body
+8+i
, &hostkey
, &keystr2
, 0);
1433 * Log the host key fingerprint.
1437 logevent("Host key fingerprint is:");
1438 strcpy(logmsg
, " ");
1439 hostkey
.comment
= NULL
;
1440 rsa_fingerprint(logmsg
+strlen(logmsg
), sizeof(logmsg
)-strlen(logmsg
),
1445 ssh1_remote_protoflags
= GET_32BIT(pktin
.body
+8+i
+j
);
1446 supported_ciphers_mask
= GET_32BIT(pktin
.body
+12+i
+j
);
1447 supported_auths_mask
= GET_32BIT(pktin
.body
+16+i
+j
);
1449 ssh1_local_protoflags
= ssh1_remote_protoflags
& SSH1_PROTOFLAGS_SUPPORTED
;
1450 ssh1_local_protoflags
|= SSH1_PROTOFLAG_SCREEN_NUMBER
;
1453 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1454 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1455 MD5Update(&md5c
, pktin
.body
, 8);
1456 MD5Final(session_id
, &md5c
);
1458 for (i
=0; i
<32; i
++)
1459 session_key
[i
] = random_byte();
1461 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1463 rsabuf
= smalloc(len
);
1465 fatalbox("Out of memory");
1468 * Verify the host key.
1472 * First format the key into a string.
1474 int len
= rsastr_len(&hostkey
);
1475 char fingerprint
[100];
1476 char *keystr
= smalloc(len
);
1478 fatalbox("Out of memory");
1479 rsastr_fmt(keystr
, &hostkey
);
1480 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
1481 verify_ssh_host_key(savedhost
, savedport
, "rsa", keystr
, fingerprint
);
1485 for (i
=0; i
<32; i
++) {
1486 rsabuf
[i
] = session_key
[i
];
1488 rsabuf
[i
] ^= session_id
[i
];
1491 if (hostkey
.bytes
> servkey
.bytes
) {
1492 rsaencrypt(rsabuf
, 32, &servkey
);
1493 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1495 rsaencrypt(rsabuf
, 32, &hostkey
);
1496 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1499 logevent("Encrypted session key");
1501 switch (cfg
.cipher
) {
1502 case CIPHER_BLOWFISH
: cipher_type
= SSH_CIPHER_BLOWFISH
; break;
1503 case CIPHER_DES
: cipher_type
= SSH_CIPHER_DES
; break;
1504 case CIPHER_3DES
: cipher_type
= SSH_CIPHER_3DES
; break;
1506 c_write_str("AES not supported in SSH1, falling back to 3DES\r\n");
1507 cipher_type
= SSH_CIPHER_3DES
;
1510 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1511 c_write_str("Selected cipher not supported, falling back to 3DES\r\n");
1512 cipher_type
= SSH_CIPHER_3DES
;
1514 switch (cipher_type
) {
1515 case SSH_CIPHER_3DES
: logevent("Using 3DES encryption"); break;
1516 case SSH_CIPHER_DES
: logevent("Using single-DES encryption"); break;
1517 case SSH_CIPHER_BLOWFISH
: logevent("Using Blowfish encryption"); break;
1520 send_packet(SSH1_CMSG_SESSION_KEY
,
1521 PKT_CHAR
, cipher_type
,
1522 PKT_DATA
, cookie
, 8,
1523 PKT_CHAR
, (len
*8) >> 8, PKT_CHAR
, (len
*8) & 0xFF,
1524 PKT_DATA
, rsabuf
, len
,
1525 PKT_INT
, ssh1_local_protoflags
,
1528 logevent("Trying to enable encryption...");
1532 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
1533 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
1535 cipher
->sesskey(session_key
);
1539 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1540 bombout(("Encryption not successfully enabled"));
1544 logevent("Successfully started encryption");
1550 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
1552 if (!ssh_get_line("login as: ",
1553 username
, sizeof(username
), FALSE
)) {
1555 * get_line failed to get a username.
1558 logevent("No username provided. Abandoning session.");
1559 ssh_state
= SSH_STATE_CLOSED
;
1563 c_write_str("login as: ");
1566 crWaitUntil(!ispkt
);
1567 while (inlen
--) switch (c
= *in
++) {
1574 c_write_str("\b \b");
1580 c_write_str("\b \b");
1589 if (((c
>= ' ' && c
<= '~') ||
1590 ((unsigned char)c
>= 160)) && pos
< 40) {
1591 username
[pos
++] = c
;
1597 c_write_str("\r\n");
1598 username
[strcspn(username
, "\n\r")] = '\0';
1601 strncpy(username
, cfg
.username
, 99);
1602 username
[99] = '\0';
1605 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
1607 char userlog
[22+sizeof(username
)];
1608 sprintf(userlog
, "Sent username \"%s\"", username
);
1610 if (flags
& FLAG_INTERACTIVE
&&
1611 (!((flags
& FLAG_STDERR
) && (flags
& FLAG_VERBOSE
)))) {
1612 strcat(userlog
, "\r\n");
1613 c_write_str(userlog
);
1620 tried_publickey
= 0;
1622 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
1623 static char password
[100];
1624 static char prompt
[200];
1627 static int pwpkt_type
;
1629 * Show password prompt, having first obtained it via a TIS
1630 * or CryptoCard exchange if we're doing TIS or CryptoCard
1633 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
1634 if (agent_exists()) {
1636 * Attempt RSA authentication using Pageant.
1638 static unsigned char request
[5], *response
, *p
;
1639 static int responselen
;
1640 static int i
, nkeys
;
1641 static int authed
= FALSE
;
1644 logevent("Pageant is running. Requesting keys.");
1646 /* Request the keys held by the agent. */
1647 PUT_32BIT(request
, 1);
1648 request
[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES
;
1649 agent_query(request
, 5, &r
, &responselen
);
1650 response
= (unsigned char *)r
;
1651 if (response
&& responselen
>= 5 &&
1652 response
[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER
) {
1654 nkeys
= GET_32BIT(p
); p
+= 4;
1655 { char buf
[64]; sprintf(buf
, "Pageant has %d SSH1 keys", nkeys
);
1657 for (i
= 0; i
< nkeys
; i
++) {
1658 static struct RSAKey key
;
1659 static Bignum challenge
;
1660 static char *commentp
;
1661 static int commentlen
;
1663 { char buf
[64]; sprintf(buf
, "Trying Pageant key #%d", i
);
1666 p
+= ssh1_read_bignum(p
, &key
.exponent
);
1667 p
+= ssh1_read_bignum(p
, &key
.modulus
);
1668 commentlen
= GET_32BIT(p
); p
+= 4;
1669 commentp
= p
; p
+= commentlen
;
1670 send_packet(SSH1_CMSG_AUTH_RSA
,
1671 PKT_BIGNUM
, key
.modulus
, PKT_END
);
1673 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1674 logevent("Key refused");
1677 logevent("Received RSA challenge");
1678 ssh1_read_bignum(pktin
.body
, &challenge
);
1680 char *agentreq
, *q
, *ret
;
1682 len
= 1 + 4; /* message type, bit count */
1683 len
+= ssh1_bignum_length(key
.exponent
);
1684 len
+= ssh1_bignum_length(key
.modulus
);
1685 len
+= ssh1_bignum_length(challenge
);
1686 len
+= 16; /* session id */
1687 len
+= 4; /* response format */
1688 agentreq
= smalloc(4 + len
);
1689 PUT_32BIT(agentreq
, len
);
1691 *q
++ = SSH1_AGENTC_RSA_CHALLENGE
;
1692 PUT_32BIT(q
, ssh1_bignum_bitcount(key
.modulus
));
1694 q
+= ssh1_write_bignum(q
, key
.exponent
);
1695 q
+= ssh1_write_bignum(q
, key
.modulus
);
1696 q
+= ssh1_write_bignum(q
, challenge
);
1697 memcpy(q
, session_id
, 16); q
+= 16;
1698 PUT_32BIT(q
, 1); /* response format */
1699 agent_query(agentreq
, len
+4, &ret
, &retlen
);
1702 if (ret
[4] == SSH1_AGENT_RSA_RESPONSE
) {
1703 logevent("Sending Pageant's response");
1704 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1705 PKT_DATA
, ret
+5, 16, PKT_END
);
1708 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1709 logevent("Pageant's response accepted");
1710 if (flags
& FLAG_VERBOSE
) {
1711 c_write_str("Authenticated using RSA key \"");
1712 c_write(commentp
, commentlen
);
1713 c_write_str("\" from agent\r\n");
1717 logevent("Pageant's response not accepted");
1719 logevent("Pageant failed to answer challenge");
1723 logevent("No reply received from Pageant");
1726 freebn(key
.exponent
);
1727 freebn(key
.modulus
);
1736 if (*cfg
.keyfile
&& !tried_publickey
)
1737 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
1739 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1741 (supported_auths_mask
& (1<<SSH1_AUTH_TIS
))) {
1742 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
1743 logevent("Requested TIS authentication");
1744 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
1746 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
1747 logevent("TIS authentication declined");
1748 if (flags
& FLAG_INTERACTIVE
)
1749 c_write_str("TIS authentication refused.\r\n");
1751 int challengelen
= ((pktin
.body
[0] << 24) |
1752 (pktin
.body
[1] << 16) |
1753 (pktin
.body
[2] << 8) |
1755 logevent("Received TIS challenge");
1756 if (challengelen
> sizeof(prompt
)-1)
1757 challengelen
= sizeof(prompt
)-1; /* prevent overrun */
1758 memcpy(prompt
, pktin
.body
+4, challengelen
);
1759 prompt
[challengelen
] = '\0';
1762 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1764 (supported_auths_mask
& (1<<SSH1_AUTH_CCARD
))) {
1765 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
1766 logevent("Requested CryptoCard authentication");
1767 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
1769 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
1770 logevent("CryptoCard authentication declined");
1771 c_write_str("CryptoCard authentication refused.\r\n");
1773 int challengelen
= ((pktin
.body
[0] << 24) |
1774 (pktin
.body
[1] << 16) |
1775 (pktin
.body
[2] << 8) |
1777 logevent("Received CryptoCard challenge");
1778 if (challengelen
> sizeof(prompt
)-1)
1779 challengelen
= sizeof(prompt
)-1; /* prevent overrun */
1780 memcpy(prompt
, pktin
.body
+4, challengelen
);
1781 strncpy(prompt
+ challengelen
, "\r\nResponse : ",
1782 sizeof(prompt
)-challengelen
);
1783 prompt
[sizeof(prompt
)-1] = '\0';
1786 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
1787 sprintf(prompt
, "%.90s@%.90s's password: ",
1788 username
, savedhost
);
1790 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1791 char *comment
= NULL
;
1792 if (flags
& FLAG_VERBOSE
)
1793 c_write_str("Trying public key authentication.\r\n");
1794 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
1795 if (flags
& FLAG_VERBOSE
)
1796 c_write_str("No passphrase required.\r\n");
1799 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
1804 if (!ssh_get_line(prompt
, password
, sizeof(password
), TRUE
)) {
1806 * get_line failed to get a password (for example
1807 * because one was supplied on the command line
1808 * which has already failed to work). Terminate.
1810 logevent("No more passwords to try");
1811 ssh_state
= SSH_STATE_CLOSED
;
1815 c_write_str(prompt
);
1819 crWaitUntil(!ispkt
);
1820 while (inlen
--) switch (c
= *in
++) {
1837 if (((c
>= ' ' && c
<= '~') ||
1838 ((unsigned char)c
>= 160)) && pos
< sizeof(password
))
1839 password
[pos
++] = c
;
1843 c_write_str("\r\n");
1847 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1849 * Try public key authentication with the specified
1852 static struct RSAKey pubkey
;
1853 static Bignum challenge
, response
;
1855 static unsigned char buffer
[32];
1857 tried_publickey
= 1;
1858 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
1860 c_write_str("Couldn't load public key from ");
1861 c_write_str(cfg
.keyfile
);
1862 c_write_str(".\r\n");
1863 continue; /* go and try password */
1866 c_write_str("Wrong passphrase.\r\n");
1867 tried_publickey
= 0;
1868 continue; /* try again */
1872 * Send a public key attempt.
1874 send_packet(SSH1_CMSG_AUTH_RSA
,
1875 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
1878 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1879 c_write_str("Server refused our public key.\r\n");
1880 continue; /* go and try password */
1882 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1883 bombout(("Bizarre response to offer of public key"));
1886 ssh1_read_bignum(pktin
.body
, &challenge
);
1887 response
= rsadecrypt(challenge
, &pubkey
);
1888 freebn(pubkey
.private_exponent
); /* burn the evidence */
1890 for (i
= 0; i
< 32; i
++) {
1891 buffer
[i
] = bignum_byte(response
, 31-i
);
1895 MD5Update(&md5c
, buffer
, 32);
1896 MD5Update(&md5c
, session_id
, 16);
1897 MD5Final(buffer
, &md5c
);
1899 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1900 PKT_DATA
, buffer
, 16, PKT_END
);
1903 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1904 if (flags
& FLAG_VERBOSE
)
1905 c_write_str("Failed to authenticate with our public key.\r\n");
1906 continue; /* go and try password */
1907 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1908 bombout(("Bizarre response to RSA authentication response"));
1912 break; /* we're through! */
1914 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
1916 * Defence against traffic analysis: we send a
1917 * whole bunch of packets containing strings of
1918 * different lengths. One of these strings is the
1919 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
1920 * The others are all random data in
1921 * SSH1_MSG_IGNORE packets. This way a passive
1922 * listener can't tell which is the password, and
1923 * hence can't deduce the password length.
1925 * Anybody with a password length greater than 16
1926 * bytes is going to have enough entropy in their
1927 * password that a listener won't find it _that_
1928 * much help to know how long it is. So what we'll
1931 * - if password length < 16, we send 15 packets
1932 * containing string lengths 1 through 15
1934 * - otherwise, we let N be the nearest multiple
1935 * of 8 below the password length, and send 8
1936 * packets containing string lengths N through
1937 * N+7. This won't obscure the order of
1938 * magnitude of the password length, but it will
1939 * introduce a bit of extra uncertainty.
1941 * A few servers (the old 1.2.18 through 1.2.22)
1942 * can't deal with SSH1_MSG_IGNORE. For these
1943 * servers, we need an alternative defence. We make
1944 * use of the fact that the password is interpreted
1945 * as a C string: so we can append a NUL, then some
1948 if (ssh_remote_bugs
& BUG_CHOKES_ON_SSH1_IGNORE
) {
1953 len
= strlen(password
);
1954 if (len
< sizeof(string
)) {
1956 strcpy(string
, password
);
1957 len
++; /* cover the zero byte */
1958 while (len
< sizeof(string
)) {
1959 string
[len
++] = (char)random_byte();
1964 send_packet(pwpkt_type
, PKT_INT
, len
,
1965 PKT_DATA
, s
, len
, PKT_END
);
1967 int bottom
, top
, pwlen
, i
;
1970 pwlen
= strlen(password
);
1972 bottom
= 0; /* zero length passwords are OK! :-) */
1975 bottom
= pwlen
&~ 7;
1979 assert(pwlen
>= bottom
&& pwlen
<= top
);
1981 randomstr
= smalloc(top
+1);
1983 for (i
= bottom
; i
<= top
; i
++) {
1985 defer_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
1987 for (j
= 0; j
< i
; j
++) {
1989 randomstr
[j
] = random_byte();
1990 } while (randomstr
[j
] == '\0');
1992 randomstr
[i
] = '\0';
1993 defer_packet(SSH1_MSG_IGNORE
,
1994 PKT_STR
, randomstr
, PKT_END
);
1997 ssh_pkt_defersend();
2000 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
2003 logevent("Sent password");
2004 memset(password
, 0, strlen(password
));
2006 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2007 if (flags
& FLAG_VERBOSE
)
2008 c_write_str("Access denied\r\n");
2009 logevent("Authentication refused");
2010 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2011 logevent("Received disconnect request");
2012 ssh_state
= SSH_STATE_CLOSED
;
2014 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
2015 bombout(("Strange packet received, type %d", pktin
.type
));
2020 logevent("Authentication successful");
2025 void sshfwd_close(struct ssh_channel
*c
) {
2026 if (c
&& !c
->closes
) {
2027 if (ssh_version
== 1) {
2028 send_packet(SSH1_MSG_CHANNEL_CLOSE
, PKT_INT
, c
->remoteid
, PKT_END
);
2030 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2031 ssh2_pkt_adduint32(c
->remoteid
);
2035 if (c
->type
== CHAN_X11
) {
2037 logevent("X11 connection terminated");
2042 void sshfwd_write(struct ssh_channel
*c
, char *buf
, int len
) {
2043 if (ssh_version
== 1) {
2044 send_packet(SSH1_MSG_CHANNEL_DATA
,
2045 PKT_INT
, c
->remoteid
,
2050 ssh2_add_channel_data(c
, buf
, len
);
2055 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
) {
2060 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
2063 if (ssh_state
== SSH_STATE_CLOSED
)
2066 if (cfg
.agentfwd
&& agent_exists()) {
2067 logevent("Requesting agent forwarding");
2068 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
2069 do { crReturnV
; } while (!ispkt
);
2070 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
2071 bombout(("Protocol confusion"));
2073 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2074 logevent("Agent forwarding refused");
2076 logevent("Agent forwarding enabled");
2077 ssh_agentfwd_enabled
= TRUE
;
2081 if (cfg
.x11_forward
) {
2082 char proto
[20], data
[64];
2083 logevent("Requesting X11 forwarding");
2084 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
2085 if (ssh1_local_protoflags
& SSH1_PROTOFLAG_SCREEN_NUMBER
) {
2086 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2087 PKT_STR
, proto
, PKT_STR
, data
,
2091 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING
,
2092 PKT_STR
, proto
, PKT_STR
, data
,
2095 do { crReturnV
; } while (!ispkt
);
2096 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
2097 bombout(("Protocol confusion"));
2099 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2100 logevent("X11 forwarding refused");
2102 logevent("X11 forwarding enabled");
2103 ssh_X11_fwd_enabled
= TRUE
;
2108 send_packet(SSH1_CMSG_REQUEST_PTY
,
2109 PKT_STR
, cfg
.termtype
,
2110 PKT_INT
, rows
, PKT_INT
, cols
,
2111 PKT_INT
, 0, PKT_INT
, 0,
2114 ssh_state
= SSH_STATE_INTERMED
;
2115 do { crReturnV
; } while (!ispkt
);
2116 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
2117 bombout(("Protocol confusion"));
2119 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2120 c_write_str("Server refused to allocate pty\r\n");
2121 ssh_editing
= ssh_echoing
= 1;
2123 logevent("Allocated pty");
2125 ssh_editing
= ssh_echoing
= 1;
2128 if (cfg
.compression
) {
2129 send_packet(SSH1_CMSG_REQUEST_COMPRESSION
, PKT_INT
, 6, PKT_END
);
2130 do { crReturnV
; } while (!ispkt
);
2131 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
2132 bombout(("Protocol confusion"));
2134 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2135 c_write_str("Server refused to compress\r\n");
2137 logevent("Started compression");
2138 ssh1_compressing
= TRUE
;
2139 zlib_compress_init();
2140 zlib_decompress_init();
2143 if (*cfg
.remote_cmd_ptr
)
2144 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cfg
.remote_cmd_ptr
, PKT_END
);
2146 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
2147 logevent("Started session");
2149 ssh_state
= SSH_STATE_SESSION
;
2153 ssh_special(TS_EOF
);
2155 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
2157 ssh_channels
= newtree234(ssh_channelcmp
);
2161 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
2162 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
2163 long len
= GET_32BIT(pktin
.body
);
2164 from_backend(pktin
.type
== SSH1_SMSG_STDERR_DATA
,
2166 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2167 ssh_state
= SSH_STATE_CLOSED
;
2168 logevent("Received disconnect request");
2170 } else if (pktin
.type
== SSH1_SMSG_X11_OPEN
) {
2171 /* Remote side is trying to open a channel to talk to our
2172 * X-Server. Give them back a local channel number. */
2174 struct ssh_channel
*c
, *d
;
2177 logevent("Received X11 connect request");
2178 /* Refuse if X11 forwarding is disabled. */
2179 if (!ssh_X11_fwd_enabled
) {
2180 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2181 PKT_INT
, GET_32BIT(pktin
.body
),
2183 logevent("Rejected X11 connect request");
2185 c
= smalloc(sizeof(struct ssh_channel
));
2187 if ( x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
2188 logevent("opening X11 forward connection failed");
2190 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2191 PKT_INT
, GET_32BIT(pktin
.body
),
2194 logevent("opening X11 forward connection succeeded");
2195 for (i
=1, d
= first234(ssh_channels
, &e
); d
; d
= next234(&e
)) {
2197 break; /* found a free number */
2200 c
->remoteid
= GET_32BIT(pktin
.body
);
2203 c
->type
= CHAN_X11
; /* identify channel type */
2204 add234(ssh_channels
, c
);
2205 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2206 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2208 logevent("Opened X11 forward channel");
2211 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
2212 /* Remote side is trying to open a channel to talk to our
2213 * agent. Give them back a local channel number. */
2215 struct ssh_channel
*c
;
2218 /* Refuse if agent forwarding is disabled. */
2219 if (!ssh_agentfwd_enabled
) {
2220 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE
,
2221 PKT_INT
, GET_32BIT(pktin
.body
),
2225 for (c
= first234(ssh_channels
, &e
); c
; c
= next234(&e
)) {
2227 break; /* found a free number */
2230 c
= smalloc(sizeof(struct ssh_channel
));
2231 c
->remoteid
= GET_32BIT(pktin
.body
);
2234 c
->type
= CHAN_AGENT
; /* identify channel type */
2235 c
->u
.a
.lensofar
= 0;
2236 add234(ssh_channels
, c
);
2237 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
2238 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
2241 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
2242 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
2243 /* Remote side closes a channel. */
2244 unsigned i
= GET_32BIT(pktin
.body
);
2245 struct ssh_channel
*c
;
2246 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2249 closetype
= (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
2250 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
, PKT_END
);
2251 if ((c
->closes
== 0) && (c
->type
== CHAN_X11
)) {
2252 logevent("X11 connection closed");
2253 assert(c
->u
.x11
.s
!= NULL
);
2254 x11_close(c
->u
.x11
.s
);
2257 c
->closes
|= closetype
;
2258 if (c
->closes
== 3) {
2259 del234(ssh_channels
, c
);
2263 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
2264 /* Data sent down one of our channels. */
2265 int i
= GET_32BIT(pktin
.body
);
2266 int len
= GET_32BIT(pktin
.body
+4);
2267 unsigned char *p
= pktin
.body
+8;
2268 struct ssh_channel
*c
;
2269 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
2273 x11_send(c
->u
.x11
.s
, p
, len
);
2276 /* Data for an agent message. Buffer it. */
2278 if (c
->u
.a
.lensofar
< 4) {
2279 int l
= min(4 - c
->u
.a
.lensofar
, len
);
2280 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
, l
);
2281 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
2283 if (c
->u
.a
.lensofar
== 4) {
2284 c
->u
.a
.totallen
= 4 + GET_32BIT(c
->u
.a
.msglen
);
2285 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
2286 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
2288 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
2289 int l
= min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
, len
);
2290 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
, l
);
2291 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
2293 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
2294 void *reply
, *sentreply
;
2296 agent_query(c
->u
.a
.message
, c
->u
.a
.totallen
,
2301 /* Fake SSH_AGENT_FAILURE. */
2302 sentreply
= "\0\0\0\1\5";
2305 send_packet(SSH1_MSG_CHANNEL_DATA
,
2306 PKT_INT
, c
->remoteid
,
2308 PKT_DATA
, sentreply
, replylen
,
2312 sfree(c
->u
.a
.message
);
2313 c
->u
.a
.lensofar
= 0;
2319 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
2320 /* may be from EXEC_SHELL on some servers */
2321 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
2322 /* may be from EXEC_SHELL on some servers
2323 * if no pty is available or in other odd cases. Ignore */
2324 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
2325 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
2327 bombout(("Strange packet received: type %d", pktin
.type
));
2332 int len
= min(inlen
, 512);
2333 send_packet(SSH1_CMSG_STDIN_DATA
,
2334 PKT_INT
, len
, PKT_DATA
, in
, len
, PKT_END
);
2345 * Utility routine for decoding comma-separated strings in KEXINIT.
2347 static int in_commasep_string(char *needle
, char *haystack
, int haylen
) {
2348 int needlen
= strlen(needle
);
2351 * Is it at the start of the string?
2353 if (haylen
>= needlen
&& /* haystack is long enough */
2354 !memcmp(needle
, haystack
, needlen
) && /* initial match */
2355 (haylen
== needlen
|| haystack
[needlen
] == ',')
2356 /* either , or EOS follows */
2360 * If not, search for the next comma and resume after that.
2361 * If no comma found, terminate.
2363 while (haylen
> 0 && *haystack
!= ',')
2364 haylen
--, haystack
++;
2367 haylen
--, haystack
++; /* skip over comma itself */
2372 * SSH2 key creation method.
2374 static void ssh2_mkkey(Bignum K
, char *H
, char *sessid
, char chr
, char *keyspace
) {
2376 /* First 20 bytes. */
2379 SHA_Bytes(&s
, H
, 20);
2380 SHA_Bytes(&s
, &chr
, 1);
2381 SHA_Bytes(&s
, sessid
, 20);
2382 SHA_Final(&s
, keyspace
);
2383 /* Next 20 bytes. */
2386 SHA_Bytes(&s
, H
, 20);
2387 SHA_Bytes(&s
, keyspace
, 20);
2388 SHA_Final(&s
, keyspace
+20);
2392 * Handle the SSH2 transport layer.
2394 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
2396 static int i
, j
, len
, nbits
, pbits
;
2398 static Bignum p
, g
, e
, f
, K
;
2399 static int kex_init_value
, kex_reply_value
;
2400 static const struct ssh_mac
**maclist
;
2402 static const struct ssh2_cipher
*cscipher_tobe
= NULL
;
2403 static const struct ssh2_cipher
*sccipher_tobe
= NULL
;
2404 static const struct ssh_mac
*csmac_tobe
= NULL
;
2405 static const struct ssh_mac
*scmac_tobe
= NULL
;
2406 static const struct ssh_compress
*cscomp_tobe
= NULL
;
2407 static const struct ssh_compress
*sccomp_tobe
= NULL
;
2408 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
2409 static int hostkeylen
, siglen
;
2410 static void *hkey
; /* actual host key */
2411 static unsigned char exchange_hash
[20];
2412 static unsigned char keyspace
[40];
2413 static const struct ssh2_ciphers
*preferred_cipher
;
2414 static const struct ssh_compress
*preferred_comp
;
2415 static int first_kex
;
2422 * Set up the preferred cipher and compression.
2424 if (cfg
.cipher
== CIPHER_BLOWFISH
) {
2425 preferred_cipher
= &ssh2_blowfish
;
2426 } else if (cfg
.cipher
== CIPHER_DES
) {
2427 logevent("Single DES not supported in SSH2; using 3DES");
2428 preferred_cipher
= &ssh2_3des
;
2429 } else if (cfg
.cipher
== CIPHER_3DES
) {
2430 preferred_cipher
= &ssh2_3des
;
2431 } else if (cfg
.cipher
== CIPHER_AES
) {
2432 preferred_cipher
= &ssh2_aes
;
2434 /* Shouldn't happen, but we do want to initialise to _something_. */
2435 preferred_cipher
= &ssh2_3des
;
2437 if (cfg
.compression
)
2438 preferred_comp
= &ssh_zlib
;
2440 preferred_comp
= &ssh_comp_none
;
2443 * Be prepared to work around the buggy MAC problem.
2445 if (cfg
.buggymac
|| (ssh_remote_bugs
& BUG_SSH2_HMAC
))
2446 maclist
= buggymacs
, nmacs
= lenof(buggymacs
);
2448 maclist
= macs
, nmacs
= lenof(macs
);
2452 * Construct and send our key exchange packet.
2454 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
2455 for (i
= 0; i
< 16; i
++)
2456 ssh2_pkt_addbyte((unsigned char)random_byte());
2457 /* List key exchange algorithms. */
2458 ssh2_pkt_addstring_start();
2459 for (i
= 0; i
< lenof(kex_algs
); i
++) {
2460 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
2461 if (i
< lenof(kex_algs
)-1)
2462 ssh2_pkt_addstring_str(",");
2464 /* List server host key algorithms. */
2465 ssh2_pkt_addstring_start();
2466 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
2467 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
2468 if (i
< lenof(hostkey_algs
)-1)
2469 ssh2_pkt_addstring_str(",");
2471 /* List client->server encryption algorithms. */
2472 ssh2_pkt_addstring_start();
2473 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2474 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2475 for (j
= 0; j
< c
->nciphers
; j
++) {
2476 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
2477 if (i
< lenof(ciphers
) || j
< c
->nciphers
-1)
2478 ssh2_pkt_addstring_str(",");
2481 /* List server->client encryption algorithms. */
2482 ssh2_pkt_addstring_start();
2483 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2484 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2485 for (j
= 0; j
< c
->nciphers
; j
++) {
2486 ssh2_pkt_addstring_str(c
->list
[j
]->name
);
2487 if (i
< lenof(ciphers
) || j
< c
->nciphers
-1)
2488 ssh2_pkt_addstring_str(",");
2491 /* List client->server MAC algorithms. */
2492 ssh2_pkt_addstring_start();
2493 for (i
= 0; i
< nmacs
; i
++) {
2494 ssh2_pkt_addstring_str(maclist
[i
]->name
);
2496 ssh2_pkt_addstring_str(",");
2498 /* List server->client MAC algorithms. */
2499 ssh2_pkt_addstring_start();
2500 for (i
= 0; i
< nmacs
; i
++) {
2501 ssh2_pkt_addstring_str(maclist
[i
]->name
);
2503 ssh2_pkt_addstring_str(",");
2505 /* List client->server compression algorithms. */
2506 ssh2_pkt_addstring_start();
2507 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2508 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2509 ssh2_pkt_addstring_str(c
->name
);
2510 if (i
< lenof(compressions
))
2511 ssh2_pkt_addstring_str(",");
2513 /* List server->client compression algorithms. */
2514 ssh2_pkt_addstring_start();
2515 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2516 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2517 ssh2_pkt_addstring_str(c
->name
);
2518 if (i
< lenof(compressions
))
2519 ssh2_pkt_addstring_str(",");
2521 /* List client->server languages. Empty list. */
2522 ssh2_pkt_addstring_start();
2523 /* List server->client languages. Empty list. */
2524 ssh2_pkt_addstring_start();
2525 /* First KEX packet does _not_ follow, because we're not that brave. */
2526 ssh2_pkt_addbool(FALSE
);
2528 ssh2_pkt_adduint32(0);
2530 exhash
= exhashbase
;
2531 sha_string(&exhash
, pktout
.data
+5, pktout
.length
-5);
2535 if (!ispkt
) crWaitUntil(ispkt
);
2536 sha_string(&exhash
, pktin
.data
+5, pktin
.length
-5);
2539 * Now examine the other side's KEXINIT to see what we're up
2542 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
2543 bombout(("expected key exchange packet from server"));
2546 kex
= NULL
; hostkey
= NULL
; cscipher_tobe
= NULL
; sccipher_tobe
= NULL
;
2547 csmac_tobe
= NULL
; scmac_tobe
= NULL
; cscomp_tobe
= NULL
; sccomp_tobe
= NULL
;
2548 pktin
.savedpos
+= 16; /* skip garbage cookie */
2549 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
2550 for (i
= 0; i
< lenof(kex_algs
); i
++) {
2551 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
2556 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
2557 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
2558 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
2559 hostkey
= hostkey_algs
[i
];
2563 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
2564 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2565 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2566 for (j
= 0; j
< c
->nciphers
; j
++) {
2567 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
2568 cscipher_tobe
= c
->list
[j
];
2575 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
2576 for (i
= 0; i
< lenof(ciphers
)+1; i
++) {
2577 const struct ssh2_ciphers
*c
= i
==0 ? preferred_cipher
: ciphers
[i
-1];
2578 for (j
= 0; j
< c
->nciphers
; j
++) {
2579 if (in_commasep_string(c
->list
[j
]->name
, str
, len
)) {
2580 sccipher_tobe
= c
->list
[j
];
2587 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
2588 for (i
= 0; i
< nmacs
; i
++) {
2589 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
2590 csmac_tobe
= maclist
[i
];
2594 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
2595 for (i
= 0; i
< nmacs
; i
++) {
2596 if (in_commasep_string(maclist
[i
]->name
, str
, len
)) {
2597 scmac_tobe
= maclist
[i
];
2601 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
2602 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2603 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2604 if (in_commasep_string(c
->name
, str
, len
)) {
2609 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
2610 for (i
= 0; i
< lenof(compressions
)+1; i
++) {
2611 const struct ssh_compress
*c
= i
==0 ? preferred_comp
: compressions
[i
-1];
2612 if (in_commasep_string(c
->name
, str
, len
)) {
2619 * Work out the number of bits of key we will need from the key
2620 * exchange. We start with the maximum key length of either
2626 csbits
= cscipher_tobe
->keylen
;
2627 scbits
= sccipher_tobe
->keylen
;
2628 nbits
= (csbits
> scbits ? csbits
: scbits
);
2630 /* The keys only have 160-bit entropy, since they're based on
2631 * a SHA-1 hash. So cap the key size at 160 bits. */
2632 if (nbits
> 160) nbits
= 160;
2635 * If we're doing Diffie-Hellman group exchange, start by
2636 * requesting a group.
2638 if (kex
== &ssh_diffiehellman_gex
) {
2639 logevent("Doing Diffie-Hellman group exchange");
2641 * Work out how big a DH group we will need to allow that
2644 pbits
= 512 << ((nbits
-1) / 64);
2645 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST
);
2646 ssh2_pkt_adduint32(pbits
);
2650 if (pktin
.type
!= SSH2_MSG_KEX_DH_GEX_GROUP
) {
2651 bombout(("expected key exchange group packet from server"));
2654 p
= ssh2_pkt_getmp();
2655 g
= ssh2_pkt_getmp();
2656 dh_setup_group(p
, g
);
2657 kex_init_value
= SSH2_MSG_KEX_DH_GEX_INIT
;
2658 kex_reply_value
= SSH2_MSG_KEX_DH_GEX_REPLY
;
2661 kex_init_value
= SSH2_MSG_KEXDH_INIT
;
2662 kex_reply_value
= SSH2_MSG_KEXDH_REPLY
;
2665 logevent("Doing Diffie-Hellman key exchange");
2667 * Now generate and send e for Diffie-Hellman.
2669 e
= dh_create_e(nbits
*2);
2670 ssh2_pkt_init(kex_init_value
);
2675 if (pktin
.type
!= kex_reply_value
) {
2676 bombout(("expected key exchange reply packet from server"));
2679 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
2680 f
= ssh2_pkt_getmp();
2681 ssh2_pkt_getstring(&sigdata
, &siglen
);
2685 sha_string(&exhash
, hostkeydata
, hostkeylen
);
2686 if (kex
== &ssh_diffiehellman_gex
) {
2687 sha_uint32(&exhash
, pbits
);
2688 sha_mpint(&exhash
, p
);
2689 sha_mpint(&exhash
, g
);
2691 sha_mpint(&exhash
, e
);
2692 sha_mpint(&exhash
, f
);
2693 sha_mpint(&exhash
, K
);
2694 SHA_Final(&exhash
, exchange_hash
);
2699 debug(("Exchange hash is:\r\n"));
2700 for (i
= 0; i
< 20; i
++)
2701 debug((" %02x", exchange_hash
[i
]));
2705 hkey
= hostkey
->newkey(hostkeydata
, hostkeylen
);
2706 if (!hostkey
->verifysig(hkey
, sigdata
, siglen
, exchange_hash
, 20)) {
2707 bombout(("Server failed host key check"));
2712 * Expect SSH2_MSG_NEWKEYS from server.
2715 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
2716 bombout(("expected new-keys packet from server"));
2721 * Authenticate remote host: verify host key. (We've already
2722 * checked the signature of the exchange hash.)
2724 keystr
= hostkey
->fmtkey(hkey
);
2725 fingerprint
= hostkey
->fingerprint(hkey
);
2726 verify_ssh_host_key(savedhost
, savedport
, hostkey
->keytype
,
2727 keystr
, fingerprint
);
2728 if (first_kex
) { /* don't bother logging this in rekeys */
2729 logevent("Host key fingerprint is:");
2730 logevent(fingerprint
);
2734 hostkey
->freekey(hkey
);
2737 * Send SSH2_MSG_NEWKEYS.
2739 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
2743 * Create and initialise session keys.
2745 cscipher
= cscipher_tobe
;
2746 sccipher
= sccipher_tobe
;
2749 cscomp
= cscomp_tobe
;
2750 sccomp
= sccomp_tobe
;
2751 cscomp
->compress_init();
2752 sccomp
->decompress_init();
2754 * Set IVs after keys. Here we use the exchange hash from the
2755 * _first_ key exchange.
2758 memcpy(ssh2_session_id
, exchange_hash
, sizeof(exchange_hash
));
2759 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'C', keyspace
);
2760 cscipher
->setcskey(keyspace
);
2761 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'D', keyspace
);
2762 sccipher
->setsckey(keyspace
);
2763 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'A', keyspace
);
2764 cscipher
->setcsiv(keyspace
);
2765 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'B', keyspace
);
2766 sccipher
->setsciv(keyspace
);
2767 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'E', keyspace
);
2768 csmac
->setcskey(keyspace
);
2769 ssh2_mkkey(K
, exchange_hash
, ssh2_session_id
, 'F', keyspace
);
2770 scmac
->setsckey(keyspace
);
2773 * If this is the first key exchange phase, we must pass the
2774 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
2775 * wants to see it but because it will need time to initialise
2776 * itself before it sees an actual packet. In subsequent key
2777 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
2778 * it would only confuse the layer above.
2786 * Now we're encrypting. Begin returning 1 to the protocol main
2787 * function so that other things can run on top of the
2788 * transport. If we ever see a KEXINIT, we must go back to the
2791 while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
)) {
2794 logevent("Server initiated key re-exchange");
2795 goto begin_key_exchange
;
2801 * Add data to an SSH2 channel output buffer.
2803 static void ssh2_add_channel_data(struct ssh_channel
*c
, char *buf
, int len
) {
2804 if (c
->v2
.outbufsize
<
2805 c
->v2
.outbuflen
+ len
) {
2807 c
->v2
.outbuflen
+ len
+ 1024;
2808 c
->v2
.outbuffer
= srealloc(c
->v2
.outbuffer
,
2811 memcpy(c
->v2
.outbuffer
+ c
->v2
.outbuflen
,
2813 c
->v2
.outbuflen
+= len
;
2817 * Attempt to send data on an SSH2 channel.
2819 static void ssh2_try_send(struct ssh_channel
*c
) {
2820 while (c
->v2
.remwindow
> 0 &&
2821 c
->v2
.outbuflen
> 0) {
2822 unsigned len
= c
->v2
.remwindow
;
2823 if (len
> c
->v2
.outbuflen
)
2824 len
= c
->v2
.outbuflen
;
2825 if (len
> c
->v2
.remmaxpkt
)
2826 len
= c
->v2
.remmaxpkt
;
2827 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
2828 ssh2_pkt_adduint32(c
->remoteid
);
2829 ssh2_pkt_addstring_start();
2830 ssh2_pkt_addstring_data(c
->v2
.outbuffer
, len
);
2832 c
->v2
.outbuflen
-= len
;
2833 memmove(c
->v2
.outbuffer
, c
->v2
.outbuffer
+len
,
2835 c
->v2
.remwindow
-= len
;
2840 * Handle the SSH2 userauth and connection layers.
2842 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
2844 static unsigned long remote_winsize
;
2845 static unsigned long remote_maxpkt
;
2847 AUTH_INVALID
, AUTH_PUBLICKEY_AGENT
, AUTH_PUBLICKEY_FILE
, AUTH_PASSWORD
2851 AUTH_TYPE_PUBLICKEY
,
2852 AUTH_TYPE_PUBLICKEY_OFFER_LOUD
,
2853 AUTH_TYPE_PUBLICKEY_OFFER_QUIET
,
2856 static int gotit
, need_pw
, can_pubkey
, can_passwd
;
2857 static int tried_pubkey_config
, tried_agent
;
2858 static int we_are_in
;
2859 static char username
[100];
2860 static char pwprompt
[200];
2861 static char password
[100];
2866 * Request userauth protocol, and await a response to it.
2868 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
2869 ssh2_pkt_addstring("ssh-userauth");
2871 crWaitUntilV(ispkt
);
2872 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
2873 bombout(("Server refused user authentication protocol"));
2878 * We repeat this whole loop, including the username prompt,
2879 * until we manage a successful authentication. If the user
2880 * types the wrong _password_, they are sent back to the
2881 * beginning to try another username. (If they specify a
2882 * username in the config, they are never asked, even if they
2883 * do give a wrong password.)
2885 * I think this best serves the needs of
2887 * - the people who have no configuration, no keys, and just
2888 * want to try repeated (username,password) pairs until they
2889 * type both correctly
2891 * - people who have keys and configuration but occasionally
2892 * need to fall back to passwords
2894 * - people with a key held in Pageant, who might not have
2895 * logged in to a particular machine before; so they want to
2896 * type a username, and then _either_ their key will be
2897 * accepted, _or_ they will type a password. If they mistype
2898 * the username they will want to be able to get back and
2909 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
2911 if (!ssh_get_line("login as: ",
2912 username
, sizeof(username
), FALSE
)) {
2914 * get_line failed to get a username.
2917 logevent("No username provided. Abandoning session.");
2918 ssh_state
= SSH_STATE_CLOSED
;
2922 c_write_str("login as: ");
2925 crWaitUntilV(!ispkt
);
2926 while (inlen
--) switch (c
= *in
++) {
2933 c_write_str("\b \b");
2939 c_write_str("\b \b");
2948 if (((c
>= ' ' && c
<= '~') ||
2949 ((unsigned char)c
>= 160)) && pos
< 40) {
2950 username
[pos
++] = c
;
2957 c_write_str("\r\n");
2958 username
[strcspn(username
, "\n\r")] = '\0';
2961 strncpy(username
, cfg
.username
, 99);
2962 username
[99] = '\0';
2963 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
2964 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
2970 * Send an authentication request using method "none": (a)
2971 * just in case it succeeds, and (b) so that we know what
2972 * authentication methods we can usefully try next.
2974 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
2975 ssh2_pkt_addstring(username
);
2976 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2977 ssh2_pkt_addstring("none"); /* method */
2979 type
= AUTH_TYPE_NONE
;
2983 tried_pubkey_config
= FALSE
;
2984 tried_agent
= FALSE
;
2988 * Wait for the result of the last authentication request.
2991 crWaitUntilV(ispkt
);
2992 while (pktin
.type
== SSH2_MSG_USERAUTH_BANNER
) {
2996 * Don't show the banner if we're operating in
2997 * non-verbose non-interactive mode. (It's probably
2998 * a script, which means nobody will read the
2999 * banner _anyway_, and moreover the printing of
3000 * the banner will screw up processing on the
3001 * output of (say) plink.)
3003 if (flags
& (FLAG_VERBOSE
| FLAG_INTERACTIVE
)) {
3004 ssh2_pkt_getstring(&banner
, &size
);
3006 c_write_untrusted(banner
, size
);
3008 crWaitUntilV(ispkt
);
3010 if (pktin
.type
== SSH2_MSG_USERAUTH_SUCCESS
) {
3011 logevent("Access granted");
3016 if (pktin
.type
!= SSH2_MSG_USERAUTH_FAILURE
) {
3017 bombout(("Strange packet received during authentication: type %d",
3024 * OK, we're now sitting on a USERAUTH_FAILURE message, so
3025 * we can look at the string in it and know what we can
3026 * helpfully try next.
3031 ssh2_pkt_getstring(&methods
, &methlen
);
3032 if (!ssh2_pkt_getbool()) {
3034 * We have received an unequivocal Access
3035 * Denied. This can translate to a variety of
3038 * - if we'd just tried "none" authentication,
3039 * it's not worth printing anything at all
3041 * - if we'd just tried a public key _offer_,
3042 * the message should be "Server refused our
3043 * key" (or no message at all if the key
3044 * came from Pageant)
3046 * - if we'd just tried anything else, the
3047 * message really should be "Access denied".
3049 * Additionally, if we'd just tried password
3050 * authentication, we should break out of this
3051 * whole loop so as to go back to the username
3054 if (type
== AUTH_TYPE_NONE
) {
3056 } else if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
||
3057 type
== AUTH_TYPE_PUBLICKEY_OFFER_QUIET
) {
3058 if (type
== AUTH_TYPE_PUBLICKEY_OFFER_LOUD
)
3059 c_write_str("Server refused our key\r\n");
3060 logevent("Server refused public key");
3062 c_write_str("Access denied\r\n");
3063 logevent("Access denied");
3064 if (type
== AUTH_TYPE_PASSWORD
) {
3070 c_write_str("Further authentication required\r\n");
3071 logevent("Further authentication required");
3074 can_pubkey
= in_commasep_string("publickey", methods
, methlen
);
3075 can_passwd
= in_commasep_string("password", methods
, methlen
);
3080 if (!method
&& can_pubkey
&& agent_exists
&& !tried_agent
) {
3082 * Attempt public-key authentication using Pageant.
3084 static unsigned char request
[5], *response
, *p
;
3085 static int responselen
;
3086 static int i
, nkeys
;
3087 static int authed
= FALSE
;
3092 logevent("Pageant is running. Requesting keys.");
3094 /* Request the keys held by the agent. */
3095 PUT_32BIT(request
, 1);
3096 request
[4] = SSH2_AGENTC_REQUEST_IDENTITIES
;
3097 agent_query(request
, 5, &r
, &responselen
);
3098 response
= (unsigned char *)r
;
3099 if (response
&& responselen
>= 5 &&
3100 response
[4] == SSH2_AGENT_IDENTITIES_ANSWER
) {
3102 nkeys
= GET_32BIT(p
); p
+= 4;
3103 { char buf
[64]; sprintf(buf
, "Pageant has %d SSH2 keys", nkeys
);
3105 for (i
= 0; i
< nkeys
; i
++) {
3106 static char *pkblob
, *alg
, *commentp
;
3107 static int pklen
, alglen
, commentlen
;
3108 static int siglen
, retlen
, len
;
3109 static char *q
, *agentreq
, *ret
;
3111 { char buf
[64]; sprintf(buf
, "Trying Pageant key #%d", i
);
3113 pklen
= GET_32BIT(p
); p
+= 4;
3114 pkblob
= p
; p
+= pklen
;
3115 alglen
= GET_32BIT(pkblob
);
3117 commentlen
= GET_32BIT(p
); p
+= 4;
3118 commentp
= p
; p
+= commentlen
;
3119 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3120 ssh2_pkt_addstring(username
);
3121 ssh2_pkt_addstring("ssh-connection");/* service requested */
3122 ssh2_pkt_addstring("publickey");/* method */
3123 ssh2_pkt_addbool(FALSE
); /* no signature included */
3124 ssh2_pkt_addstring_start();
3125 ssh2_pkt_addstring_data(alg
, alglen
);
3126 ssh2_pkt_addstring_start();
3127 ssh2_pkt_addstring_data(pkblob
, pklen
);
3130 crWaitUntilV(ispkt
);
3131 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3132 logevent("Key refused");
3136 if (flags
& FLAG_VERBOSE
) {
3137 c_write_str("Authenticating with public key \"");
3138 c_write(commentp
, commentlen
);
3139 c_write_str("\" from agent\r\n");
3143 * Server is willing to accept the key.
3144 * Construct a SIGN_REQUEST.
3146 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3147 ssh2_pkt_addstring(username
);
3148 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3149 ssh2_pkt_addstring("publickey"); /* method */
3150 ssh2_pkt_addbool(TRUE
);
3151 ssh2_pkt_addstring_start();
3152 ssh2_pkt_addstring_data(alg
, alglen
);
3153 ssh2_pkt_addstring_start();
3154 ssh2_pkt_addstring_data(pkblob
, pklen
);
3156 siglen
= pktout
.length
- 5 + 4 + 20;
3157 len
= 1; /* message type */
3158 len
+= 4 + pklen
; /* key blob */
3159 len
+= 4 + siglen
; /* data to sign */
3160 len
+= 4; /* flags */
3161 agentreq
= smalloc(4 + len
);
3162 PUT_32BIT(agentreq
, len
);
3164 *q
++ = SSH2_AGENTC_SIGN_REQUEST
;
3165 PUT_32BIT(q
, pklen
); q
+= 4;
3166 memcpy(q
, pkblob
, pklen
); q
+= pklen
;
3167 PUT_32BIT(q
, siglen
); q
+= 4;
3168 /* Now the data to be signed... */
3169 PUT_32BIT(q
, 20); q
+= 4;
3170 memcpy(q
, ssh2_session_id
, 20); q
+= 20;
3171 memcpy(q
, pktout
.data
+5, pktout
.length
-5);
3172 q
+= pktout
.length
-5;
3173 /* And finally the (zero) flags word. */
3175 agent_query(agentreq
, len
+4, &ret
, &retlen
);
3178 if (ret
[4] == SSH2_AGENT_SIGN_RESPONSE
) {
3179 logevent("Sending Pageant's response");
3180 ssh2_pkt_addstring_start();
3181 ssh2_pkt_addstring_data(ret
+9, GET_32BIT(ret
+5));
3186 logevent("Pageant failed to answer challenge");
3196 if (!method
&& can_pubkey
&& *cfg
.keyfile
&& !tried_pubkey_config
) {
3197 unsigned char *pub_blob
;
3198 char *algorithm
, *comment
;
3201 tried_pubkey_config
= TRUE
;
3204 * Try the public key supplied in the configuration.
3206 * First, offer the public blob to see if the server is
3207 * willing to accept it.
3209 pub_blob
= ssh2_userkey_loadpub(cfg
.keyfile
, &algorithm
,
3212 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3213 ssh2_pkt_addstring(username
);
3214 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3215 ssh2_pkt_addstring("publickey");/* method */
3216 ssh2_pkt_addbool(FALSE
); /* no signature included */
3217 ssh2_pkt_addstring(algorithm
);
3218 ssh2_pkt_addstring_start();
3219 ssh2_pkt_addstring_data(pub_blob
, pub_blob_len
);
3221 logevent("Offered public key"); /* FIXME */
3223 crWaitUntilV(ispkt
);
3224 if (pktin
.type
!= SSH2_MSG_USERAUTH_PK_OK
) {
3226 type
= AUTH_TYPE_PUBLICKEY_OFFER_LOUD
;
3227 continue; /* key refused; give up on it */
3230 logevent("Offer of public key accepted");
3232 * Actually attempt a serious authentication using
3235 if (ssh2_userkey_encrypted(cfg
.keyfile
, &comment
)) {
3236 sprintf(pwprompt
, "Passphrase for key \"%.100s\": ", comment
);
3241 c_write_str("Authenticating with public key \"");
3242 c_write_str(comment
);
3243 c_write_str("\"\r\n");
3244 method
= AUTH_PUBLICKEY_FILE
;
3248 if (!method
&& can_passwd
) {
3249 method
= AUTH_PASSWORD
;
3250 sprintf(pwprompt
, "%.90s@%.90s's password: ", username
, savedhost
);
3256 if (!ssh_get_line(pwprompt
, password
,
3257 sizeof(password
), TRUE
)) {
3259 * get_line failed to get a password (for
3260 * example because one was supplied on the
3261 * command line which has already failed to
3264 logevent("No more passwords to try");
3265 ssh_state
= SSH_STATE_CLOSED
;
3272 c_write_str(pwprompt
);
3277 crWaitUntilV(!ispkt
);
3278 while (inlen
--) switch (c
= *in
++) {
3295 if (((c
>= ' ' && c
<= '~') ||
3296 ((unsigned char)c
>= 160)) && pos
< 40)
3297 password
[pos
++] = c
;
3301 c_write_str("\r\n");
3305 if (method
== AUTH_PUBLICKEY_FILE
) {
3307 * We have our passphrase. Now try the actual authentication.
3309 struct ssh2_userkey
*key
;
3311 key
= ssh2_load_userkey(cfg
.keyfile
, password
);
3312 if (key
== SSH2_WRONG_PASSPHRASE
|| key
== NULL
) {
3313 if (key
== SSH2_WRONG_PASSPHRASE
) {
3314 c_write_str("Wrong passphrase\r\n");
3315 tried_pubkey_config
= FALSE
;
3317 c_write_str("Unable to load private key\r\n");
3318 tried_pubkey_config
= TRUE
;
3320 /* Send a spurious AUTH_NONE to return to the top. */
3321 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3322 ssh2_pkt_addstring(username
);
3323 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3324 ssh2_pkt_addstring("none"); /* method */
3326 type
= AUTH_TYPE_NONE
;
3328 unsigned char *blob
, *sigdata
;
3329 int blob_len
, sigdata_len
;
3332 * We have loaded the private key and the server
3333 * has announced that it's willing to accept it.
3334 * Hallelujah. Generate a signature and send it.
3336 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3337 ssh2_pkt_addstring(username
);
3338 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3339 ssh2_pkt_addstring("publickey"); /* method */
3340 ssh2_pkt_addbool(TRUE
);
3341 ssh2_pkt_addstring(key
->alg
->name
);
3342 blob
= key
->alg
->public_blob(key
->data
, &blob_len
);
3343 ssh2_pkt_addstring_start();
3344 ssh2_pkt_addstring_data(blob
, blob_len
);
3348 * The data to be signed is:
3352 * followed by everything so far placed in the
3355 sigdata_len
= pktout
.length
- 5 + 4 + 20;
3356 sigdata
= smalloc(sigdata_len
);
3357 PUT_32BIT(sigdata
, 20);
3358 memcpy(sigdata
+4, ssh2_session_id
, 20);
3359 memcpy(sigdata
+24, pktout
.data
+5, pktout
.length
-5);
3360 blob
= key
->alg
->sign(key
->data
, sigdata
, sigdata_len
, &blob_len
);
3361 ssh2_pkt_addstring_start();
3362 ssh2_pkt_addstring_data(blob
, blob_len
);
3367 type
= AUTH_TYPE_PUBLICKEY
;
3369 } else if (method
== AUTH_PASSWORD
) {
3371 * We send the password packet lumped tightly together with
3372 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
3373 * string long enough to make the total length of the two
3374 * packets constant. This should ensure that a passive
3375 * listener doing traffic analyis can't work out the length
3378 * For this to work, we need an assumption about the
3379 * maximum length of the password packet. I think 256 is
3380 * pretty conservative. Anyone using a password longer than
3381 * that probably doesn't have much to worry about from
3382 * people who find out how long their password is!
3384 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
3385 ssh2_pkt_addstring(username
);
3386 ssh2_pkt_addstring("ssh-connection"); /* service requested */
3387 ssh2_pkt_addstring("password");
3388 ssh2_pkt_addbool(FALSE
);
3389 ssh2_pkt_addstring(password
);
3392 * We'll include a string that's an exact multiple of the
3393 * cipher block size. If the cipher is NULL for some
3394 * reason, we don't do this trick at all because we gain
3400 stringlen
= (256 - deferred_len
);
3401 stringlen
+= cscipher
->blksize
- 1;
3402 stringlen
-= (stringlen
% cscipher
->blksize
);
3405 * Temporarily disable actual compression,
3406 * so we can guarantee to get this string
3407 * exactly the length we want it. The
3408 * compression-disabling routine should
3409 * return an integer indicating how many
3410 * bytes we should adjust our string length
3413 stringlen
-= cscomp
->disable_compression();
3415 ssh2_pkt_init(SSH2_MSG_IGNORE
);
3416 ssh2_pkt_addstring_start();
3417 for (i
= 0; i
< stringlen
; i
++) {
3418 char c
= (char)random_byte();
3419 ssh2_pkt_addstring_data(&c
, 1);
3423 ssh_pkt_defersend();
3424 logevent("Sent password");
3425 type
= AUTH_TYPE_PASSWORD
;
3427 c_write_str("No supported authentication methods left to try!\r\n");
3428 logevent("No supported authentications offered. Disconnecting");
3429 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3430 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
3431 ssh2_pkt_addstring("No supported authentication methods available");
3432 ssh2_pkt_addstring("en"); /* language tag */
3434 ssh_state
= SSH_STATE_CLOSED
;
3438 } while (!we_are_in
);
3441 * Now we're authenticated for the connection protocol. The
3442 * connection protocol will automatically have started at this
3443 * point; there's no need to send SERVICE_REQUEST.
3447 * So now create a channel with a session in it.
3449 mainchan
= smalloc(sizeof(struct ssh_channel
));
3450 mainchan
->localid
= 100; /* as good as any */
3451 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
3452 ssh2_pkt_addstring("session");
3453 ssh2_pkt_adduint32(mainchan
->localid
);
3454 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
3455 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
3457 crWaitUntilV(ispkt
);
3458 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
3459 bombout(("Server refused to open a session"));
3461 /* FIXME: error data comes back in FAILURE packet */
3463 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
3464 bombout(("Server's channel confirmation cited wrong channel"));
3467 mainchan
->remoteid
= ssh2_pkt_getuint32();
3468 mainchan
->type
= CHAN_MAINSESSION
;
3469 mainchan
->closes
= 0;
3470 mainchan
->v2
.remwindow
= ssh2_pkt_getuint32();
3471 mainchan
->v2
.remmaxpkt
= ssh2_pkt_getuint32();
3472 mainchan
->v2
.outbuffer
= NULL
;
3473 mainchan
->v2
.outbuflen
= mainchan
->v2
.outbufsize
= 0;
3474 ssh_channels
= newtree234(ssh_channelcmp
);
3475 add234(ssh_channels
, mainchan
);
3476 logevent("Opened channel for session");
3479 * Potentially enable X11 forwarding.
3481 if (cfg
.x11_forward
) {
3482 char proto
[20], data
[64];
3483 logevent("Requesting X11 forwarding");
3484 x11_invent_auth(proto
, sizeof(proto
), data
, sizeof(data
));
3485 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3486 ssh2_pkt_adduint32(mainchan
->remoteid
);
3487 ssh2_pkt_addstring("x11-req");
3488 ssh2_pkt_addbool(1); /* want reply */
3489 ssh2_pkt_addbool(0); /* many connections */
3490 ssh2_pkt_addstring(proto
);
3491 ssh2_pkt_addstring(data
);
3492 ssh2_pkt_adduint32(0); /* screen number */
3496 crWaitUntilV(ispkt
);
3497 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3498 unsigned i
= ssh2_pkt_getuint32();
3499 struct ssh_channel
*c
;
3500 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3502 continue; /* nonexistent channel */
3503 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3505 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3507 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3508 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3509 bombout(("Server got confused by X11 forwarding request"));
3512 logevent("X11 forwarding refused");
3514 logevent("X11 forwarding enabled");
3515 ssh_X11_fwd_enabled
= TRUE
;
3520 * Potentially enable agent forwarding.
3522 if (cfg
.agentfwd
&& agent_exists()) {
3523 logevent("Requesting OpenSSH-style agent forwarding");
3524 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3525 ssh2_pkt_adduint32(mainchan
->remoteid
);
3526 ssh2_pkt_addstring("auth-agent-req@openssh.com");
3527 ssh2_pkt_addbool(1); /* want reply */
3531 crWaitUntilV(ispkt
);
3532 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3533 unsigned i
= ssh2_pkt_getuint32();
3534 struct ssh_channel
*c
;
3535 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3537 continue; /* nonexistent channel */
3538 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3540 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3542 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3543 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3544 bombout(("Server got confused by agent forwarding request"));
3547 logevent("Agent forwarding refused");
3549 logevent("Agent forwarding enabled");
3550 ssh_agentfwd_enabled
= TRUE
;
3555 * Now allocate a pty for the session.
3558 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3559 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
3560 ssh2_pkt_addstring("pty-req");
3561 ssh2_pkt_addbool(1); /* want reply */
3562 ssh2_pkt_addstring(cfg
.termtype
);
3563 ssh2_pkt_adduint32(cols
);
3564 ssh2_pkt_adduint32(rows
);
3565 ssh2_pkt_adduint32(0); /* pixel width */
3566 ssh2_pkt_adduint32(0); /* pixel height */
3567 ssh2_pkt_addstring_start();
3568 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
3570 ssh_state
= SSH_STATE_INTERMED
;
3573 crWaitUntilV(ispkt
);
3574 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3575 unsigned i
= ssh2_pkt_getuint32();
3576 struct ssh_channel
*c
;
3577 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3579 continue; /* nonexistent channel */
3580 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3582 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3584 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3585 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3586 bombout(("Server got confused by pty request"));
3589 c_write_str("Server refused to allocate pty\r\n");
3590 ssh_editing
= ssh_echoing
= 1;
3592 logevent("Allocated pty");
3595 ssh_editing
= ssh_echoing
= 1;
3599 * Start a shell or a remote command.
3601 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3602 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
3603 if (cfg
.ssh_subsys
) {
3604 ssh2_pkt_addstring("subsystem");
3605 ssh2_pkt_addbool(1); /* want reply */
3606 ssh2_pkt_addstring(cfg
.remote_cmd_ptr
);
3607 } else if (*cfg
.remote_cmd_ptr
) {
3608 ssh2_pkt_addstring("exec");
3609 ssh2_pkt_addbool(1); /* want reply */
3610 ssh2_pkt_addstring(cfg
.remote_cmd_ptr
);
3612 ssh2_pkt_addstring("shell");
3613 ssh2_pkt_addbool(1); /* want reply */
3617 crWaitUntilV(ispkt
);
3618 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3619 unsigned i
= ssh2_pkt_getuint32();
3620 struct ssh_channel
*c
;
3621 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3623 continue; /* nonexistent channel */
3624 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3626 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3627 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
3628 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
3629 bombout(("Server got confused by shell/command request"));
3632 bombout(("Server refused to start a shell/command"));
3635 logevent("Started a shell/command");
3638 ssh_state
= SSH_STATE_SESSION
;
3642 ssh_special(TS_EOF
);
3647 ldisc_send(NULL
, 0); /* cause ldisc to notice changes */
3650 static int try_send
;
3654 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
3655 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
3658 unsigned i
= ssh2_pkt_getuint32();
3659 struct ssh_channel
*c
;
3660 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3662 continue; /* nonexistent channel */
3663 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
3664 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
3665 continue; /* extended but not stderr */
3666 ssh2_pkt_getstring(&data
, &length
);
3669 case CHAN_MAINSESSION
:
3670 from_backend(pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
,
3674 x11_send(c
->u
.x11
.s
, data
, length
);
3677 while (length
> 0) {
3678 if (c
->u
.a
.lensofar
< 4) {
3679 int l
= min(4 - c
->u
.a
.lensofar
, length
);
3680 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, data
, l
);
3681 data
+= l
; length
-= l
; c
->u
.a
.lensofar
+= l
;
3683 if (c
->u
.a
.lensofar
== 4) {
3684 c
->u
.a
.totallen
= 4 + GET_32BIT(c
->u
.a
.msglen
);
3685 c
->u
.a
.message
= smalloc(c
->u
.a
.totallen
);
3686 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
3688 if (c
->u
.a
.lensofar
>= 4 && length
> 0) {
3689 int l
= min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
,
3691 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, data
, l
);
3692 data
+= l
; length
-= l
; c
->u
.a
.lensofar
+= l
;
3694 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
3695 void *reply
, *sentreply
;
3697 agent_query(c
->u
.a
.message
, c
->u
.a
.totallen
,
3702 /* Fake SSH_AGENT_FAILURE. */
3703 sentreply
= "\0\0\0\1\5";
3706 ssh2_add_channel_data(c
, sentreply
, replylen
);
3710 sfree(c
->u
.a
.message
);
3711 c
->u
.a
.lensofar
= 0;
3717 * Enlarge the window again at the remote
3718 * side, just in case it ever runs down and
3719 * they fail to send us any more data.
3721 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
3722 ssh2_pkt_adduint32(c
->remoteid
);
3723 ssh2_pkt_adduint32(length
);
3726 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
3727 ssh_state
= SSH_STATE_CLOSED
;
3728 logevent("Received disconnect message");
3730 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
3731 continue; /* exit status et al; ignore (FIXME?) */
3732 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
3733 unsigned i
= ssh2_pkt_getuint32();
3734 struct ssh_channel
*c
;
3736 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3738 continue; /* nonexistent channel */
3740 if (c
->type
== CHAN_X11
) {
3742 * Remote EOF on an X11 channel means we should
3743 * wrap up and close the channel ourselves.
3745 x11_close(c
->u
.x11
.s
);
3747 } else if (c
->type
== CHAN_AGENT
) {
3750 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
3751 unsigned i
= ssh2_pkt_getuint32();
3752 struct ssh_channel
*c
;
3755 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3757 continue; /* nonexistent channel */
3758 if (c
->closes
== 0) {
3759 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
3760 ssh2_pkt_adduint32(c
->remoteid
);
3763 /* Do pre-close processing on the channel. */
3765 case CHAN_MAINSESSION
:
3766 break; /* nothing to see here, move along */
3772 del234(ssh_channels
, c
);
3773 sfree(c
->v2
.outbuffer
);
3777 * See if that was the last channel left open.
3779 c
= first234(ssh_channels
, &e
);
3781 logevent("All channels closed. Disconnecting");
3782 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
3783 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION
);
3784 ssh2_pkt_addstring("All open channels closed");
3785 ssh2_pkt_addstring("en"); /* language tag */
3787 ssh_state
= SSH_STATE_CLOSED
;
3790 continue; /* remote sends close; ignore (FIXME) */
3791 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
3792 unsigned i
= ssh2_pkt_getuint32();
3793 struct ssh_channel
*c
;
3794 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
3796 continue; /* nonexistent channel */
3797 c
->v2
.remwindow
+= ssh2_pkt_getuint32();
3799 } else if (pktin
.type
== SSH2_MSG_CHANNEL_OPEN
) {
3803 struct ssh_channel
*c
;
3804 ssh2_pkt_getstring(&type
, &typelen
);
3805 c
= smalloc(sizeof(struct ssh_channel
));
3807 if (typelen
== 3 && !memcmp(type
, "x11", 3)) {
3808 if (!ssh_X11_fwd_enabled
)
3809 error
= "X11 forwarding is not enabled";
3810 else if ( x11_init(&c
->u
.x11
.s
, cfg
.x11_display
, c
) != NULL
) {
3811 error
= "Unable to open an X11 connection";
3815 } else if (typelen
== 22 &&
3816 !memcmp(type
, "auth-agent@openssh.com", 3)) {
3817 if (!ssh_agentfwd_enabled
)
3818 error
= "Agent forwarding is not enabled";
3820 c
->type
= CHAN_AGENT
; /* identify channel type */
3821 c
->u
.a
.lensofar
= 0;
3824 error
= "Unsupported channel type requested";
3827 c
->remoteid
= ssh2_pkt_getuint32();
3829 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
3830 ssh2_pkt_adduint32(c
->remoteid
);
3831 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED
);
3832 ssh2_pkt_addstring(error
);
3833 ssh2_pkt_addstring("en"); /* language tag */
3837 struct ssh_channel
*d
;
3841 for (i
=1, d
= first234(ssh_channels
, &e
); d
;
3844 break; /* found a free number */
3849 c
->v2
.remwindow
= ssh2_pkt_getuint32();
3850 c
->v2
.remmaxpkt
= ssh2_pkt_getuint32();
3851 c
->v2
.outbuffer
= NULL
;
3852 c
->v2
.outbuflen
= c
->v2
.outbufsize
= 0;
3853 add234(ssh_channels
, c
);
3854 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
3855 ssh2_pkt_adduint32(c
->remoteid
);
3856 ssh2_pkt_adduint32(c
->localid
);
3857 ssh2_pkt_adduint32(0x8000UL
); /* our window size */
3858 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
3862 bombout(("Strange packet received: type %d", pktin
.type
));
3867 * We have spare data. Add it to the channel buffer.
3869 ssh2_add_channel_data(mainchan
, in
, inlen
);
3874 struct ssh_channel
*c
;
3876 * Try to send data on all channels if we can.
3878 for (c
= first234(ssh_channels
, &e
); c
; c
= next234(&e
))
3887 * Handle the top-level SSH2 protocol.
3889 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
3891 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
3893 do_ssh2_authconn(in
, inlen
, ispkt
);
3897 * Called to set up the connection.
3899 * Returns an error message, or NULL on success.
3901 static char *ssh_init (char *host
, int port
, char **realhost
) {
3905 if(crypto_startup() == 0)
3906 return "Microsoft high encryption pack not installed!";
3913 p
= connect_to_host(host
, port
, realhost
);
3921 * Called to send data down the Telnet connection.
3923 static void ssh_send (char *buf
, int len
) {
3924 if (s
== NULL
|| ssh_protocol
== NULL
)
3927 ssh_protocol(buf
, len
, 0);
3931 * Called to set the size of the window from SSH's POV.
3933 static void ssh_size(void) {
3934 switch (ssh_state
) {
3935 case SSH_STATE_BEFORE_SIZE
:
3936 case SSH_STATE_PREPACKET
:
3937 case SSH_STATE_CLOSED
:
3938 break; /* do nothing */
3939 case SSH_STATE_INTERMED
:
3940 size_needed
= TRUE
; /* buffer for later */
3942 case SSH_STATE_SESSION
:
3944 if (ssh_version
== 1) {
3945 send_packet(SSH1_CMSG_WINDOW_SIZE
,
3946 PKT_INT
, rows
, PKT_INT
, cols
,
3947 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
3949 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
3950 ssh2_pkt_adduint32(mainchan
->remoteid
);
3951 ssh2_pkt_addstring("window-change");
3952 ssh2_pkt_addbool(0);
3953 ssh2_pkt_adduint32(cols
);
3954 ssh2_pkt_adduint32(rows
);
3955 ssh2_pkt_adduint32(0);
3956 ssh2_pkt_adduint32(0);
3965 * Send Telnet special codes. TS_EOF is useful for `plink', so you
3966 * can send an EOF and collect resulting output (e.g. `plink
3969 static void ssh_special (Telnet_Special code
) {
3970 if (code
== TS_EOF
) {
3971 if (ssh_state
!= SSH_STATE_SESSION
) {
3973 * Buffer the EOF in case we are pre-SESSION, so we can
3974 * send it as soon as we reach SESSION.
3980 if (ssh_version
== 1) {
3981 send_packet(SSH1_CMSG_EOF
, PKT_END
);
3983 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
3984 ssh2_pkt_adduint32(mainchan
->remoteid
);
3987 logevent("Sent EOF message");
3988 } else if (code
== TS_PING
) {
3989 if (ssh_state
== SSH_STATE_CLOSED
|| ssh_state
== SSH_STATE_PREPACKET
)
3991 if (ssh_version
== 1) {
3992 send_packet(SSH1_MSG_IGNORE
, PKT_STR
, "", PKT_END
);
3994 ssh2_pkt_init(SSH2_MSG_IGNORE
);
3995 ssh2_pkt_addstring_start();
4003 static Socket
ssh_socket(void) { return s
; }
4005 static int ssh_sendok(void) { return ssh_send_ok
; }
4007 static int ssh_ldisc(int option
) {
4008 if (option
== LD_ECHO
) return ssh_echoing
;
4009 if (option
== LD_EDIT
) return ssh_editing
;
4013 Backend ssh_backend
= {