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 savedport
;
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
);
294 static void c_writedata (char *buf
, int len
) {
308 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
309 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
311 static int ssh_version
;
312 static void (*ssh_protocol
)(unsigned char *in
, int inlen
, int ispkt
);
313 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
314 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
315 static void ssh_size(void);
317 static int (*s_rdpkt
)(unsigned char **data
, int *datalen
);
320 * Collect incoming data in the incoming packet buffer.
321 * Decipher and verify the packet when it is completely read.
322 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
323 * Update the *data and *datalen variables.
324 * Return the additional nr of bytes needed, or 0 when
325 * a complete packet is available.
327 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
329 static long len
, pad
, biglen
, to_read
;
330 static unsigned long realcrc
, gotcrc
;
331 static unsigned char *p
;
341 for (i
= len
= 0; i
< 4; i
++) {
342 while ((*datalen
) == 0)
344 len
= (len
<< 8) + **data
;
345 (*data
)++, (*datalen
)--;
349 if (len
== 0x52656d6f) { /* "Remo"te server has closed ... */
350 len
= 0x300; /* big enough to carry to end */
356 pktin
.length
= len
- 5;
358 if (pktin
.maxlen
< biglen
) {
359 pktin
.maxlen
= biglen
;
360 pktin
.data
= (pktin
.data
== NULL ?
malloc(biglen
+APIEXTRA
) :
361 realloc(pktin
.data
, biglen
+APIEXTRA
));
363 fatalbox("Out of memory");
368 while (to_read
> 0) {
371 while ((*datalen
) == 0)
373 if (chunk
> (*datalen
))
375 memcpy(p
, *data
, chunk
);
383 cipher
->decrypt(pktin
.data
, biglen
);
385 pktin
.type
= pktin
.data
[pad
];
386 pktin
.body
= pktin
.data
+ pad
+ 1;
388 realcrc
= crc32(pktin
.data
, biglen
-4);
389 gotcrc
= GET_32BIT(pktin
.data
+biglen
-4);
390 if (gotcrc
!= realcrc
) {
391 bombout(("Incorrect CRC received on packet"));
395 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
396 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
397 pktin
.type
== SSH1_MSG_DEBUG
||
398 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
399 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
400 long strlen
= GET_32BIT(pktin
.body
);
401 if (strlen
+ 4 != pktin
.length
) {
402 bombout(("Received data packet with bogus string length"));
407 if (pktin
.type
== SSH1_MSG_DEBUG
) {
408 /* log debug message */
410 int strlen
= GET_32BIT(pktin
.body
);
411 strcpy(buf
, "Remote: ");
412 if (strlen
> 70) strlen
= 70;
413 memcpy(buf
+8, pktin
.body
+4, strlen
);
414 buf
[8+strlen
] = '\0';
417 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
425 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
427 static long len
, pad
, payload
, packetlen
, maclen
;
429 static int cipherblk
;
430 static unsigned long incoming_sequence
= 0;
440 cipherblk
= cipher
->blksize
;
446 if (pktin
.maxlen
< cipherblk
) {
447 pktin
.maxlen
= cipherblk
;
448 pktin
.data
= (pktin
.data
== NULL ?
malloc(cipherblk
+APIEXTRA
) :
449 realloc(pktin
.data
, cipherblk
+APIEXTRA
));
451 fatalbox("Out of memory");
455 * Acquire and decrypt the first block of the packet. This will
456 * contain the length and padding details.
458 for (i
= len
= 0; i
< cipherblk
; i
++) {
459 while ((*datalen
) == 0)
460 crReturn(cipherblk
-i
);
461 pktin
.data
[i
] = *(*data
)++;
465 if (!memcmp(pktin
.data
, "Remo", 4)) {/* "Remo"te server has closed ... */
470 sccipher
->decrypt(pktin
.data
, cipherblk
);
473 * Now get the length and padding figures.
475 len
= GET_32BIT(pktin
.data
);
479 * This enables us to deduce the payload length.
481 payload
= len
- pad
- 1;
483 pktin
.length
= payload
+ 5;
486 * So now we can work out the total packet length.
489 maclen
= scmac ? scmac
->len
: 0;
492 * Adjust memory allocation if packet is too big.
494 if (pktin
.maxlen
< packetlen
+maclen
) {
495 pktin
.maxlen
= packetlen
+maclen
;
496 pktin
.data
= (pktin
.data
== NULL ?
malloc(pktin
.maxlen
+APIEXTRA
) :
497 realloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
));
499 fatalbox("Out of memory");
503 * Read and decrypt the remainder of the packet.
505 for (i
= cipherblk
; i
< packetlen
+ maclen
; i
++) {
506 while ((*datalen
) == 0)
507 crReturn(packetlen
+ maclen
- i
);
508 pktin
.data
[i
] = *(*data
)++;
511 /* Decrypt everything _except_ the MAC. */
513 sccipher
->decrypt(pktin
.data
+ cipherblk
, packetlen
- cipherblk
);
516 debug(("Got packet len=%d pad=%d\r\n", len
, pad
));
517 for (i
= 0; i
< packetlen
; i
++)
518 debug((" %02x", (unsigned char)pktin
.data
[i
]));
525 if (scmac
&& !scmac
->verify(pktin
.data
, len
+4, incoming_sequence
)) {
526 bombout(("Incorrect MAC received on packet"));
529 incoming_sequence
++; /* whether or not we MACed */
532 pktin
.type
= pktin
.data
[5];
534 if (pktin
.type
== SSH2_MSG_IGNORE
|| pktin
.type
== SSH2_MSG_DEBUG
)
535 goto next_packet
; /* FIXME: print DEBUG message */
540 static void ssh_gotdata(unsigned char *data
, int datalen
)
542 while (datalen
> 0) {
543 if ( s_rdpkt(&data
, &datalen
) == 0 ) {
544 ssh_protocol(NULL
, 0, 1);
545 if (ssh_state
== SSH_STATE_CLOSED
) {
553 static void s_wrpkt_start(int type
, int len
) {
556 len
+= 5; /* type and CRC */
560 pktout
.length
= len
-5;
561 if (pktout
.maxlen
< biglen
) {
562 pktout
.maxlen
= biglen
;
564 /* Allocate enough buffer space for extra block
565 * for MS CryptEncrypt() */
566 pktout
.data
= (pktout
.data
== NULL ?
malloc(biglen
+12) :
567 realloc(pktout
.data
, biglen
+12));
569 pktout
.data
= (pktout
.data
== NULL ?
malloc(biglen
+4) :
570 realloc(pktout
.data
, biglen
+4));
573 fatalbox("Out of memory");
577 pktout
.body
= pktout
.data
+4+pad
+1;
580 static void s_wrpkt(void) {
581 int pad
, len
, biglen
, i
;
584 len
= pktout
.length
+ 5; /* type and CRC */
588 pktout
.body
[-1] = pktout
.type
;
589 for (i
=0; i
<pad
; i
++)
590 pktout
.data
[i
+4] = random_byte();
591 crc
= crc32(pktout
.data
+4, biglen
-4);
592 PUT_32BIT(pktout
.data
+biglen
, crc
);
593 PUT_32BIT(pktout
.data
, len
);
596 cipher
->encrypt(pktout
.data
+4, biglen
);
598 s_write(pktout
.data
, biglen
+4);
602 * Construct a packet with the specified contents and
603 * send it to the server.
605 static void send_packet(int pkttype
, ...)
608 unsigned char *p
, *argp
, argchar
;
609 unsigned long argint
;
610 int pktlen
, argtype
, arglen
;
614 va_start(args
, pkttype
);
615 while ((argtype
= va_arg(args
, int)) != PKT_END
) {
618 (void) va_arg(args
, int);
622 (void) va_arg(args
, char);
626 (void) va_arg(args
, unsigned char *);
627 arglen
= va_arg(args
, int);
631 argp
= va_arg(args
, unsigned char *);
632 arglen
= strlen(argp
);
633 pktlen
+= 4 + arglen
;
636 bn
= va_arg(args
, Bignum
);
637 pktlen
+= ssh1_bignum_length(bn
);
645 s_wrpkt_start(pkttype
, pktlen
);
648 va_start(args
, pkttype
);
649 while ((argtype
= va_arg(args
, int)) != PKT_END
) {
652 argint
= va_arg(args
, int);
653 PUT_32BIT(p
, argint
);
657 argchar
= va_arg(args
, unsigned char);
662 argp
= va_arg(args
, unsigned char *);
663 arglen
= va_arg(args
, int);
664 memcpy(p
, argp
, arglen
);
668 argp
= va_arg(args
, unsigned char *);
669 arglen
= strlen(argp
);
670 PUT_32BIT(p
, arglen
);
671 memcpy(p
+ 4, argp
, arglen
);
675 bn
= va_arg(args
, Bignum
);
676 p
+= ssh1_write_bignum(p
, bn
);
687 * Connect to specified host and port.
688 * Returns an error message, or NULL on success.
689 * Also places the canonical host name into `realhost'.
691 static char *connect_to_host(char *host
, int port
, char **realhost
)
701 savedhost
= malloc(1+strlen(host
));
703 fatalbox("Out of memory");
704 strcpy(savedhost
, host
);
707 port
= 22; /* default ssh port */
720 if ( (a
= inet_addr(host
)) == (unsigned long) INADDR_NONE
) {
721 if ( (h
= gethostbyname(host
)) == NULL
)
722 switch (WSAGetLastError()) {
723 case WSAENETDOWN
: return "Network is down";
724 case WSAHOST_NOT_FOUND
: case WSANO_DATA
:
725 return "Host does not exist";
726 case WSATRY_AGAIN
: return "Host not found";
727 default: return "gethostbyname: unknown error";
729 memcpy (&a
, h
->h_addr
, sizeof(a
));
730 *realhost
= h
->h_name
;
741 s
= socket(AF_INET
, SOCK_STREAM
, 0);
742 if (s
== INVALID_SOCKET
)
743 switch (WSAGetLastError()) {
744 case WSAENETDOWN
: return "Network is down";
745 case WSAEAFNOSUPPORT
: return "TCP/IP support not present";
746 default: return "socket(): unknown error";
750 * Bind to local address.
752 addr
.sin_family
= AF_INET
;
753 addr
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
754 addr
.sin_port
= htons(0);
755 if (bind (s
, (struct sockaddr
*)&addr
, sizeof(addr
)) == SOCKET_ERROR
)
756 switch (WSAGetLastError()) {
757 case WSAENETDOWN
: return "Network is down";
758 default: return "bind(): unknown error";
762 * Connect to remote address.
764 addr
.sin_addr
.s_addr
= htonl(a
);
765 addr
.sin_port
= htons((short)port
);
766 if (connect (s
, (struct sockaddr
*)&addr
, sizeof(addr
)) == SOCKET_ERROR
)
767 switch (WSAGetLastError()) {
768 case WSAENETDOWN
: return "Network is down";
769 case WSAECONNREFUSED
: return "Connection refused";
770 case WSAENETUNREACH
: return "Network is unreachable";
771 case WSAEHOSTUNREACH
: return "No route to host";
772 default: return "connect(): unknown error";
776 send(s
, "connect ", 8, 0);
777 send(s
, FWhost
, strlen(FWhost
), 0);
780 sprintf(buf
, " %d\n", FWport
);
781 send (s
, buf
, strlen(buf
), 0);
788 static int ssh_versioncmp(char *a
, char *b
) {
790 unsigned long av
, bv
;
792 av
= strtoul(a
, &ae
, 10);
793 bv
= strtoul(b
, &be
, 10);
794 if (av
!= bv
) return (av
< bv ?
-1 : +1);
795 if (*ae
== '.') ae
++;
796 if (*be
== '.') be
++;
797 av
= strtoul(ae
, &ae
, 10);
798 bv
= strtoul(be
, &be
, 10);
799 if (av
!= bv
) return (av
< bv ?
-1 : +1);
805 * Utility routine for putting an SSH-protocol `string' into a SHA
809 void sha_string(SHA_State
*s
, void *str
, int len
) {
810 unsigned char lenblk
[4];
811 PUT_32BIT(lenblk
, len
);
812 SHA_Bytes(s
, lenblk
, 4);
813 SHA_Bytes(s
, str
, len
);
817 * SSH2 packet construction functions.
819 void ssh2_pkt_adddata(void *data
, int len
) {
820 pktout
.length
+= len
;
821 if (pktout
.maxlen
< pktout
.length
) {
822 pktout
.maxlen
= pktout
.length
+ 256;
823 pktout
.data
= (pktout
.data
== NULL ?
malloc(pktout
.maxlen
+APIEXTRA
) :
824 realloc(pktout
.data
, pktout
.maxlen
+APIEXTRA
));
826 fatalbox("Out of memory");
828 memcpy(pktout
.data
+pktout
.length
-len
, data
, len
);
830 void ssh2_pkt_addbyte(unsigned char byte
) {
831 ssh2_pkt_adddata(&byte
, 1);
833 void ssh2_pkt_init(int pkt_type
) {
835 ssh2_pkt_addbyte((unsigned char)pkt_type
);
837 void ssh2_pkt_addbool(unsigned char value
) {
838 ssh2_pkt_adddata(&value
, 1);
840 void ssh2_pkt_adduint32(unsigned long value
) {
843 ssh2_pkt_adddata(x
, 4);
845 void ssh2_pkt_addstring_start(void) {
846 ssh2_pkt_adduint32(0);
847 pktout
.savedpos
= pktout
.length
;
849 void ssh2_pkt_addstring_str(char *data
) {
850 ssh2_pkt_adddata(data
, strlen(data
));
851 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
852 pktout
.length
- pktout
.savedpos
);
854 void ssh2_pkt_addstring_data(char *data
, int len
) {
855 ssh2_pkt_adddata(data
, len
);
856 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
857 pktout
.length
- pktout
.savedpos
);
859 void ssh2_pkt_addstring(char *data
) {
860 ssh2_pkt_addstring_start();
861 ssh2_pkt_addstring_str(data
);
863 char *ssh2_mpint_fmt(Bignum b
, int *len
) {
866 p
= malloc(n
* 2 + 1);
868 fatalbox("out of memory");
870 for (i
= 0; i
< n
; i
++) {
871 p
[i
*2+1] = (b
[n
-i
] >> 8) & 0xFF;
872 p
[i
*2+2] = (b
[n
-i
] ) & 0xFF;
875 while (p
[i
] == 0 && (p
[i
+1] & 0x80) == 0)
877 memmove(p
, p
+i
, n
*2+1-i
);
881 void ssh2_pkt_addmp(Bignum b
) {
884 p
= ssh2_mpint_fmt(b
, &len
);
885 ssh2_pkt_addstring_start();
886 ssh2_pkt_addstring_data(p
, len
);
889 void ssh2_pkt_send(void) {
890 int cipherblk
, maclen
, padding
, i
;
891 static unsigned long outgoing_sequence
= 0;
894 * Add padding. At least four bytes, and must also bring total
895 * length (minus MAC) up to a multiple of the block size.
897 cipherblk
= cipher ? cipher
->blksize
: 8; /* block size */
898 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
900 padding
+= (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
901 pktout
.data
[4] = padding
;
902 for (i
= 0; i
< padding
; i
++)
903 pktout
.data
[pktout
.length
+ i
] = random_byte();
904 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
906 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
908 outgoing_sequence
++; /* whether or not we MACed */
911 debug(("Sending packet len=%d\r\n", pktout
.length
+padding
));
912 for (i
= 0; i
< pktout
.length
+padding
; i
++)
913 debug((" %02x", (unsigned char)pktout
.data
[i
]));
918 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
919 maclen
= csmac ? csmac
->len
: 0;
921 s_write(pktout
.data
, pktout
.length
+ padding
+ maclen
);
925 void bndebug(char *string
, Bignum b
) {
928 p
= ssh2_mpint_fmt(b
, &len
);
929 debug(("%s", string
));
930 for (i
= 0; i
< len
; i
++)
931 debug((" %02x", p
[i
]));
937 void sha_mpint(SHA_State
*s
, Bignum b
) {
940 p
= ssh2_mpint_fmt(b
, &len
);
941 sha_string(s
, p
, len
);
946 * SSH2 packet decode functions.
948 unsigned long ssh2_pkt_getuint32(void) {
950 if (pktin
.length
- pktin
.savedpos
< 4)
951 return 0; /* arrgh, no way to decline (FIXME?) */
952 value
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
956 void ssh2_pkt_getstring(char **p
, int *length
) {
958 if (pktin
.length
- pktin
.savedpos
< 4)
960 *length
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
962 if (pktin
.length
- pktin
.savedpos
< *length
)
964 *p
= pktin
.data
+pktin
.savedpos
;
965 pktin
.savedpos
+= *length
;
967 Bignum
ssh2_pkt_getmp(void) {
972 ssh2_pkt_getstring(&p
, &length
);
976 bombout(("internal error: Can't handle negative mpints"));
979 b
= newbn((length
+1)/2);
980 for (i
= 0; i
< length
; i
++) {
983 b
[j
/2+1] |= ((unsigned char)p
[i
]) << 8;
985 b
[j
/2+1] |= ((unsigned char)p
[i
]);
990 static int do_ssh_init(void) {
994 char vlog
[sizeof(vstring
)+20];
999 while (s_read(&c
, 1) == 1) {
1000 if (c
== 'S' && i
< 2) i
++;
1001 else if (c
== 'S' && i
== 2) i
= 2;
1002 else if (c
== 'H' && i
== 2) break;
1006 if (s_read(&c
,1) != 1 || c
!= 'S') return 0;
1007 if (s_read(&c
,1) != 1 || c
!= 'S') return 0;
1008 if (s_read(&c
,1) != 1 || c
!= 'H') return 0;
1010 strcpy(vstring
, "SSH-");
1012 if (s_read(&c
,1) != 1 || c
!= '-') return 0;
1015 if (s_read(&c
,1) != 1)
1017 if (vsp
< vstring
+sizeof(vstring
)-1)
1023 } else if (i
< sizeof(version
)-1)
1031 sprintf(vlog
, "Server version: %s", vstring
);
1032 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1036 * Server version "1.99" means we can choose whether we use v1
1037 * or v2 protocol. Choice is based on cfg.sshprot.
1039 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1041 * This is a v2 server. Begin v2 protocol.
1043 char *verstring
= "SSH-2.0-PuTTY";
1046 * Hash our version string and their version string.
1048 sha_string(&exhash
, verstring
, strlen(verstring
));
1049 sha_string(&exhash
, vstring
, strcspn(vstring
, "\r\n"));
1050 sprintf(vstring
, "%s\n", verstring
);
1051 sprintf(vlog
, "We claim version: %s", verstring
);
1053 logevent("Using SSH protocol version 2");
1054 s_write(vstring
, strlen(vstring
));
1055 ssh_protocol
= ssh2_protocol
;
1057 s_rdpkt
= ssh2_rdpkt
;
1060 * This is a v1 server. Begin v1 protocol.
1062 sprintf(vstring
, "SSH-%s-PuTTY\n",
1063 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"));
1064 sprintf(vlog
, "We claim version: %s", vstring
);
1065 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1067 logevent("Using SSH protocol version 1");
1068 s_write(vstring
, strlen(vstring
));
1069 ssh_protocol
= ssh1_protocol
;
1071 s_rdpkt
= ssh1_rdpkt
;
1078 * Handle the key exchange and user authentication phases.
1080 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1083 unsigned char *rsabuf
, *keystr1
, *keystr2
;
1084 unsigned char cookie
[8];
1085 struct RSAKey servkey
, hostkey
;
1086 struct MD5Context md5c
;
1087 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1088 static int tried_publickey
;
1089 static unsigned char session_id
[16];
1094 if (!ispkt
) crWaitUntil(ispkt
);
1096 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
) {
1097 bombout(("Public key packet not received"));
1101 logevent("Received public keys");
1103 memcpy(cookie
, pktin
.body
, 8);
1105 i
= makekey(pktin
.body
+8, &servkey
, &keystr1
, 0);
1106 j
= makekey(pktin
.body
+8+i
, &hostkey
, &keystr2
, 0);
1109 * Log the host key fingerprint.
1113 logevent("Host key fingerprint is:");
1114 strcpy(logmsg
, " ");
1115 hostkey
.comment
= NULL
;
1116 rsa_fingerprint(logmsg
+strlen(logmsg
), sizeof(logmsg
)-strlen(logmsg
),
1121 supported_ciphers_mask
= GET_32BIT(pktin
.body
+12+i
+j
);
1122 supported_auths_mask
= GET_32BIT(pktin
.body
+16+i
+j
);
1125 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1126 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1127 MD5Update(&md5c
, pktin
.body
, 8);
1128 MD5Final(session_id
, &md5c
);
1130 for (i
=0; i
<32; i
++)
1131 session_key
[i
] = random_byte();
1133 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1135 rsabuf
= malloc(len
);
1137 fatalbox("Out of memory");
1140 * Verify the host key.
1144 * First format the key into a string.
1146 int len
= rsastr_len(&hostkey
);
1147 char fingerprint
[100];
1148 char *keystr
= malloc(len
);
1150 fatalbox("Out of memory");
1151 rsastr_fmt(keystr
, &hostkey
);
1152 rsa_fingerprint(fingerprint
, sizeof(fingerprint
), &hostkey
);
1153 verify_ssh_host_key(savedhost
, savedport
, "rsa", keystr
, fingerprint
);
1157 for (i
=0; i
<32; i
++) {
1158 rsabuf
[i
] = session_key
[i
];
1160 rsabuf
[i
] ^= session_id
[i
];
1163 if (hostkey
.bytes
> servkey
.bytes
) {
1164 rsaencrypt(rsabuf
, 32, &servkey
);
1165 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1167 rsaencrypt(rsabuf
, 32, &hostkey
);
1168 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1171 logevent("Encrypted session key");
1173 cipher_type
= cfg
.cipher
== CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH
:
1174 cfg
.cipher
== CIPHER_DES ? SSH_CIPHER_DES
:
1176 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1177 c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
1178 cipher_type
= SSH_CIPHER_3DES
;
1180 switch (cipher_type
) {
1181 case SSH_CIPHER_3DES
: logevent("Using 3DES encryption"); break;
1182 case SSH_CIPHER_DES
: logevent("Using single-DES encryption"); break;
1183 case SSH_CIPHER_BLOWFISH
: logevent("Using Blowfish encryption"); break;
1186 send_packet(SSH1_CMSG_SESSION_KEY
,
1187 PKT_CHAR
, cipher_type
,
1188 PKT_DATA
, cookie
, 8,
1189 PKT_CHAR
, (len
*8) >> 8, PKT_CHAR
, (len
*8) & 0xFF,
1190 PKT_DATA
, rsabuf
, len
,
1194 logevent("Trying to enable encryption...");
1198 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
1199 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
1201 cipher
->sesskey(session_key
);
1205 if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1206 bombout(("Encryption not successfully enabled"));
1210 logevent("Successfully started encryption");
1214 static char username
[100];
1217 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
1218 c_write("login as: ", 10);
1221 crWaitUntil(!ispkt
);
1222 while (inlen
--) switch (c
= *in
++) {
1229 c_write("\b \b", 3);
1235 c_write("\b \b", 3);
1244 if (((c
>= ' ' && c
<= '~') ||
1245 ((unsigned char)c
>= 160)) && pos
< 40) {
1246 username
[pos
++] = c
;
1253 username
[strcspn(username
, "\n\r")] = '\0';
1256 strncpy(username
, cfg
.username
, 99);
1257 username
[99] = '\0';
1258 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
1259 sprintf(stuff
, "Sent username \"%s\".\r\n", username
);
1260 c_write(stuff
, strlen(stuff
));
1264 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
1266 char userlog
[20+sizeof(username
)];
1267 sprintf(userlog
, "Sent username \"%s\"", username
);
1274 tried_publickey
= 0;
1276 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
1277 static char password
[100];
1278 static char prompt
[200];
1281 static int pwpkt_type
;
1283 * Show password prompt, having first obtained it via a TIS
1284 * or CryptoCard exchange if we're doing TIS or CryptoCard
1287 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
1288 if (agent_exists()) {
1290 * Attempt RSA authentication using Pageant.
1292 static unsigned char request
[5], *response
, *p
;
1293 static int responselen
;
1294 static int i
, nkeys
;
1295 static int authed
= FALSE
;
1298 logevent("Pageant is running. Requesting keys.");
1300 /* Request the keys held by the agent. */
1301 PUT_32BIT(request
, 1);
1302 request
[4] = SSH_AGENTC_REQUEST_RSA_IDENTITIES
;
1303 agent_query(request
, 5, &r
, &responselen
);
1304 response
= (unsigned char *)r
;
1307 nkeys
= GET_32BIT(p
); p
+= 4;
1308 { char buf
[64]; sprintf(buf
, "Pageant has %d keys", nkeys
);
1310 for (i
= 0; i
< nkeys
; i
++) {
1311 static struct RSAKey key
;
1312 static Bignum challenge
;
1313 static char *commentp
;
1314 static int commentlen
;
1316 { char buf
[64]; sprintf(buf
, "Trying Pageant key #%d", i
);
1319 p
+= ssh1_read_bignum(p
, &key
.exponent
);
1320 p
+= ssh1_read_bignum(p
, &key
.modulus
);
1321 commentlen
= GET_32BIT(p
); p
+= 4;
1322 commentp
= p
; p
+= commentlen
;
1323 send_packet(SSH1_CMSG_AUTH_RSA
,
1324 PKT_BIGNUM
, key
.modulus
, PKT_END
);
1326 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1327 logevent("Key refused");
1330 logevent("Received RSA challenge");
1331 ssh1_read_bignum(pktin
.body
, &challenge
);
1333 char *agentreq
, *q
, *ret
;
1335 len
= 1 + 4; /* message type, bit count */
1336 len
+= ssh1_bignum_length(key
.exponent
);
1337 len
+= ssh1_bignum_length(key
.modulus
);
1338 len
+= ssh1_bignum_length(challenge
);
1339 len
+= 16; /* session id */
1340 len
+= 4; /* response format */
1341 agentreq
= malloc(4 + len
);
1342 PUT_32BIT(agentreq
, len
);
1344 *q
++ = SSH_AGENTC_RSA_CHALLENGE
;
1345 PUT_32BIT(q
, ssh1_bignum_bitcount(key
.modulus
));
1347 q
+= ssh1_write_bignum(q
, key
.exponent
);
1348 q
+= ssh1_write_bignum(q
, key
.modulus
);
1349 q
+= ssh1_write_bignum(q
, challenge
);
1350 memcpy(q
, session_id
, 16); q
+= 16;
1351 PUT_32BIT(q
, 1); /* response format */
1352 agent_query(agentreq
, len
+4, &ret
, &retlen
);
1355 if (ret
[4] == SSH_AGENT_RSA_RESPONSE
) {
1356 logevent("Sending Pageant's response");
1357 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1358 PKT_DATA
, ret
+5, 16, PKT_END
);
1361 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1362 logevent("Pageant's response accepted");
1363 if (flags
& FLAG_VERBOSE
) {
1364 c_write("Authenticated using RSA key \"",
1366 c_write(commentp
, commentlen
);
1367 c_write("\" from agent\r\n", 14);
1371 logevent("Pageant's response not accepted");
1373 logevent("Pageant failed to answer challenge");
1377 logevent("No reply received from Pageant");
1380 freebn(key
.exponent
);
1381 freebn(key
.modulus
);
1390 if (*cfg
.keyfile
&& !tried_publickey
)
1391 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
1393 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1395 (supported_auths_mask
& (1<<SSH1_AUTH_TIS
))) {
1396 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
1397 logevent("Requested TIS authentication");
1398 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
1400 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
1401 logevent("TIS authentication declined");
1402 if (flags
& FLAG_INTERACTIVE
)
1403 c_write("TIS authentication refused.\r\n", 29);
1405 int challengelen
= ((pktin
.body
[0] << 24) |
1406 (pktin
.body
[1] << 16) |
1407 (pktin
.body
[2] << 8) |
1409 logevent("Received TIS challenge");
1410 if (challengelen
> sizeof(prompt
)-1)
1411 challengelen
= sizeof(prompt
)-1; /* prevent overrun */
1412 memcpy(prompt
, pktin
.body
+4, challengelen
);
1413 prompt
[challengelen
] = '\0';
1416 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1418 (supported_auths_mask
& (1<<SSH1_AUTH_CCARD
))) {
1419 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
1420 logevent("Requested CryptoCard authentication");
1421 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
1423 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
1424 logevent("CryptoCard authentication declined");
1425 c_write("CryptoCard authentication refused.\r\n", 29);
1427 int challengelen
= ((pktin
.body
[0] << 24) |
1428 (pktin
.body
[1] << 16) |
1429 (pktin
.body
[2] << 8) |
1431 logevent("Received CryptoCard challenge");
1432 if (challengelen
> sizeof(prompt
)-1)
1433 challengelen
= sizeof(prompt
)-1; /* prevent overrun */
1434 memcpy(prompt
, pktin
.body
+4, challengelen
);
1435 strncpy(prompt
+ challengelen
, "\r\nResponse : ",
1436 sizeof(prompt
)-challengelen
);
1437 prompt
[sizeof(prompt
)-1] = '\0';
1440 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
) {
1441 sprintf(prompt
, "%.90s@%.90s's password: ",
1442 cfg
.username
, savedhost
);
1444 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1445 char *comment
= NULL
;
1446 if (flags
& FLAG_VERBOSE
)
1447 c_write("Trying public key authentication.\r\n", 35);
1448 if (!rsakey_encrypted(cfg
.keyfile
, &comment
)) {
1449 if (flags
& FLAG_VERBOSE
)
1450 c_write("No passphrase required.\r\n", 25);
1453 sprintf(prompt
, "Passphrase for key \"%.100s\": ", comment
);
1457 if (!(flags
& FLAG_INTERACTIVE
)) {
1458 if (!ssh_get_password(prompt
, password
, sizeof(password
))) {
1460 * get_password failed to get a password (for
1461 * example because one was supplied on the command
1462 * line which has already failed to work).
1465 logevent("No more passwords to try");
1466 ssh_state
= SSH_STATE_CLOSED
;
1470 c_write(prompt
, strlen(prompt
));
1474 crWaitUntil(!ispkt
);
1475 while (inlen
--) switch (c
= *in
++) {
1492 if (((c
>= ' ' && c
<= '~') ||
1493 ((unsigned char)c
>= 160)) && pos
< sizeof(password
))
1494 password
[pos
++] = c
;
1502 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1504 * Try public key authentication with the specified
1507 static struct RSAKey pubkey
;
1508 static Bignum challenge
, response
;
1510 static unsigned char buffer
[32];
1512 tried_publickey
= 1;
1513 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
1515 c_write("Couldn't load public key from ", 30);
1516 c_write(cfg
.keyfile
, strlen(cfg
.keyfile
));
1517 c_write(".\r\n", 3);
1518 continue; /* go and try password */
1521 c_write("Wrong passphrase.\r\n", 19);
1522 tried_publickey
= 0;
1523 continue; /* try again */
1527 * Send a public key attempt.
1529 send_packet(SSH1_CMSG_AUTH_RSA
,
1530 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
1533 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1534 c_write("Server refused our public key.\r\n", 32);
1535 continue; /* go and try password */
1537 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1538 bombout(("Bizarre response to offer of public key"));
1541 ssh1_read_bignum(pktin
.body
, &challenge
);
1542 response
= rsadecrypt(challenge
, &pubkey
);
1543 freebn(pubkey
.private_exponent
); /* burn the evidence */
1545 for (i
= 0; i
< 32; i
+= 2) {
1546 buffer
[i
] = response
[16-i
/2] >> 8;
1547 buffer
[i
+1] = response
[16-i
/2] & 0xFF;
1551 MD5Update(&md5c
, buffer
, 32);
1552 MD5Update(&md5c
, session_id
, 16);
1553 MD5Final(buffer
, &md5c
);
1555 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1556 PKT_DATA
, buffer
, 16, PKT_END
);
1559 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1560 if (flags
& FLAG_VERBOSE
)
1561 c_write("Failed to authenticate with our public key.\r\n",
1563 continue; /* go and try password */
1564 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1565 bombout(("Bizarre response to RSA authentication response"));
1569 break; /* we're through! */
1571 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
1573 logevent("Sent password");
1574 memset(password
, 0, strlen(password
));
1576 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1577 if (flags
& FLAG_VERBOSE
)
1578 c_write("Access denied\r\n", 15);
1579 logevent("Authentication refused");
1580 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
1581 logevent("Received disconnect request");
1582 ssh_state
= SSH_STATE_CLOSED
;
1584 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1585 bombout(("Strange packet received, type %d", pktin
.type
));
1590 logevent("Authentication successful");
1595 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
) {
1600 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
1603 if (ssh_state
== SSH_STATE_CLOSED
)
1606 if (cfg
.agentfwd
&& agent_exists()) {
1607 logevent("Requesting agent forwarding");
1608 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
1609 do { crReturnV
; } while (!ispkt
);
1610 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
1611 bombout(("Protocol confusion"));
1613 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1614 logevent("Agent forwarding refused");
1616 logevent("Agent forwarding enabled");
1620 send_packet(SSH1_CMSG_REQUEST_PTY
,
1621 PKT_STR
, cfg
.termtype
,
1622 PKT_INT
, rows
, PKT_INT
, cols
,
1623 PKT_INT
, 0, PKT_INT
, 0,
1626 ssh_state
= SSH_STATE_INTERMED
;
1627 do { crReturnV
; } while (!ispkt
);
1628 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
1629 bombout(("Protocol confusion"));
1631 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1632 c_write("Server refused to allocate pty\r\n", 32);
1634 logevent("Allocated pty");
1637 if (*cfg
.remote_cmd
)
1638 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cfg
.remote_cmd
, PKT_END
);
1640 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
1641 logevent("Started session");
1643 ssh_state
= SSH_STATE_SESSION
;
1648 ssh_channels
= newtree234(ssh_channelcmp
);
1653 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
1654 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
1655 long len
= GET_32BIT(pktin
.body
);
1656 c_writedata(pktin
.body
+4, len
);
1657 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
1658 ssh_state
= SSH_STATE_CLOSED
;
1659 logevent("Received disconnect request");
1660 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
1661 /* Remote side is trying to open a channel to talk to our
1662 * agent. Give them back a local channel number. */
1664 struct ssh_channel
*c
;
1666 for (c
= first234(ssh_channels
, &e
); c
; c
= next234(&e
)) {
1668 break; /* found a free number */
1671 c
= malloc(sizeof(struct ssh_channel
));
1672 c
->remoteid
= GET_32BIT(pktin
.body
);
1675 c
->type
= SSH1_SMSG_AGENT_OPEN
; /* identify channel type */
1676 c
->u
.a
.lensofar
= 0;
1677 add234(ssh_channels
, c
);
1678 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
1679 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
1681 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
1682 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
1683 /* Remote side closes a channel. */
1684 unsigned i
= GET_32BIT(pktin
.body
);
1685 struct ssh_channel
*c
;
1686 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
1689 closetype
= (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
1690 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
, PKT_END
);
1691 c
->closes
|= closetype
;
1692 if (c
->closes
== 3) {
1693 del234(ssh_channels
, c
);
1697 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
1698 /* Data sent down one of our channels. */
1699 int i
= GET_32BIT(pktin
.body
);
1700 int len
= GET_32BIT(pktin
.body
+4);
1701 unsigned char *p
= pktin
.body
+8;
1702 struct ssh_channel
*c
;
1703 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
1706 case SSH1_SMSG_AGENT_OPEN
:
1707 /* Data for an agent message. Buffer it. */
1709 if (c
->u
.a
.lensofar
< 4) {
1710 int l
= min(4 - c
->u
.a
.lensofar
, len
);
1711 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
, l
);
1712 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
1714 if (c
->u
.a
.lensofar
== 4) {
1715 c
->u
.a
.totallen
= 4 + GET_32BIT(c
->u
.a
.msglen
);
1716 c
->u
.a
.message
= malloc(c
->u
.a
.totallen
);
1717 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
1719 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
1720 int l
= min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
, len
);
1721 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
, l
);
1722 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
1724 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
1725 void *reply
, *sentreply
;
1727 agent_query(c
->u
.a
.message
, c
->u
.a
.totallen
,
1732 /* Fake SSH_AGENT_FAILURE. */
1733 sentreply
= "\0\0\0\1\5";
1736 send_packet(SSH1_MSG_CHANNEL_DATA
,
1737 PKT_INT
, c
->remoteid
,
1739 PKT_DATA
, sentreply
, replylen
,
1743 free(c
->u
.a
.message
);
1744 c
->u
.a
.lensofar
= 0;
1750 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1751 /* may be from EXEC_SHELL on some servers */
1752 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1753 /* may be from EXEC_SHELL on some servers
1754 * if no pty is available or in other odd cases. Ignore */
1755 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
1756 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
1758 bombout(("Strange packet received: type %d", pktin
.type
));
1762 send_packet(SSH1_CMSG_STDIN_DATA
,
1763 PKT_INT
, inlen
, PKT_DATA
, in
, inlen
, PKT_END
);
1771 * Utility routine for decoding comma-separated strings in KEXINIT.
1773 int in_commasep_string(char *needle
, char *haystack
, int haylen
) {
1774 int needlen
= strlen(needle
);
1777 * Is it at the start of the string?
1779 if (haylen
>= needlen
&& /* haystack is long enough */
1780 !memcmp(needle
, haystack
, needlen
) && /* initial match */
1781 (haylen
== needlen
|| haystack
[needlen
] == ',')
1782 /* either , or EOS follows */
1786 * If not, search for the next comma and resume after that.
1787 * If no comma found, terminate.
1789 while (haylen
> 0 && *haystack
!= ',')
1790 haylen
--, haystack
++;
1793 haylen
--, haystack
++; /* skip over comma itself */
1798 * SSH2 key creation method.
1800 void ssh2_mkkey(Bignum K
, char *H
, char chr
, char *keyspace
) {
1802 /* First 20 bytes. */
1805 SHA_Bytes(&s
, H
, 20);
1806 SHA_Bytes(&s
, &chr
, 1);
1807 SHA_Bytes(&s
, H
, 20);
1808 SHA_Final(&s
, keyspace
);
1809 /* Next 20 bytes. */
1812 SHA_Bytes(&s
, H
, 20);
1813 SHA_Bytes(&s
, keyspace
, 20);
1814 SHA_Final(&s
, keyspace
+20);
1818 * Handle the SSH2 transport layer.
1820 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
1824 static Bignum e
, f
, K
;
1825 static struct ssh_cipher
*cscipher_tobe
= NULL
;
1826 static struct ssh_cipher
*sccipher_tobe
= NULL
;
1827 static struct ssh_mac
*csmac_tobe
= NULL
;
1828 static struct ssh_mac
*scmac_tobe
= NULL
;
1829 static struct ssh_compress
*cscomp_tobe
= NULL
;
1830 static struct ssh_compress
*sccomp_tobe
= NULL
;
1831 static char *hostkeydata
, *sigdata
, *keystr
, *fingerprint
;
1832 static int hostkeylen
, siglen
;
1833 static unsigned char exchange_hash
[20];
1834 static unsigned char keyspace
[40];
1840 * Set up the preferred cipher.
1842 if (cfg
.cipher
== CIPHER_BLOWFISH
) {
1843 ciphers
[0] = &ssh_blowfish_ssh2
;
1844 } else if (cfg
.cipher
== CIPHER_DES
) {
1845 logevent("Single DES not supported in SSH2; using 3DES");
1846 ciphers
[0] = &ssh_3des_ssh2
;
1847 } else if (cfg
.cipher
== CIPHER_3DES
) {
1848 ciphers
[0] = &ssh_3des_ssh2
;
1850 /* Shouldn't happen, but we do want to initialise to _something_. */
1851 ciphers
[0] = &ssh_3des_ssh2
;
1856 * Construct and send our key exchange packet.
1858 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
1859 for (i
= 0; i
< 16; i
++)
1860 ssh2_pkt_addbyte((unsigned char)random_byte());
1861 /* List key exchange algorithms. */
1862 ssh2_pkt_addstring_start();
1863 for (i
= 0; i
< lenof(kex_algs
); i
++) {
1864 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
1865 if (i
< lenof(kex_algs
)-1)
1866 ssh2_pkt_addstring_str(",");
1868 /* List server host key algorithms. */
1869 ssh2_pkt_addstring_start();
1870 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
1871 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
1872 if (i
< lenof(hostkey_algs
)-1)
1873 ssh2_pkt_addstring_str(",");
1875 /* List client->server encryption algorithms. */
1876 ssh2_pkt_addstring_start();
1877 for (i
= 0; i
< lenof(ciphers
); i
++) {
1878 ssh2_pkt_addstring_str(ciphers
[i
]->name
);
1879 if (i
< lenof(ciphers
)-1)
1880 ssh2_pkt_addstring_str(",");
1882 /* List server->client encryption algorithms. */
1883 ssh2_pkt_addstring_start();
1884 for (i
= 0; i
< lenof(ciphers
); i
++) {
1885 ssh2_pkt_addstring_str(ciphers
[i
]->name
);
1886 if (i
< lenof(ciphers
)-1)
1887 ssh2_pkt_addstring_str(",");
1889 /* List client->server MAC algorithms. */
1890 ssh2_pkt_addstring_start();
1891 for (i
= 0; i
< lenof(macs
); i
++) {
1892 ssh2_pkt_addstring_str(macs
[i
]->name
);
1893 if (i
< lenof(macs
)-1)
1894 ssh2_pkt_addstring_str(",");
1896 /* List server->client MAC algorithms. */
1897 ssh2_pkt_addstring_start();
1898 for (i
= 0; i
< lenof(macs
); i
++) {
1899 ssh2_pkt_addstring_str(macs
[i
]->name
);
1900 if (i
< lenof(macs
)-1)
1901 ssh2_pkt_addstring_str(",");
1903 /* List client->server compression algorithms. */
1904 ssh2_pkt_addstring_start();
1905 for (i
= 0; i
< lenof(compressions
); i
++) {
1906 ssh2_pkt_addstring_str(compressions
[i
]->name
);
1907 if (i
< lenof(compressions
)-1)
1908 ssh2_pkt_addstring_str(",");
1910 /* List server->client compression algorithms. */
1911 ssh2_pkt_addstring_start();
1912 for (i
= 0; i
< lenof(compressions
); i
++) {
1913 ssh2_pkt_addstring_str(compressions
[i
]->name
);
1914 if (i
< lenof(compressions
)-1)
1915 ssh2_pkt_addstring_str(",");
1917 /* List client->server languages. Empty list. */
1918 ssh2_pkt_addstring_start();
1919 /* List server->client languages. Empty list. */
1920 ssh2_pkt_addstring_start();
1921 /* First KEX packet does _not_ follow, because we're not that brave. */
1922 ssh2_pkt_addbool(FALSE
);
1924 ssh2_pkt_adduint32(0);
1925 sha_string(&exhash
, pktout
.data
+5, pktout
.length
-5);
1928 if (!ispkt
) crWaitUntil(ispkt
);
1929 sha_string(&exhash
, pktin
.data
+5, pktin
.length
-5);
1932 * Now examine the other side's KEXINIT to see what we're up
1935 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
1936 bombout(("expected key exchange packet from server"));
1939 kex
= NULL
; hostkey
= NULL
; cscipher_tobe
= NULL
; sccipher_tobe
= NULL
;
1940 csmac_tobe
= NULL
; scmac_tobe
= NULL
; cscomp_tobe
= NULL
; sccomp_tobe
= NULL
;
1941 pktin
.savedpos
+= 16; /* skip garbage cookie */
1942 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
1943 for (i
= 0; i
< lenof(kex_algs
); i
++) {
1944 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
1949 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
1950 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
1951 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
1952 hostkey
= hostkey_algs
[i
];
1956 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
1957 for (i
= 0; i
< lenof(ciphers
); i
++) {
1958 if (in_commasep_string(ciphers
[i
]->name
, str
, len
)) {
1959 cscipher_tobe
= ciphers
[i
];
1963 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
1964 for (i
= 0; i
< lenof(ciphers
); i
++) {
1965 if (in_commasep_string(ciphers
[i
]->name
, str
, len
)) {
1966 sccipher_tobe
= ciphers
[i
];
1970 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
1971 for (i
= 0; i
< lenof(macs
); i
++) {
1972 if (in_commasep_string(macs
[i
]->name
, str
, len
)) {
1973 csmac_tobe
= macs
[i
];
1977 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
1978 for (i
= 0; i
< lenof(macs
); i
++) {
1979 if (in_commasep_string(macs
[i
]->name
, str
, len
)) {
1980 scmac_tobe
= macs
[i
];
1984 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
1985 for (i
= 0; i
< lenof(compressions
); i
++) {
1986 if (in_commasep_string(compressions
[i
]->name
, str
, len
)) {
1987 cscomp_tobe
= compressions
[i
];
1991 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
1992 for (i
= 0; i
< lenof(compressions
); i
++) {
1993 if (in_commasep_string(compressions
[i
]->name
, str
, len
)) {
1994 sccomp_tobe
= compressions
[i
];
2000 * Currently we only support Diffie-Hellman and DSS, so let's
2001 * bomb out if those aren't selected.
2003 if (kex
!= &ssh_diffiehellman
|| hostkey
!= &ssh_dss
) {
2004 bombout(("internal fault: chaos in SSH 2 transport layer"));
2009 * Now we begin the fun. Generate and send e for Diffie-Hellman.
2012 ssh2_pkt_init(SSH2_MSG_KEXDH_INIT
);
2017 if (pktin
.type
!= SSH2_MSG_KEXDH_REPLY
) {
2018 bombout(("expected key exchange packet from server"));
2021 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
2022 f
= ssh2_pkt_getmp();
2023 ssh2_pkt_getstring(&sigdata
, &siglen
);
2027 sha_string(&exhash
, hostkeydata
, hostkeylen
);
2028 sha_mpint(&exhash
, e
);
2029 sha_mpint(&exhash
, f
);
2030 sha_mpint(&exhash
, K
);
2031 SHA_Final(&exhash
, exchange_hash
);
2034 debug(("Exchange hash is:\r\n"));
2035 for (i
= 0; i
< 20; i
++)
2036 debug((" %02x", exchange_hash
[i
]));
2040 hostkey
->setkey(hostkeydata
, hostkeylen
);
2041 if (!hostkey
->verifysig(sigdata
, siglen
, exchange_hash
, 20)) {
2042 bombout(("Server failed host key check"));
2047 * Expect SSH2_MSG_NEWKEYS from server.
2050 if (pktin
.type
!= SSH2_MSG_NEWKEYS
) {
2051 bombout(("expected new-keys packet from server"));
2056 * Authenticate remote host: verify host key. (We've already
2057 * checked the signature of the exchange hash.)
2059 keystr
= hostkey
->fmtkey();
2060 fingerprint
= hostkey
->fingerprint();
2061 verify_ssh_host_key(savedhost
, savedport
, hostkey
->keytype
,
2062 keystr
, fingerprint
);
2063 logevent("Host key fingerprint is:");
2064 logevent(fingerprint
);
2069 * Send SSH2_MSG_NEWKEYS.
2071 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
2075 * Create and initialise session keys.
2077 cscipher
= cscipher_tobe
;
2078 sccipher
= sccipher_tobe
;
2081 cscomp
= cscomp_tobe
;
2082 sccomp
= sccomp_tobe
;
2084 * Set IVs after keys.
2086 ssh2_mkkey(K
, exchange_hash
, 'C', keyspace
); cscipher
->setcskey(keyspace
);
2087 ssh2_mkkey(K
, exchange_hash
, 'D', keyspace
); cscipher
->setsckey(keyspace
);
2088 ssh2_mkkey(K
, exchange_hash
, 'A', keyspace
); cscipher
->setcsiv(keyspace
);
2089 ssh2_mkkey(K
, exchange_hash
, 'B', keyspace
); sccipher
->setsciv(keyspace
);
2090 ssh2_mkkey(K
, exchange_hash
, 'E', keyspace
); csmac
->setcskey(keyspace
);
2091 ssh2_mkkey(K
, exchange_hash
, 'F', keyspace
); scmac
->setsckey(keyspace
);
2094 * Now we're encrypting. Begin returning 1 to the protocol main
2095 * function so that other things can run on top of the
2096 * transport. If we ever see a KEXINIT, we must go back to the
2101 } while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
));
2102 goto begin_key_exchange
;
2108 * Handle the SSH2 userauth and connection layers.
2110 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
2112 static unsigned long remote_winsize
;
2113 static unsigned long remote_maxpkt
;
2118 * Request userauth protocol, and await a response to it.
2120 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
2121 ssh2_pkt_addstring("ssh-userauth");
2123 crWaitUntilV(ispkt
);
2124 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
) {
2125 bombout(("Server refused user authentication protocol"));
2130 * FIXME: currently we support only password authentication.
2131 * (This places us technically in violation of the SSH2 spec.
2132 * We must fix this.)
2136 * Get a username and a password.
2138 static char username
[100];
2139 static char password
[100];
2143 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
2144 c_write("login as: ", 10);
2147 crWaitUntilV(!ispkt
);
2148 while (inlen
--) switch (c
= *in
++) {
2155 c_write("\b \b", 3);
2161 c_write("\b \b", 3);
2170 if (((c
>= ' ' && c
<= '~') ||
2171 ((unsigned char)c
>= 160)) && pos
< 40) {
2172 username
[pos
++] = c
;
2179 username
[strcspn(username
, "\n\r")] = '\0';
2182 strncpy(username
, cfg
.username
, 99);
2183 username
[99] = '\0';
2184 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
2185 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
2186 c_write(stuff
, strlen(stuff
));
2190 if (!(flags
& FLAG_INTERACTIVE
)) {
2192 sprintf(prompt
, "%.90s@%.90s's password: ", cfg
.username
, savedhost
);
2193 if (!ssh_get_password(prompt
, password
, sizeof(password
))) {
2195 * get_password failed to get a password (for
2196 * example because one was supplied on the command
2197 * line which has already failed to work).
2200 logevent("No more passwords to try");
2201 ssh_state
= SSH_STATE_CLOSED
;
2205 c_write("password: ", 10);
2210 crWaitUntilV(!ispkt
);
2211 while (inlen
--) switch (c
= *in
++) {
2228 if (((c
>= ' ' && c
<= '~') ||
2229 ((unsigned char)c
>= 160)) && pos
< 40)
2230 password
[pos
++] = c
;
2237 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
2238 ssh2_pkt_addstring(username
);
2239 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2240 ssh2_pkt_addstring("password");
2241 ssh2_pkt_addbool(FALSE
);
2242 ssh2_pkt_addstring(password
);
2245 crWaitUntilV(ispkt
);
2246 if (pktin
.type
!= SSH2_MSG_USERAUTH_SUCCESS
) {
2247 c_write("Access denied\r\n", 15);
2248 logevent("Authentication refused");
2254 * Now we're authenticated for the connection protocol. The
2255 * connection protocol will automatically have started at this
2256 * point; there's no need to send SERVICE_REQUEST.
2260 * So now create a channel with a session in it.
2262 mainchan
= malloc(sizeof(struct ssh_channel
));
2263 mainchan
->localid
= 100; /* as good as any */
2264 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
2265 ssh2_pkt_addstring("session");
2266 ssh2_pkt_adduint32(mainchan
->localid
);
2267 ssh2_pkt_adduint32(0x7FFFFFFFUL
); /* our window size */
2268 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
2270 crWaitUntilV(ispkt
);
2271 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
2272 bombout(("Server refused to open a session"));
2274 /* FIXME: error data comes back in FAILURE packet */
2276 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
2277 bombout(("Server's channel confirmation cited wrong channel"));
2280 mainchan
->remoteid
= ssh2_pkt_getuint32();
2281 mainchan
->u
.v2
.remwindow
= ssh2_pkt_getuint32();
2282 mainchan
->u
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
2283 mainchan
->u
.v2
.outbuffer
= NULL
;
2284 mainchan
->u
.v2
.outbuflen
= mainchan
->u
.v2
.outbufsize
= 0;
2285 logevent("Opened channel for session");
2288 * Now allocate a pty for the session.
2291 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
2292 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
2293 ssh2_pkt_addstring("pty-req");
2294 ssh2_pkt_addbool(1); /* want reply */
2295 ssh2_pkt_addstring(cfg
.termtype
);
2296 ssh2_pkt_adduint32(cols
);
2297 ssh2_pkt_adduint32(rows
);
2298 ssh2_pkt_adduint32(0); /* pixel width */
2299 ssh2_pkt_adduint32(0); /* pixel height */
2300 ssh2_pkt_addstring_start();
2301 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
2305 crWaitUntilV(ispkt
);
2306 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
2307 /* FIXME: be able to handle other channels here */
2308 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2309 continue; /* wrong channel */
2310 mainchan
->u
.v2
.remwindow
+= ssh2_pkt_getuint32();
2312 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
2314 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
2315 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
2316 bombout(("Server got confused by pty request"));
2319 c_write("Server refused to allocate pty\r\n", 32);
2321 logevent("Allocated pty");
2326 * Start a shell or a remote command.
2328 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
2329 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
2330 if (*cfg
.remote_cmd
) {
2331 ssh2_pkt_addstring("exec");
2332 ssh2_pkt_addbool(1); /* want reply */
2333 ssh2_pkt_addstring(cfg
.remote_cmd
);
2335 ssh2_pkt_addstring("shell");
2336 ssh2_pkt_addbool(1); /* want reply */
2340 crWaitUntilV(ispkt
);
2341 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
2342 /* FIXME: be able to handle other channels here */
2343 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2344 continue; /* wrong channel */
2345 mainchan
->u
.v2
.remwindow
+= ssh2_pkt_getuint32();
2347 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
2348 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
2349 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
2350 bombout(("Server got confused by shell/command request"));
2353 bombout(("Server refused to start a shell/command"));
2356 logevent("Started a shell/command");
2365 static int try_send
;
2369 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
2370 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
2373 /* FIXME: be able to handle other channels here */
2374 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2375 continue; /* wrong channel */
2376 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
2377 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
2378 continue; /* extended but not stderr */
2379 ssh2_pkt_getstring(&data
, &length
);
2381 c_writedata(data
, length
);
2383 * Enlarge the window again at the remote side,
2384 * just in case it ever runs down and they fail
2385 * to send us any more data.
2387 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
2388 ssh2_pkt_adduint32(mainchan
->remoteid
);
2389 ssh2_pkt_adduint32(length
);
2392 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
2393 ssh_state
= SSH_STATE_CLOSED
;
2394 logevent("Received disconnect message");
2395 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
2396 continue; /* exit status et al; ignore (FIXME?) */
2397 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
2398 continue; /* remote sends EOF; ignore */
2399 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
2400 /* FIXME: be able to handle other channels here */
2401 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2402 continue; /* wrong channel */
2403 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2404 ssh2_pkt_adduint32(mainchan
->remoteid
);
2406 /* FIXME: mark the channel as closed */
2407 if (1 /* FIXME: "all channels are closed" */) {
2408 logevent("All channels closed. Disconnecting");
2409 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
2412 continue; /* remote sends close; ignore (FIXME) */
2413 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
2414 /* FIXME: be able to handle other channels here */
2415 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2416 continue; /* wrong channel */
2417 mainchan
->u
.v2
.remwindow
+= ssh2_pkt_getuint32();
2420 bombout(("Strange packet received: type %d", pktin
.type
));
2425 * We have spare data. Add it to the channel buffer.
2427 if (mainchan
->u
.v2
.outbufsize
<
2428 mainchan
->u
.v2
.outbuflen
+ inlen
) {
2429 mainchan
->u
.v2
.outbufsize
=
2430 mainchan
->u
.v2
.outbuflen
+ inlen
+ 1024;
2431 mainchan
->u
.v2
.outbuffer
= srealloc(mainchan
->u
.v2
.outbuffer
,
2432 mainchan
->u
.v2
.outbufsize
);
2434 memcpy(mainchan
->u
.v2
.outbuffer
+ mainchan
->u
.v2
.outbuflen
,
2436 mainchan
->u
.v2
.outbuflen
+= inlen
;
2441 * Try to send data on the channel if we can. (FIXME:
2442 * on _all_ channels.)
2444 while (mainchan
->u
.v2
.remwindow
> 0 &&
2445 mainchan
->u
.v2
.outbuflen
> 0) {
2446 unsigned len
= mainchan
->u
.v2
.remwindow
;
2447 if (len
> mainchan
->u
.v2
.outbuflen
)
2448 len
= mainchan
->u
.v2
.outbuflen
;
2449 if (len
> mainchan
->u
.v2
.remmaxpkt
)
2450 len
= mainchan
->u
.v2
.remmaxpkt
;
2451 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
2452 ssh2_pkt_adduint32(mainchan
->remoteid
);
2453 ssh2_pkt_addstring_start();
2454 ssh2_pkt_addstring_data(mainchan
->u
.v2
.outbuffer
, len
);
2456 mainchan
->u
.v2
.outbuflen
-= len
;
2457 memmove(mainchan
->u
.v2
.outbuffer
, mainchan
->u
.v2
.outbuffer
+len
,
2458 mainchan
->u
.v2
.outbuflen
);
2459 mainchan
->u
.v2
.remwindow
-= len
;
2468 * Handle the top-level SSH2 protocol.
2470 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
2472 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
2474 do_ssh2_authconn(in
, inlen
, ispkt
);
2478 * Called to set up the connection. Will arrange for WM_NETEVENT
2479 * messages to be passed to the specified window, whose window
2480 * procedure should then call telnet_msg().
2482 * Returns an error message, or NULL on success.
2484 static char *ssh_init (HWND hwnd
, char *host
, int port
, char **realhost
) {
2488 if(crypto_startup() == 0)
2489 return "Microsoft high encryption pack not installed!";
2492 p
= connect_to_host(host
, port
, realhost
);
2497 return "Protocol initialisation error";
2499 if (hwnd
&& WSAAsyncSelect (s
, hwnd
, WM_NETEVENT
, FD_READ
| FD_CLOSE
) == SOCKET_ERROR
)
2500 switch (WSAGetLastError()) {
2501 case WSAENETDOWN
: return "Network is down";
2502 default: return "WSAAsyncSelect(): unknown error";
2509 * Process a WM_NETEVENT message. Will return 0 if the connection
2510 * has closed, or <0 for a socket error.
2512 static int ssh_msg (WPARAM wParam
, LPARAM lParam
) {
2517 * Because reading less than the whole of the available pending
2518 * data can generate an FD_READ event, we need to allow for the
2519 * possibility that FD_READ may arrive with FD_CLOSE already in
2520 * the queue; so it's possible that we can get here even with s
2521 * invalid. If so, we return 1 and don't worry about it.
2523 if (s
== INVALID_SOCKET
)
2526 if (WSAGETSELECTERROR(lParam
) != 0) {
2529 return -WSAGETSELECTERROR(lParam
);
2532 switch (WSAGETSELECTEVENT(lParam
)) {
2535 ret
= recv(s
, buf
, sizeof(buf
), 0);
2536 if (ret
< 0 && WSAGetLastError() == WSAEWOULDBLOCK
)
2538 if (ret
< 0) { /* any _other_ error */
2541 return -10000-WSAGetLastError();
2547 ssh_gotdata (buf
, ret
);
2548 if (ssh_state
== SSH_STATE_CLOSED
) {
2555 return 1; /* shouldn't happen, but WTF */
2559 * Called to send data down the Telnet connection.
2561 static void ssh_send (char *buf
, int len
) {
2562 if (s
== INVALID_SOCKET
)
2565 ssh_protocol(buf
, len
, 0);
2569 * Called to set the size of the window from Telnet's POV.
2571 static void ssh_size(void) {
2572 switch (ssh_state
) {
2573 case SSH_STATE_BEFORE_SIZE
:
2574 case SSH_STATE_CLOSED
:
2575 break; /* do nothing */
2576 case SSH_STATE_INTERMED
:
2577 size_needed
= TRUE
; /* buffer for later */
2579 case SSH_STATE_SESSION
:
2581 send_packet(SSH1_CMSG_WINDOW_SIZE
,
2582 PKT_INT
, rows
, PKT_INT
, cols
,
2583 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
2589 * Send Telnet special codes. TS_EOF is useful for `plink', so you
2590 * can send an EOF and collect resulting output (e.g. `plink
2593 static void ssh_special (Telnet_Special code
) {
2594 if (code
== TS_EOF
) {
2595 if (ssh_version
== 1) {
2596 send_packet(SSH1_CMSG_EOF
, PKT_END
);
2598 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
2599 ssh2_pkt_adduint32(mainchan
->remoteid
);
2602 logevent("Sent EOF message");
2608 static SOCKET
ssh_socket(void) { return s
; }
2610 static int ssh_sendok(void) { return ssh_send_ok
; }
2612 Backend ssh_backend
= {