25 #define logevent(s) { logevent(s); \
26 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
27 fprintf(stderr, "%s\n", s); }
29 #define bombout(msg) ( ssh_state == SSH_STATE_CLOSED, closesocket(s), \
30 s = INVALID_SOCKET, connection_fatal msg )
32 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
33 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
34 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
35 #define SSH1_CMSG_USER 4 /* 0x4 */
36 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
37 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
38 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
39 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
40 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
41 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
42 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
43 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
44 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
45 #define SSH1_SMSG_FAILURE 15 /* 0xf */
46 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
47 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
48 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
49 #define SSH1_CMSG_EOF 19 /* 0x13 */
50 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
51 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
52 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
53 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
54 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
55 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
56 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
57 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
58 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
59 #define SSH1_MSG_IGNORE 32 /* 0x20 */
60 #define SSH1_MSG_DEBUG 36 /* 0x24 */
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 SSH_AGENTC_REQUEST_RSA_IDENTITIES 1 /* 0x1 */
72 #define SSH_AGENT_RSA_IDENTITIES_ANSWER 2 /* 0x2 */
73 #define SSH_AGENTC_RSA_CHALLENGE 3 /* 0x3 */
74 #define SSH_AGENT_RSA_RESPONSE 4 /* 0x4 */
75 #define SSH_AGENT_FAILURE 5 /* 0x5 */
76 #define SSH_AGENT_SUCCESS 6 /* 0x6 */
77 #define SSH_AGENTC_ADD_RSA_IDENTITY 7 /* 0x7 */
78 #define SSH_AGENTC_REMOVE_RSA_IDENTITY 8 /* 0x8 */
80 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
81 #define SSH2_MSG_IGNORE 2 /* 0x2 */
82 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
83 #define SSH2_MSG_DEBUG 4 /* 0x4 */
84 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
85 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
86 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
87 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
88 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
89 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
90 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
91 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
92 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
93 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
94 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
95 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
96 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
97 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
98 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
99 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
100 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
101 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
102 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
103 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
104 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
105 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
106 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
107 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
108 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
109 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
111 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
112 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
113 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
114 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
116 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
118 #define GET_32BIT(cp) \
119 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
120 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
121 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
122 ((unsigned long)(unsigned char)(cp)[3]))
124 #define PUT_32BIT(cp, value) { \
125 (cp)[0] = (unsigned char)((value) >> 24); \
126 (cp)[1] = (unsigned char)((value) >> 16); \
127 (cp)[2] = (unsigned char)((value) >> 8); \
128 (cp)[3] = (unsigned char)(value); }
130 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
132 /* Coroutine mechanics for the sillier bits of the code */
133 #define crBegin1 static int crLine = 0;
134 #define crBegin2 switch(crLine) { case 0:;
135 #define crBegin crBegin1; crBegin2;
136 #define crFinish(z) } crLine = 0; return (z)
137 #define crFinishV } crLine = 0; return
138 #define crReturn(z) \
140 crLine=__LINE__; return (z); case __LINE__:;\
144 crLine=__LINE__; return; case __LINE__:;\
146 #define crStop(z) do{ crLine = 0; return (z); }while(0)
147 #define crStopV do{ crLine = 0; return; }while(0)
148 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
149 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
151 extern struct ssh_cipher ssh_3des
;
152 extern struct ssh_cipher ssh_3des_ssh2
;
153 extern struct ssh_cipher ssh_des
;
154 extern struct ssh_cipher ssh_blowfish_ssh1
;
155 extern struct ssh_cipher ssh_blowfish_ssh2
;
158 * Ciphers for SSH2. We miss out single-DES because it isn't
159 * supported; also 3DES and Blowfish are both done differently from
160 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
161 * endianness and different-sized keys.)
163 * The first entry in this array is set up to be whatever the user
164 * asks for as a cipher. Thereafter there is a fixed preference
165 * order of fallback ciphers.
167 struct ssh_cipher
*ciphers
[] = { NULL
, &ssh_blowfish_ssh2
, &ssh_3des_ssh2
};
169 extern struct ssh_kex ssh_diffiehellman
;
170 struct ssh_kex
*kex_algs
[] = { &ssh_diffiehellman
};
172 extern struct ssh_hostkey ssh_dss
;
173 struct ssh_hostkey
*hostkey_algs
[] = { &ssh_dss
};
175 extern struct ssh_mac ssh_sha1
;
177 static SHA_State exhash
;
179 static void nullmac_key(unsigned char *key
) { }
180 static void nullmac_generate(unsigned char *blk
, int len
, unsigned long seq
) { }
181 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
) { return 1; }
182 struct ssh_mac ssh_mac_none
= {
183 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
185 struct ssh_mac
*macs
[] = { &ssh_sha1
, &ssh_mac_none
};
187 struct ssh_compress ssh_comp_none
= {
190 struct ssh_compress
*compressions
[] = { &ssh_comp_none
};
192 static SOCKET s
= INVALID_SOCKET
;
194 static unsigned char session_key
[32];
195 static struct ssh_cipher
*cipher
= NULL
;
196 static struct ssh_cipher
*cscipher
= NULL
;
197 static struct ssh_cipher
*sccipher
= NULL
;
198 static struct ssh_mac
*csmac
= NULL
;
199 static struct ssh_mac
*scmac
= NULL
;
200 static struct ssh_compress
*cscomp
= NULL
;
201 static struct ssh_compress
*sccomp
= NULL
;
202 static struct ssh_kex
*kex
= NULL
;
203 static struct ssh_hostkey
*hostkey
= NULL
;
204 int (*ssh_get_password
)(const char *prompt
, char *str
, int maxlen
) = NULL
;
206 static char *savedhost
;
207 static int ssh_send_ok
;
210 * 2-3-4 tree storing channels.
213 unsigned remoteid
, localid
;
217 struct ssh_agent_channel
{
218 unsigned char *message
;
219 unsigned char msglen
[4];
220 int lensofar
, totallen
;
222 struct ssh2_data_channel
{
223 unsigned char *outbuffer
;
224 unsigned outbuflen
, outbufsize
;
225 unsigned remwindow
, remmaxpkt
;
229 static tree234
*ssh_channels
; /* indexed by local id */
230 static int ssh_channelcmp(void *av
, void *bv
) {
231 struct ssh_channel
*a
= (struct ssh_channel
*)av
;
232 struct ssh_channel
*b
= (struct ssh_channel
*)bv
;
233 if (a
->localid
< b
->localid
) return -1;
234 if (a
->localid
> b
->localid
) return +1;
237 static int ssh_channelfind(void *av
, void *bv
) {
238 unsigned *a
= (unsigned *)av
;
239 struct ssh_channel
*b
= (struct ssh_channel
*)bv
;
240 if (*a
< b
->localid
) return -1;
241 if (*a
> b
->localid
) return +1;
245 static struct ssh_channel
*mainchan
; /* primary session channel */
248 SSH_STATE_BEFORE_SIZE
,
252 } ssh_state
= SSH_STATE_BEFORE_SIZE
;
254 static int size_needed
= FALSE
;
256 static void s_write (char *buf
, int len
) {
258 int i
= send (s
, buf
, len
, 0);
261 bombout(("Lost connection while sending"));
269 static int s_read (char *buf
, int len
) {
272 int i
= recv (s
, buf
, len
, 0);
275 len
-= i
, buf
+= i
, ret
+= i
;
282 static void c_write (char *buf
, int len
) {
283 if ((flags
& FLAG_STDERR
)) {
285 for (i
= 0; i
< len
; i
++)
287 fputc(buf
[i
], stderr
);
303 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
304 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
306 static int ssh_version
;
307 static void (*ssh_protocol
)(unsigned char *in
, int inlen
, int ispkt
);
308 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
309 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
310 static void ssh_size(void);
312 static int (*s_rdpkt
)(unsigned char **data
, int *datalen
);
315 * Collect incoming data in the incoming packet buffer.
316 * Decipher and verify the packet when it is completely read.
317 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
318 * Update the *data and *datalen variables.
319 * Return the additional nr of bytes needed, or 0 when
320 * a complete packet is available.
322 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
324 static long len
, pad
, biglen
, to_read
;
325 static unsigned long realcrc
, gotcrc
;
326 static unsigned char *p
;
336 for (i
= len
= 0; i
< 4; i
++) {
337 while ((*datalen
) == 0)
339 len
= (len
<< 8) + **data
;
340 (*data
)++, (*datalen
)--;
344 if (len
== 0x52656d6f) { /* "Remo"te server has closed ... */
345 len
= 0x300; /* big enough to carry to end */
351 pktin
.length
= len
- 5;
353 if (pktin
.maxlen
< biglen
) {
354 pktin
.maxlen
= biglen
;
355 pktin
.data
= (pktin
.data
== NULL ?
malloc(biglen
+APIEXTRA
) :
356 realloc(pktin
.data
, biglen
+APIEXTRA
));
358 fatalbox("Out of memory");
363 while (to_read
> 0) {
366 while ((*datalen
) == 0)
368 if (chunk
> (*datalen
))
370 memcpy(p
, *data
, chunk
);
378 cipher
->decrypt(pktin
.data
, biglen
);
380 pktin
.type
= pktin
.data
[pad
];
381 pktin
.body
= pktin
.data
+ pad
+ 1;
383 realcrc
= crc32(pktin
.data
, biglen
-4);
384 gotcrc
= GET_32BIT(pktin
.data
+biglen
-4);
385 if (gotcrc
!= realcrc
) {
386 bombout(("Incorrect CRC received on packet"));
390 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
391 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
392 pktin
.type
== SSH1_MSG_DEBUG
||
393 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
394 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
395 long strlen
= GET_32BIT(pktin
.body
);
396 if (strlen
+ 4 != pktin
.length
) {
397 bombout(("Received data packet with bogus string length"));
402 if (pktin
.type
== SSH1_MSG_DEBUG
) {
403 /* log debug message */
405 int strlen
= GET_32BIT(pktin
.body
);
406 strcpy(buf
, "Remote: ");
407 if (strlen
> 70) strlen
= 70;
408 memcpy(buf
+8, pktin
.body
+4, strlen
);
409 buf
[8+strlen
] = '\0';
412 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
420 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
422 static long len
, pad
, payload
, packetlen
, maclen
;
424 static int cipherblk
;
425 static unsigned long incoming_sequence
= 0;
435 cipherblk
= cipher
->blksize
;
441 if (pktin
.maxlen
< cipherblk
) {
442 pktin
.maxlen
= cipherblk
;
443 pktin
.data
= (pktin
.data
== NULL ?
malloc(cipherblk
+APIEXTRA
) :
444 realloc(pktin
.data
, cipherblk
+APIEXTRA
));
446 fatalbox("Out of memory");
450 * Acquire and decrypt the first block of the packet. This will
451 * contain the length and padding details.
453 for (i
= len
= 0; i
< cipherblk
; i
++) {
454 while ((*datalen
) == 0)
455 crReturn(cipherblk
-i
);
456 pktin
.data
[i
] = *(*data
)++;
460 if (!memcmp(pktin
.data
, "Remo", 4)) {/* "Remo"te server has closed ... */
465 sccipher
->decrypt(pktin
.data
, cipherblk
);
468 * Now get the length and padding figures.
470 len
= GET_32BIT(pktin
.data
);
474 * This enables us to deduce the payload length.
476 payload
= len
- pad
- 1;
478 pktin
.length
= payload
+ 5;
481 * So now we can work out the total packet length.
484 maclen
= scmac ? scmac
->len
: 0;
487 * Adjust memory allocation if packet is too big.
489 if (pktin
.maxlen
< packetlen
+maclen
) {
490 pktin
.maxlen
= packetlen
+maclen
;
491 pktin
.data
= (pktin
.data
== NULL ?
malloc(pktin
.maxlen
+APIEXTRA
) :
492 realloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
));
494 fatalbox("Out of memory");
498 * Read and decrypt the remainder of the packet.
500 for (i
= cipherblk
; i
< packetlen
+ maclen
; i
++) {
501 while ((*datalen
) == 0)
502 crReturn(packetlen
+ maclen
- i
);
503 pktin
.data
[i
] = *(*data
)++;
506 /* Decrypt everything _except_ the MAC. */
508 sccipher
->decrypt(pktin
.data
+ cipherblk
, packetlen
- cipherblk
);
511 debug(("Got packet len=%d pad=%d\r\n", len
, pad
));
512 for (i
= 0; i
< packetlen
; i
++)
513 debug((" %02x", (unsigned char)pktin
.data
[i
]));
520 if (scmac
&& !scmac
->verify(pktin
.data
, len
+4, incoming_sequence
)) {
521 bombout(("Incorrect MAC received on packet"));
524 incoming_sequence
++; /* whether or not we MACed */
527 pktin
.type
= pktin
.data
[5];
529 if (pktin
.type
== SSH2_MSG_IGNORE
|| pktin
.type
== SSH2_MSG_DEBUG
)
530 goto next_packet
; /* FIXME: print DEBUG message */
535 static void ssh_gotdata(unsigned char *data
, int datalen
)
537 while (datalen
> 0) {
538 if ( s_rdpkt(&data
, &datalen
) == 0 ) {
539 ssh_protocol(NULL
, 0, 1);
540 if (ssh_state
== SSH_STATE_CLOSED
) {
548 static void s_wrpkt_start(int type
, int len
) {
551 len
+= 5; /* type and CRC */
555 pktout
.length
= len
-5;
556 if (pktout
.maxlen
< biglen
) {
557 pktout
.maxlen
= biglen
;
559 /* Allocate enough buffer space for extra block
560 * for MS CryptEncrypt() */
561 pktout
.data
= (pktout
.data
== NULL ?
malloc(biglen
+12) :
562 realloc(pktout
.data
, biglen
+12));
564 pktout
.data
= (pktout
.data
== NULL ?
malloc(biglen
+4) :
565 realloc(pktout
.data
, biglen
+4));
568 fatalbox("Out of memory");
572 pktout
.body
= pktout
.data
+4+pad
+1;
575 static void s_wrpkt(void) {
576 int pad
, len
, biglen
, i
;
579 len
= pktout
.length
+ 5; /* type and CRC */
583 pktout
.body
[-1] = pktout
.type
;
584 for (i
=0; i
<pad
; i
++)
585 pktout
.data
[i
+4] = random_byte();
586 crc
= crc32(pktout
.data
+4, biglen
-4);
587 PUT_32BIT(pktout
.data
+biglen
, crc
);
588 PUT_32BIT(pktout
.data
, len
);
591 cipher
->encrypt(pktout
.data
+4, biglen
);
593 s_write(pktout
.data
, biglen
+4);
597 * Construct a packet with the specified contents and
598 * send it to the server.
600 static void send_packet(int pkttype
, ...)
603 unsigned char *p
, *argp
, argchar
;
604 unsigned long argint
;
605 int pktlen
, argtype
, arglen
;
609 va_start(args
, pkttype
);
610 while ((argtype
= va_arg(args
, int)) != PKT_END
) {
613 (void) va_arg(args
, int);
617 (void) va_arg(args
, char);
621 (void) va_arg(args
, unsigned char *);
622 arglen
= va_arg(args
, int);
626 argp
= va_arg(args
, unsigned char *);
627 arglen
= strlen(argp
);
628 pktlen
+= 4 + arglen
;
631 bn
= va_arg(args
, Bignum
);
632 pktlen
+= ssh1_bignum_length(bn
);
640 s_wrpkt_start(pkttype
, pktlen
);
643 va_start(args
, pkttype
);
644 while ((argtype
= va_arg(args
, int)) != PKT_END
) {
647 argint
= va_arg(args
, int);
648 PUT_32BIT(p
, argint
);
652 argchar
= va_arg(args
, unsigned char);
657 argp
= va_arg(args
, unsigned char *);
658 arglen
= va_arg(args
, int);
659 memcpy(p
, argp
, arglen
);
663 argp
= va_arg(args
, unsigned char *);
664 arglen
= strlen(argp
);
665 PUT_32BIT(p
, arglen
);
666 memcpy(p
+ 4, argp
, arglen
);
670 bn
= va_arg(args
, Bignum
);
671 p
+= ssh1_write_bignum(p
, bn
);
682 * Connect to specified host and port.
683 * Returns an error message, or NULL on success.
684 * Also places the canonical host name into `realhost'.
686 static char *connect_to_host(char *host
, int port
, char **realhost
)
696 savedhost
= malloc(1+strlen(host
));
698 fatalbox("Out of memory");
699 strcpy(savedhost
, host
);
702 port
= 22; /* default ssh port */
714 if ( (a
= inet_addr(host
)) == (unsigned long) INADDR_NONE
) {
715 if ( (h
= gethostbyname(host
)) == NULL
)
716 switch (WSAGetLastError()) {
717 case WSAENETDOWN
: return "Network is down";
718 case WSAHOST_NOT_FOUND
: case WSANO_DATA
:
719 return "Host does not exist";
720 case WSATRY_AGAIN
: return "Host not found";
721 default: return "gethostbyname: unknown error";
723 memcpy (&a
, h
->h_addr
, sizeof(a
));
724 *realhost
= h
->h_name
;
735 s
= socket(AF_INET
, SOCK_STREAM
, 0);
736 if (s
== INVALID_SOCKET
)
737 switch (WSAGetLastError()) {
738 case WSAENETDOWN
: return "Network is down";
739 case WSAEAFNOSUPPORT
: return "TCP/IP support not present";
740 default: return "socket(): unknown error";
744 * Bind to local address.
746 addr
.sin_family
= AF_INET
;
747 addr
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
748 addr
.sin_port
= htons(0);
749 if (bind (s
, (struct sockaddr
*)&addr
, sizeof(addr
)) == SOCKET_ERROR
)
750 switch (WSAGetLastError()) {
751 case WSAENETDOWN
: return "Network is down";
752 default: return "bind(): unknown error";
756 * Connect to remote address.
758 addr
.sin_addr
.s_addr
= htonl(a
);
759 addr
.sin_port
= htons((short)port
);
760 if (connect (s
, (struct sockaddr
*)&addr
, sizeof(addr
)) == SOCKET_ERROR
)
761 switch (WSAGetLastError()) {
762 case WSAENETDOWN
: return "Network is down";
763 case WSAECONNREFUSED
: return "Connection refused";
764 case WSAENETUNREACH
: return "Network is unreachable";
765 case WSAEHOSTUNREACH
: return "No route to host";
766 default: return "connect(): unknown error";
770 send(s
, "connect ", 8, 0);
771 send(s
, FWhost
, strlen(FWhost
), 0);
774 sprintf(buf
, " %d\n", FWport
);
775 send (s
, buf
, strlen(buf
), 0);
782 static int ssh_versioncmp(char *a
, char *b
) {
784 unsigned long av
, bv
;
786 av
= strtoul(a
, &ae
, 10);
787 bv
= strtoul(b
, &be
, 10);
788 if (av
!= bv
) return (av
< bv ?
-1 : +1);
789 if (*ae
== '.') ae
++;
790 if (*be
== '.') be
++;
791 av
= strtoul(ae
, &ae
, 10);
792 bv
= strtoul(be
, &be
, 10);
793 if (av
!= bv
) return (av
< bv ?
-1 : +1);
799 * Utility routine for putting an SSH-protocol `string' into a SHA
803 void sha_string(SHA_State
*s
, void *str
, int len
) {
804 unsigned char lenblk
[4];
805 PUT_32BIT(lenblk
, len
);
806 SHA_Bytes(s
, lenblk
, 4);
807 SHA_Bytes(s
, str
, len
);
811 * SSH2 packet construction functions.
813 void ssh2_pkt_adddata(void *data
, int len
) {
814 pktout
.length
+= len
;
815 if (pktout
.maxlen
< pktout
.length
) {
816 pktout
.maxlen
= pktout
.length
+ 256;
817 pktout
.data
= (pktout
.data
== NULL ?
malloc(pktout
.maxlen
+APIEXTRA
) :
818 realloc(pktout
.data
, pktout
.maxlen
+APIEXTRA
));
820 fatalbox("Out of memory");
822 memcpy(pktout
.data
+pktout
.length
-len
, data
, len
);
824 void ssh2_pkt_addbyte(unsigned char byte
) {
825 ssh2_pkt_adddata(&byte
, 1);
827 void ssh2_pkt_init(int pkt_type
) {
829 ssh2_pkt_addbyte((unsigned char)pkt_type
);
831 void ssh2_pkt_addbool(unsigned char value
) {
832 ssh2_pkt_adddata(&value
, 1);
834 void ssh2_pkt_adduint32(unsigned long value
) {
837 ssh2_pkt_adddata(x
, 4);
839 void ssh2_pkt_addstring_start(void) {
840 ssh2_pkt_adduint32(0);
841 pktout
.savedpos
= pktout
.length
;
843 void ssh2_pkt_addstring_str(char *data
) {
844 ssh2_pkt_adddata(data
, strlen(data
));
845 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
846 pktout
.length
- pktout
.savedpos
);
848 void ssh2_pkt_addstring_data(char *data
, int len
) {
849 ssh2_pkt_adddata(data
, len
);
850 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
851 pktout
.length
- pktout
.savedpos
);
853 void ssh2_pkt_addstring(char *data
) {
854 ssh2_pkt_addstring_start();
855 ssh2_pkt_addstring_str(data
);
857 char *ssh2_mpint_fmt(Bignum b
, int *len
) {
860 p
= malloc(n
* 2 + 1);
862 fatalbox("out of memory");
864 for (i
= 0; i
< n
; i
++) {
865 p
[i
*2+1] = (b
[n
-i
] >> 8) & 0xFF;
866 p
[i
*2+2] = (b
[n
-i
] ) & 0xFF;
869 while (p
[i
] == 0 && (p
[i
+1] & 0x80) == 0)
871 memmove(p
, p
+i
, n
*2+1-i
);
875 void ssh2_pkt_addmp(Bignum b
) {
878 p
= ssh2_mpint_fmt(b
, &len
);
879 ssh2_pkt_addstring_start();
880 ssh2_pkt_addstring_data(p
, len
);
883 void ssh2_pkt_send(void) {
884 int cipherblk
, maclen
, padding
, i
;
885 static unsigned long outgoing_sequence
= 0;
888 * Add padding. At least four bytes, and must also bring total
889 * length (minus MAC) up to a multiple of the block size.
891 cipherblk
= cipher ? cipher
->blksize
: 8; /* block size */
892 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
894 padding
+= (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
895 pktout
.data
[4] = padding
;
896 for (i
= 0; i
< padding
; i
++)
897 pktout
.data
[pktout
.length
+ i
] = random_byte();
898 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
900 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
902 outgoing_sequence
++; /* whether or not we MACed */
905 debug(("Sending packet len=%d\r\n", pktout
.length
+padding
));
906 for (i
= 0; i
< pktout
.length
+padding
; i
++)
907 debug((" %02x", (unsigned char)pktout
.data
[i
]));
912 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
913 maclen
= csmac ? csmac
->len
: 0;
915 s_write(pktout
.data
, pktout
.length
+ padding
+ maclen
);
919 void bndebug(char *string
, Bignum b
) {
922 p
= ssh2_mpint_fmt(b
, &len
);
923 debug(("%s", string
));
924 for (i
= 0; i
< len
; i
++)
925 debug((" %02x", p
[i
]));
931 void sha_mpint(SHA_State
*s
, Bignum b
) {
934 p
= ssh2_mpint_fmt(b
, &len
);
935 sha_string(s
, p
, len
);
940 * SSH2 packet decode functions.
942 unsigned long ssh2_pkt_getuint32(void) {
944 if (pktin
.length
- pktin
.savedpos
< 4)
945 return 0; /* arrgh, no way to decline (FIXME?) */
946 value
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
950 void ssh2_pkt_getstring(char **p
, int *length
) {
952 if (pktin
.length
- pktin
.savedpos
< 4)
954 *length
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
956 if (pktin
.length
- pktin
.savedpos
< *length
)
958 *p
= pktin
.data
+pktin
.savedpos
;
959 pktin
.savedpos
+= *length
;
961 Bignum
ssh2_pkt_getmp(void) {
966 ssh2_pkt_getstring(&p
, &length
);
970 bombout(("internal error: Can't handle negative mpints"));
973 b
= newbn((length
+1)/2);
974 for (i
= 0; i
< length
; i
++) {
977 b
[j
/2+1] |= ((unsigned char)p
[i
]) << 8;
979 b
[j
/2+1] |= ((unsigned char)p
[i
]);
984 static int do_ssh_init(void) {
988 char vlog
[sizeof(vstring
)+20];
993 while (s_read(&c
, 1) == 1) {
994 if (c
== 'S' && i
< 2) i
++;
995 else if (c
== 'S' && i
== 2) i
= 2;
996 else if (c
== 'H' && i
== 2) break;
1000 if (s_read(&c
,1) != 1 || c
!= 'S') return 0;
1001 if (s_read(&c
,1) != 1 || c
!= 'S') return 0;
1002 if (s_read(&c
,1) != 1 || c
!= 'H') return 0;
1004 strcpy(vstring
, "SSH-");
1006 if (s_read(&c
,1) != 1 || c
!= '-') return 0;
1009 if (s_read(&c
,1) != 1)
1011 if (vsp
< vstring
+sizeof(vstring
)-1)
1017 } else if (i
< sizeof(version
)-1)
1025 sprintf(vlog
, "Server version: %s", vstring
);
1026 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1030 * Server version "1.99" means we can choose whether we use v1
1031 * or v2 protocol. Choice is based on cfg.sshprot.
1033 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1035 * This is a v2 server. Begin v2 protocol.
1037 char *verstring
= "SSH-2.0-PuTTY";
1040 * Hash our version string and their version string.
1042 sha_string(&exhash
, verstring
, strlen(verstring
));
1043 sha_string(&exhash
, vstring
, strcspn(vstring
, "\r\n"));
1044 sprintf(vstring
, "%s\n", verstring
);
1045 sprintf(vlog
, "We claim version: %s", verstring
);
1047 logevent("Using SSH protocol version 2");
1048 s_write(vstring
, strlen(vstring
));
1049 ssh_protocol
= ssh2_protocol
;
1051 s_rdpkt
= ssh2_rdpkt
;
1054 * This is a v1 server. Begin v1 protocol.
1056 sprintf(vstring
, "SSH-%s-PuTTY\n",
1057 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"));
1058 sprintf(vlog
, "We claim version: %s", vstring
);
1059 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1061 logevent("Using SSH protocol version 1");
1062 s_write(vstring
, strlen(vstring
));
1063 ssh_protocol
= ssh1_protocol
;
1065 s_rdpkt
= ssh1_rdpkt
;
1072 * Handle the key exchange and user authentication phases.
1074 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1077 unsigned char *rsabuf
, *keystr1
, *keystr2
;
1078 unsigned char cookie
[8];
1079 struct RSAKey servkey
, hostkey
;
1080 struct MD5Context md5c
;
1081 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1082 static int tried_publickey
;
1083 static unsigned char session_id
[16];
1088 if (!ispkt
) crWaitUntil(ispkt
);
1090 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1091 bombout(("Public key packet not received"));
1095 logevent("Received public keys");
1097 memcpy(cookie
, pktin
.body
, 8);
1099 i
= makekey(pktin
.body
+8, &servkey
, &keystr1
, 0);
1100 j
= makekey(pktin
.body
+8+i
, &hostkey
, &keystr2
, 0);
1103 * Log the host key fingerprint.
1107 logevent("Host key fingerprint is:");
1108 strcpy(logmsg
, " ");
1109 hostkey
.comment
= NULL
;
1110 rsa_fingerprint(logmsg
+strlen(logmsg
), sizeof(logmsg
)-strlen(logmsg
),
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];
1270 static char prompt
[200];
1273 static int pwpkt_type
;
1275 * Show password prompt, having first obtained it via a TIS
1276 * or CryptoCard exchange if we're doing TIS or CryptoCard
1279 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
1280 if (agent_exists()) {
1282 * Attempt RSA authentication using Pageant.
1284 static unsigned char request
[5], *response
, *p
;
1285 static int responselen
;
1286 static int i
, nkeys
;
1287 static int authed
= FALSE
;
1290 logevent("Pageant is running. Requesting keys.");
1292 /* Request the keys held by the agent. */
1293 PUT_32BIT(request
, 1);
1294 request
[4] = SSH_AGENTC_REQUEST_RSA_IDENTITIES
;
1295 agent_query(request
, 5, &r
, &responselen
);
1296 response
= (unsigned char *)r
;
1299 nkeys
= GET_32BIT(p
); p
+= 4;
1300 { char buf
[64]; sprintf(buf
, "Pageant has %d keys", nkeys
);
1302 for (i
= 0; i
< nkeys
; i
++) {
1303 static struct RSAKey key
;
1304 static Bignum challenge
;
1305 static char *commentp
;
1306 static int commentlen
;
1308 { char buf
[64]; sprintf(buf
, "Trying Pageant key #%d", i
);
1311 p
+= ssh1_read_bignum(p
, &key
.exponent
);
1312 p
+= ssh1_read_bignum(p
, &key
.modulus
);
1313 commentlen
= GET_32BIT(p
); p
+= 4;
1314 commentp
= p
; p
+= commentlen
;
1315 send_packet(SSH1_CMSG_AUTH_RSA
,
1316 PKT_BIGNUM
, key
.modulus
, PKT_END
);
1318 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1319 logevent("Key refused");
1322 logevent("Received RSA challenge");
1323 ssh1_read_bignum(pktin
.body
, &challenge
);
1325 char *agentreq
, *q
, *ret
;
1327 len
= 1 + 4; /* message type, bit count */
1328 len
+= ssh1_bignum_length(key
.exponent
);
1329 len
+= ssh1_bignum_length(key
.modulus
);
1330 len
+= ssh1_bignum_length(challenge
);
1331 len
+= 16; /* session id */
1332 len
+= 4; /* response format */
1333 agentreq
= malloc(4 + len
);
1334 PUT_32BIT(agentreq
, len
);
1336 *q
++ = SSH_AGENTC_RSA_CHALLENGE
;
1337 PUT_32BIT(q
, ssh1_bignum_bitcount(key
.modulus
));
1339 q
+= ssh1_write_bignum(q
, key
.exponent
);
1340 q
+= ssh1_write_bignum(q
, key
.modulus
);
1341 q
+= ssh1_write_bignum(q
, challenge
);
1342 memcpy(q
, session_id
, 16); q
+= 16;
1343 PUT_32BIT(q
, 1); /* response format */
1344 agent_query(agentreq
, len
+4, &ret
, &retlen
);
1347 if (ret
[4] == SSH_AGENT_RSA_RESPONSE
) {
1348 logevent("Sending Pageant's response");
1349 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1350 PKT_DATA
, ret
+5, 16, PKT_END
);
1353 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1354 logevent("Pageant's response accepted");
1355 if (flags
& FLAG_VERBOSE
) {
1356 c_write("Authenticated using RSA key \"",
1358 c_write(commentp
, commentlen
);
1359 c_write("\" from agent\r\n", 14);
1363 logevent("Pageant's response not accepted");
1365 logevent("Pageant failed to answer challenge");
1369 logevent("No reply received from Pageant");
1372 freebn(key
.exponent
);
1373 freebn(key
.modulus
);
1382 if (*cfg
.keyfile
&& !tried_publickey
)
1383 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
1385 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1387 (supported_auths_mask
& (1<<SSH1_AUTH_TIS
))) {
1388 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
1389 logevent("Requested TIS authentication");
1390 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
1392 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
1393 logevent("TIS authentication declined");
1394 if (flags
& FLAG_INTERACTIVE
)
1395 c_write("TIS authentication refused.\r\n", 29);
1397 int challengelen
= ((pktin
.body
[0] << 24) |
1398 (pktin
.body
[1] << 16) |
1399 (pktin
.body
[2] << 8) |
1401 logevent("Received TIS challenge");
1402 if (challengelen
> sizeof(prompt
)-1)
1403 challengelen
= sizeof(prompt
)-1; /* prevent overrun */
1404 memcpy(prompt
, pktin
.body
+4, challengelen
);
1405 prompt
[challengelen
] = '\0';
1408 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1410 (supported_auths_mask
& (1<<SSH1_AUTH_CCARD
))) {
1411 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
1412 logevent("Requested CryptoCard authentication");
1413 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
1415 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
1416 logevent("CryptoCard authentication declined");
1417 c_write("CryptoCard authentication refused.\r\n", 29);
1419 int challengelen
= ((pktin
.body
[0] << 24) |
1420 (pktin
.body
[1] << 16) |
1421 (pktin
.body
[2] << 8) |
1423 logevent("Received CryptoCard challenge");
1424 if (challengelen
> sizeof(prompt
)-1)
1425 challengelen
= sizeof(prompt
)-1; /* prevent overrun */
1426 memcpy(prompt
, pktin
.body
+4, challengelen
);
1427 strncpy(prompt
+ challengelen
, "\r\nResponse : ",
1428 sizeof(prompt
)-challengelen
);
1429 prompt
[sizeof(prompt
)-1] = '\0';
1432 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
1433 sprintf(prompt
, "%.90s@%.90s's password: ",
1434 cfg
.username
, savedhost
);
1436 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1437 char *comment
= NULL
;
1438 if (flags
& FLAG_VERBOSE
)
1439 c_write("Trying public key authentication.\r\n", 35);
1440 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
1441 if (flags
& FLAG_VERBOSE
)
1442 c_write("No passphrase required.\r\n", 25);
1445 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
1449 if (!(flags
& FLAG_INTERACTIVE
)) {
1450 if (!ssh_get_password(prompt
, password
, sizeof(password
))) {
1452 * get_password failed to get a password (for
1453 * example because one was supplied on the command
1454 * line which has already failed to work).
1457 logevent("No more passwords to try");
1458 ssh_state
= SSH_STATE_CLOSED
;
1462 c_write(prompt
, strlen(prompt
));
1466 crWaitUntil(!ispkt
);
1467 while (inlen
--) switch (c
= *in
++) {
1484 if (((c
>= ' ' && c
<= '~') ||
1485 ((unsigned char)c
>= 160)) && pos
< sizeof(password
))
1486 password
[pos
++] = c
;
1494 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1496 * Try public key authentication with the specified
1499 static struct RSAKey pubkey
;
1500 static Bignum challenge
, response
;
1502 static unsigned char buffer
[32];
1504 tried_publickey
= 1;
1505 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
1507 c_write("Couldn't load public key from ", 30);
1508 c_write(cfg
.keyfile
, strlen(cfg
.keyfile
));
1509 c_write(".\r\n", 3);
1510 continue; /* go and try password */
1513 c_write("Wrong passphrase.\r\n", 19);
1514 tried_publickey
= 0;
1515 continue; /* try again */
1519 * Send a public key attempt.
1521 send_packet(SSH1_CMSG_AUTH_RSA
,
1522 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
1525 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1526 c_write("Server refused our public key.\r\n", 32);
1527 continue; /* go and try password */
1529 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1530 bombout(("Bizarre response to offer of public key"));
1533 ssh1_read_bignum(pktin
.body
, &challenge
);
1534 response
= rsadecrypt(challenge
, &pubkey
);
1535 freebn(pubkey
.private_exponent
); /* burn the evidence */
1537 for (i
= 0; i
< 32; i
+= 2) {
1538 buffer
[i
] = response
[16-i
/2] >> 8;
1539 buffer
[i
+1] = response
[16-i
/2] & 0xFF;
1543 MD5Update(&md5c
, buffer
, 32);
1544 MD5Update(&md5c
, session_id
, 16);
1545 MD5Final(buffer
, &md5c
);
1547 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1548 PKT_DATA
, buffer
, 16, PKT_END
);
1551 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1552 if (flags
& FLAG_VERBOSE
)
1553 c_write("Failed to authenticate with our public key.\r\n",
1555 continue; /* go and try password */
1556 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1557 bombout(("Bizarre response to RSA authentication response"));
1561 break; /* we're through! */
1563 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
1565 logevent("Sent password");
1566 memset(password
, 0, strlen(password
));
1568 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1569 if (flags
& FLAG_VERBOSE
)
1570 c_write("Access denied\r\n", 15);
1571 logevent("Authentication refused");
1572 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
1573 logevent("Received disconnect request");
1574 ssh_state
= SSH_STATE_CLOSED
;
1576 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1577 bombout(("Strange packet received, type %d", pktin
.type
));
1582 logevent("Authentication successful");
1587 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
) {
1592 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
1595 if (ssh_state
== SSH_STATE_CLOSED
)
1598 if (cfg
.agentfwd
&& agent_exists()) {
1599 logevent("Requesting agent forwarding");
1600 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
1601 do { crReturnV
; } while (!ispkt
);
1602 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
1603 bombout(("Protocol confusion"));
1605 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1606 logevent("Agent forwarding refused");
1608 logevent("Agent forwarding enabled");
1612 send_packet(SSH1_CMSG_REQUEST_PTY
,
1613 PKT_STR
, cfg
.termtype
,
1614 PKT_INT
, rows
, PKT_INT
, cols
,
1615 PKT_INT
, 0, PKT_INT
, 0,
1618 ssh_state
= SSH_STATE_INTERMED
;
1619 do { crReturnV
; } while (!ispkt
);
1620 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
1621 bombout(("Protocol confusion"));
1623 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1624 c_write("Server refused to allocate pty\r\n", 32);
1626 logevent("Allocated pty");
1629 if (*cfg
.remote_cmd
)
1630 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cfg
.remote_cmd
, PKT_END
);
1632 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
1633 logevent("Started session");
1635 ssh_state
= SSH_STATE_SESSION
;
1640 ssh_channels
= newtree234(ssh_channelcmp
);
1645 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
1646 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
1647 long len
= GET_32BIT(pktin
.body
);
1648 c_write(pktin
.body
+4, len
);
1649 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
1650 ssh_state
= SSH_STATE_CLOSED
;
1651 logevent("Received disconnect request");
1652 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
1653 /* Remote side is trying to open a channel to talk to our
1654 * agent. Give them back a local channel number. */
1656 struct ssh_channel
*c
;
1658 for (c
= first234(ssh_channels
, &e
); c
; c
= next234(&e
)) {
1660 break; /* found a free number */
1663 c
= malloc(sizeof(struct ssh_channel
));
1664 c
->remoteid
= GET_32BIT(pktin
.body
);
1667 c
->type
= SSH1_SMSG_AGENT_OPEN
; /* identify channel type */
1668 c
->u
.a
.lensofar
= 0;
1669 add234(ssh_channels
, c
);
1670 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
1671 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
1673 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
1674 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
1675 /* Remote side closes a channel. */
1676 unsigned i
= GET_32BIT(pktin
.body
);
1677 struct ssh_channel
*c
;
1678 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
1681 closetype
= (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
1682 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
, PKT_END
);
1683 c
->closes
|= closetype
;
1684 if (c
->closes
== 3) {
1685 del234(ssh_channels
, c
);
1689 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
1690 /* Data sent down one of our channels. */
1691 int i
= GET_32BIT(pktin
.body
);
1692 int len
= GET_32BIT(pktin
.body
+4);
1693 unsigned char *p
= pktin
.body
+8;
1694 struct ssh_channel
*c
;
1695 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
1698 case SSH1_SMSG_AGENT_OPEN
:
1699 /* Data for an agent message. Buffer it. */
1701 if (c
->u
.a
.lensofar
< 4) {
1702 int l
= min(4 - c
->u
.a
.lensofar
, len
);
1703 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
, l
);
1704 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
1706 if (c
->u
.a
.lensofar
== 4) {
1707 c
->u
.a
.totallen
= 4 + GET_32BIT(c
->u
.a
.msglen
);
1708 c
->u
.a
.message
= malloc(c
->u
.a
.totallen
);
1709 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
1711 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
1712 int l
= min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
, len
);
1713 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
, l
);
1714 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
1716 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
1717 void *reply
, *sentreply
;
1719 agent_query(c
->u
.a
.message
, c
->u
.a
.totallen
,
1724 /* Fake SSH_AGENT_FAILURE. */
1725 sentreply
= "\0\0\0\1\5";
1728 send_packet(SSH1_MSG_CHANNEL_DATA
,
1729 PKT_INT
, c
->remoteid
,
1731 PKT_DATA
, sentreply
, replylen
,
1735 free(c
->u
.a
.message
);
1736 c
->u
.a
.lensofar
= 0;
1742 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1743 /* may be from EXEC_SHELL on some servers */
1744 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1745 /* may be from EXEC_SHELL on some servers
1746 * if no pty is available or in other odd cases. Ignore */
1747 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
1748 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
1750 bombout(("Strange packet received: type %d", pktin
.type
));
1754 send_packet(SSH1_CMSG_STDIN_DATA
,
1755 PKT_INT
, inlen
, PKT_DATA
, in
, inlen
, PKT_END
);
1763 * Utility routine for decoding comma-separated strings in KEXINIT.
1765 int in_commasep_string(char *needle
, char *haystack
, int haylen
) {
1766 int needlen
= strlen(needle
);
1769 * Is it at the start of the string?
1771 if (haylen
>= needlen
&& /* haystack is long enough */
1772 !memcmp(needle
, haystack
, needlen
) && /* initial match */
1773 (haylen
== needlen
|| haystack
[needlen
] == ',')
1774 /* either , or EOS follows */
1778 * If not, search for the next comma and resume after that.
1779 * If no comma found, terminate.
1781 while (haylen
> 0 && *haystack
!= ',')
1782 haylen
--, haystack
++;
1785 haylen
--, haystack
++; /* skip over comma itself */
1790 * SSH2 key creation method.
1792 void ssh2_mkkey(Bignum K
, char *H
, char chr
, char *keyspace
) {
1794 /* First 20 bytes. */
1797 SHA_Bytes(&s
, H
, 20);
1798 SHA_Bytes(&s
, &chr
, 1);
1799 SHA_Bytes(&s
, H
, 20);
1800 SHA_Final(&s
, keyspace
);
1801 /* Next 20 bytes. */
1804 SHA_Bytes(&s
, H
, 20);
1805 SHA_Bytes(&s
, keyspace
, 20);
1806 SHA_Final(&s
, keyspace
+20);
1810 * Handle the SSH2 transport layer.
1812 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
1816 static Bignum e
, f
, K
;
1817 static struct ssh_cipher
*cscipher_tobe
= NULL
;
1818 static struct ssh_cipher
*sccipher_tobe
= NULL
;
1819 static struct ssh_mac
*csmac_tobe
= NULL
;
1820 static struct ssh_mac
*scmac_tobe
= NULL
;
1821 static struct ssh_compress
*cscomp_tobe
= NULL
;
1822 static struct ssh_compress
*sccomp_tobe
= NULL
;
1823 static char *hostkeydata
, *sigdata
, *keystr
;
1824 static int hostkeylen
, siglen
;
1825 static unsigned char exchange_hash
[20];
1826 static unsigned char keyspace
[40];
1832 * Set up the preferred cipher.
1834 if (cfg
.cipher
== CIPHER_BLOWFISH
) {
1835 ciphers
[0] = &ssh_blowfish_ssh2
;
1836 } else if (cfg
.cipher
== CIPHER_DES
) {
1837 logevent("Single DES not supported in SSH2; using 3DES");
1838 ciphers
[0] = &ssh_3des_ssh2
;
1839 } else if (cfg
.cipher
== CIPHER_3DES
) {
1840 ciphers
[0] = &ssh_3des_ssh2
;
1842 /* Shouldn't happen, but we do want to initialise to _something_. */
1843 ciphers
[0] = &ssh_3des_ssh2
;
1848 * Construct and send our key exchange packet.
1850 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
1851 for (i
= 0; i
< 16; i
++)
1852 ssh2_pkt_addbyte((unsigned char)random_byte());
1853 /* List key exchange algorithms. */
1854 ssh2_pkt_addstring_start();
1855 for (i
= 0; i
< lenof(kex_algs
); i
++) {
1856 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
1857 if (i
< lenof(kex_algs
)-1)
1858 ssh2_pkt_addstring_str(",");
1860 /* List server host key algorithms. */
1861 ssh2_pkt_addstring_start();
1862 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
1863 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
1864 if (i
< lenof(hostkey_algs
)-1)
1865 ssh2_pkt_addstring_str(",");
1867 /* List client->server encryption algorithms. */
1868 ssh2_pkt_addstring_start();
1869 for (i
= 0; i
< lenof(ciphers
); i
++) {
1870 ssh2_pkt_addstring_str(ciphers
[i
]->name
);
1871 if (i
< lenof(ciphers
)-1)
1872 ssh2_pkt_addstring_str(",");
1874 /* List server->client encryption algorithms. */
1875 ssh2_pkt_addstring_start();
1876 for (i
= 0; i
< lenof(ciphers
); i
++) {
1877 ssh2_pkt_addstring_str(ciphers
[i
]->name
);
1878 if (i
< lenof(ciphers
)-1)
1879 ssh2_pkt_addstring_str(",");
1881 /* List client->server MAC algorithms. */
1882 ssh2_pkt_addstring_start();
1883 for (i
= 0; i
< lenof(macs
); i
++) {
1884 ssh2_pkt_addstring_str(macs
[i
]->name
);
1885 if (i
< lenof(macs
)-1)
1886 ssh2_pkt_addstring_str(",");
1888 /* List server->client MAC algorithms. */
1889 ssh2_pkt_addstring_start();
1890 for (i
= 0; i
< lenof(macs
); i
++) {
1891 ssh2_pkt_addstring_str(macs
[i
]->name
);
1892 if (i
< lenof(macs
)-1)
1893 ssh2_pkt_addstring_str(",");
1895 /* List client->server compression algorithms. */
1896 ssh2_pkt_addstring_start();
1897 for (i
= 0; i
< lenof(compressions
); i
++) {
1898 ssh2_pkt_addstring_str(compressions
[i
]->name
);
1899 if (i
< lenof(compressions
)-1)
1900 ssh2_pkt_addstring_str(",");
1902 /* List server->client compression algorithms. */
1903 ssh2_pkt_addstring_start();
1904 for (i
= 0; i
< lenof(compressions
); i
++) {
1905 ssh2_pkt_addstring_str(compressions
[i
]->name
);
1906 if (i
< lenof(compressions
)-1)
1907 ssh2_pkt_addstring_str(",");
1909 /* List client->server languages. Empty list. */
1910 ssh2_pkt_addstring_start();
1911 /* List server->client languages. Empty list. */
1912 ssh2_pkt_addstring_start();
1913 /* First KEX packet does _not_ follow, because we're not that brave. */
1914 ssh2_pkt_addbool(FALSE
);
1916 ssh2_pkt_adduint32(0);
1917 sha_string(&exhash
, pktout
.data
+5, pktout
.length
-5);
1920 if (!ispkt
) crWaitUntil(ispkt
);
1921 sha_string(&exhash
, pktin
.data
+5, pktin
.length
-5);
1924 * Now examine the other side's KEXINIT to see what we're up
1927 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
1928 bombout(("expected key exchange packet from server"));
1931 kex
= NULL
; hostkey
= NULL
; cscipher_tobe
= NULL
; sccipher_tobe
= NULL
;
1932 csmac_tobe
= NULL
; scmac_tobe
= NULL
; cscomp_tobe
= NULL
; sccomp_tobe
= NULL
;
1933 pktin
.savedpos
+= 16; /* skip garbage cookie */
1934 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
1935 for (i
= 0; i
< lenof(kex_algs
); i
++) {
1936 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
1941 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
1942 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
1943 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
1944 hostkey
= hostkey_algs
[i
];
1948 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
1949 for (i
= 0; i
< lenof(ciphers
); i
++) {
1950 if (in_commasep_string(ciphers
[i
]->name
, str
, len
)) {
1951 cscipher_tobe
= ciphers
[i
];
1955 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
1956 for (i
= 0; i
< lenof(ciphers
); i
++) {
1957 if (in_commasep_string(ciphers
[i
]->name
, str
, len
)) {
1958 sccipher_tobe
= ciphers
[i
];
1962 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
1963 for (i
= 0; i
< lenof(macs
); i
++) {
1964 if (in_commasep_string(macs
[i
]->name
, str
, len
)) {
1965 csmac_tobe
= macs
[i
];
1969 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
1970 for (i
= 0; i
< lenof(macs
); i
++) {
1971 if (in_commasep_string(macs
[i
]->name
, str
, len
)) {
1972 scmac_tobe
= macs
[i
];
1976 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
1977 for (i
= 0; i
< lenof(compressions
); i
++) {
1978 if (in_commasep_string(compressions
[i
]->name
, str
, len
)) {
1979 cscomp_tobe
= compressions
[i
];
1983 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
1984 for (i
= 0; i
< lenof(compressions
); i
++) {
1985 if (in_commasep_string(compressions
[i
]->name
, str
, len
)) {
1986 sccomp_tobe
= compressions
[i
];
1992 * Currently we only support Diffie-Hellman and DSS, so let's
1993 * bomb out if those aren't selected.
1995 if (kex
!= &ssh_diffiehellman
|| hostkey
!= &ssh_dss
) {
1996 bombout(("internal fault: chaos in SSH 2 transport layer"));
2001 * Now we begin the fun. Generate and send e for Diffie-Hellman.
2004 ssh2_pkt_init(SSH2_MSG_KEXDH_INIT
);
2009 if (pktin
.type
!= SSH2_MSG_KEXDH_REPLY
) {
2010 bombout(("expected key exchange packet from server"));
2013 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
2014 f
= ssh2_pkt_getmp();
2015 ssh2_pkt_getstring(&sigdata
, &siglen
);
2019 sha_string(&exhash
, hostkeydata
, hostkeylen
);
2020 sha_mpint(&exhash
, e
);
2021 sha_mpint(&exhash
, f
);
2022 sha_mpint(&exhash
, K
);
2023 SHA_Final(&exhash
, exchange_hash
);
2026 debug(("Exchange hash is:\r\n"));
2027 for (i
= 0; i
< 20; i
++)
2028 debug((" %02x", exchange_hash
[i
]));
2032 hostkey
->setkey(hostkeydata
, hostkeylen
);
2033 if (!hostkey
->verifysig(sigdata
, siglen
, exchange_hash
, 20)) {
2034 bombout(("Server failed host key check"));
2039 * Expect SSH2_MSG_NEWKEYS from server.
2042 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
2043 bombout(("expected new-keys packet from server"));
2048 * Authenticate remote host: verify host key. (We've already
2049 * checked the signature of the exchange hash.)
2051 keystr
= hostkey
->fmtkey();
2052 verify_ssh_host_key(savedhost
, keystr
);
2056 * Send SSH2_MSG_NEWKEYS.
2058 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
2062 * Create and initialise session keys.
2064 cscipher
= cscipher_tobe
;
2065 sccipher
= sccipher_tobe
;
2068 cscomp
= cscomp_tobe
;
2069 sccomp
= sccomp_tobe
;
2071 * Set IVs after keys.
2073 ssh2_mkkey(K
, exchange_hash
, 'C', keyspace
); cscipher
->setcskey(keyspace
);
2074 ssh2_mkkey(K
, exchange_hash
, 'D', keyspace
); cscipher
->setsckey(keyspace
);
2075 ssh2_mkkey(K
, exchange_hash
, 'A', keyspace
); cscipher
->setcsiv(keyspace
);
2076 ssh2_mkkey(K
, exchange_hash
, 'B', keyspace
); sccipher
->setsciv(keyspace
);
2077 ssh2_mkkey(K
, exchange_hash
, 'E', keyspace
); csmac
->setcskey(keyspace
);
2078 ssh2_mkkey(K
, exchange_hash
, 'F', keyspace
); scmac
->setsckey(keyspace
);
2081 * Now we're encrypting. Begin returning 1 to the protocol main
2082 * function so that other things can run on top of the
2083 * transport. If we ever see a KEXINIT, we must go back to the
2088 } while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
));
2089 goto begin_key_exchange
;
2095 * Handle the SSH2 userauth and connection layers.
2097 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
2099 static unsigned long remote_winsize
;
2100 static unsigned long remote_maxpkt
;
2105 * Request userauth protocol, and await a response to it.
2107 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
2108 ssh2_pkt_addstring("ssh-userauth");
2110 crWaitUntilV(ispkt
);
2111 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
2112 bombout(("Server refused user authentication protocol"));
2117 * FIXME: currently we support only password authentication.
2118 * (This places us technically in violation of the SSH2 spec.
2119 * We must fix this.)
2123 * Get a username and a password.
2125 static char username
[100];
2126 static char password
[100];
2130 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
2131 c_write("login as: ", 10);
2134 crWaitUntilV(!ispkt
);
2135 while (inlen
--) switch (c
= *in
++) {
2142 c_write("\b \b", 3);
2148 c_write("\b \b", 3);
2157 if (((c
>= ' ' && c
<= '~') ||
2158 ((unsigned char)c
>= 160)) && pos
< 40) {
2159 username
[pos
++] = c
;
2166 username
[strcspn(username
, "\n\r")] = '\0';
2169 strncpy(username
, cfg
.username
, 99);
2170 username
[99] = '\0';
2171 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
2172 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
2173 c_write(stuff
, strlen(stuff
));
2177 if (!(flags
& FLAG_INTERACTIVE
)) {
2179 sprintf(prompt
, "%s@%s's password: ", cfg
.username
, savedhost
);
2180 if (!ssh_get_password(prompt
, password
, sizeof(password
))) {
2182 * get_password failed to get a password (for
2183 * example because one was supplied on the command
2184 * line which has already failed to work).
2187 logevent("No more passwords to try");
2188 ssh_state
= SSH_STATE_CLOSED
;
2192 c_write("password: ", 10);
2197 crWaitUntilV(!ispkt
);
2198 while (inlen
--) switch (c
= *in
++) {
2215 if (((c
>= ' ' && c
<= '~') ||
2216 ((unsigned char)c
>= 160)) && pos
< 40)
2217 password
[pos
++] = c
;
2224 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
2225 ssh2_pkt_addstring(username
);
2226 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2227 ssh2_pkt_addstring("password");
2228 ssh2_pkt_addbool(FALSE
);
2229 ssh2_pkt_addstring(password
);
2232 crWaitUntilV(ispkt
);
2233 if (pktin
.type
!= SSH2_MSG_USERAUTH_SUCCESS
) {
2234 c_write("Access denied\r\n", 15);
2235 logevent("Authentication refused");
2241 * Now we're authenticated for the connection protocol. The
2242 * connection protocol will automatically have started at this
2243 * point; there's no need to send SERVICE_REQUEST.
2247 * So now create a channel with a session in it.
2249 mainchan
= malloc(sizeof(struct ssh_channel
));
2250 mainchan
->localid
= 100; /* as good as any */
2251 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
2252 ssh2_pkt_addstring("session");
2253 ssh2_pkt_adduint32(mainchan
->localid
);
2254 ssh2_pkt_adduint32(0x7FFFFFFFUL
); /* our window size */
2255 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
2257 crWaitUntilV(ispkt
);
2258 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
2259 bombout(("Server refused to open a session"));
2261 /* FIXME: error data comes back in FAILURE packet */
2263 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
2264 bombout(("Server's channel confirmation cited wrong channel"));
2267 mainchan
->remoteid
= ssh2_pkt_getuint32();
2268 mainchan
->u
.v2
.remwindow
= ssh2_pkt_getuint32();
2269 mainchan
->u
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
2270 mainchan
->u
.v2
.outbuffer
= NULL
;
2271 mainchan
->u
.v2
.outbuflen
= mainchan
->u
.v2
.outbufsize
= 0;
2272 logevent("Opened channel for session");
2275 * Now allocate a pty for the session.
2278 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
2279 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
2280 ssh2_pkt_addstring("pty-req");
2281 ssh2_pkt_addbool(1); /* want reply */
2282 ssh2_pkt_addstring(cfg
.termtype
);
2283 ssh2_pkt_adduint32(cols
);
2284 ssh2_pkt_adduint32(rows
);
2285 ssh2_pkt_adduint32(0); /* pixel width */
2286 ssh2_pkt_adduint32(0); /* pixel height */
2287 ssh2_pkt_addstring_start();
2288 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
2292 crWaitUntilV(ispkt
);
2293 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
2294 /* FIXME: be able to handle other channels here */
2295 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2296 continue; /* wrong channel */
2297 mainchan
->u
.v2
.remwindow
+= ssh2_pkt_getuint32();
2299 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
2301 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
2302 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
2303 bombout(("Server got confused by pty request"));
2306 c_write("Server refused to allocate pty\r\n", 32);
2308 logevent("Allocated pty");
2313 * Start a shell or a remote command.
2315 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
2316 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
2317 if (*cfg
.remote_cmd
) {
2318 ssh2_pkt_addstring("exec");
2319 ssh2_pkt_addbool(1); /* want reply */
2320 ssh2_pkt_addstring(cfg
.remote_cmd
);
2322 ssh2_pkt_addstring("shell");
2323 ssh2_pkt_addbool(1); /* want reply */
2327 crWaitUntilV(ispkt
);
2328 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
2329 /* FIXME: be able to handle other channels here */
2330 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2331 continue; /* wrong channel */
2332 mainchan
->u
.v2
.remwindow
+= ssh2_pkt_getuint32();
2334 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
2335 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
2336 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
2337 bombout(("Server got confused by shell/command request"));
2340 bombout(("Server refused to start a shell/command"));
2343 logevent("Started a shell/command");
2352 static int try_send
;
2356 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
2357 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
2360 /* FIXME: be able to handle other channels here */
2361 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2362 continue; /* wrong channel */
2363 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
2364 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
2365 continue; /* extended but not stderr */
2366 ssh2_pkt_getstring(&data
, &length
);
2368 c_write(data
, length
);
2370 * Enlarge the window again at the remote side,
2371 * just in case it ever runs down and they fail
2372 * to send us any more data.
2374 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
2375 ssh2_pkt_adduint32(mainchan
->remoteid
);
2376 ssh2_pkt_adduint32(length
);
2379 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
2380 ssh_state
= SSH_STATE_CLOSED
;
2381 logevent("Received disconnect message");
2382 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
2383 continue; /* exit status et al; ignore (FIXME?) */
2384 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
2385 continue; /* remote sends EOF; ignore */
2386 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
2387 /* FIXME: be able to handle other channels here */
2388 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2389 continue; /* wrong channel */
2390 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2391 ssh2_pkt_adduint32(mainchan
->remoteid
);
2393 /* FIXME: mark the channel as closed */
2394 if (1 /* FIXME: "all channels are closed" */) {
2395 logevent("All channels closed. Disconnecting");
2396 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
2399 continue; /* remote sends close; ignore (FIXME) */
2400 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
2401 /* FIXME: be able to handle other channels here */
2402 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2403 continue; /* wrong channel */
2404 mainchan
->u
.v2
.remwindow
+= ssh2_pkt_getuint32();
2407 bombout(("Strange packet received: type %d", pktin
.type
));
2412 * We have spare data. Add it to the channel buffer.
2414 if (mainchan
->u
.v2
.outbufsize
<
2415 mainchan
->u
.v2
.outbuflen
+ inlen
) {
2416 mainchan
->u
.v2
.outbufsize
=
2417 mainchan
->u
.v2
.outbuflen
+ inlen
+ 1024;
2418 mainchan
->u
.v2
.outbuffer
= srealloc(mainchan
->u
.v2
.outbuffer
,
2419 mainchan
->u
.v2
.outbufsize
);
2421 memcpy(mainchan
->u
.v2
.outbuffer
+ mainchan
->u
.v2
.outbuflen
,
2423 mainchan
->u
.v2
.outbuflen
+= inlen
;
2428 * Try to send data on the channel if we can. (FIXME:
2429 * on _all_ channels.)
2431 while (mainchan
->u
.v2
.remwindow
> 0 &&
2432 mainchan
->u
.v2
.outbuflen
> 0) {
2433 unsigned len
= mainchan
->u
.v2
.remwindow
;
2434 if (len
> mainchan
->u
.v2
.outbuflen
)
2435 len
= mainchan
->u
.v2
.outbuflen
;
2436 if (len
> mainchan
->u
.v2
.remmaxpkt
)
2437 len
= mainchan
->u
.v2
.remmaxpkt
;
2438 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
2439 ssh2_pkt_adduint32(mainchan
->remoteid
);
2440 ssh2_pkt_addstring_start();
2441 ssh2_pkt_addstring_data(mainchan
->u
.v2
.outbuffer
, len
);
2443 mainchan
->u
.v2
.outbuflen
-= len
;
2444 memmove(mainchan
->u
.v2
.outbuffer
, mainchan
->u
.v2
.outbuffer
+len
,
2445 mainchan
->u
.v2
.outbuflen
);
2446 mainchan
->u
.v2
.remwindow
-= len
;
2455 * Handle the top-level SSH2 protocol.
2457 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
2459 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
2461 do_ssh2_authconn(in
, inlen
, ispkt
);
2465 * Called to set up the connection. Will arrange for WM_NETEVENT
2466 * messages to be passed to the specified window, whose window
2467 * procedure should then call telnet_msg().
2469 * Returns an error message, or NULL on success.
2471 static char *ssh_init (HWND hwnd
, char *host
, int port
, char **realhost
) {
2475 if(crypto_startup() == 0)
2476 return "Microsoft high encryption pack not installed!";
2479 p
= connect_to_host(host
, port
, realhost
);
2484 return "Protocol initialisation error";
2486 if (hwnd
&& WSAAsyncSelect (s
, hwnd
, WM_NETEVENT
, FD_READ
| FD_CLOSE
) == SOCKET_ERROR
)
2487 switch (WSAGetLastError()) {
2488 case WSAENETDOWN
: return "Network is down";
2489 default: return "WSAAsyncSelect(): unknown error";
2496 * Process a WM_NETEVENT message. Will return 0 if the connection
2497 * has closed, or <0 for a socket error.
2499 static int ssh_msg (WPARAM wParam
, LPARAM lParam
) {
2504 * Because reading less than the whole of the available pending
2505 * data can generate an FD_READ event, we need to allow for the
2506 * possibility that FD_READ may arrive with FD_CLOSE already in
2507 * the queue; so it's possible that we can get here even with s
2508 * invalid. If so, we return 1 and don't worry about it.
2510 if (s
== INVALID_SOCKET
)
2513 if (WSAGETSELECTERROR(lParam
) != 0) {
2516 return -WSAGETSELECTERROR(lParam
);
2519 switch (WSAGETSELECTEVENT(lParam
)) {
2522 ret
= recv(s
, buf
, sizeof(buf
), 0);
2523 if (ret
< 0 && WSAGetLastError() == WSAEWOULDBLOCK
)
2525 if (ret
< 0) { /* any _other_ error */
2528 return -10000-WSAGetLastError();
2534 ssh_gotdata (buf
, ret
);
2535 if (ssh_state
== SSH_STATE_CLOSED
) {
2542 return 1; /* shouldn't happen, but WTF */
2546 * Called to send data down the Telnet connection.
2548 static void ssh_send (char *buf
, int len
) {
2549 if (s
== INVALID_SOCKET
)
2552 ssh_protocol(buf
, len
, 0);
2556 * Called to set the size of the window from Telnet's POV.
2558 static void ssh_size(void) {
2559 switch (ssh_state
) {
2560 case SSH_STATE_BEFORE_SIZE
:
2561 case SSH_STATE_CLOSED
:
2562 break; /* do nothing */
2563 case SSH_STATE_INTERMED
:
2564 size_needed
= TRUE
; /* buffer for later */
2566 case SSH_STATE_SESSION
:
2568 send_packet(SSH1_CMSG_WINDOW_SIZE
,
2569 PKT_INT
, rows
, PKT_INT
, cols
,
2570 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
2576 * Send Telnet special codes. TS_EOF is useful for `plink', so you
2577 * can send an EOF and collect resulting output (e.g. `plink
2580 static void ssh_special (Telnet_Special code
) {
2581 if (code
== TS_EOF
) {
2582 if (ssh_version
== 1) {
2583 send_packet(SSH1_CMSG_EOF
, PKT_END
);
2585 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
2586 ssh2_pkt_adduint32(mainchan
->remoteid
);
2589 logevent("Sent EOF message");
2597 * Read and decrypt one incoming SSH packet.
2598 * (only used by pSCP)
2600 static void get_packet(void)
2602 unsigned char buf
[4096], *p
;
2609 while ((to_read
= s_rdpkt(&p
, &len
)) > 0) {
2610 if (to_read
> sizeof(buf
)) to_read
= sizeof(buf
);
2611 len
= s_read(buf
, to_read
);
2612 if (len
!= to_read
) {
2624 * Receive a block of data over the SSH link. Block until
2625 * all data is available. Return nr of bytes read (0 if lost connection).
2626 * (only used by pSCP)
2628 int ssh_scp_recv(unsigned char *buf
, int len
)
2630 static int pending_input_len
= 0;
2631 static unsigned char *pending_input_ptr
;
2634 if (pending_input_len
>= to_read
) {
2635 memcpy(buf
, pending_input_ptr
, to_read
);
2636 pending_input_ptr
+= to_read
;
2637 pending_input_len
-= to_read
;
2641 if (pending_input_len
> 0) {
2642 memcpy(buf
, pending_input_ptr
, pending_input_len
);
2643 buf
+= pending_input_len
;
2644 to_read
-= pending_input_len
;
2645 pending_input_len
= 0;
2648 if (s
== INVALID_SOCKET
)
2650 while (to_read
> 0) {
2652 if (s
== INVALID_SOCKET
)
2654 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
) {
2655 int plen
= GET_32BIT(pktin
.body
);
2656 if (plen
<= to_read
) {
2657 memcpy(buf
, pktin
.body
+ 4, plen
);
2661 memcpy(buf
, pktin
.body
+ 4, to_read
);
2662 pending_input_len
= plen
- to_read
;
2663 pending_input_ptr
= pktin
.body
+ 4 + to_read
;
2666 } else if (pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
2667 int plen
= GET_32BIT(pktin
.body
);
2668 fwrite(pktin
.body
+ 4, plen
, 1, stderr
);
2669 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2670 logevent("Received disconnect request");
2671 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
||
2672 pktin
.type
== SSH1_SMSG_FAILURE
) {
2674 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
2676 sprintf(logbuf
, "Remote exit status: %d", GET_32BIT(pktin
.body
));
2678 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
2679 logevent("Closing connection");
2683 bombout(("Strange packet received: type %d", pktin
.type
));
2692 * Send a block of data over the SSH link.
2693 * Block until all data is sent.
2694 * (only used by pSCP)
2696 void ssh_scp_send(unsigned char *buf
, int len
)
2698 if (s
== INVALID_SOCKET
)
2700 send_packet(SSH1_CMSG_STDIN_DATA
,
2701 PKT_INT
, len
, PKT_DATA
, buf
, len
, PKT_END
);
2705 * Send an EOF notification to the server.
2706 * (only used by pSCP)
2708 void ssh_scp_send_eof(void)
2710 if (s
== INVALID_SOCKET
)
2712 send_packet(SSH1_CMSG_EOF
, PKT_END
);
2716 * Set up the connection, login on the remote host and
2717 * start execution of a command.
2718 * Returns an error message, or NULL on success.
2719 * (only used by pSCP)
2721 char *ssh_scp_init(char *host
, int port
, char *cmd
, char **realhost
)
2726 if (crypto_startup() == 0)
2727 return "Microsoft high encryption pack not installed!";
2730 p
= connect_to_host(host
, port
, realhost
);
2737 return "Protocol initialisation error";
2739 /* Exchange keys and login */
2742 if (s
== INVALID_SOCKET
)
2743 return "Connection closed by remote host";
2744 } while (!do_ssh1_login(NULL
, 0, 1));
2746 if (ssh_state
== SSH_STATE_CLOSED
) {
2749 return "Session initialisation error";
2752 /* Execute command */
2753 sprintf(buf
, "Sending command: %.100s", cmd
);
2755 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
2760 static SOCKET
ssh_socket(void) { return s
; }
2762 static int ssh_sendok(void) { return ssh_send_ok
; }
2764 Backend ssh_backend
= {