24 #define logevent(s) { logevent(s); \
25 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
26 fprintf(stderr, "%s\n", s); }
28 #define bombout(msg) ( ssh_state == SSH_STATE_CLOSED, closesocket(s), \
29 s = INVALID_SOCKET, connection_fatal msg )
31 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
32 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
33 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
34 #define SSH1_CMSG_USER 4 /* 0x4 */
35 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
36 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
37 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
38 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
39 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
40 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
41 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
42 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
43 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
44 #define SSH1_SMSG_FAILURE 15 /* 0xf */
45 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
46 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
47 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
48 #define SSH1_CMSG_EOF 19 /* 0x13 */
49 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
50 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
51 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
52 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
53 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
54 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
55 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
56 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
57 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
58 #define SSH1_MSG_IGNORE 32 /* 0x20 */
59 #define SSH1_MSG_DEBUG 36 /* 0x24 */
60 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
61 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
62 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
63 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
64 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
65 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
67 #define SSH1_AUTH_TIS 5 /* 0x5 */
68 #define SSH1_AUTH_CCARD 16 /* 0x10 */
70 #define SSH_AGENTC_REQUEST_RSA_IDENTITIES 1 /* 0x1 */
71 #define SSH_AGENT_RSA_IDENTITIES_ANSWER 2 /* 0x2 */
72 #define SSH_AGENTC_RSA_CHALLENGE 3 /* 0x3 */
73 #define SSH_AGENT_RSA_RESPONSE 4 /* 0x4 */
74 #define SSH_AGENT_FAILURE 5 /* 0x5 */
75 #define SSH_AGENT_SUCCESS 6 /* 0x6 */
76 #define SSH_AGENTC_ADD_RSA_IDENTITY 7 /* 0x7 */
77 #define SSH_AGENTC_REMOVE_RSA_IDENTITY 8 /* 0x8 */
79 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
80 #define SSH2_MSG_IGNORE 2 /* 0x2 */
81 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
82 #define SSH2_MSG_DEBUG 4 /* 0x4 */
83 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
84 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
85 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
86 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
87 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
88 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
89 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
90 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
91 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
92 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
93 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
94 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
95 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
96 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
97 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
98 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
99 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
100 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
101 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
102 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
103 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
104 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
105 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
106 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
107 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
108 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
110 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
111 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
112 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
113 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
115 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
117 #define GET_32BIT(cp) \
118 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
119 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
120 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
121 ((unsigned long)(unsigned char)(cp)[3]))
123 #define PUT_32BIT(cp, value) { \
124 (cp)[0] = (unsigned char)((value) >> 24); \
125 (cp)[1] = (unsigned char)((value) >> 16); \
126 (cp)[2] = (unsigned char)((value) >> 8); \
127 (cp)[3] = (unsigned char)(value); }
129 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
131 /* Coroutine mechanics for the sillier bits of the code */
132 #define crBegin1 static int crLine = 0;
133 #define crBegin2 switch(crLine) { case 0:;
134 #define crBegin crBegin1; crBegin2;
135 #define crFinish(z) } crLine = 0; return (z)
136 #define crFinishV } crLine = 0; return
137 #define crReturn(z) \
139 crLine=__LINE__; return (z); case __LINE__:;\
143 crLine=__LINE__; return; case __LINE__:;\
145 #define crStop(z) do{ crLine = 0; return (z); }while(0)
146 #define crStopV do{ crLine = 0; return; }while(0)
147 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
148 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
150 extern struct ssh_cipher ssh_3des
;
151 extern struct ssh_cipher ssh_3des_ssh2
;
152 extern struct ssh_cipher ssh_des
;
153 extern struct ssh_cipher ssh_blowfish_ssh1
;
154 extern struct ssh_cipher ssh_blowfish_ssh2
;
157 * Ciphers for SSH2. We miss out single-DES because it isn't
158 * supported; also 3DES and Blowfish are both done differently from
159 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
160 * endianness and different-sized keys.)
162 * The first entry in this array is set up to be whatever the user
163 * asks for as a cipher. Thereafter there is a fixed preference
164 * order of fallback ciphers.
166 struct ssh_cipher
*ciphers
[] = { NULL
, &ssh_blowfish_ssh2
, &ssh_3des_ssh2
};
168 extern struct ssh_kex ssh_diffiehellman
;
169 struct ssh_kex
*kex_algs
[] = { &ssh_diffiehellman
};
171 extern struct ssh_hostkey ssh_dss
;
172 struct ssh_hostkey
*hostkey_algs
[] = { &ssh_dss
};
174 extern struct ssh_mac ssh_sha1
;
176 static SHA_State exhash
;
178 static void nullmac_key(unsigned char *key
) { }
179 static void nullmac_generate(unsigned char *blk
, int len
, unsigned long seq
) { }
180 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
) { return 1; }
181 struct ssh_mac ssh_mac_none
= {
182 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
184 struct ssh_mac
*macs
[] = { &ssh_sha1
, &ssh_mac_none
};
186 struct ssh_compress ssh_comp_none
= {
189 struct ssh_compress
*compressions
[] = { &ssh_comp_none
};
191 static SOCKET s
= INVALID_SOCKET
;
193 static unsigned char session_key
[32];
194 static struct ssh_cipher
*cipher
= NULL
;
195 static struct ssh_cipher
*cscipher
= NULL
;
196 static struct ssh_cipher
*sccipher
= NULL
;
197 static struct ssh_mac
*csmac
= NULL
;
198 static struct ssh_mac
*scmac
= NULL
;
199 static struct ssh_compress
*cscomp
= NULL
;
200 static struct ssh_compress
*sccomp
= NULL
;
201 static struct ssh_kex
*kex
= NULL
;
202 static struct ssh_hostkey
*hostkey
= NULL
;
203 int (*ssh_get_password
)(const char *prompt
, char *str
, int maxlen
) = NULL
;
205 static char *savedhost
;
206 static int ssh_send_ok
;
209 * 2-3-4 tree storing channels.
212 unsigned remoteid
, localid
;
216 struct ssh_agent_channel
{
217 unsigned char *message
;
218 unsigned char msglen
[4];
219 int lensofar
, totallen
;
221 struct ssh2_data_channel
{
222 unsigned char *outbuffer
;
223 unsigned outbuflen
, outbufsize
;
224 unsigned remwindow
, remmaxpkt
;
228 static tree234
*ssh_channels
; /* indexed by local id */
229 static int ssh_channelcmp(void *av
, void *bv
) {
230 struct ssh_channel
*a
= (struct ssh_channel
*)av
;
231 struct ssh_channel
*b
= (struct ssh_channel
*)bv
;
232 if (a
->localid
< b
->localid
) return -1;
233 if (a
->localid
> b
->localid
) return +1;
236 static int ssh_channelfind(void *av
, void *bv
) {
237 unsigned *a
= (unsigned *)av
;
238 struct ssh_channel
*b
= (struct ssh_channel
*)bv
;
239 if (*a
< b
->localid
) return -1;
240 if (*a
> b
->localid
) return +1;
244 static struct ssh_channel
*mainchan
; /* primary session channel */
247 SSH_STATE_BEFORE_SIZE
,
251 } ssh_state
= SSH_STATE_BEFORE_SIZE
;
253 static int size_needed
= FALSE
;
255 static void s_write (char *buf
, int len
) {
257 int i
= send (s
, buf
, len
, 0);
260 bombout(("Lost connection while sending"));
268 static int s_read (char *buf
, int len
) {
271 int i
= recv (s
, buf
, len
, 0);
274 len
-= i
, buf
+= i
, ret
+= i
;
281 static void c_write (char *buf
, int len
) {
282 if ((flags
& FLAG_STDERR
)) {
284 for (i
= 0; i
< len
; i
++)
286 fputc(buf
[i
], stderr
);
293 static void c_writedata (char *buf
, int len
) {
307 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
308 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
310 static int ssh_version
;
311 static void (*ssh_protocol
)(unsigned char *in
, int inlen
, int ispkt
);
312 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
313 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
314 static void ssh_size(void);
316 static int (*s_rdpkt
)(unsigned char **data
, int *datalen
);
319 * Collect incoming data in the incoming packet buffer.
320 * Decipher and verify the packet when it is completely read.
321 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
322 * Update the *data and *datalen variables.
323 * Return the additional nr of bytes needed, or 0 when
324 * a complete packet is available.
326 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
328 static long len
, pad
, biglen
, to_read
;
329 static unsigned long realcrc
, gotcrc
;
330 static unsigned char *p
;
340 for (i
= len
= 0; i
< 4; i
++) {
341 while ((*datalen
) == 0)
343 len
= (len
<< 8) + **data
;
344 (*data
)++, (*datalen
)--;
348 if (len
== 0x52656d6f) { /* "Remo"te server has closed ... */
349 len
= 0x300; /* big enough to carry to end */
355 pktin
.length
= len
- 5;
357 if (pktin
.maxlen
< biglen
) {
358 pktin
.maxlen
= biglen
;
359 pktin
.data
= (pktin
.data
== NULL ?
malloc(biglen
+APIEXTRA
) :
360 realloc(pktin
.data
, biglen
+APIEXTRA
));
362 fatalbox("Out of memory");
367 while (to_read
> 0) {
370 while ((*datalen
) == 0)
372 if (chunk
> (*datalen
))
374 memcpy(p
, *data
, chunk
);
382 cipher
->decrypt(pktin
.data
, biglen
);
384 pktin
.type
= pktin
.data
[pad
];
385 pktin
.body
= pktin
.data
+ pad
+ 1;
387 realcrc
= crc32(pktin
.data
, biglen
-4);
388 gotcrc
= GET_32BIT(pktin
.data
+biglen
-4);
389 if (gotcrc
!= realcrc
) {
390 bombout(("Incorrect CRC received on packet"));
394 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
395 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
396 pktin
.type
== SSH1_MSG_DEBUG
||
397 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
398 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
399 long strlen
= GET_32BIT(pktin
.body
);
400 if (strlen
+ 4 != pktin
.length
) {
401 bombout(("Received data packet with bogus string length"));
406 if (pktin
.type
== SSH1_MSG_DEBUG
) {
407 /* log debug message */
409 int strlen
= GET_32BIT(pktin
.body
);
410 strcpy(buf
, "Remote: ");
411 if (strlen
> 70) strlen
= 70;
412 memcpy(buf
+8, pktin
.body
+4, strlen
);
413 buf
[8+strlen
] = '\0';
416 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
424 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
426 static long len
, pad
, payload
, packetlen
, maclen
;
428 static int cipherblk
;
429 static unsigned long incoming_sequence
= 0;
439 cipherblk
= cipher
->blksize
;
445 if (pktin
.maxlen
< cipherblk
) {
446 pktin
.maxlen
= cipherblk
;
447 pktin
.data
= (pktin
.data
== NULL ?
malloc(cipherblk
+APIEXTRA
) :
448 realloc(pktin
.data
, cipherblk
+APIEXTRA
));
450 fatalbox("Out of memory");
454 * Acquire and decrypt the first block of the packet. This will
455 * contain the length and padding details.
457 for (i
= len
= 0; i
< cipherblk
; i
++) {
458 while ((*datalen
) == 0)
459 crReturn(cipherblk
-i
);
460 pktin
.data
[i
] = *(*data
)++;
464 if (!memcmp(pktin
.data
, "Remo", 4)) {/* "Remo"te server has closed ... */
469 sccipher
->decrypt(pktin
.data
, cipherblk
);
472 * Now get the length and padding figures.
474 len
= GET_32BIT(pktin
.data
);
478 * This enables us to deduce the payload length.
480 payload
= len
- pad
- 1;
482 pktin
.length
= payload
+ 5;
485 * So now we can work out the total packet length.
488 maclen
= scmac ? scmac
->len
: 0;
491 * Adjust memory allocation if packet is too big.
493 if (pktin
.maxlen
< packetlen
+maclen
) {
494 pktin
.maxlen
= packetlen
+maclen
;
495 pktin
.data
= (pktin
.data
== NULL ?
malloc(pktin
.maxlen
+APIEXTRA
) :
496 realloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
));
498 fatalbox("Out of memory");
502 * Read and decrypt the remainder of the packet.
504 for (i
= cipherblk
; i
< packetlen
+ maclen
; i
++) {
505 while ((*datalen
) == 0)
506 crReturn(packetlen
+ maclen
- i
);
507 pktin
.data
[i
] = *(*data
)++;
510 /* Decrypt everything _except_ the MAC. */
512 sccipher
->decrypt(pktin
.data
+ cipherblk
, packetlen
- cipherblk
);
515 debug(("Got packet len=%d pad=%d\r\n", len
, pad
));
516 for (i
= 0; i
< packetlen
; i
++)
517 debug((" %02x", (unsigned char)pktin
.data
[i
]));
524 if (scmac
&& !scmac
->verify(pktin
.data
, len
+4, incoming_sequence
)) {
525 bombout(("Incorrect MAC received on packet"));
528 incoming_sequence
++; /* whether or not we MACed */
531 pktin
.type
= pktin
.data
[5];
533 if (pktin
.type
== SSH2_MSG_IGNORE
|| pktin
.type
== SSH2_MSG_DEBUG
)
534 goto next_packet
; /* FIXME: print DEBUG message */
539 static void ssh_gotdata(unsigned char *data
, int datalen
)
541 while (datalen
> 0) {
542 if ( s_rdpkt(&data
, &datalen
) == 0 ) {
543 ssh_protocol(NULL
, 0, 1);
544 if (ssh_state
== SSH_STATE_CLOSED
) {
552 static void s_wrpkt_start(int type
, int len
) {
555 len
+= 5; /* type and CRC */
559 pktout
.length
= len
-5;
560 if (pktout
.maxlen
< biglen
) {
561 pktout
.maxlen
= biglen
;
563 /* Allocate enough buffer space for extra block
564 * for MS CryptEncrypt() */
565 pktout
.data
= (pktout
.data
== NULL ?
malloc(biglen
+12) :
566 realloc(pktout
.data
, biglen
+12));
568 pktout
.data
= (pktout
.data
== NULL ?
malloc(biglen
+4) :
569 realloc(pktout
.data
, biglen
+4));
572 fatalbox("Out of memory");
576 pktout
.body
= pktout
.data
+4+pad
+1;
579 static void s_wrpkt(void) {
580 int pad
, len
, biglen
, i
;
583 len
= pktout
.length
+ 5; /* type and CRC */
587 pktout
.body
[-1] = pktout
.type
;
588 for (i
=0; i
<pad
; i
++)
589 pktout
.data
[i
+4] = random_byte();
590 crc
= crc32(pktout
.data
+4, biglen
-4);
591 PUT_32BIT(pktout
.data
+biglen
, crc
);
592 PUT_32BIT(pktout
.data
, len
);
595 cipher
->encrypt(pktout
.data
+4, biglen
);
597 s_write(pktout
.data
, biglen
+4);
601 * Construct a packet with the specified contents and
602 * send it to the server.
604 static void send_packet(int pkttype
, ...)
607 unsigned char *p
, *argp
, argchar
;
608 unsigned long argint
;
609 int pktlen
, argtype
, arglen
;
613 va_start(args
, pkttype
);
614 while ((argtype
= va_arg(args
, int)) != PKT_END
) {
617 (void) va_arg(args
, int);
621 (void) va_arg(args
, char);
625 (void) va_arg(args
, unsigned char *);
626 arglen
= va_arg(args
, int);
630 argp
= va_arg(args
, unsigned char *);
631 arglen
= strlen(argp
);
632 pktlen
+= 4 + arglen
;
635 bn
= va_arg(args
, Bignum
);
636 pktlen
+= ssh1_bignum_length(bn
);
644 s_wrpkt_start(pkttype
, pktlen
);
647 va_start(args
, pkttype
);
648 while ((argtype
= va_arg(args
, int)) != PKT_END
) {
651 argint
= va_arg(args
, int);
652 PUT_32BIT(p
, argint
);
656 argchar
= va_arg(args
, unsigned char);
661 argp
= va_arg(args
, unsigned char *);
662 arglen
= va_arg(args
, int);
663 memcpy(p
, argp
, arglen
);
667 argp
= va_arg(args
, unsigned char *);
668 arglen
= strlen(argp
);
669 PUT_32BIT(p
, arglen
);
670 memcpy(p
+ 4, argp
, arglen
);
674 bn
= va_arg(args
, Bignum
);
675 p
+= ssh1_write_bignum(p
, bn
);
686 * Connect to specified host and port.
687 * Returns an error message, or NULL on success.
688 * Also places the canonical host name into `realhost'.
690 static char *connect_to_host(char *host
, int port
, char **realhost
)
700 savedhost
= malloc(1+strlen(host
));
702 fatalbox("Out of memory");
703 strcpy(savedhost
, host
);
706 port
= 22; /* default ssh port */
718 if ( (a
= inet_addr(host
)) == (unsigned long) INADDR_NONE
) {
719 if ( (h
= gethostbyname(host
)) == NULL
)
720 switch (WSAGetLastError()) {
721 case WSAENETDOWN
: return "Network is down";
722 case WSAHOST_NOT_FOUND
: case WSANO_DATA
:
723 return "Host does not exist";
724 case WSATRY_AGAIN
: return "Host not found";
725 default: return "gethostbyname: unknown error";
727 memcpy (&a
, h
->h_addr
, sizeof(a
));
728 *realhost
= h
->h_name
;
739 s
= socket(AF_INET
, SOCK_STREAM
, 0);
740 if (s
== INVALID_SOCKET
)
741 switch (WSAGetLastError()) {
742 case WSAENETDOWN
: return "Network is down";
743 case WSAEAFNOSUPPORT
: return "TCP/IP support not present";
744 default: return "socket(): unknown error";
748 * Bind to local address.
750 addr
.sin_family
= AF_INET
;
751 addr
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
752 addr
.sin_port
= htons(0);
753 if (bind (s
, (struct sockaddr
*)&addr
, sizeof(addr
)) == SOCKET_ERROR
)
754 switch (WSAGetLastError()) {
755 case WSAENETDOWN
: return "Network is down";
756 default: return "bind(): unknown error";
760 * Connect to remote address.
762 addr
.sin_addr
.s_addr
= htonl(a
);
763 addr
.sin_port
= htons((short)port
);
764 if (connect (s
, (struct sockaddr
*)&addr
, sizeof(addr
)) == SOCKET_ERROR
)
765 switch (WSAGetLastError()) {
766 case WSAENETDOWN
: return "Network is down";
767 case WSAECONNREFUSED
: return "Connection refused";
768 case WSAENETUNREACH
: return "Network is unreachable";
769 case WSAEHOSTUNREACH
: return "No route to host";
770 default: return "connect(): unknown error";
774 send(s
, "connect ", 8, 0);
775 send(s
, FWhost
, strlen(FWhost
), 0);
778 sprintf(buf
, " %d\n", FWport
);
779 send (s
, buf
, strlen(buf
), 0);
786 static int ssh_versioncmp(char *a
, char *b
) {
788 unsigned long av
, bv
;
790 av
= strtoul(a
, &ae
, 10);
791 bv
= strtoul(b
, &be
, 10);
792 if (av
!= bv
) return (av
< bv ?
-1 : +1);
793 if (*ae
== '.') ae
++;
794 if (*be
== '.') be
++;
795 av
= strtoul(ae
, &ae
, 10);
796 bv
= strtoul(be
, &be
, 10);
797 if (av
!= bv
) return (av
< bv ?
-1 : +1);
803 * Utility routine for putting an SSH-protocol `string' into a SHA
807 void sha_string(SHA_State
*s
, void *str
, int len
) {
808 unsigned char lenblk
[4];
809 PUT_32BIT(lenblk
, len
);
810 SHA_Bytes(s
, lenblk
, 4);
811 SHA_Bytes(s
, str
, len
);
815 * SSH2 packet construction functions.
817 void ssh2_pkt_adddata(void *data
, int len
) {
818 pktout
.length
+= len
;
819 if (pktout
.maxlen
< pktout
.length
) {
820 pktout
.maxlen
= pktout
.length
+ 256;
821 pktout
.data
= (pktout
.data
== NULL ?
malloc(pktout
.maxlen
+APIEXTRA
) :
822 realloc(pktout
.data
, pktout
.maxlen
+APIEXTRA
));
824 fatalbox("Out of memory");
826 memcpy(pktout
.data
+pktout
.length
-len
, data
, len
);
828 void ssh2_pkt_addbyte(unsigned char byte
) {
829 ssh2_pkt_adddata(&byte
, 1);
831 void ssh2_pkt_init(int pkt_type
) {
833 ssh2_pkt_addbyte((unsigned char)pkt_type
);
835 void ssh2_pkt_addbool(unsigned char value
) {
836 ssh2_pkt_adddata(&value
, 1);
838 void ssh2_pkt_adduint32(unsigned long value
) {
841 ssh2_pkt_adddata(x
, 4);
843 void ssh2_pkt_addstring_start(void) {
844 ssh2_pkt_adduint32(0);
845 pktout
.savedpos
= pktout
.length
;
847 void ssh2_pkt_addstring_str(char *data
) {
848 ssh2_pkt_adddata(data
, strlen(data
));
849 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
850 pktout
.length
- pktout
.savedpos
);
852 void ssh2_pkt_addstring_data(char *data
, int len
) {
853 ssh2_pkt_adddata(data
, len
);
854 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
855 pktout
.length
- pktout
.savedpos
);
857 void ssh2_pkt_addstring(char *data
) {
858 ssh2_pkt_addstring_start();
859 ssh2_pkt_addstring_str(data
);
861 char *ssh2_mpint_fmt(Bignum b
, int *len
) {
864 p
= malloc(n
* 2 + 1);
866 fatalbox("out of memory");
868 for (i
= 0; i
< n
; i
++) {
869 p
[i
*2+1] = (b
[n
-i
] >> 8) & 0xFF;
870 p
[i
*2+2] = (b
[n
-i
] ) & 0xFF;
873 while (p
[i
] == 0 && (p
[i
+1] & 0x80) == 0)
875 memmove(p
, p
+i
, n
*2+1-i
);
879 void ssh2_pkt_addmp(Bignum b
) {
882 p
= ssh2_mpint_fmt(b
, &len
);
883 ssh2_pkt_addstring_start();
884 ssh2_pkt_addstring_data(p
, len
);
887 void ssh2_pkt_send(void) {
888 int cipherblk
, maclen
, padding
, i
;
889 static unsigned long outgoing_sequence
= 0;
892 * Add padding. At least four bytes, and must also bring total
893 * length (minus MAC) up to a multiple of the block size.
895 cipherblk
= cipher ? cipher
->blksize
: 8; /* block size */
896 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
898 padding
+= (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
899 pktout
.data
[4] = padding
;
900 for (i
= 0; i
< padding
; i
++)
901 pktout
.data
[pktout
.length
+ i
] = random_byte();
902 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
904 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
906 outgoing_sequence
++; /* whether or not we MACed */
909 debug(("Sending packet len=%d\r\n", pktout
.length
+padding
));
910 for (i
= 0; i
< pktout
.length
+padding
; i
++)
911 debug((" %02x", (unsigned char)pktout
.data
[i
]));
916 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
917 maclen
= csmac ? csmac
->len
: 0;
919 s_write(pktout
.data
, pktout
.length
+ padding
+ maclen
);
923 void bndebug(char *string
, Bignum b
) {
926 p
= ssh2_mpint_fmt(b
, &len
);
927 debug(("%s", string
));
928 for (i
= 0; i
< len
; i
++)
929 debug((" %02x", p
[i
]));
935 void sha_mpint(SHA_State
*s
, Bignum b
) {
938 p
= ssh2_mpint_fmt(b
, &len
);
939 sha_string(s
, p
, len
);
944 * SSH2 packet decode functions.
946 unsigned long ssh2_pkt_getuint32(void) {
948 if (pktin
.length
- pktin
.savedpos
< 4)
949 return 0; /* arrgh, no way to decline (FIXME?) */
950 value
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
954 void ssh2_pkt_getstring(char **p
, int *length
) {
956 if (pktin
.length
- pktin
.savedpos
< 4)
958 *length
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
960 if (pktin
.length
- pktin
.savedpos
< *length
)
962 *p
= pktin
.data
+pktin
.savedpos
;
963 pktin
.savedpos
+= *length
;
965 Bignum
ssh2_pkt_getmp(void) {
970 ssh2_pkt_getstring(&p
, &length
);
974 bombout(("internal error: Can't handle negative mpints"));
977 b
= newbn((length
+1)/2);
978 for (i
= 0; i
< length
; i
++) {
981 b
[j
/2+1] |= ((unsigned char)p
[i
]) << 8;
983 b
[j
/2+1] |= ((unsigned char)p
[i
]);
988 static int do_ssh_init(void) {
992 char vlog
[sizeof(vstring
)+20];
997 while (s_read(&c
, 1) == 1) {
998 if (c
== 'S' && i
< 2) i
++;
999 else if (c
== 'S' && i
== 2) i
= 2;
1000 else if (c
== 'H' && i
== 2) break;
1004 if (s_read(&c
,1) != 1 || c
!= 'S') return 0;
1005 if (s_read(&c
,1) != 1 || c
!= 'S') return 0;
1006 if (s_read(&c
,1) != 1 || c
!= 'H') return 0;
1008 strcpy(vstring
, "SSH-");
1010 if (s_read(&c
,1) != 1 || c
!= '-') return 0;
1013 if (s_read(&c
,1) != 1)
1015 if (vsp
< vstring
+sizeof(vstring
)-1)
1021 } else if (i
< sizeof(version
)-1)
1029 sprintf(vlog
, "Server version: %s", vstring
);
1030 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1034 * Server version "1.99" means we can choose whether we use v1
1035 * or v2 protocol. Choice is based on cfg.sshprot.
1037 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1039 * This is a v2 server. Begin v2 protocol.
1041 char *verstring
= "SSH-2.0-PuTTY";
1044 * Hash our version string and their version string.
1046 sha_string(&exhash
, verstring
, strlen(verstring
));
1047 sha_string(&exhash
, vstring
, strcspn(vstring
, "\r\n"));
1048 sprintf(vstring
, "%s\n", verstring
);
1049 sprintf(vlog
, "We claim version: %s", verstring
);
1051 logevent("Using SSH protocol version 2");
1052 s_write(vstring
, strlen(vstring
));
1053 ssh_protocol
= ssh2_protocol
;
1055 s_rdpkt
= ssh2_rdpkt
;
1058 * This is a v1 server. Begin v1 protocol.
1060 sprintf(vstring
, "SSH-%s-PuTTY\n",
1061 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"));
1062 sprintf(vlog
, "We claim version: %s", vstring
);
1063 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1065 logevent("Using SSH protocol version 1");
1066 s_write(vstring
, strlen(vstring
));
1067 ssh_protocol
= ssh1_protocol
;
1069 s_rdpkt
= ssh1_rdpkt
;
1076 * Handle the key exchange and user authentication phases.
1078 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1081 unsigned char *rsabuf
, *keystr1
, *keystr2
;
1082 unsigned char cookie
[8];
1083 struct RSAKey servkey
, hostkey
;
1084 struct MD5Context md5c
;
1085 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1086 static int tried_publickey
;
1087 static unsigned char session_id
[16];
1092 if (!ispkt
) crWaitUntil(ispkt
);
1094 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1095 bombout(("Public key packet not received"));
1099 logevent("Received public keys");
1101 memcpy(cookie
, pktin
.body
, 8);
1103 i
= makekey(pktin
.body
+8, &servkey
, &keystr1
, 0);
1104 j
= makekey(pktin
.body
+8+i
, &hostkey
, &keystr2
, 0);
1107 * Log the host key fingerprint.
1111 logevent("Host key fingerprint is:");
1112 strcpy(logmsg
, " ");
1113 hostkey
.comment
= NULL
;
1114 rsa_fingerprint(logmsg
+strlen(logmsg
), sizeof(logmsg
)-strlen(logmsg
),
1119 supported_ciphers_mask
= GET_32BIT(pktin
.body
+12+i
+j
);
1120 supported_auths_mask
= GET_32BIT(pktin
.body
+16+i
+j
);
1123 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1124 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1125 MD5Update(&md5c
, pktin
.body
, 8);
1126 MD5Final(session_id
, &md5c
);
1128 for (i
=0; i
<32; i
++)
1129 session_key
[i
] = random_byte();
1131 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1133 rsabuf
= malloc(len
);
1135 fatalbox("Out of memory");
1138 * Verify the host key.
1142 * First format the key into a string.
1144 int len
= rsastr_len(&hostkey
);
1145 char fingerprint
[100];
1146 char *keystr
= malloc(len
);
1148 fatalbox("Out of memory");
1149 rsastr_fmt(keystr
, &hostkey
);
1150 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
1151 verify_ssh_host_key(savedhost
, "rsa", keystr
, fingerprint
);
1155 for (i
=0; i
<32; i
++) {
1156 rsabuf
[i
] = session_key
[i
];
1158 rsabuf
[i
] ^= session_id
[i
];
1161 if (hostkey
.bytes
> servkey
.bytes
) {
1162 rsaencrypt(rsabuf
, 32, &servkey
);
1163 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1165 rsaencrypt(rsabuf
, 32, &hostkey
);
1166 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1169 logevent("Encrypted session key");
1171 cipher_type
= cfg
.cipher
== CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH
:
1172 cfg
.cipher
== CIPHER_DES ? SSH_CIPHER_DES
:
1174 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1175 c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
1176 cipher_type
= SSH_CIPHER_3DES
;
1178 switch (cipher_type
) {
1179 case SSH_CIPHER_3DES
: logevent("Using 3DES encryption"); break;
1180 case SSH_CIPHER_DES
: logevent("Using single-DES encryption"); break;
1181 case SSH_CIPHER_BLOWFISH
: logevent("Using Blowfish encryption"); break;
1184 send_packet(SSH1_CMSG_SESSION_KEY
,
1185 PKT_CHAR
, cipher_type
,
1186 PKT_DATA
, cookie
, 8,
1187 PKT_CHAR
, (len
*8) >> 8, PKT_CHAR
, (len
*8) & 0xFF,
1188 PKT_DATA
, rsabuf
, len
,
1192 logevent("Trying to enable encryption...");
1196 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
1197 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
1199 cipher
->sesskey(session_key
);
1203 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1204 bombout(("Encryption not successfully enabled"));
1208 logevent("Successfully started encryption");
1212 static char username
[100];
1215 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
1216 c_write("login as: ", 10);
1219 crWaitUntil(!ispkt
);
1220 while (inlen
--) switch (c
= *in
++) {
1227 c_write("\b \b", 3);
1233 c_write("\b \b", 3);
1242 if (((c
>= ' ' && c
<= '~') ||
1243 ((unsigned char)c
>= 160)) && pos
< 40) {
1244 username
[pos
++] = c
;
1251 username
[strcspn(username
, "\n\r")] = '\0';
1254 strncpy(username
, cfg
.username
, 99);
1255 username
[99] = '\0';
1256 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
1257 sprintf(stuff
, "Sent username \"%s\".\r\n", username
);
1258 c_write(stuff
, strlen(stuff
));
1262 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
1264 char userlog
[20+sizeof(username
)];
1265 sprintf(userlog
, "Sent username \"%s\"", username
);
1272 tried_publickey
= 0;
1274 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
1275 static char password
[100];
1276 static char prompt
[200];
1279 static int pwpkt_type
;
1281 * Show password prompt, having first obtained it via a TIS
1282 * or CryptoCard exchange if we're doing TIS or CryptoCard
1285 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
1286 if (agent_exists()) {
1288 * Attempt RSA authentication using Pageant.
1290 static unsigned char request
[5], *response
, *p
;
1291 static int responselen
;
1292 static int i
, nkeys
;
1293 static int authed
= FALSE
;
1296 logevent("Pageant is running. Requesting keys.");
1298 /* Request the keys held by the agent. */
1299 PUT_32BIT(request
, 1);
1300 request
[4] = SSH_AGENTC_REQUEST_RSA_IDENTITIES
;
1301 agent_query(request
, 5, &r
, &responselen
);
1302 response
= (unsigned char *)r
;
1305 nkeys
= GET_32BIT(p
); p
+= 4;
1306 { char buf
[64]; sprintf(buf
, "Pageant has %d keys", nkeys
);
1308 for (i
= 0; i
< nkeys
; i
++) {
1309 static struct RSAKey key
;
1310 static Bignum challenge
;
1311 static char *commentp
;
1312 static int commentlen
;
1314 { char buf
[64]; sprintf(buf
, "Trying Pageant key #%d", i
);
1317 p
+= ssh1_read_bignum(p
, &key
.exponent
);
1318 p
+= ssh1_read_bignum(p
, &key
.modulus
);
1319 commentlen
= GET_32BIT(p
); p
+= 4;
1320 commentp
= p
; p
+= commentlen
;
1321 send_packet(SSH1_CMSG_AUTH_RSA
,
1322 PKT_BIGNUM
, key
.modulus
, PKT_END
);
1324 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1325 logevent("Key refused");
1328 logevent("Received RSA challenge");
1329 ssh1_read_bignum(pktin
.body
, &challenge
);
1331 char *agentreq
, *q
, *ret
;
1333 len
= 1 + 4; /* message type, bit count */
1334 len
+= ssh1_bignum_length(key
.exponent
);
1335 len
+= ssh1_bignum_length(key
.modulus
);
1336 len
+= ssh1_bignum_length(challenge
);
1337 len
+= 16; /* session id */
1338 len
+= 4; /* response format */
1339 agentreq
= malloc(4 + len
);
1340 PUT_32BIT(agentreq
, len
);
1342 *q
++ = SSH_AGENTC_RSA_CHALLENGE
;
1343 PUT_32BIT(q
, ssh1_bignum_bitcount(key
.modulus
));
1345 q
+= ssh1_write_bignum(q
, key
.exponent
);
1346 q
+= ssh1_write_bignum(q
, key
.modulus
);
1347 q
+= ssh1_write_bignum(q
, challenge
);
1348 memcpy(q
, session_id
, 16); q
+= 16;
1349 PUT_32BIT(q
, 1); /* response format */
1350 agent_query(agentreq
, len
+4, &ret
, &retlen
);
1353 if (ret
[4] == SSH_AGENT_RSA_RESPONSE
) {
1354 logevent("Sending Pageant's response");
1355 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1356 PKT_DATA
, ret
+5, 16, PKT_END
);
1359 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1360 logevent("Pageant's response accepted");
1361 if (flags
& FLAG_VERBOSE
) {
1362 c_write("Authenticated using RSA key \"",
1364 c_write(commentp
, commentlen
);
1365 c_write("\" from agent\r\n", 14);
1369 logevent("Pageant's response not accepted");
1371 logevent("Pageant failed to answer challenge");
1375 logevent("No reply received from Pageant");
1378 freebn(key
.exponent
);
1379 freebn(key
.modulus
);
1388 if (*cfg
.keyfile
&& !tried_publickey
)
1389 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
1391 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1393 (supported_auths_mask
& (1<<SSH1_AUTH_TIS
))) {
1394 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
1395 logevent("Requested TIS authentication");
1396 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
1398 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
1399 logevent("TIS authentication declined");
1400 if (flags
& FLAG_INTERACTIVE
)
1401 c_write("TIS authentication refused.\r\n", 29);
1403 int challengelen
= ((pktin
.body
[0] << 24) |
1404 (pktin
.body
[1] << 16) |
1405 (pktin
.body
[2] << 8) |
1407 logevent("Received TIS challenge");
1408 if (challengelen
> sizeof(prompt
)-1)
1409 challengelen
= sizeof(prompt
)-1; /* prevent overrun */
1410 memcpy(prompt
, pktin
.body
+4, challengelen
);
1411 prompt
[challengelen
] = '\0';
1414 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1416 (supported_auths_mask
& (1<<SSH1_AUTH_CCARD
))) {
1417 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
1418 logevent("Requested CryptoCard authentication");
1419 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
1421 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
1422 logevent("CryptoCard authentication declined");
1423 c_write("CryptoCard authentication refused.\r\n", 29);
1425 int challengelen
= ((pktin
.body
[0] << 24) |
1426 (pktin
.body
[1] << 16) |
1427 (pktin
.body
[2] << 8) |
1429 logevent("Received CryptoCard challenge");
1430 if (challengelen
> sizeof(prompt
)-1)
1431 challengelen
= sizeof(prompt
)-1; /* prevent overrun */
1432 memcpy(prompt
, pktin
.body
+4, challengelen
);
1433 strncpy(prompt
+ challengelen
, "\r\nResponse : ",
1434 sizeof(prompt
)-challengelen
);
1435 prompt
[sizeof(prompt
)-1] = '\0';
1438 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
1439 sprintf(prompt
, "%.90s@%.90s's password: ",
1440 cfg
.username
, savedhost
);
1442 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1443 char *comment
= NULL
;
1444 if (flags
& FLAG_VERBOSE
)
1445 c_write("Trying public key authentication.\r\n", 35);
1446 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
1447 if (flags
& FLAG_VERBOSE
)
1448 c_write("No passphrase required.\r\n", 25);
1451 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
1455 if (!(flags
& FLAG_INTERACTIVE
)) {
1456 if (!ssh_get_password(prompt
, password
, sizeof(password
))) {
1458 * get_password failed to get a password (for
1459 * example because one was supplied on the command
1460 * line which has already failed to work).
1463 logevent("No more passwords to try");
1464 ssh_state
= SSH_STATE_CLOSED
;
1468 c_write(prompt
, strlen(prompt
));
1472 crWaitUntil(!ispkt
);
1473 while (inlen
--) switch (c
= *in
++) {
1490 if (((c
>= ' ' && c
<= '~') ||
1491 ((unsigned char)c
>= 160)) && pos
< sizeof(password
))
1492 password
[pos
++] = c
;
1500 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1502 * Try public key authentication with the specified
1505 static struct RSAKey pubkey
;
1506 static Bignum challenge
, response
;
1508 static unsigned char buffer
[32];
1510 tried_publickey
= 1;
1511 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
1513 c_write("Couldn't load public key from ", 30);
1514 c_write(cfg
.keyfile
, strlen(cfg
.keyfile
));
1515 c_write(".\r\n", 3);
1516 continue; /* go and try password */
1519 c_write("Wrong passphrase.\r\n", 19);
1520 tried_publickey
= 0;
1521 continue; /* try again */
1525 * Send a public key attempt.
1527 send_packet(SSH1_CMSG_AUTH_RSA
,
1528 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
1531 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1532 c_write("Server refused our public key.\r\n", 32);
1533 continue; /* go and try password */
1535 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1536 bombout(("Bizarre response to offer of public key"));
1539 ssh1_read_bignum(pktin
.body
, &challenge
);
1540 response
= rsadecrypt(challenge
, &pubkey
);
1541 freebn(pubkey
.private_exponent
); /* burn the evidence */
1543 for (i
= 0; i
< 32; i
+= 2) {
1544 buffer
[i
] = response
[16-i
/2] >> 8;
1545 buffer
[i
+1] = response
[16-i
/2] & 0xFF;
1549 MD5Update(&md5c
, buffer
, 32);
1550 MD5Update(&md5c
, session_id
, 16);
1551 MD5Final(buffer
, &md5c
);
1553 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1554 PKT_DATA
, buffer
, 16, PKT_END
);
1557 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1558 if (flags
& FLAG_VERBOSE
)
1559 c_write("Failed to authenticate with our public key.\r\n",
1561 continue; /* go and try password */
1562 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1563 bombout(("Bizarre response to RSA authentication response"));
1567 break; /* we're through! */
1569 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
1571 logevent("Sent password");
1572 memset(password
, 0, strlen(password
));
1574 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1575 if (flags
& FLAG_VERBOSE
)
1576 c_write("Access denied\r\n", 15);
1577 logevent("Authentication refused");
1578 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
1579 logevent("Received disconnect request");
1580 ssh_state
= SSH_STATE_CLOSED
;
1582 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1583 bombout(("Strange packet received, type %d", pktin
.type
));
1588 logevent("Authentication successful");
1593 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
) {
1598 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
1601 if (ssh_state
== SSH_STATE_CLOSED
)
1604 if (cfg
.agentfwd
&& agent_exists()) {
1605 logevent("Requesting agent forwarding");
1606 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
1607 do { crReturnV
; } while (!ispkt
);
1608 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
1609 bombout(("Protocol confusion"));
1611 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1612 logevent("Agent forwarding refused");
1614 logevent("Agent forwarding enabled");
1618 send_packet(SSH1_CMSG_REQUEST_PTY
,
1619 PKT_STR
, cfg
.termtype
,
1620 PKT_INT
, rows
, PKT_INT
, cols
,
1621 PKT_INT
, 0, PKT_INT
, 0,
1624 ssh_state
= SSH_STATE_INTERMED
;
1625 do { crReturnV
; } while (!ispkt
);
1626 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
1627 bombout(("Protocol confusion"));
1629 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1630 c_write("Server refused to allocate pty\r\n", 32);
1632 logevent("Allocated pty");
1635 if (*cfg
.remote_cmd
)
1636 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cfg
.remote_cmd
, PKT_END
);
1638 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
1639 logevent("Started session");
1641 ssh_state
= SSH_STATE_SESSION
;
1646 ssh_channels
= newtree234(ssh_channelcmp
);
1651 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
1652 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
1653 long len
= GET_32BIT(pktin
.body
);
1654 c_writedata(pktin
.body
+4, len
);
1655 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
1656 ssh_state
= SSH_STATE_CLOSED
;
1657 logevent("Received disconnect request");
1658 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
1659 /* Remote side is trying to open a channel to talk to our
1660 * agent. Give them back a local channel number. */
1662 struct ssh_channel
*c
;
1664 for (c
= first234(ssh_channels
, &e
); c
; c
= next234(&e
)) {
1666 break; /* found a free number */
1669 c
= malloc(sizeof(struct ssh_channel
));
1670 c
->remoteid
= GET_32BIT(pktin
.body
);
1673 c
->type
= SSH1_SMSG_AGENT_OPEN
; /* identify channel type */
1674 c
->u
.a
.lensofar
= 0;
1675 add234(ssh_channels
, c
);
1676 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
1677 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
1679 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
1680 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
1681 /* Remote side closes a channel. */
1682 unsigned i
= GET_32BIT(pktin
.body
);
1683 struct ssh_channel
*c
;
1684 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
1687 closetype
= (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
1688 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
, PKT_END
);
1689 c
->closes
|= closetype
;
1690 if (c
->closes
== 3) {
1691 del234(ssh_channels
, c
);
1695 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
1696 /* Data sent down one of our channels. */
1697 int i
= GET_32BIT(pktin
.body
);
1698 int len
= GET_32BIT(pktin
.body
+4);
1699 unsigned char *p
= pktin
.body
+8;
1700 struct ssh_channel
*c
;
1701 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
1704 case SSH1_SMSG_AGENT_OPEN
:
1705 /* Data for an agent message. Buffer it. */
1707 if (c
->u
.a
.lensofar
< 4) {
1708 int l
= min(4 - c
->u
.a
.lensofar
, len
);
1709 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
, l
);
1710 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
1712 if (c
->u
.a
.lensofar
== 4) {
1713 c
->u
.a
.totallen
= 4 + GET_32BIT(c
->u
.a
.msglen
);
1714 c
->u
.a
.message
= malloc(c
->u
.a
.totallen
);
1715 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
1717 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
1718 int l
= min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
, len
);
1719 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
, l
);
1720 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
1722 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
1723 void *reply
, *sentreply
;
1725 agent_query(c
->u
.a
.message
, c
->u
.a
.totallen
,
1730 /* Fake SSH_AGENT_FAILURE. */
1731 sentreply
= "\0\0\0\1\5";
1734 send_packet(SSH1_MSG_CHANNEL_DATA
,
1735 PKT_INT
, c
->remoteid
,
1737 PKT_DATA
, sentreply
, replylen
,
1741 free(c
->u
.a
.message
);
1742 c
->u
.a
.lensofar
= 0;
1748 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1749 /* may be from EXEC_SHELL on some servers */
1750 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1751 /* may be from EXEC_SHELL on some servers
1752 * if no pty is available or in other odd cases. Ignore */
1753 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
1754 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
1756 bombout(("Strange packet received: type %d", pktin
.type
));
1760 send_packet(SSH1_CMSG_STDIN_DATA
,
1761 PKT_INT
, inlen
, PKT_DATA
, in
, inlen
, PKT_END
);
1769 * Utility routine for decoding comma-separated strings in KEXINIT.
1771 int in_commasep_string(char *needle
, char *haystack
, int haylen
) {
1772 int needlen
= strlen(needle
);
1775 * Is it at the start of the string?
1777 if (haylen
>= needlen
&& /* haystack is long enough */
1778 !memcmp(needle
, haystack
, needlen
) && /* initial match */
1779 (haylen
== needlen
|| haystack
[needlen
] == ',')
1780 /* either , or EOS follows */
1784 * If not, search for the next comma and resume after that.
1785 * If no comma found, terminate.
1787 while (haylen
> 0 && *haystack
!= ',')
1788 haylen
--, haystack
++;
1791 haylen
--, haystack
++; /* skip over comma itself */
1796 * SSH2 key creation method.
1798 void ssh2_mkkey(Bignum K
, char *H
, char chr
, char *keyspace
) {
1800 /* First 20 bytes. */
1803 SHA_Bytes(&s
, H
, 20);
1804 SHA_Bytes(&s
, &chr
, 1);
1805 SHA_Bytes(&s
, H
, 20);
1806 SHA_Final(&s
, keyspace
);
1807 /* Next 20 bytes. */
1810 SHA_Bytes(&s
, H
, 20);
1811 SHA_Bytes(&s
, keyspace
, 20);
1812 SHA_Final(&s
, keyspace
+20);
1816 * Handle the SSH2 transport layer.
1818 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
1822 static Bignum e
, f
, K
;
1823 static struct ssh_cipher
*cscipher_tobe
= NULL
;
1824 static struct ssh_cipher
*sccipher_tobe
= NULL
;
1825 static struct ssh_mac
*csmac_tobe
= NULL
;
1826 static struct ssh_mac
*scmac_tobe
= NULL
;
1827 static struct ssh_compress
*cscomp_tobe
= NULL
;
1828 static struct ssh_compress
*sccomp_tobe
= NULL
;
1829 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
1830 static int hostkeylen
, siglen
;
1831 static unsigned char exchange_hash
[20];
1832 static unsigned char keyspace
[40];
1838 * Set up the preferred cipher.
1840 if (cfg
.cipher
== CIPHER_BLOWFISH
) {
1841 ciphers
[0] = &ssh_blowfish_ssh2
;
1842 } else if (cfg
.cipher
== CIPHER_DES
) {
1843 logevent("Single DES not supported in SSH2; using 3DES");
1844 ciphers
[0] = &ssh_3des_ssh2
;
1845 } else if (cfg
.cipher
== CIPHER_3DES
) {
1846 ciphers
[0] = &ssh_3des_ssh2
;
1848 /* Shouldn't happen, but we do want to initialise to _something_. */
1849 ciphers
[0] = &ssh_3des_ssh2
;
1854 * Construct and send our key exchange packet.
1856 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
1857 for (i
= 0; i
< 16; i
++)
1858 ssh2_pkt_addbyte((unsigned char)random_byte());
1859 /* List key exchange algorithms. */
1860 ssh2_pkt_addstring_start();
1861 for (i
= 0; i
< lenof(kex_algs
); i
++) {
1862 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
1863 if (i
< lenof(kex_algs
)-1)
1864 ssh2_pkt_addstring_str(",");
1866 /* List server host key algorithms. */
1867 ssh2_pkt_addstring_start();
1868 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
1869 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
1870 if (i
< lenof(hostkey_algs
)-1)
1871 ssh2_pkt_addstring_str(",");
1873 /* List client->server encryption algorithms. */
1874 ssh2_pkt_addstring_start();
1875 for (i
= 0; i
< lenof(ciphers
); i
++) {
1876 ssh2_pkt_addstring_str(ciphers
[i
]->name
);
1877 if (i
< lenof(ciphers
)-1)
1878 ssh2_pkt_addstring_str(",");
1880 /* List server->client encryption algorithms. */
1881 ssh2_pkt_addstring_start();
1882 for (i
= 0; i
< lenof(ciphers
); i
++) {
1883 ssh2_pkt_addstring_str(ciphers
[i
]->name
);
1884 if (i
< lenof(ciphers
)-1)
1885 ssh2_pkt_addstring_str(",");
1887 /* List client->server MAC algorithms. */
1888 ssh2_pkt_addstring_start();
1889 for (i
= 0; i
< lenof(macs
); i
++) {
1890 ssh2_pkt_addstring_str(macs
[i
]->name
);
1891 if (i
< lenof(macs
)-1)
1892 ssh2_pkt_addstring_str(",");
1894 /* List server->client MAC algorithms. */
1895 ssh2_pkt_addstring_start();
1896 for (i
= 0; i
< lenof(macs
); i
++) {
1897 ssh2_pkt_addstring_str(macs
[i
]->name
);
1898 if (i
< lenof(macs
)-1)
1899 ssh2_pkt_addstring_str(",");
1901 /* List client->server compression algorithms. */
1902 ssh2_pkt_addstring_start();
1903 for (i
= 0; i
< lenof(compressions
); i
++) {
1904 ssh2_pkt_addstring_str(compressions
[i
]->name
);
1905 if (i
< lenof(compressions
)-1)
1906 ssh2_pkt_addstring_str(",");
1908 /* List server->client compression algorithms. */
1909 ssh2_pkt_addstring_start();
1910 for (i
= 0; i
< lenof(compressions
); i
++) {
1911 ssh2_pkt_addstring_str(compressions
[i
]->name
);
1912 if (i
< lenof(compressions
)-1)
1913 ssh2_pkt_addstring_str(",");
1915 /* List client->server languages. Empty list. */
1916 ssh2_pkt_addstring_start();
1917 /* List server->client languages. Empty list. */
1918 ssh2_pkt_addstring_start();
1919 /* First KEX packet does _not_ follow, because we're not that brave. */
1920 ssh2_pkt_addbool(FALSE
);
1922 ssh2_pkt_adduint32(0);
1923 sha_string(&exhash
, pktout
.data
+5, pktout
.length
-5);
1926 if (!ispkt
) crWaitUntil(ispkt
);
1927 sha_string(&exhash
, pktin
.data
+5, pktin
.length
-5);
1930 * Now examine the other side's KEXINIT to see what we're up
1933 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
1934 bombout(("expected key exchange packet from server"));
1937 kex
= NULL
; hostkey
= NULL
; cscipher_tobe
= NULL
; sccipher_tobe
= NULL
;
1938 csmac_tobe
= NULL
; scmac_tobe
= NULL
; cscomp_tobe
= NULL
; sccomp_tobe
= NULL
;
1939 pktin
.savedpos
+= 16; /* skip garbage cookie */
1940 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
1941 for (i
= 0; i
< lenof(kex_algs
); i
++) {
1942 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
1947 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
1948 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
1949 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
1950 hostkey
= hostkey_algs
[i
];
1954 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
1955 for (i
= 0; i
< lenof(ciphers
); i
++) {
1956 if (in_commasep_string(ciphers
[i
]->name
, str
, len
)) {
1957 cscipher_tobe
= ciphers
[i
];
1961 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
1962 for (i
= 0; i
< lenof(ciphers
); i
++) {
1963 if (in_commasep_string(ciphers
[i
]->name
, str
, len
)) {
1964 sccipher_tobe
= ciphers
[i
];
1968 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
1969 for (i
= 0; i
< lenof(macs
); i
++) {
1970 if (in_commasep_string(macs
[i
]->name
, str
, len
)) {
1971 csmac_tobe
= macs
[i
];
1975 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
1976 for (i
= 0; i
< lenof(macs
); i
++) {
1977 if (in_commasep_string(macs
[i
]->name
, str
, len
)) {
1978 scmac_tobe
= macs
[i
];
1982 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
1983 for (i
= 0; i
< lenof(compressions
); i
++) {
1984 if (in_commasep_string(compressions
[i
]->name
, str
, len
)) {
1985 cscomp_tobe
= compressions
[i
];
1989 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
1990 for (i
= 0; i
< lenof(compressions
); i
++) {
1991 if (in_commasep_string(compressions
[i
]->name
, str
, len
)) {
1992 sccomp_tobe
= compressions
[i
];
1998 * Currently we only support Diffie-Hellman and DSS, so let's
1999 * bomb out if those aren't selected.
2001 if (kex
!= &ssh_diffiehellman
|| hostkey
!= &ssh_dss
) {
2002 bombout(("internal fault: chaos in SSH 2 transport layer"));
2007 * Now we begin the fun. Generate and send e for Diffie-Hellman.
2010 ssh2_pkt_init(SSH2_MSG_KEXDH_INIT
);
2015 if (pktin
.type
!= SSH2_MSG_KEXDH_REPLY
) {
2016 bombout(("expected key exchange packet from server"));
2019 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
2020 f
= ssh2_pkt_getmp();
2021 ssh2_pkt_getstring(&sigdata
, &siglen
);
2025 sha_string(&exhash
, hostkeydata
, hostkeylen
);
2026 sha_mpint(&exhash
, e
);
2027 sha_mpint(&exhash
, f
);
2028 sha_mpint(&exhash
, K
);
2029 SHA_Final(&exhash
, exchange_hash
);
2032 debug(("Exchange hash is:\r\n"));
2033 for (i
= 0; i
< 20; i
++)
2034 debug((" %02x", exchange_hash
[i
]));
2038 hostkey
->setkey(hostkeydata
, hostkeylen
);
2039 if (!hostkey
->verifysig(sigdata
, siglen
, exchange_hash
, 20)) {
2040 bombout(("Server failed host key check"));
2045 * Expect SSH2_MSG_NEWKEYS from server.
2048 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
2049 bombout(("expected new-keys packet from server"));
2054 * Authenticate remote host: verify host key. (We've already
2055 * checked the signature of the exchange hash.)
2057 keystr
= hostkey
->fmtkey();
2058 fingerprint
= hostkey
->fingerprint();
2059 verify_ssh_host_key(savedhost
, hostkey
->keytype
, keystr
, fingerprint
);
2060 logevent("Host key fingerprint is:");
2061 logevent(fingerprint
);
2066 * Send SSH2_MSG_NEWKEYS.
2068 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
2072 * Create and initialise session keys.
2074 cscipher
= cscipher_tobe
;
2075 sccipher
= sccipher_tobe
;
2078 cscomp
= cscomp_tobe
;
2079 sccomp
= sccomp_tobe
;
2081 * Set IVs after keys.
2083 ssh2_mkkey(K
, exchange_hash
, 'C', keyspace
); cscipher
->setcskey(keyspace
);
2084 ssh2_mkkey(K
, exchange_hash
, 'D', keyspace
); cscipher
->setsckey(keyspace
);
2085 ssh2_mkkey(K
, exchange_hash
, 'A', keyspace
); cscipher
->setcsiv(keyspace
);
2086 ssh2_mkkey(K
, exchange_hash
, 'B', keyspace
); sccipher
->setsciv(keyspace
);
2087 ssh2_mkkey(K
, exchange_hash
, 'E', keyspace
); csmac
->setcskey(keyspace
);
2088 ssh2_mkkey(K
, exchange_hash
, 'F', keyspace
); scmac
->setsckey(keyspace
);
2091 * Now we're encrypting. Begin returning 1 to the protocol main
2092 * function so that other things can run on top of the
2093 * transport. If we ever see a KEXINIT, we must go back to the
2098 } while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
));
2099 goto begin_key_exchange
;
2105 * Handle the SSH2 userauth and connection layers.
2107 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
2109 static unsigned long remote_winsize
;
2110 static unsigned long remote_maxpkt
;
2115 * Request userauth protocol, and await a response to it.
2117 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
2118 ssh2_pkt_addstring("ssh-userauth");
2120 crWaitUntilV(ispkt
);
2121 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
2122 bombout(("Server refused user authentication protocol"));
2127 * FIXME: currently we support only password authentication.
2128 * (This places us technically in violation of the SSH2 spec.
2129 * We must fix this.)
2133 * Get a username and a password.
2135 static char username
[100];
2136 static char password
[100];
2140 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
2141 c_write("login as: ", 10);
2144 crWaitUntilV(!ispkt
);
2145 while (inlen
--) switch (c
= *in
++) {
2152 c_write("\b \b", 3);
2158 c_write("\b \b", 3);
2167 if (((c
>= ' ' && c
<= '~') ||
2168 ((unsigned char)c
>= 160)) && pos
< 40) {
2169 username
[pos
++] = c
;
2176 username
[strcspn(username
, "\n\r")] = '\0';
2179 strncpy(username
, cfg
.username
, 99);
2180 username
[99] = '\0';
2181 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
2182 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
2183 c_write(stuff
, strlen(stuff
));
2187 if (!(flags
& FLAG_INTERACTIVE
)) {
2189 sprintf(prompt
, "%.90s@%.90s's password: ", cfg
.username
, savedhost
);
2190 if (!ssh_get_password(prompt
, password
, sizeof(password
))) {
2192 * get_password failed to get a password (for
2193 * example because one was supplied on the command
2194 * line which has already failed to work).
2197 logevent("No more passwords to try");
2198 ssh_state
= SSH_STATE_CLOSED
;
2202 c_write("password: ", 10);
2207 crWaitUntilV(!ispkt
);
2208 while (inlen
--) switch (c
= *in
++) {
2225 if (((c
>= ' ' && c
<= '~') ||
2226 ((unsigned char)c
>= 160)) && pos
< 40)
2227 password
[pos
++] = c
;
2234 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
2235 ssh2_pkt_addstring(username
);
2236 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2237 ssh2_pkt_addstring("password");
2238 ssh2_pkt_addbool(FALSE
);
2239 ssh2_pkt_addstring(password
);
2242 crWaitUntilV(ispkt
);
2243 if (pktin
.type
!= SSH2_MSG_USERAUTH_SUCCESS
) {
2244 c_write("Access denied\r\n", 15);
2245 logevent("Authentication refused");
2251 * Now we're authenticated for the connection protocol. The
2252 * connection protocol will automatically have started at this
2253 * point; there's no need to send SERVICE_REQUEST.
2257 * So now create a channel with a session in it.
2259 mainchan
= malloc(sizeof(struct ssh_channel
));
2260 mainchan
->localid
= 100; /* as good as any */
2261 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
2262 ssh2_pkt_addstring("session");
2263 ssh2_pkt_adduint32(mainchan
->localid
);
2264 ssh2_pkt_adduint32(0x7FFFFFFFUL
); /* our window size */
2265 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
2267 crWaitUntilV(ispkt
);
2268 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
2269 bombout(("Server refused to open a session"));
2271 /* FIXME: error data comes back in FAILURE packet */
2273 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
2274 bombout(("Server's channel confirmation cited wrong channel"));
2277 mainchan
->remoteid
= ssh2_pkt_getuint32();
2278 mainchan
->u
.v2
.remwindow
= ssh2_pkt_getuint32();
2279 mainchan
->u
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
2280 mainchan
->u
.v2
.outbuffer
= NULL
;
2281 mainchan
->u
.v2
.outbuflen
= mainchan
->u
.v2
.outbufsize
= 0;
2282 logevent("Opened channel for session");
2285 * Now allocate a pty for the session.
2288 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
2289 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
2290 ssh2_pkt_addstring("pty-req");
2291 ssh2_pkt_addbool(1); /* want reply */
2292 ssh2_pkt_addstring(cfg
.termtype
);
2293 ssh2_pkt_adduint32(cols
);
2294 ssh2_pkt_adduint32(rows
);
2295 ssh2_pkt_adduint32(0); /* pixel width */
2296 ssh2_pkt_adduint32(0); /* pixel height */
2297 ssh2_pkt_addstring_start();
2298 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
2302 crWaitUntilV(ispkt
);
2303 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
2304 /* FIXME: be able to handle other channels here */
2305 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2306 continue; /* wrong channel */
2307 mainchan
->u
.v2
.remwindow
+= ssh2_pkt_getuint32();
2309 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
2311 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
2312 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
2313 bombout(("Server got confused by pty request"));
2316 c_write("Server refused to allocate pty\r\n", 32);
2318 logevent("Allocated pty");
2323 * Start a shell or a remote command.
2325 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
2326 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
2327 if (*cfg
.remote_cmd
) {
2328 ssh2_pkt_addstring("exec");
2329 ssh2_pkt_addbool(1); /* want reply */
2330 ssh2_pkt_addstring(cfg
.remote_cmd
);
2332 ssh2_pkt_addstring("shell");
2333 ssh2_pkt_addbool(1); /* want reply */
2337 crWaitUntilV(ispkt
);
2338 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
2339 /* FIXME: be able to handle other channels here */
2340 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2341 continue; /* wrong channel */
2342 mainchan
->u
.v2
.remwindow
+= ssh2_pkt_getuint32();
2344 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
2345 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
2346 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
2347 bombout(("Server got confused by shell/command request"));
2350 bombout(("Server refused to start a shell/command"));
2353 logevent("Started a shell/command");
2362 static int try_send
;
2366 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
2367 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
2370 /* FIXME: be able to handle other channels here */
2371 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2372 continue; /* wrong channel */
2373 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
2374 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
2375 continue; /* extended but not stderr */
2376 ssh2_pkt_getstring(&data
, &length
);
2378 c_writedata(data
, length
);
2380 * Enlarge the window again at the remote side,
2381 * just in case it ever runs down and they fail
2382 * to send us any more data.
2384 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
2385 ssh2_pkt_adduint32(mainchan
->remoteid
);
2386 ssh2_pkt_adduint32(length
);
2389 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
2390 ssh_state
= SSH_STATE_CLOSED
;
2391 logevent("Received disconnect message");
2392 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
2393 continue; /* exit status et al; ignore (FIXME?) */
2394 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
2395 continue; /* remote sends EOF; ignore */
2396 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
2397 /* FIXME: be able to handle other channels here */
2398 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2399 continue; /* wrong channel */
2400 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2401 ssh2_pkt_adduint32(mainchan
->remoteid
);
2403 /* FIXME: mark the channel as closed */
2404 if (1 /* FIXME: "all channels are closed" */) {
2405 logevent("All channels closed. Disconnecting");
2406 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
2409 continue; /* remote sends close; ignore (FIXME) */
2410 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
2411 /* FIXME: be able to handle other channels here */
2412 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2413 continue; /* wrong channel */
2414 mainchan
->u
.v2
.remwindow
+= ssh2_pkt_getuint32();
2417 bombout(("Strange packet received: type %d", pktin
.type
));
2422 * We have spare data. Add it to the channel buffer.
2424 if (mainchan
->u
.v2
.outbufsize
<
2425 mainchan
->u
.v2
.outbuflen
+ inlen
) {
2426 mainchan
->u
.v2
.outbufsize
=
2427 mainchan
->u
.v2
.outbuflen
+ inlen
+ 1024;
2428 mainchan
->u
.v2
.outbuffer
= srealloc(mainchan
->u
.v2
.outbuffer
,
2429 mainchan
->u
.v2
.outbufsize
);
2431 memcpy(mainchan
->u
.v2
.outbuffer
+ mainchan
->u
.v2
.outbuflen
,
2433 mainchan
->u
.v2
.outbuflen
+= inlen
;
2438 * Try to send data on the channel if we can. (FIXME:
2439 * on _all_ channels.)
2441 while (mainchan
->u
.v2
.remwindow
> 0 &&
2442 mainchan
->u
.v2
.outbuflen
> 0) {
2443 unsigned len
= mainchan
->u
.v2
.remwindow
;
2444 if (len
> mainchan
->u
.v2
.outbuflen
)
2445 len
= mainchan
->u
.v2
.outbuflen
;
2446 if (len
> mainchan
->u
.v2
.remmaxpkt
)
2447 len
= mainchan
->u
.v2
.remmaxpkt
;
2448 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
2449 ssh2_pkt_adduint32(mainchan
->remoteid
);
2450 ssh2_pkt_addstring_start();
2451 ssh2_pkt_addstring_data(mainchan
->u
.v2
.outbuffer
, len
);
2453 mainchan
->u
.v2
.outbuflen
-= len
;
2454 memmove(mainchan
->u
.v2
.outbuffer
, mainchan
->u
.v2
.outbuffer
+len
,
2455 mainchan
->u
.v2
.outbuflen
);
2456 mainchan
->u
.v2
.remwindow
-= len
;
2465 * Handle the top-level SSH2 protocol.
2467 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
2469 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
2471 do_ssh2_authconn(in
, inlen
, ispkt
);
2475 * Called to set up the connection. Will arrange for WM_NETEVENT
2476 * messages to be passed to the specified window, whose window
2477 * procedure should then call telnet_msg().
2479 * Returns an error message, or NULL on success.
2481 static char *ssh_init (HWND hwnd
, char *host
, int port
, char **realhost
) {
2485 if(crypto_startup() == 0)
2486 return "Microsoft high encryption pack not installed!";
2489 p
= connect_to_host(host
, port
, realhost
);
2494 return "Protocol initialisation error";
2496 if (hwnd
&& WSAAsyncSelect (s
, hwnd
, WM_NETEVENT
, FD_READ
| FD_CLOSE
) == SOCKET_ERROR
)
2497 switch (WSAGetLastError()) {
2498 case WSAENETDOWN
: return "Network is down";
2499 default: return "WSAAsyncSelect(): unknown error";
2506 * Process a WM_NETEVENT message. Will return 0 if the connection
2507 * has closed, or <0 for a socket error.
2509 static int ssh_msg (WPARAM wParam
, LPARAM lParam
) {
2514 * Because reading less than the whole of the available pending
2515 * data can generate an FD_READ event, we need to allow for the
2516 * possibility that FD_READ may arrive with FD_CLOSE already in
2517 * the queue; so it's possible that we can get here even with s
2518 * invalid. If so, we return 1 and don't worry about it.
2520 if (s
== INVALID_SOCKET
)
2523 if (WSAGETSELECTERROR(lParam
) != 0) {
2526 return -WSAGETSELECTERROR(lParam
);
2529 switch (WSAGETSELECTEVENT(lParam
)) {
2532 ret
= recv(s
, buf
, sizeof(buf
), 0);
2533 if (ret
< 0 && WSAGetLastError() == WSAEWOULDBLOCK
)
2535 if (ret
< 0) { /* any _other_ error */
2538 return -10000-WSAGetLastError();
2544 ssh_gotdata (buf
, ret
);
2545 if (ssh_state
== SSH_STATE_CLOSED
) {
2552 return 1; /* shouldn't happen, but WTF */
2556 * Called to send data down the Telnet connection.
2558 static void ssh_send (char *buf
, int len
) {
2559 if (s
== INVALID_SOCKET
)
2562 ssh_protocol(buf
, len
, 0);
2566 * Called to set the size of the window from Telnet's POV.
2568 static void ssh_size(void) {
2569 switch (ssh_state
) {
2570 case SSH_STATE_BEFORE_SIZE
:
2571 case SSH_STATE_CLOSED
:
2572 break; /* do nothing */
2573 case SSH_STATE_INTERMED
:
2574 size_needed
= TRUE
; /* buffer for later */
2576 case SSH_STATE_SESSION
:
2578 send_packet(SSH1_CMSG_WINDOW_SIZE
,
2579 PKT_INT
, rows
, PKT_INT
, cols
,
2580 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
2586 * Send Telnet special codes. TS_EOF is useful for `plink', so you
2587 * can send an EOF and collect resulting output (e.g. `plink
2590 static void ssh_special (Telnet_Special code
) {
2591 if (code
== TS_EOF
) {
2592 if (ssh_version
== 1) {
2593 send_packet(SSH1_CMSG_EOF
, PKT_END
);
2595 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
2596 ssh2_pkt_adduint32(mainchan
->remoteid
);
2599 logevent("Sent EOF message");
2605 static SOCKET
ssh_socket(void) { return s
; }
2607 static int ssh_sendok(void) { return ssh_send_ok
; }
2609 Backend ssh_backend
= {