19 #define logevent(s) { logevent(s); \
20 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
21 fprintf(stderr, "%s\n", s); }
23 #define bombout(msg) ( ssh_state == SSH_STATE_CLOSED, closesocket(s), \
24 s = INVALID_SOCKET, 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_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
51 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
52 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
53 #define SSH1_MSG_IGNORE 32 /* 0x20 */
54 #define SSH1_MSG_DEBUG 36 /* 0x24 */
55 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
56 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
57 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
58 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
59 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
60 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
62 #define SSH1_AUTH_TIS 5 /* 0x5 */
63 #define SSH1_AUTH_CCARD 16 /* 0x10 */
65 #define SSH_AGENTC_REQUEST_RSA_IDENTITIES 1 /* 0x1 */
66 #define SSH_AGENT_RSA_IDENTITIES_ANSWER 2 /* 0x2 */
67 #define SSH_AGENTC_RSA_CHALLENGE 3 /* 0x3 */
68 #define SSH_AGENT_RSA_RESPONSE 4 /* 0x4 */
69 #define SSH_AGENT_FAILURE 5 /* 0x5 */
70 #define SSH_AGENT_SUCCESS 6 /* 0x6 */
71 #define SSH_AGENTC_ADD_RSA_IDENTITY 7 /* 0x7 */
72 #define SSH_AGENTC_REMOVE_RSA_IDENTITY 8 /* 0x8 */
74 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
75 #define SSH2_MSG_IGNORE 2 /* 0x2 */
76 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
77 #define SSH2_MSG_DEBUG 4 /* 0x4 */
78 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
79 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
80 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
81 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
82 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
83 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
84 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
85 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
86 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
87 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
88 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
89 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
90 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
91 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
92 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
93 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
94 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
95 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
96 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
97 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
98 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
99 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
100 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
101 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
102 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
103 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
105 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
106 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
107 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
108 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
110 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
112 #define GET_32BIT(cp) \
113 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
114 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
115 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
116 ((unsigned long)(unsigned char)(cp)[3]))
118 #define PUT_32BIT(cp, value) { \
119 (cp)[0] = (unsigned char)((value) >> 24); \
120 (cp)[1] = (unsigned char)((value) >> 16); \
121 (cp)[2] = (unsigned char)((value) >> 8); \
122 (cp)[3] = (unsigned char)(value); }
124 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
126 /* Coroutine mechanics for the sillier bits of the code */
127 #define crBegin1 static int crLine = 0;
128 #define crBegin2 switch(crLine) { case 0:;
129 #define crBegin crBegin1; crBegin2;
130 #define crFinish(z) } crLine = 0; return (z)
131 #define crFinishV } crLine = 0; return
132 #define crReturn(z) \
134 crLine=__LINE__; return (z); case __LINE__:;\
138 crLine=__LINE__; return; case __LINE__:;\
140 #define crStop(z) do{ crLine = 0; return (z); }while(0)
141 #define crStopV do{ crLine = 0; return; }while(0)
142 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
143 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
145 extern struct ssh_cipher ssh_3des
;
146 extern struct ssh_cipher ssh_3des_ssh2
;
147 extern struct ssh_cipher ssh_des
;
148 extern struct ssh_cipher ssh_blowfish_ssh1
;
149 extern struct ssh_cipher ssh_blowfish_ssh2
;
152 * Ciphers for SSH2. We miss out single-DES because it isn't
153 * supported; also 3DES and Blowfish are both done differently from
154 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
155 * endianness and different-sized keys.)
157 * The first entry in this array is set up to be whatever the user
158 * asks for as a cipher. Thereafter there is a fixed preference
159 * order of fallback ciphers.
161 struct ssh_cipher
*ciphers
[] = { NULL
, &ssh_blowfish_ssh2
, &ssh_3des_ssh2
};
163 extern struct ssh_kex ssh_diffiehellman
;
164 struct ssh_kex
*kex_algs
[] = { &ssh_diffiehellman
};
166 extern struct ssh_hostkey ssh_dss
;
167 struct ssh_hostkey
*hostkey_algs
[] = { &ssh_dss
};
169 extern struct ssh_mac ssh_sha1
;
171 static SHA_State exhash
;
173 static void nullmac_key(unsigned char *key
) { }
174 static void nullmac_generate(unsigned char *blk
, int len
, unsigned long seq
) { }
175 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
) { return 1; }
176 struct ssh_mac ssh_mac_none
= {
177 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
179 struct ssh_mac
*macs
[] = { &ssh_sha1
, &ssh_mac_none
};
181 struct ssh_compress ssh_comp_none
= {
184 struct ssh_compress
*compressions
[] = { &ssh_comp_none
};
186 static SOCKET s
= INVALID_SOCKET
;
188 static unsigned char session_key
[32];
189 static struct ssh_cipher
*cipher
= NULL
;
190 static struct ssh_cipher
*cscipher
= NULL
;
191 static struct ssh_cipher
*sccipher
= NULL
;
192 static struct ssh_mac
*csmac
= NULL
;
193 static struct ssh_mac
*scmac
= NULL
;
194 static struct ssh_compress
*cscomp
= NULL
;
195 static struct ssh_compress
*sccomp
= NULL
;
196 static struct ssh_kex
*kex
= NULL
;
197 static struct ssh_hostkey
*hostkey
= NULL
;
198 int (*ssh_get_password
)(const char *prompt
, char *str
, int maxlen
) = NULL
;
200 static char *savedhost
;
201 static int ssh_send_ok
;
204 * 2-3-4 tree storing channels.
207 unsigned remoteid
, localid
;
211 struct ssh_agent_channel
{
212 unsigned char *message
;
213 unsigned char msglen
[4];
214 int lensofar
, totallen
;
216 struct ssh2_data_channel
{
217 unsigned char *outbuffer
;
218 unsigned outbuflen
, outbufsize
;
219 unsigned remwindow
, remmaxpkt
;
223 static tree234
*ssh_channels
; /* indexed by local id */
224 static int ssh_channelcmp(void *av
, void *bv
) {
225 struct ssh_channel
*a
= (struct ssh_channel
*)av
;
226 struct ssh_channel
*b
= (struct ssh_channel
*)bv
;
227 if (a
->localid
< b
->localid
) return -1;
228 if (a
->localid
> b
->localid
) return +1;
231 static int ssh_channelfind(void *av
, void *bv
) {
232 unsigned *a
= (unsigned *)av
;
233 struct ssh_channel
*b
= (struct ssh_channel
*)bv
;
234 if (*a
< b
->localid
) return -1;
235 if (*a
> b
->localid
) return +1;
239 static struct ssh_channel
*mainchan
; /* primary session channel */
242 SSH_STATE_BEFORE_SIZE
,
246 } ssh_state
= SSH_STATE_BEFORE_SIZE
;
248 static int size_needed
= FALSE
;
250 static void s_write (char *buf
, int len
) {
252 int i
= send (s
, buf
, len
, 0);
255 bombout(("Lost connection while sending"));
263 static int s_read (char *buf
, int len
) {
266 int i
= recv (s
, buf
, len
, 0);
269 len
-= i
, buf
+= i
, ret
+= i
;
276 static void c_write (char *buf
, int len
) {
277 if ((flags
& FLAG_STDERR
)) {
279 for (i
= 0; i
< len
; i
++)
281 fputc(buf
[i
], stderr
);
297 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
298 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
300 static int ssh_version
;
301 static void (*ssh_protocol
)(unsigned char *in
, int inlen
, int ispkt
);
302 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
303 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
304 static void ssh_size(void);
306 static int (*s_rdpkt
)(unsigned char **data
, int *datalen
);
309 * Collect incoming data in the incoming packet buffer.
310 * Decipher and verify the packet when it is completely read.
311 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
312 * Update the *data and *datalen variables.
313 * Return the additional nr of bytes needed, or 0 when
314 * a complete packet is available.
316 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
318 static long len
, pad
, biglen
, to_read
;
319 static unsigned long realcrc
, gotcrc
;
320 static unsigned char *p
;
330 for (i
= len
= 0; i
< 4; i
++) {
331 while ((*datalen
) == 0)
333 len
= (len
<< 8) + **data
;
334 (*data
)++, (*datalen
)--;
338 if (len
== 0x52656d6f) { /* "Remo"te server has closed ... */
339 len
= 0x300; /* big enough to carry to end */
345 pktin
.length
= len
- 5;
347 if (pktin
.maxlen
< biglen
) {
348 pktin
.maxlen
= biglen
;
349 pktin
.data
= (pktin
.data
== NULL ?
malloc(biglen
+APIEXTRA
) :
350 realloc(pktin
.data
, biglen
+APIEXTRA
));
352 fatalbox("Out of memory");
357 while (to_read
> 0) {
360 while ((*datalen
) == 0)
362 if (chunk
> (*datalen
))
364 memcpy(p
, *data
, chunk
);
372 cipher
->decrypt(pktin
.data
, biglen
);
374 pktin
.type
= pktin
.data
[pad
];
375 pktin
.body
= pktin
.data
+ pad
+ 1;
377 realcrc
= crc32(pktin
.data
, biglen
-4);
378 gotcrc
= GET_32BIT(pktin
.data
+biglen
-4);
379 if (gotcrc
!= realcrc
) {
380 bombout(("Incorrect CRC received on packet"));
384 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
385 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
386 pktin
.type
== SSH1_MSG_DEBUG
||
387 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
388 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
389 long strlen
= GET_32BIT(pktin
.body
);
390 if (strlen
+ 4 != pktin
.length
) {
391 bombout(("Received data packet with bogus string length"));
396 if (pktin
.type
== SSH1_MSG_DEBUG
) {
397 /* log debug message */
399 int strlen
= GET_32BIT(pktin
.body
);
400 strcpy(buf
, "Remote: ");
401 if (strlen
> 70) strlen
= 70;
402 memcpy(buf
+8, pktin
.body
+4, strlen
);
403 buf
[8+strlen
] = '\0';
406 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
414 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
416 static long len
, pad
, payload
, packetlen
, maclen
;
418 static int cipherblk
;
419 static unsigned long incoming_sequence
= 0;
429 cipherblk
= cipher
->blksize
;
435 if (pktin
.maxlen
< cipherblk
) {
436 pktin
.maxlen
= cipherblk
;
437 pktin
.data
= (pktin
.data
== NULL ?
malloc(cipherblk
+APIEXTRA
) :
438 realloc(pktin
.data
, cipherblk
+APIEXTRA
));
440 fatalbox("Out of memory");
444 * Acquire and decrypt the first block of the packet. This will
445 * contain the length and padding details.
447 for (i
= len
= 0; i
< cipherblk
; i
++) {
448 while ((*datalen
) == 0)
449 crReturn(cipherblk
-i
);
450 pktin
.data
[i
] = *(*data
)++;
454 if (!memcmp(pktin
.data
, "Remo", 4)) {/* "Remo"te server has closed ... */
459 sccipher
->decrypt(pktin
.data
, cipherblk
);
462 * Now get the length and padding figures.
464 len
= GET_32BIT(pktin
.data
);
468 * This enables us to deduce the payload length.
470 payload
= len
- pad
- 1;
472 pktin
.length
= payload
+ 5;
475 * So now we can work out the total packet length.
478 maclen
= scmac ? scmac
->len
: 0;
481 * Adjust memory allocation if packet is too big.
483 if (pktin
.maxlen
< packetlen
+maclen
) {
484 pktin
.maxlen
= packetlen
+maclen
;
485 pktin
.data
= (pktin
.data
== NULL ?
malloc(pktin
.maxlen
+APIEXTRA
) :
486 realloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
));
488 fatalbox("Out of memory");
492 * Read and decrypt the remainder of the packet.
494 for (i
= cipherblk
; i
< packetlen
+ maclen
; i
++) {
495 while ((*datalen
) == 0)
496 crReturn(packetlen
+ maclen
- i
);
497 pktin
.data
[i
] = *(*data
)++;
500 /* Decrypt everything _except_ the MAC. */
502 sccipher
->decrypt(pktin
.data
+ cipherblk
, packetlen
- cipherblk
);
505 debug(("Got packet len=%d pad=%d\r\n", len
, pad
));
506 for (i
= 0; i
< packetlen
; i
++)
507 debug((" %02x", (unsigned char)pktin
.data
[i
]));
514 if (scmac
&& !scmac
->verify(pktin
.data
, len
+4, incoming_sequence
)) {
515 bombout(("Incorrect MAC received on packet"));
518 incoming_sequence
++; /* whether or not we MACed */
521 pktin
.type
= pktin
.data
[5];
523 if (pktin
.type
== SSH2_MSG_IGNORE
|| pktin
.type
== SSH2_MSG_DEBUG
)
524 goto next_packet
; /* FIXME: print DEBUG message */
529 static void ssh_gotdata(unsigned char *data
, int datalen
)
531 while (datalen
> 0) {
532 if ( s_rdpkt(&data
, &datalen
) == 0 ) {
533 ssh_protocol(NULL
, 0, 1);
534 if (ssh_state
== SSH_STATE_CLOSED
) {
542 static void s_wrpkt_start(int type
, int len
) {
545 len
+= 5; /* type and CRC */
549 pktout
.length
= len
-5;
550 if (pktout
.maxlen
< biglen
) {
551 pktout
.maxlen
= biglen
;
553 /* Allocate enough buffer space for extra block
554 * for MS CryptEncrypt() */
555 pktout
.data
= (pktout
.data
== NULL ?
malloc(biglen
+12) :
556 realloc(pktout
.data
, biglen
+12));
558 pktout
.data
= (pktout
.data
== NULL ?
malloc(biglen
+4) :
559 realloc(pktout
.data
, biglen
+4));
562 fatalbox("Out of memory");
566 pktout
.body
= pktout
.data
+4+pad
+1;
569 static void s_wrpkt(void) {
570 int pad
, len
, biglen
, i
;
573 len
= pktout
.length
+ 5; /* type and CRC */
577 pktout
.body
[-1] = pktout
.type
;
578 for (i
=0; i
<pad
; i
++)
579 pktout
.data
[i
+4] = random_byte();
580 crc
= crc32(pktout
.data
+4, biglen
-4);
581 PUT_32BIT(pktout
.data
+biglen
, crc
);
582 PUT_32BIT(pktout
.data
, len
);
585 cipher
->encrypt(pktout
.data
+4, biglen
);
587 s_write(pktout
.data
, biglen
+4);
591 * Construct a packet with the specified contents and
592 * send it to the server.
594 static void send_packet(int pkttype
, ...)
597 unsigned char *p
, *argp
, argchar
;
598 unsigned long argint
;
599 int pktlen
, argtype
, arglen
;
603 va_start(args
, pkttype
);
604 while ((argtype
= va_arg(args
, int)) != PKT_END
) {
607 (void) va_arg(args
, int);
611 (void) va_arg(args
, char);
615 (void) va_arg(args
, unsigned char *);
616 arglen
= va_arg(args
, int);
620 argp
= va_arg(args
, unsigned char *);
621 arglen
= strlen(argp
);
622 pktlen
+= 4 + arglen
;
625 bn
= va_arg(args
, Bignum
);
626 pktlen
+= ssh1_bignum_length(bn
);
634 s_wrpkt_start(pkttype
, pktlen
);
637 va_start(args
, pkttype
);
638 while ((argtype
= va_arg(args
, int)) != PKT_END
) {
641 argint
= va_arg(args
, int);
642 PUT_32BIT(p
, argint
);
646 argchar
= va_arg(args
, unsigned char);
651 argp
= va_arg(args
, unsigned char *);
652 arglen
= va_arg(args
, int);
653 memcpy(p
, argp
, arglen
);
657 argp
= va_arg(args
, unsigned char *);
658 arglen
= strlen(argp
);
659 PUT_32BIT(p
, arglen
);
660 memcpy(p
+ 4, argp
, arglen
);
664 bn
= va_arg(args
, Bignum
);
665 p
+= ssh1_write_bignum(p
, bn
);
676 * Connect to specified host and port.
677 * Returns an error message, or NULL on success.
678 * Also places the canonical host name into `realhost'.
680 static char *connect_to_host(char *host
, int port
, char **realhost
)
690 savedhost
= malloc(1+strlen(host
));
692 fatalbox("Out of memory");
693 strcpy(savedhost
, host
);
696 port
= 22; /* default ssh port */
708 if ( (a
= inet_addr(host
)) == (unsigned long) INADDR_NONE
) {
709 if ( (h
= gethostbyname(host
)) == NULL
)
710 switch (WSAGetLastError()) {
711 case WSAENETDOWN
: return "Network is down";
712 case WSAHOST_NOT_FOUND
: case WSANO_DATA
:
713 return "Host does not exist";
714 case WSATRY_AGAIN
: return "Host not found";
715 default: return "gethostbyname: unknown error";
717 memcpy (&a
, h
->h_addr
, sizeof(a
));
718 *realhost
= h
->h_name
;
729 s
= socket(AF_INET
, SOCK_STREAM
, 0);
730 if (s
== INVALID_SOCKET
)
731 switch (WSAGetLastError()) {
732 case WSAENETDOWN
: return "Network is down";
733 case WSAEAFNOSUPPORT
: return "TCP/IP support not present";
734 default: return "socket(): unknown error";
738 * Bind to local address.
740 addr
.sin_family
= AF_INET
;
741 addr
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
742 addr
.sin_port
= htons(0);
743 if (bind (s
, (struct sockaddr
*)&addr
, sizeof(addr
)) == SOCKET_ERROR
)
744 switch (WSAGetLastError()) {
745 case WSAENETDOWN
: return "Network is down";
746 default: return "bind(): unknown error";
750 * Connect to remote address.
752 addr
.sin_addr
.s_addr
= htonl(a
);
753 addr
.sin_port
= htons((short)port
);
754 if (connect (s
, (struct sockaddr
*)&addr
, sizeof(addr
)) == SOCKET_ERROR
)
755 switch (WSAGetLastError()) {
756 case WSAENETDOWN
: return "Network is down";
757 case WSAECONNREFUSED
: return "Connection refused";
758 case WSAENETUNREACH
: return "Network is unreachable";
759 case WSAEHOSTUNREACH
: return "No route to host";
760 default: return "connect(): unknown error";
764 send(s
, "connect ", 8, 0);
765 send(s
, FWhost
, strlen(FWhost
), 0);
768 sprintf(buf
, " %d\n", FWport
);
769 send (s
, buf
, strlen(buf
), 0);
776 static int ssh_versioncmp(char *a
, char *b
) {
778 unsigned long av
, bv
;
780 av
= strtoul(a
, &ae
, 10);
781 bv
= strtoul(b
, &be
, 10);
782 if (av
!= bv
) return (av
< bv ?
-1 : +1);
783 if (*ae
== '.') ae
++;
784 if (*be
== '.') be
++;
785 av
= strtoul(ae
, &ae
, 10);
786 bv
= strtoul(be
, &be
, 10);
787 if (av
!= bv
) return (av
< bv ?
-1 : +1);
793 * Utility routine for putting an SSH-protocol `string' into a SHA
797 void sha_string(SHA_State
*s
, void *str
, int len
) {
798 unsigned char lenblk
[4];
799 PUT_32BIT(lenblk
, len
);
800 SHA_Bytes(s
, lenblk
, 4);
801 SHA_Bytes(s
, str
, len
);
805 * SSH2 packet construction functions.
807 void ssh2_pkt_adddata(void *data
, int len
) {
808 pktout
.length
+= len
;
809 if (pktout
.maxlen
< pktout
.length
) {
810 pktout
.maxlen
= pktout
.length
+ 256;
811 pktout
.data
= (pktout
.data
== NULL ?
malloc(pktout
.maxlen
+APIEXTRA
) :
812 realloc(pktout
.data
, pktout
.maxlen
+APIEXTRA
));
814 fatalbox("Out of memory");
816 memcpy(pktout
.data
+pktout
.length
-len
, data
, len
);
818 void ssh2_pkt_addbyte(unsigned char byte
) {
819 ssh2_pkt_adddata(&byte
, 1);
821 void ssh2_pkt_init(int pkt_type
) {
823 ssh2_pkt_addbyte((unsigned char)pkt_type
);
825 void ssh2_pkt_addbool(unsigned char value
) {
826 ssh2_pkt_adddata(&value
, 1);
828 void ssh2_pkt_adduint32(unsigned long value
) {
831 ssh2_pkt_adddata(x
, 4);
833 void ssh2_pkt_addstring_start(void) {
834 ssh2_pkt_adduint32(0);
835 pktout
.savedpos
= pktout
.length
;
837 void ssh2_pkt_addstring_str(char *data
) {
838 ssh2_pkt_adddata(data
, strlen(data
));
839 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
840 pktout
.length
- pktout
.savedpos
);
842 void ssh2_pkt_addstring_data(char *data
, int len
) {
843 ssh2_pkt_adddata(data
, len
);
844 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
845 pktout
.length
- pktout
.savedpos
);
847 void ssh2_pkt_addstring(char *data
) {
848 ssh2_pkt_addstring_start();
849 ssh2_pkt_addstring_str(data
);
851 char *ssh2_mpint_fmt(Bignum b
, int *len
) {
854 p
= malloc(n
* 2 + 1);
856 fatalbox("out of memory");
858 for (i
= 0; i
< n
; i
++) {
859 p
[i
*2+1] = (b
[n
-i
] >> 8) & 0xFF;
860 p
[i
*2+2] = (b
[n
-i
] ) & 0xFF;
863 while (p
[i
] == 0 && (p
[i
+1] & 0x80) == 0)
865 memmove(p
, p
+i
, n
*2+1-i
);
869 void ssh2_pkt_addmp(Bignum b
) {
872 p
= ssh2_mpint_fmt(b
, &len
);
873 ssh2_pkt_addstring_start();
874 ssh2_pkt_addstring_data(p
, len
);
877 void ssh2_pkt_send(void) {
878 int cipherblk
, maclen
, padding
, i
;
879 static unsigned long outgoing_sequence
= 0;
882 * Add padding. At least four bytes, and must also bring total
883 * length (minus MAC) up to a multiple of the block size.
885 cipherblk
= cipher ? cipher
->blksize
: 8; /* block size */
886 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
888 padding
+= (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
889 pktout
.data
[4] = padding
;
890 for (i
= 0; i
< padding
; i
++)
891 pktout
.data
[pktout
.length
+ i
] = random_byte();
892 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
894 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
896 outgoing_sequence
++; /* whether or not we MACed */
899 debug(("Sending packet len=%d\r\n", pktout
.length
+padding
));
900 for (i
= 0; i
< pktout
.length
+padding
; i
++)
901 debug((" %02x", (unsigned char)pktout
.data
[i
]));
906 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
907 maclen
= csmac ? csmac
->len
: 0;
909 s_write(pktout
.data
, pktout
.length
+ padding
+ maclen
);
913 void bndebug(char *string
, Bignum b
) {
916 p
= ssh2_mpint_fmt(b
, &len
);
917 debug(("%s", string
));
918 for (i
= 0; i
< len
; i
++)
919 debug((" %02x", p
[i
]));
925 void sha_mpint(SHA_State
*s
, Bignum b
) {
928 p
= ssh2_mpint_fmt(b
, &len
);
929 sha_string(s
, p
, len
);
934 * SSH2 packet decode functions.
936 unsigned long ssh2_pkt_getuint32(void) {
938 if (pktin
.length
- pktin
.savedpos
< 4)
939 return 0; /* arrgh, no way to decline (FIXME?) */
940 value
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
944 void ssh2_pkt_getstring(char **p
, int *length
) {
946 if (pktin
.length
- pktin
.savedpos
< 4)
948 *length
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
950 if (pktin
.length
- pktin
.savedpos
< *length
)
952 *p
= pktin
.data
+pktin
.savedpos
;
953 pktin
.savedpos
+= *length
;
955 Bignum
ssh2_pkt_getmp(void) {
960 ssh2_pkt_getstring(&p
, &length
);
964 bombout(("internal error: Can't handle negative mpints"));
967 b
= newbn((length
+1)/2);
968 for (i
= 0; i
< length
; i
++) {
971 b
[j
/2+1] |= ((unsigned char)p
[i
]) << 8;
973 b
[j
/2+1] |= ((unsigned char)p
[i
]);
978 static int do_ssh_init(void) {
982 char vlog
[sizeof(vstring
)+20];
987 while (s_read(&c
, 1) == 1) {
988 if (c
== 'S' && i
< 2) i
++;
989 else if (c
== 'S' && i
== 2) i
= 2;
990 else if (c
== 'H' && i
== 2) break;
994 if (s_read(&c
,1) != 1 || c
!= 'S') return 0;
995 if (s_read(&c
,1) != 1 || c
!= 'S') return 0;
996 if (s_read(&c
,1) != 1 || c
!= 'H') return 0;
998 strcpy(vstring
, "SSH-");
1000 if (s_read(&c
,1) != 1 || c
!= '-') return 0;
1003 if (s_read(&c
,1) != 1)
1005 if (vsp
< vstring
+sizeof(vstring
)-1)
1011 } else if (i
< sizeof(version
)-1)
1019 sprintf(vlog
, "Server version: %s", vstring
);
1020 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1024 * Server version "1.99" means we can choose whether we use v1
1025 * or v2 protocol. Choice is based on cfg.sshprot.
1027 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1029 * This is a v2 server. Begin v2 protocol.
1031 char *verstring
= "SSH-2.0-PuTTY";
1034 * Hash our version string and their version string.
1036 sha_string(&exhash
, verstring
, strlen(verstring
));
1037 sha_string(&exhash
, vstring
, strcspn(vstring
, "\r\n"));
1038 sprintf(vstring
, "%s\n", verstring
);
1039 sprintf(vlog
, "We claim version: %s", verstring
);
1041 logevent("Using SSH protocol version 2");
1042 s_write(vstring
, strlen(vstring
));
1043 ssh_protocol
= ssh2_protocol
;
1045 s_rdpkt
= ssh2_rdpkt
;
1048 * This is a v1 server. Begin v1 protocol.
1050 sprintf(vstring
, "SSH-%s-PuTTY\n",
1051 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"));
1052 sprintf(vlog
, "We claim version: %s", vstring
);
1053 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1055 logevent("Using SSH protocol version 1");
1056 s_write(vstring
, strlen(vstring
));
1057 ssh_protocol
= ssh1_protocol
;
1059 s_rdpkt
= ssh1_rdpkt
;
1066 * Handle the key exchange and user authentication phases.
1068 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1071 unsigned char *rsabuf
, *keystr1
, *keystr2
;
1072 unsigned char cookie
[8];
1073 struct RSAKey servkey
, hostkey
;
1074 struct MD5Context md5c
;
1075 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1076 static int tried_publickey
;
1077 static unsigned char session_id
[16];
1082 if (!ispkt
) crWaitUntil(ispkt
);
1084 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1085 bombout(("Public key packet not received"));
1089 logevent("Received public keys");
1091 memcpy(cookie
, pktin
.body
, 8);
1093 i
= makekey(pktin
.body
+8, &servkey
, &keystr1
, 0);
1094 j
= makekey(pktin
.body
+8+i
, &hostkey
, &keystr2
, 0);
1097 * Hash the host key and print the hash in the log box. Just as
1098 * a last resort in case the registry's host key checking is
1099 * compromised, we'll allow the user some ability to verify
1103 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1104 MD5Final(session_id
, &md5c
);
1108 logevent("Host key MD5 is:");
1109 strcpy(logmsg
, " ");
1110 for (i
= 0; i
< 16; i
++)
1111 sprintf(logmsg
+strlen(logmsg
), "%02x", session_id
[i
]);
1115 supported_ciphers_mask
= GET_32BIT(pktin
.body
+12+i
+j
);
1116 supported_auths_mask
= GET_32BIT(pktin
.body
+16+i
+j
);
1119 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1120 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1121 MD5Update(&md5c
, pktin
.body
, 8);
1122 MD5Final(session_id
, &md5c
);
1124 for (i
=0; i
<32; i
++)
1125 session_key
[i
] = random_byte();
1127 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1129 rsabuf
= malloc(len
);
1131 fatalbox("Out of memory");
1134 * Verify the host key.
1138 * First format the key into a string.
1140 int len
= rsastr_len(&hostkey
);
1141 char *keystr
= malloc(len
);
1143 fatalbox("Out of memory");
1144 rsastr_fmt(keystr
, &hostkey
);
1145 verify_ssh_host_key(savedhost
, keystr
);
1149 for (i
=0; i
<32; i
++) {
1150 rsabuf
[i
] = session_key
[i
];
1152 rsabuf
[i
] ^= session_id
[i
];
1155 if (hostkey
.bytes
> servkey
.bytes
) {
1156 rsaencrypt(rsabuf
, 32, &servkey
);
1157 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1159 rsaencrypt(rsabuf
, 32, &hostkey
);
1160 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1163 logevent("Encrypted session key");
1165 cipher_type
= cfg
.cipher
== CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH
:
1166 cfg
.cipher
== CIPHER_DES ? SSH_CIPHER_DES
:
1168 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1169 c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
1170 cipher_type
= SSH_CIPHER_3DES
;
1172 switch (cipher_type
) {
1173 case SSH_CIPHER_3DES
: logevent("Using 3DES encryption"); break;
1174 case SSH_CIPHER_DES
: logevent("Using single-DES encryption"); break;
1175 case SSH_CIPHER_BLOWFISH
: logevent("Using Blowfish encryption"); break;
1178 send_packet(SSH1_CMSG_SESSION_KEY
,
1179 PKT_CHAR
, cipher_type
,
1180 PKT_DATA
, cookie
, 8,
1181 PKT_CHAR
, (len
*8) >> 8, PKT_CHAR
, (len
*8) & 0xFF,
1182 PKT_DATA
, rsabuf
, len
,
1186 logevent("Trying to enable encryption...");
1190 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
1191 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
1193 cipher
->sesskey(session_key
);
1197 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1198 bombout(("Encryption not successfully enabled"));
1202 logevent("Successfully started encryption");
1206 static char username
[100];
1209 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
1210 c_write("login as: ", 10);
1213 crWaitUntil(!ispkt
);
1214 while (inlen
--) switch (c
= *in
++) {
1221 c_write("\b \b", 3);
1227 c_write("\b \b", 3);
1236 if (((c
>= ' ' && c
<= '~') ||
1237 ((unsigned char)c
>= 160)) && pos
< 40) {
1238 username
[pos
++] = c
;
1245 username
[strcspn(username
, "\n\r")] = '\0';
1248 strncpy(username
, cfg
.username
, 99);
1249 username
[99] = '\0';
1250 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
1251 sprintf(stuff
, "Sent username \"%s\".\r\n", username
);
1252 c_write(stuff
, strlen(stuff
));
1256 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
1258 char userlog
[20+sizeof(username
)];
1259 sprintf(userlog
, "Sent username \"%s\"", username
);
1266 tried_publickey
= 0;
1268 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
1269 static char password
[100];
1272 static int pwpkt_type
;
1274 * Show password prompt, having first obtained it via a TIS
1275 * or CryptoCard exchange if we're doing TIS or CryptoCard
1278 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
1279 if (agent_exists()) {
1281 * Attempt RSA authentication using Pageant.
1283 static unsigned char request
[5], *response
, *p
;
1284 static int responselen
;
1285 static int i
, nkeys
;
1286 static int authed
= FALSE
;
1289 logevent("Pageant is running. Requesting keys.");
1291 /* Request the keys held by the agent. */
1292 PUT_32BIT(request
, 1);
1293 request
[4] = SSH_AGENTC_REQUEST_RSA_IDENTITIES
;
1294 agent_query(request
, 5, &r
, &responselen
);
1295 response
= (unsigned char *)r
;
1298 nkeys
= GET_32BIT(p
); p
+= 4;
1299 { char buf
[64]; sprintf(buf
, "Pageant has %d keys", nkeys
);
1301 for (i
= 0; i
< nkeys
; i
++) {
1302 static struct RSAKey key
;
1303 static Bignum challenge
;
1304 static char *commentp
;
1305 static int commentlen
;
1307 { char buf
[64]; sprintf(buf
, "Trying Pageant key #%d", i
);
1310 p
+= ssh1_read_bignum(p
, &key
.exponent
);
1311 p
+= ssh1_read_bignum(p
, &key
.modulus
);
1312 commentlen
= GET_32BIT(p
); p
+= 4;
1313 commentp
= p
; p
+= commentlen
;
1314 send_packet(SSH1_CMSG_AUTH_RSA
,
1315 PKT_BIGNUM
, key
.modulus
, PKT_END
);
1317 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1318 logevent("Key refused");
1321 logevent("Received RSA challenge");
1322 ssh1_read_bignum(pktin
.body
, &challenge
);
1324 char *agentreq
, *q
, *ret
;
1326 len
= 1 + 4; /* message type, bit count */
1327 len
+= ssh1_bignum_length(key
.exponent
);
1328 len
+= ssh1_bignum_length(key
.modulus
);
1329 len
+= ssh1_bignum_length(challenge
);
1330 len
+= 16; /* session id */
1331 len
+= 4; /* response format */
1332 agentreq
= malloc(4 + len
);
1333 PUT_32BIT(agentreq
, len
);
1335 *q
++ = SSH_AGENTC_RSA_CHALLENGE
;
1336 PUT_32BIT(q
, ssh1_bignum_bitcount(key
.modulus
));
1338 q
+= ssh1_write_bignum(q
, key
.exponent
);
1339 q
+= ssh1_write_bignum(q
, key
.modulus
);
1340 q
+= ssh1_write_bignum(q
, challenge
);
1341 memcpy(q
, session_id
, 16); q
+= 16;
1342 PUT_32BIT(q
, 1); /* response format */
1343 agent_query(agentreq
, len
+4, &ret
, &retlen
);
1346 if (ret
[4] == SSH_AGENT_RSA_RESPONSE
) {
1347 logevent("Sending Pageant's response");
1348 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1349 PKT_DATA
, ret
+5, 16, PKT_END
);
1352 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1353 logevent("Pageant's response accepted");
1354 c_write("Authenticated using RSA key \"",
1356 c_write(commentp
, commentlen
);
1357 c_write("\" from agent\r\n", 14);
1360 logevent("Pageant's response not accepted");
1362 logevent("Pageant failed to answer challenge");
1366 logevent("No reply received from Pageant");
1369 freebn(key
.exponent
);
1370 freebn(key
.modulus
);
1379 if (*cfg
.keyfile
&& !tried_publickey
)
1380 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
1382 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
&&
1383 !(flags
& FLAG_INTERACTIVE
)) {
1385 sprintf(prompt
, "%s@%s's password: ", cfg
.username
, savedhost
);
1386 if (!ssh_get_password(prompt
, password
, sizeof(password
))) {
1388 * get_password failed to get a password (for
1389 * example because one was supplied on the command
1390 * line which has already failed to work).
1393 logevent("No more passwords to try");
1394 ssh_state
= SSH_STATE_CLOSED
;
1399 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1401 (supported_auths_mask
& (1<<SSH1_AUTH_TIS
))) {
1402 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
1403 logevent("Requested TIS authentication");
1404 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
1406 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
1407 logevent("TIS authentication declined");
1408 c_write("TIS authentication refused.\r\n", 29);
1410 int challengelen
= ((pktin
.body
[0] << 24) |
1411 (pktin
.body
[1] << 16) |
1412 (pktin
.body
[2] << 8) |
1414 logevent("Received TIS challenge");
1415 c_write(pktin
.body
+4, challengelen
);
1418 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1420 (supported_auths_mask
& (1<<SSH1_AUTH_CCARD
))) {
1421 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
1422 logevent("Requested CryptoCard authentication");
1423 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
1425 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
1426 logevent("CryptoCard authentication declined");
1427 c_write("CryptoCard authentication refused.\r\n", 29);
1429 int challengelen
= ((pktin
.body
[0] << 24) |
1430 (pktin
.body
[1] << 16) |
1431 (pktin
.body
[2] << 8) |
1433 logevent("Received CryptoCard challenge");
1434 c_write(pktin
.body
+4, challengelen
);
1435 c_write("\r\nResponse : ", 13);
1438 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
)
1439 c_write("password: ", 10);
1440 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1441 if (flags
& FLAG_VERBOSE
)
1442 c_write("Trying public key authentication.\r\n", 35);
1443 if (!rsakey_encrypted(cfg
.keyfile
)) {
1444 if (flags
& FLAG_VERBOSE
)
1445 c_write("No passphrase required.\r\n", 25);
1448 c_write("passphrase: ", 12);
1454 crWaitUntil(!ispkt
);
1455 while (inlen
--) switch (c
= *in
++) {
1472 if (((c
>= ' ' && c
<= '~') ||
1473 ((unsigned char)c
>= 160)) && pos
< sizeof(password
))
1474 password
[pos
++] = c
;
1483 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1485 * Try public key authentication with the specified
1488 static struct RSAKey pubkey
;
1489 static Bignum challenge
, response
;
1491 static unsigned char buffer
[32];
1493 tried_publickey
= 1;
1494 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
1496 c_write("Couldn't load public key from ", 30);
1497 c_write(cfg
.keyfile
, strlen(cfg
.keyfile
));
1498 c_write(".\r\n", 3);
1499 continue; /* go and try password */
1502 c_write("Wrong passphrase.\r\n", 19);
1503 tried_publickey
= 0;
1504 continue; /* try again */
1508 * Send a public key attempt.
1510 send_packet(SSH1_CMSG_AUTH_RSA
,
1511 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
1514 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1515 if (flags
& FLAG_VERBOSE
)
1516 c_write("Server refused our public key.\r\n", 32);
1517 continue; /* go and try password */
1519 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1520 bombout(("Bizarre response to offer of public key"));
1523 ssh1_read_bignum(pktin
.body
, &challenge
);
1524 response
= rsadecrypt(challenge
, &pubkey
);
1525 freebn(pubkey
.private_exponent
); /* burn the evidence */
1527 for (i
= 0; i
< 32; i
+= 2) {
1528 buffer
[i
] = response
[16-i
/2] >> 8;
1529 buffer
[i
+1] = response
[16-i
/2] & 0xFF;
1533 MD5Update(&md5c
, buffer
, 32);
1534 MD5Update(&md5c
, session_id
, 16);
1535 MD5Final(buffer
, &md5c
);
1537 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1538 PKT_DATA
, buffer
, 16, PKT_END
);
1541 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1542 if (flags
& FLAG_VERBOSE
)
1543 c_write("Failed to authenticate with our public key.\r\n",
1545 continue; /* go and try password */
1546 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1547 bombout(("Bizarre response to RSA authentication response"));
1551 break; /* we're through! */
1553 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
1555 logevent("Sent password");
1556 memset(password
, 0, strlen(password
));
1558 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1559 if (flags
& FLAG_VERBOSE
)
1560 c_write("Access denied\r\n", 15);
1561 logevent("Authentication refused");
1562 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
1563 logevent("Received disconnect request");
1564 ssh_state
= SSH_STATE_CLOSED
;
1566 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1567 bombout(("Strange packet received, type %d", pktin
.type
));
1572 logevent("Authentication successful");
1577 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
) {
1582 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
1585 if (ssh_state
== SSH_STATE_CLOSED
)
1588 if (cfg
.agentfwd
&& agent_exists()) {
1589 logevent("Requesting agent forwarding");
1590 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
1591 do { crReturnV
; } while (!ispkt
);
1592 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
1593 bombout(("Protocol confusion"));
1595 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1596 logevent("Agent forwarding refused");
1598 logevent("Agent forwarding enabled");
1602 send_packet(SSH1_CMSG_REQUEST_PTY
,
1603 PKT_STR
, cfg
.termtype
,
1604 PKT_INT
, rows
, PKT_INT
, cols
,
1605 PKT_INT
, 0, PKT_INT
, 0,
1608 ssh_state
= SSH_STATE_INTERMED
;
1609 do { crReturnV
; } while (!ispkt
);
1610 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
1611 bombout(("Protocol confusion"));
1613 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1614 c_write("Server refused to allocate pty\r\n", 32);
1616 logevent("Allocated pty");
1619 if (*cfg
.remote_cmd
)
1620 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cfg
.remote_cmd
, PKT_END
);
1622 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
1623 logevent("Started session");
1625 ssh_state
= SSH_STATE_SESSION
;
1630 ssh_channels
= newtree234(ssh_channelcmp
);
1635 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
1636 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
1637 long len
= GET_32BIT(pktin
.body
);
1638 c_write(pktin
.body
+4, len
);
1639 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
1640 ssh_state
= SSH_STATE_CLOSED
;
1641 logevent("Received disconnect request");
1642 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
1643 /* Remote side is trying to open a channel to talk to our
1644 * agent. Give them back a local channel number. */
1646 struct ssh_channel
*c
;
1648 for (c
= first234(ssh_channels
, &e
); c
; c
= next234(&e
)) {
1650 break; /* found a free number */
1653 c
= malloc(sizeof(struct ssh_channel
));
1654 c
->remoteid
= GET_32BIT(pktin
.body
);
1657 c
->type
= SSH1_SMSG_AGENT_OPEN
; /* identify channel type */
1658 add234(ssh_channels
, c
);
1659 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
1660 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
1662 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
1663 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
1664 /* Remote side closes a channel. */
1665 unsigned i
= GET_32BIT(pktin
.body
);
1666 struct ssh_channel
*c
;
1667 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
1670 closetype
= (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
1671 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
, PKT_END
);
1672 c
->closes
|= closetype
;
1673 if (c
->closes
== 3) {
1674 del234(ssh_channels
, c
);
1678 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
1679 /* Data sent down one of our channels. */
1680 int i
= GET_32BIT(pktin
.body
);
1681 int len
= GET_32BIT(pktin
.body
+4);
1682 unsigned char *p
= pktin
.body
+8;
1683 struct ssh_channel
*c
;
1684 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
1687 case SSH1_SMSG_AGENT_OPEN
:
1688 /* Data for an agent message. Buffer it. */
1690 if (c
->u
.a
.lensofar
< 4) {
1691 int l
= min(4 - c
->u
.a
.lensofar
, len
);
1692 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
, l
);
1693 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
1695 if (c
->u
.a
.lensofar
== 4) {
1696 c
->u
.a
.totallen
= 4 + GET_32BIT(c
->u
.a
.msglen
);
1697 c
->u
.a
.message
= malloc(c
->u
.a
.totallen
);
1698 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
1700 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
1701 int l
= min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
, len
);
1702 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
, l
);
1703 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
1705 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
1706 void *reply
, *sentreply
;
1708 agent_query(c
->u
.a
.message
, c
->u
.a
.totallen
,
1713 /* Fake SSH_AGENT_FAILURE. */
1714 sentreply
= "\0\0\0\1\5";
1717 send_packet(SSH1_MSG_CHANNEL_DATA
,
1718 PKT_INT
, c
->remoteid
,
1720 PKT_DATA
, sentreply
, replylen
,
1724 free(c
->u
.a
.message
);
1725 c
->u
.a
.lensofar
= 0;
1731 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1732 /* may be from EXEC_SHELL on some servers */
1733 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1734 /* may be from EXEC_SHELL on some servers
1735 * if no pty is available or in other odd cases. Ignore */
1736 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
1737 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
1739 bombout(("Strange packet received: type %d", pktin
.type
));
1743 send_packet(SSH1_CMSG_STDIN_DATA
,
1744 PKT_INT
, inlen
, PKT_DATA
, in
, inlen
, PKT_END
);
1752 * Utility routine for decoding comma-separated strings in KEXINIT.
1754 int in_commasep_string(char *needle
, char *haystack
, int haylen
) {
1755 int needlen
= strlen(needle
);
1758 * Is it at the start of the string?
1760 if (haylen
>= needlen
&& /* haystack is long enough */
1761 !memcmp(needle
, haystack
, needlen
) && /* initial match */
1762 (haylen
== needlen
|| haystack
[needlen
] == ',')
1763 /* either , or EOS follows */
1767 * If not, search for the next comma and resume after that.
1768 * If no comma found, terminate.
1770 while (haylen
> 0 && *haystack
!= ',')
1771 haylen
--, haystack
++;
1774 haylen
--, haystack
++; /* skip over comma itself */
1779 * SSH2 key creation method.
1781 void ssh2_mkkey(Bignum K
, char *H
, char chr
, char *keyspace
) {
1783 /* First 20 bytes. */
1786 SHA_Bytes(&s
, H
, 20);
1787 SHA_Bytes(&s
, &chr
, 1);
1788 SHA_Bytes(&s
, H
, 20);
1789 SHA_Final(&s
, keyspace
);
1790 /* Next 20 bytes. */
1793 SHA_Bytes(&s
, H
, 20);
1794 SHA_Bytes(&s
, keyspace
, 20);
1795 SHA_Final(&s
, keyspace
+20);
1799 * Handle the SSH2 transport layer.
1801 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
1805 static Bignum e
, f
, K
;
1806 static struct ssh_cipher
*cscipher_tobe
= NULL
;
1807 static struct ssh_cipher
*sccipher_tobe
= NULL
;
1808 static struct ssh_mac
*csmac_tobe
= NULL
;
1809 static struct ssh_mac
*scmac_tobe
= NULL
;
1810 static struct ssh_compress
*cscomp_tobe
= NULL
;
1811 static struct ssh_compress
*sccomp_tobe
= NULL
;
1812 static char *hostkeydata
, *sigdata
, *keystr
;
1813 static int hostkeylen
, siglen
;
1814 static unsigned char exchange_hash
[20];
1815 static unsigned char keyspace
[40];
1821 * Set up the preferred cipher.
1823 if (cfg
.cipher
== CIPHER_BLOWFISH
) {
1824 ciphers
[0] = &ssh_blowfish_ssh2
;
1825 } else if (cfg
.cipher
== CIPHER_DES
) {
1826 logevent("Single DES not supported in SSH2; using 3DES");
1827 ciphers
[0] = &ssh_3des_ssh2
;
1828 } else if (cfg
.cipher
== CIPHER_3DES
) {
1829 ciphers
[0] = &ssh_3des_ssh2
;
1831 /* Shouldn't happen, but we do want to initialise to _something_. */
1832 ciphers
[0] = &ssh_3des_ssh2
;
1837 * Construct and send our key exchange packet.
1839 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
1840 for (i
= 0; i
< 16; i
++)
1841 ssh2_pkt_addbyte((unsigned char)random_byte());
1842 /* List key exchange algorithms. */
1843 ssh2_pkt_addstring_start();
1844 for (i
= 0; i
< lenof(kex_algs
); i
++) {
1845 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
1846 if (i
< lenof(kex_algs
)-1)
1847 ssh2_pkt_addstring_str(",");
1849 /* List server host key algorithms. */
1850 ssh2_pkt_addstring_start();
1851 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
1852 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
1853 if (i
< lenof(hostkey_algs
)-1)
1854 ssh2_pkt_addstring_str(",");
1856 /* List client->server encryption algorithms. */
1857 ssh2_pkt_addstring_start();
1858 for (i
= 0; i
< lenof(ciphers
); i
++) {
1859 ssh2_pkt_addstring_str(ciphers
[i
]->name
);
1860 if (i
< lenof(ciphers
)-1)
1861 ssh2_pkt_addstring_str(",");
1863 /* List server->client encryption algorithms. */
1864 ssh2_pkt_addstring_start();
1865 for (i
= 0; i
< lenof(ciphers
); i
++) {
1866 ssh2_pkt_addstring_str(ciphers
[i
]->name
);
1867 if (i
< lenof(ciphers
)-1)
1868 ssh2_pkt_addstring_str(",");
1870 /* List client->server MAC algorithms. */
1871 ssh2_pkt_addstring_start();
1872 for (i
= 0; i
< lenof(macs
); i
++) {
1873 ssh2_pkt_addstring_str(macs
[i
]->name
);
1874 if (i
< lenof(macs
)-1)
1875 ssh2_pkt_addstring_str(",");
1877 /* List server->client MAC algorithms. */
1878 ssh2_pkt_addstring_start();
1879 for (i
= 0; i
< lenof(macs
); i
++) {
1880 ssh2_pkt_addstring_str(macs
[i
]->name
);
1881 if (i
< lenof(macs
)-1)
1882 ssh2_pkt_addstring_str(",");
1884 /* List client->server compression algorithms. */
1885 ssh2_pkt_addstring_start();
1886 for (i
= 0; i
< lenof(compressions
); i
++) {
1887 ssh2_pkt_addstring_str(compressions
[i
]->name
);
1888 if (i
< lenof(compressions
)-1)
1889 ssh2_pkt_addstring_str(",");
1891 /* List server->client compression algorithms. */
1892 ssh2_pkt_addstring_start();
1893 for (i
= 0; i
< lenof(compressions
); i
++) {
1894 ssh2_pkt_addstring_str(compressions
[i
]->name
);
1895 if (i
< lenof(compressions
)-1)
1896 ssh2_pkt_addstring_str(",");
1898 /* List client->server languages. Empty list. */
1899 ssh2_pkt_addstring_start();
1900 /* List server->client languages. Empty list. */
1901 ssh2_pkt_addstring_start();
1902 /* First KEX packet does _not_ follow, because we're not that brave. */
1903 ssh2_pkt_addbool(FALSE
);
1905 ssh2_pkt_adduint32(0);
1906 sha_string(&exhash
, pktout
.data
+5, pktout
.length
-5);
1909 if (!ispkt
) crWaitUntil(ispkt
);
1910 sha_string(&exhash
, pktin
.data
+5, pktin
.length
-5);
1913 * Now examine the other side's KEXINIT to see what we're up
1916 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
1917 bombout(("expected key exchange packet from server"));
1920 kex
= NULL
; hostkey
= NULL
; cscipher_tobe
= NULL
; sccipher_tobe
= NULL
;
1921 csmac_tobe
= NULL
; scmac_tobe
= NULL
; cscomp_tobe
= NULL
; sccomp_tobe
= NULL
;
1922 pktin
.savedpos
+= 16; /* skip garbage cookie */
1923 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
1924 for (i
= 0; i
< lenof(kex_algs
); i
++) {
1925 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
1930 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
1931 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
1932 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
1933 hostkey
= hostkey_algs
[i
];
1937 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
1938 for (i
= 0; i
< lenof(ciphers
); i
++) {
1939 if (in_commasep_string(ciphers
[i
]->name
, str
, len
)) {
1940 cscipher_tobe
= ciphers
[i
];
1944 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
1945 for (i
= 0; i
< lenof(ciphers
); i
++) {
1946 if (in_commasep_string(ciphers
[i
]->name
, str
, len
)) {
1947 sccipher_tobe
= ciphers
[i
];
1951 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
1952 for (i
= 0; i
< lenof(macs
); i
++) {
1953 if (in_commasep_string(macs
[i
]->name
, str
, len
)) {
1954 csmac_tobe
= macs
[i
];
1958 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
1959 for (i
= 0; i
< lenof(macs
); i
++) {
1960 if (in_commasep_string(macs
[i
]->name
, str
, len
)) {
1961 scmac_tobe
= macs
[i
];
1965 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
1966 for (i
= 0; i
< lenof(compressions
); i
++) {
1967 if (in_commasep_string(compressions
[i
]->name
, str
, len
)) {
1968 cscomp_tobe
= compressions
[i
];
1972 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
1973 for (i
= 0; i
< lenof(compressions
); i
++) {
1974 if (in_commasep_string(compressions
[i
]->name
, str
, len
)) {
1975 sccomp_tobe
= compressions
[i
];
1981 * Currently we only support Diffie-Hellman and DSS, so let's
1982 * bomb out if those aren't selected.
1984 if (kex
!= &ssh_diffiehellman
|| hostkey
!= &ssh_dss
) {
1985 bombout(("internal fault: chaos in SSH 2 transport layer"));
1990 * Now we begin the fun. Generate and send e for Diffie-Hellman.
1993 ssh2_pkt_init(SSH2_MSG_KEXDH_INIT
);
1998 if (pktin
.type
!= SSH2_MSG_KEXDH_REPLY
) {
1999 bombout(("expected key exchange packet from server"));
2002 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
2003 f
= ssh2_pkt_getmp();
2004 ssh2_pkt_getstring(&sigdata
, &siglen
);
2008 sha_string(&exhash
, hostkeydata
, hostkeylen
);
2009 sha_mpint(&exhash
, e
);
2010 sha_mpint(&exhash
, f
);
2011 sha_mpint(&exhash
, K
);
2012 SHA_Final(&exhash
, exchange_hash
);
2015 debug(("Exchange hash is:\r\n"));
2016 for (i
= 0; i
< 20; i
++)
2017 debug((" %02x", exchange_hash
[i
]));
2021 hostkey
->setkey(hostkeydata
, hostkeylen
);
2022 if (!hostkey
->verifysig(sigdata
, siglen
, exchange_hash
, 20)) {
2023 bombout(("Server failed host key check"));
2028 * Expect SSH2_MSG_NEWKEYS from server.
2031 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
2032 bombout(("expected new-keys packet from server"));
2037 * Authenticate remote host: verify host key. (We've already
2038 * checked the signature of the exchange hash.)
2040 keystr
= hostkey
->fmtkey();
2041 verify_ssh_host_key(savedhost
, keystr
);
2045 * Send SSH2_MSG_NEWKEYS.
2047 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
2051 * Create and initialise session keys.
2053 cscipher
= cscipher_tobe
;
2054 sccipher
= sccipher_tobe
;
2057 cscomp
= cscomp_tobe
;
2058 sccomp
= sccomp_tobe
;
2060 * Set IVs after keys.
2062 ssh2_mkkey(K
, exchange_hash
, 'C', keyspace
); cscipher
->setcskey(keyspace
);
2063 ssh2_mkkey(K
, exchange_hash
, 'D', keyspace
); cscipher
->setsckey(keyspace
);
2064 ssh2_mkkey(K
, exchange_hash
, 'A', keyspace
); cscipher
->setcsiv(keyspace
);
2065 ssh2_mkkey(K
, exchange_hash
, 'B', keyspace
); sccipher
->setsciv(keyspace
);
2066 ssh2_mkkey(K
, exchange_hash
, 'E', keyspace
); csmac
->setcskey(keyspace
);
2067 ssh2_mkkey(K
, exchange_hash
, 'F', keyspace
); scmac
->setsckey(keyspace
);
2070 * Now we're encrypting. Begin returning 1 to the protocol main
2071 * function so that other things can run on top of the
2072 * transport. If we ever see a KEXINIT, we must go back to the
2077 } while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
));
2078 goto begin_key_exchange
;
2084 * Handle the SSH2 userauth and connection layers.
2086 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
2088 static unsigned long remote_winsize
;
2089 static unsigned long remote_maxpkt
;
2094 * Request userauth protocol, and await a response to it.
2096 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
2097 ssh2_pkt_addstring("ssh-userauth");
2099 crWaitUntilV(ispkt
);
2100 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
2101 bombout(("Server refused user authentication protocol"));
2106 * FIXME: currently we support only password authentication.
2107 * (This places us technically in violation of the SSH2 spec.
2108 * We must fix this.)
2112 * Get a username and a password.
2114 static char username
[100];
2115 static char password
[100];
2119 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
2120 c_write("login as: ", 10);
2123 crWaitUntilV(!ispkt
);
2124 while (inlen
--) switch (c
= *in
++) {
2131 c_write("\b \b", 3);
2137 c_write("\b \b", 3);
2146 if (((c
>= ' ' && c
<= '~') ||
2147 ((unsigned char)c
>= 160)) && pos
< 40) {
2148 username
[pos
++] = c
;
2155 username
[strcspn(username
, "\n\r")] = '\0';
2158 strncpy(username
, cfg
.username
, 99);
2159 username
[99] = '\0';
2160 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
2161 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
2162 c_write(stuff
, strlen(stuff
));
2166 if (!(flags
& FLAG_INTERACTIVE
)) {
2168 sprintf(prompt
, "%s@%s's password: ", cfg
.username
, savedhost
);
2169 if (!ssh_get_password(prompt
, password
, sizeof(password
))) {
2171 * get_password failed to get a password (for
2172 * example because one was supplied on the command
2173 * line which has already failed to work).
2176 logevent("No more passwords to try");
2177 ssh_state
= SSH_STATE_CLOSED
;
2181 c_write("password: ", 10);
2186 crWaitUntilV(!ispkt
);
2187 while (inlen
--) switch (c
= *in
++) {
2204 if (((c
>= ' ' && c
<= '~') ||
2205 ((unsigned char)c
>= 160)) && pos
< 40)
2206 password
[pos
++] = c
;
2213 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
2214 ssh2_pkt_addstring(username
);
2215 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2216 ssh2_pkt_addstring("password");
2217 ssh2_pkt_addbool(FALSE
);
2218 ssh2_pkt_addstring(password
);
2221 crWaitUntilV(ispkt
);
2222 if (pktin
.type
!= SSH2_MSG_USERAUTH_SUCCESS
) {
2223 c_write("Access denied\r\n", 15);
2224 logevent("Authentication refused");
2230 * Now we're authenticated for the connection protocol. The
2231 * connection protocol will automatically have started at this
2232 * point; there's no need to send SERVICE_REQUEST.
2236 * So now create a channel with a session in it.
2238 mainchan
= malloc(sizeof(struct ssh_channel
));
2239 mainchan
->localid
= 100; /* as good as any */
2240 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
2241 ssh2_pkt_addstring("session");
2242 ssh2_pkt_adduint32(mainchan
->localid
);
2243 ssh2_pkt_adduint32(0x7FFFFFFFUL
); /* our window size */
2244 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
2246 crWaitUntilV(ispkt
);
2247 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
2248 bombout(("Server refused to open a session"));
2250 /* FIXME: error data comes back in FAILURE packet */
2252 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
2253 bombout(("Server's channel confirmation cited wrong channel"));
2256 mainchan
->remoteid
= ssh2_pkt_getuint32();
2257 mainchan
->u
.v2
.remwindow
= ssh2_pkt_getuint32();
2258 mainchan
->u
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
2259 mainchan
->u
.v2
.outbuffer
= NULL
;
2260 mainchan
->u
.v2
.outbuflen
= mainchan
->u
.v2
.outbufsize
= 0;
2261 logevent("Opened channel for session");
2264 * Now allocate a pty for the session.
2267 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
2268 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
2269 ssh2_pkt_addstring("pty-req");
2270 ssh2_pkt_addbool(1); /* want reply */
2271 ssh2_pkt_addstring(cfg
.termtype
);
2272 ssh2_pkt_adduint32(cols
);
2273 ssh2_pkt_adduint32(rows
);
2274 ssh2_pkt_adduint32(0); /* pixel width */
2275 ssh2_pkt_adduint32(0); /* pixel height */
2276 ssh2_pkt_addstring_start();
2277 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
2281 crWaitUntilV(ispkt
);
2282 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
2283 /* FIXME: be able to handle other channels here */
2284 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2285 continue; /* wrong channel */
2286 mainchan
->u
.v2
.remwindow
+= ssh2_pkt_getuint32();
2288 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
2290 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
2291 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
2292 bombout(("Server got confused by pty request"));
2295 c_write("Server refused to allocate pty\r\n", 32);
2297 logevent("Allocated pty");
2302 * Start a shell or a remote command.
2304 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
2305 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
2306 if (*cfg
.remote_cmd
) {
2307 ssh2_pkt_addstring("exec");
2308 ssh2_pkt_addbool(1); /* want reply */
2309 ssh2_pkt_addstring(cfg
.remote_cmd
);
2311 ssh2_pkt_addstring("shell");
2312 ssh2_pkt_addbool(1); /* want reply */
2316 crWaitUntilV(ispkt
);
2317 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
2318 /* FIXME: be able to handle other channels here */
2319 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2320 continue; /* wrong channel */
2321 mainchan
->u
.v2
.remwindow
+= ssh2_pkt_getuint32();
2323 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
2324 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
2325 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
2326 bombout(("Server got confused by shell/command request"));
2329 bombout(("Server refused to start a shell/command"));
2332 logevent("Started a shell/command");
2341 static int try_send
;
2345 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
2346 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
2349 /* FIXME: be able to handle other channels here */
2350 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2351 continue; /* wrong channel */
2352 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
2353 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
2354 continue; /* extended but not stderr */
2355 ssh2_pkt_getstring(&data
, &length
);
2357 c_write(data
, length
);
2359 * Enlarge the window again at the remote side,
2360 * just in case it ever runs down and they fail
2361 * to send us any more data.
2363 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
2364 ssh2_pkt_adduint32(mainchan
->remoteid
);
2365 ssh2_pkt_adduint32(length
);
2368 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
2369 ssh_state
= SSH_STATE_CLOSED
;
2370 logevent("Received disconnect message");
2371 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
2372 continue; /* exit status et al; ignore (FIXME?) */
2373 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
2374 continue; /* remote sends EOF; ignore */
2375 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
2376 /* FIXME: be able to handle other channels here */
2377 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2378 continue; /* wrong channel */
2379 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2380 ssh2_pkt_adduint32(mainchan
->remoteid
);
2382 /* FIXME: mark the channel as closed */
2383 if (1 /* FIXME: "all channels are closed" */) {
2384 logevent("All channels closed. Disconnecting");
2385 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
2388 continue; /* remote sends close; ignore (FIXME) */
2389 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
2390 /* FIXME: be able to handle other channels here */
2391 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2392 continue; /* wrong channel */
2393 mainchan
->u
.v2
.remwindow
+= ssh2_pkt_getuint32();
2396 bombout(("Strange packet received: type %d", pktin
.type
));
2401 * We have spare data. Add it to the channel buffer.
2403 if (mainchan
->u
.v2
.outbufsize
<
2404 mainchan
->u
.v2
.outbuflen
+ inlen
) {
2405 mainchan
->u
.v2
.outbufsize
=
2406 mainchan
->u
.v2
.outbuflen
+ inlen
+ 1024;
2407 mainchan
->u
.v2
.outbuffer
= srealloc(mainchan
->u
.v2
.outbuffer
,
2408 mainchan
->u
.v2
.outbufsize
);
2410 memcpy(mainchan
->u
.v2
.outbuffer
+ mainchan
->u
.v2
.outbuflen
,
2412 mainchan
->u
.v2
.outbuflen
+= inlen
;
2417 * Try to send data on the channel if we can. (FIXME:
2418 * on _all_ channels.)
2420 while (mainchan
->u
.v2
.remwindow
> 0 &&
2421 mainchan
->u
.v2
.outbuflen
> 0) {
2422 unsigned len
= mainchan
->u
.v2
.remwindow
;
2423 if (len
> mainchan
->u
.v2
.outbuflen
)
2424 len
= mainchan
->u
.v2
.outbuflen
;
2425 if (len
> mainchan
->u
.v2
.remmaxpkt
)
2426 len
= mainchan
->u
.v2
.remmaxpkt
;
2427 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
2428 ssh2_pkt_adduint32(mainchan
->remoteid
);
2429 ssh2_pkt_addstring_start();
2430 ssh2_pkt_addstring_data(mainchan
->u
.v2
.outbuffer
, len
);
2432 mainchan
->u
.v2
.outbuflen
-= len
;
2433 memmove(mainchan
->u
.v2
.outbuffer
, mainchan
->u
.v2
.outbuffer
+len
,
2434 mainchan
->u
.v2
.outbuflen
);
2435 mainchan
->u
.v2
.remwindow
-= len
;
2444 * Handle the top-level SSH2 protocol.
2446 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
2448 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
2450 do_ssh2_authconn(in
, inlen
, ispkt
);
2454 * Called to set up the connection. Will arrange for WM_NETEVENT
2455 * messages to be passed to the specified window, whose window
2456 * procedure should then call telnet_msg().
2458 * Returns an error message, or NULL on success.
2460 static char *ssh_init (HWND hwnd
, char *host
, int port
, char **realhost
) {
2464 if(crypto_startup() == 0)
2465 return "Microsoft high encryption pack not installed!";
2468 p
= connect_to_host(host
, port
, realhost
);
2473 return "Protocol initialisation error";
2475 if (hwnd
&& WSAAsyncSelect (s
, hwnd
, WM_NETEVENT
, FD_READ
| FD_CLOSE
) == SOCKET_ERROR
)
2476 switch (WSAGetLastError()) {
2477 case WSAENETDOWN
: return "Network is down";
2478 default: return "WSAAsyncSelect(): unknown error";
2485 * Process a WM_NETEVENT message. Will return 0 if the connection
2486 * has closed, or <0 for a socket error.
2488 static int ssh_msg (WPARAM wParam
, LPARAM lParam
) {
2493 * Because reading less than the whole of the available pending
2494 * data can generate an FD_READ event, we need to allow for the
2495 * possibility that FD_READ may arrive with FD_CLOSE already in
2496 * the queue; so it's possible that we can get here even with s
2497 * invalid. If so, we return 1 and don't worry about it.
2499 if (s
== INVALID_SOCKET
)
2502 if (WSAGETSELECTERROR(lParam
) != 0) {
2505 return -WSAGETSELECTERROR(lParam
);
2508 switch (WSAGETSELECTEVENT(lParam
)) {
2511 ret
= recv(s
, buf
, sizeof(buf
), 0);
2512 if (ret
< 0 && WSAGetLastError() == WSAEWOULDBLOCK
)
2514 if (ret
< 0) { /* any _other_ error */
2517 return -10000-WSAGetLastError();
2523 ssh_gotdata (buf
, ret
);
2524 if (ssh_state
== SSH_STATE_CLOSED
) {
2531 return 1; /* shouldn't happen, but WTF */
2535 * Called to send data down the Telnet connection.
2537 static void ssh_send (char *buf
, int len
) {
2538 if (s
== INVALID_SOCKET
)
2541 ssh_protocol(buf
, len
, 0);
2545 * Called to set the size of the window from Telnet's POV.
2547 static void ssh_size(void) {
2548 switch (ssh_state
) {
2549 case SSH_STATE_BEFORE_SIZE
:
2550 case SSH_STATE_CLOSED
:
2551 break; /* do nothing */
2552 case SSH_STATE_INTERMED
:
2553 size_needed
= TRUE
; /* buffer for later */
2555 case SSH_STATE_SESSION
:
2557 send_packet(SSH1_CMSG_WINDOW_SIZE
,
2558 PKT_INT
, rows
, PKT_INT
, cols
,
2559 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
2565 * Send Telnet special codes. TS_EOF is useful for `plink', so you
2566 * can send an EOF and collect resulting output (e.g. `plink
2569 static void ssh_special (Telnet_Special code
) {
2570 if (code
== TS_EOF
) {
2571 if (ssh_version
== 1) {
2572 send_packet(SSH1_CMSG_EOF
, PKT_END
);
2574 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
2575 ssh2_pkt_adduint32(mainchan
->remoteid
);
2578 logevent("Sent EOF message");
2586 * Read and decrypt one incoming SSH packet.
2587 * (only used by pSCP)
2589 static void get_packet(void)
2591 unsigned char buf
[4096], *p
;
2598 while ((to_read
= s_rdpkt(&p
, &len
)) > 0) {
2599 if (to_read
> sizeof(buf
)) to_read
= sizeof(buf
);
2600 len
= s_read(buf
, to_read
);
2601 if (len
!= to_read
) {
2613 * Receive a block of data over the SSH link. Block until
2614 * all data is available. Return nr of bytes read (0 if lost connection).
2615 * (only used by pSCP)
2617 int ssh_scp_recv(unsigned char *buf
, int len
)
2619 static int pending_input_len
= 0;
2620 static unsigned char *pending_input_ptr
;
2623 if (pending_input_len
>= to_read
) {
2624 memcpy(buf
, pending_input_ptr
, to_read
);
2625 pending_input_ptr
+= to_read
;
2626 pending_input_len
-= to_read
;
2630 if (pending_input_len
> 0) {
2631 memcpy(buf
, pending_input_ptr
, pending_input_len
);
2632 buf
+= pending_input_len
;
2633 to_read
-= pending_input_len
;
2634 pending_input_len
= 0;
2637 if (s
== INVALID_SOCKET
)
2639 while (to_read
> 0) {
2641 if (s
== INVALID_SOCKET
)
2643 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
) {
2644 int plen
= GET_32BIT(pktin
.body
);
2645 if (plen
<= to_read
) {
2646 memcpy(buf
, pktin
.body
+ 4, plen
);
2650 memcpy(buf
, pktin
.body
+ 4, to_read
);
2651 pending_input_len
= plen
- to_read
;
2652 pending_input_ptr
= pktin
.body
+ 4 + to_read
;
2655 } else if (pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
2656 int plen
= GET_32BIT(pktin
.body
);
2657 fwrite(pktin
.body
+ 4, plen
, 1, stderr
);
2658 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2659 logevent("Received disconnect request");
2660 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
||
2661 pktin
.type
== SSH1_SMSG_FAILURE
) {
2663 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
2665 sprintf(logbuf
, "Remote exit status: %d", GET_32BIT(pktin
.body
));
2667 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
2668 logevent("Closing connection");
2672 bombout(("Strange packet received: type %d", pktin
.type
));
2681 * Send a block of data over the SSH link.
2682 * Block until all data is sent.
2683 * (only used by pSCP)
2685 void ssh_scp_send(unsigned char *buf
, int len
)
2687 if (s
== INVALID_SOCKET
)
2689 send_packet(SSH1_CMSG_STDIN_DATA
,
2690 PKT_INT
, len
, PKT_DATA
, buf
, len
, PKT_END
);
2694 * Send an EOF notification to the server.
2695 * (only used by pSCP)
2697 void ssh_scp_send_eof(void)
2699 if (s
== INVALID_SOCKET
)
2701 send_packet(SSH1_CMSG_EOF
, PKT_END
);
2705 * Set up the connection, login on the remote host and
2706 * start execution of a command.
2707 * Returns an error message, or NULL on success.
2708 * (only used by pSCP)
2710 char *ssh_scp_init(char *host
, int port
, char *cmd
, char **realhost
)
2715 if (crypto_startup() == 0)
2716 return "Microsoft high encryption pack not installed!";
2719 p
= connect_to_host(host
, port
, realhost
);
2726 return "Protocol initialisation error";
2728 /* Exchange keys and login */
2731 if (s
== INVALID_SOCKET
)
2732 return "Connection closed by remote host";
2733 } while (!do_ssh1_login(NULL
, 0, 1));
2735 if (ssh_state
== SSH_STATE_CLOSED
) {
2738 return "Session initialisation error";
2741 /* Execute command */
2742 sprintf(buf
, "Sending command: %.100s", cmd
);
2744 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
2749 static SOCKET
ssh_socket(void) { return s
; }
2751 static int ssh_sendok(void) { return ssh_send_ok
; }
2753 Backend ssh_backend
= {