19 #define logevent(s) { logevent(s); \
20 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
21 fprintf(stderr, "%s\n", s); }
23 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
24 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
25 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
26 #define SSH1_CMSG_USER 4 /* 0x4 */
27 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
28 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
29 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
30 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
31 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
32 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
33 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
34 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
35 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
36 #define SSH1_SMSG_FAILURE 15 /* 0xf */
37 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
38 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
39 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
40 #define SSH1_CMSG_EOF 19 /* 0x13 */
41 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
42 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
43 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
44 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
45 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
46 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
47 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
48 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
49 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
50 #define SSH1_MSG_IGNORE 32 /* 0x20 */
51 #define SSH1_MSG_DEBUG 36 /* 0x24 */
52 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
53 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
54 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
55 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
56 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
57 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
59 #define SSH1_AUTH_TIS 5 /* 0x5 */
60 #define SSH1_AUTH_CCARD 16 /* 0x10 */
62 #define SSH_AGENTC_REQUEST_RSA_IDENTITIES 1 /* 0x1 */
63 #define SSH_AGENT_RSA_IDENTITIES_ANSWER 2 /* 0x2 */
64 #define SSH_AGENTC_RSA_CHALLENGE 3 /* 0x3 */
65 #define SSH_AGENT_RSA_RESPONSE 4 /* 0x4 */
66 #define SSH_AGENT_FAILURE 5 /* 0x5 */
67 #define SSH_AGENT_SUCCESS 6 /* 0x6 */
68 #define SSH_AGENTC_ADD_RSA_IDENTITY 7 /* 0x7 */
69 #define SSH_AGENTC_REMOVE_RSA_IDENTITY 8 /* 0x8 */
71 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
72 #define SSH2_MSG_IGNORE 2 /* 0x2 */
73 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
74 #define SSH2_MSG_DEBUG 4 /* 0x4 */
75 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
76 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
77 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
78 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
79 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
80 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
81 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
82 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
83 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
84 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
85 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
86 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
87 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
88 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
89 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
90 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
91 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
92 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
93 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
94 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
95 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
96 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
97 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
98 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
99 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
100 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
102 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
103 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
104 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
105 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
107 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
109 #define GET_32BIT(cp) \
110 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
111 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
112 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
113 ((unsigned long)(unsigned char)(cp)[3]))
115 #define PUT_32BIT(cp, value) { \
116 (cp)[0] = (unsigned char)((value) >> 24); \
117 (cp)[1] = (unsigned char)((value) >> 16); \
118 (cp)[2] = (unsigned char)((value) >> 8); \
119 (cp)[3] = (unsigned char)(value); }
121 enum { PKT_END
, PKT_INT
, PKT_CHAR
, PKT_DATA
, PKT_STR
, PKT_BIGNUM
};
123 /* Coroutine mechanics for the sillier bits of the code */
124 #define crBegin1 static int crLine = 0;
125 #define crBegin2 switch(crLine) { case 0:;
126 #define crBegin crBegin1; crBegin2;
127 #define crFinish(z) } crLine = 0; return (z)
128 #define crFinishV } crLine = 0; return
129 #define crReturn(z) \
131 crLine=__LINE__; return (z); case __LINE__:;\
135 crLine=__LINE__; return; case __LINE__:;\
137 #define crStop(z) do{ crLine = 0; return (z); }while(0)
138 #define crStopV do{ crLine = 0; return; }while(0)
139 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
140 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
142 extern struct ssh_cipher ssh_3des
;
143 extern struct ssh_cipher ssh_3des_ssh2
;
144 extern struct ssh_cipher ssh_des
;
145 extern struct ssh_cipher ssh_blowfish_ssh1
;
146 extern struct ssh_cipher ssh_blowfish_ssh2
;
149 * Ciphers for SSH2. We miss out single-DES because it isn't
150 * supported; also 3DES and Blowfish are both done differently from
151 * SSH1. (3DES uses outer chaining; Blowfish has the opposite
152 * endianness and different-sized keys.)
154 * The first entry in this array is set up to be whatever the user
155 * asks for as a cipher. Thereafter there is a fixed preference
156 * order of fallback ciphers.
158 struct ssh_cipher
*ciphers
[] = { NULL
, &ssh_blowfish_ssh2
, &ssh_3des_ssh2
};
160 extern struct ssh_kex ssh_diffiehellman
;
161 struct ssh_kex
*kex_algs
[] = { &ssh_diffiehellman
};
163 extern struct ssh_hostkey ssh_dss
;
164 struct ssh_hostkey
*hostkey_algs
[] = { &ssh_dss
};
166 extern struct ssh_mac ssh_sha1
;
168 static SHA_State exhash
;
170 static void nullmac_key(unsigned char *key
) { }
171 static void nullmac_generate(unsigned char *blk
, int len
, unsigned long seq
) { }
172 static int nullmac_verify(unsigned char *blk
, int len
, unsigned long seq
) { return 1; }
173 struct ssh_mac ssh_mac_none
= {
174 nullmac_key
, nullmac_key
, nullmac_generate
, nullmac_verify
, "none", 0
176 struct ssh_mac
*macs
[] = { &ssh_sha1
, &ssh_mac_none
};
178 struct ssh_compress ssh_comp_none
= {
181 struct ssh_compress
*compressions
[] = { &ssh_comp_none
};
183 static SOCKET s
= INVALID_SOCKET
;
185 static unsigned char session_key
[32];
186 static struct ssh_cipher
*cipher
= NULL
;
187 static struct ssh_cipher
*cscipher
= NULL
;
188 static struct ssh_cipher
*sccipher
= NULL
;
189 static struct ssh_mac
*csmac
= NULL
;
190 static struct ssh_mac
*scmac
= NULL
;
191 static struct ssh_compress
*cscomp
= NULL
;
192 static struct ssh_compress
*sccomp
= NULL
;
193 static struct ssh_kex
*kex
= NULL
;
194 static struct ssh_hostkey
*hostkey
= NULL
;
195 int (*ssh_get_password
)(const char *prompt
, char *str
, int maxlen
) = NULL
;
197 static char *savedhost
;
198 static int ssh_send_ok
;
201 * 2-3-4 tree storing channels.
204 unsigned remoteid
, localid
;
208 struct ssh_agent_channel
{
209 unsigned char *message
;
210 unsigned char msglen
[4];
211 int lensofar
, totallen
;
213 struct ssh2_data_channel
{
214 unsigned char *outbuffer
;
215 unsigned outbuflen
, outbufsize
;
216 unsigned remwindow
, remmaxpkt
;
220 static tree234
*ssh_channels
; /* indexed by local id */
221 static int ssh_channelcmp(void *av
, void *bv
) {
222 struct ssh_channel
*a
= (struct ssh_channel
*)av
;
223 struct ssh_channel
*b
= (struct ssh_channel
*)bv
;
224 if (a
->localid
< b
->localid
) return -1;
225 if (a
->localid
> b
->localid
) return +1;
228 static int ssh_channelfind(void *av
, void *bv
) {
229 unsigned *a
= (unsigned *)av
;
230 struct ssh_channel
*b
= (struct ssh_channel
*)bv
;
231 if (*a
< b
->localid
) return -1;
232 if (*a
> b
->localid
) return +1;
236 static struct ssh_channel
*mainchan
; /* primary session channel */
239 SSH_STATE_BEFORE_SIZE
,
243 } ssh_state
= SSH_STATE_BEFORE_SIZE
;
245 static int size_needed
= FALSE
;
247 static void s_write (char *buf
, int len
) {
249 int i
= send (s
, buf
, len
, 0);
252 fatalbox("Lost connection while sending");
258 static int s_read (char *buf
, int len
) {
261 int i
= recv (s
, buf
, len
, 0);
264 len
-= i
, buf
+= i
, ret
+= i
;
271 static void c_write (char *buf
, int len
) {
272 if ((flags
& FLAG_STDERR
)) {
274 for (i
= 0; i
< len
; i
++)
276 fputc(buf
[i
], stderr
);
292 static struct Packet pktin
= { 0, 0, NULL
, NULL
, 0 };
293 static struct Packet pktout
= { 0, 0, NULL
, NULL
, 0 };
295 static int ssh_version
;
296 static void (*ssh_protocol
)(unsigned char *in
, int inlen
, int ispkt
);
297 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
);
298 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
);
299 static void ssh_size(void);
301 static int (*s_rdpkt
)(unsigned char **data
, int *datalen
);
304 * Collect incoming data in the incoming packet buffer.
305 * Decipher and verify the packet when it is completely read.
306 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
307 * Update the *data and *datalen variables.
308 * Return the additional nr of bytes needed, or 0 when
309 * a complete packet is available.
311 static int ssh1_rdpkt(unsigned char **data
, int *datalen
)
313 static long len
, pad
, biglen
, to_read
;
314 static unsigned long realcrc
, gotcrc
;
315 static unsigned char *p
;
325 for (i
= len
= 0; i
< 4; i
++) {
326 while ((*datalen
) == 0)
328 len
= (len
<< 8) + **data
;
329 (*data
)++, (*datalen
)--;
333 if (len
== 0x52656d6f) { /* "Remo"te server has closed ... */
334 len
= 0x300; /* big enough to carry to end */
340 pktin
.length
= len
- 5;
342 if (pktin
.maxlen
< biglen
) {
343 pktin
.maxlen
= biglen
;
344 pktin
.data
= (pktin
.data
== NULL ?
malloc(biglen
+APIEXTRA
) :
345 realloc(pktin
.data
, biglen
+APIEXTRA
));
347 fatalbox("Out of memory");
352 while (to_read
> 0) {
355 while ((*datalen
) == 0)
357 if (chunk
> (*datalen
))
359 memcpy(p
, *data
, chunk
);
367 cipher
->decrypt(pktin
.data
, biglen
);
369 pktin
.type
= pktin
.data
[pad
];
370 pktin
.body
= pktin
.data
+ pad
+ 1;
372 realcrc
= crc32(pktin
.data
, biglen
-4);
373 gotcrc
= GET_32BIT(pktin
.data
+biglen
-4);
374 if (gotcrc
!= realcrc
) {
375 fatalbox("Incorrect CRC received on packet");
378 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
379 pktin
.type
== SSH1_SMSG_STDERR_DATA
||
380 pktin
.type
== SSH1_MSG_DEBUG
||
381 pktin
.type
== SSH1_SMSG_AUTH_TIS_CHALLENGE
||
382 pktin
.type
== SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
383 long strlen
= GET_32BIT(pktin
.body
);
384 if (strlen
+ 4 != pktin
.length
)
385 fatalbox("Received data packet with bogus string length");
388 if (pktin
.type
== SSH1_MSG_DEBUG
) {
389 /* log debug message */
391 int strlen
= GET_32BIT(pktin
.body
);
392 strcpy(buf
, "Remote: ");
393 if (strlen
> 70) strlen
= 70;
394 memcpy(buf
+8, pktin
.body
+4, strlen
);
395 buf
[8+strlen
] = '\0';
398 } else if (pktin
.type
== SSH1_MSG_IGNORE
) {
406 static int ssh2_rdpkt(unsigned char **data
, int *datalen
)
408 static long len
, pad
, payload
, packetlen
, maclen
;
410 static int cipherblk
;
411 static unsigned long incoming_sequence
= 0;
421 cipherblk
= cipher
->blksize
;
427 if (pktin
.maxlen
< cipherblk
) {
428 pktin
.maxlen
= cipherblk
;
429 pktin
.data
= (pktin
.data
== NULL ?
malloc(cipherblk
+APIEXTRA
) :
430 realloc(pktin
.data
, cipherblk
+APIEXTRA
));
432 fatalbox("Out of memory");
436 * Acquire and decrypt the first block of the packet. This will
437 * contain the length and padding details.
439 for (i
= len
= 0; i
< cipherblk
; i
++) {
440 while ((*datalen
) == 0)
441 crReturn(cipherblk
-i
);
442 pktin
.data
[i
] = *(*data
)++;
446 if (!memcmp(pktin
.data
, "Remo", 4)) {/* "Remo"te server has closed ... */
451 sccipher
->decrypt(pktin
.data
, cipherblk
);
454 * Now get the length and padding figures.
456 len
= GET_32BIT(pktin
.data
);
460 * This enables us to deduce the payload length.
462 payload
= len
- pad
- 1;
464 pktin
.length
= payload
+ 5;
467 * So now we can work out the total packet length.
470 maclen
= scmac ? scmac
->len
: 0;
473 * Adjust memory allocation if packet is too big.
475 if (pktin
.maxlen
< packetlen
+maclen
) {
476 pktin
.maxlen
= packetlen
+maclen
;
477 pktin
.data
= (pktin
.data
== NULL ?
malloc(pktin
.maxlen
+APIEXTRA
) :
478 realloc(pktin
.data
, pktin
.maxlen
+APIEXTRA
));
480 fatalbox("Out of memory");
484 * Read and decrypt the remainder of the packet.
486 for (i
= cipherblk
; i
< packetlen
+ maclen
; i
++) {
487 while ((*datalen
) == 0)
488 crReturn(packetlen
+ maclen
- i
);
489 pktin
.data
[i
] = *(*data
)++;
492 /* Decrypt everything _except_ the MAC. */
494 sccipher
->decrypt(pktin
.data
+ cipherblk
, packetlen
- cipherblk
);
497 debug(("Got packet len=%d pad=%d\r\n", len
, pad
));
498 for (i
= 0; i
< packetlen
; i
++)
499 debug((" %02x", (unsigned char)pktin
.data
[i
]));
506 if (scmac
&& !scmac
->verify(pktin
.data
, len
+4, incoming_sequence
))
507 fatalbox("Incorrect MAC received on packet");
508 incoming_sequence
++; /* whether or not we MACed */
511 pktin
.type
= pktin
.data
[5];
513 if (pktin
.type
== SSH2_MSG_IGNORE
|| pktin
.type
== SSH2_MSG_DEBUG
)
514 goto next_packet
; /* FIXME: print DEBUG message */
519 static void ssh_gotdata(unsigned char *data
, int datalen
)
521 while (datalen
> 0) {
522 if ( s_rdpkt(&data
, &datalen
) == 0 ) {
523 ssh_protocol(NULL
, 0, 1);
524 if (ssh_state
== SSH_STATE_CLOSED
) {
532 static void s_wrpkt_start(int type
, int len
) {
535 len
+= 5; /* type and CRC */
539 pktout
.length
= len
-5;
540 if (pktout
.maxlen
< biglen
) {
541 pktout
.maxlen
= biglen
;
543 /* Allocate enough buffer space for extra block
544 * for MS CryptEncrypt() */
545 pktout
.data
= (pktout
.data
== NULL ?
malloc(biglen
+12) :
546 realloc(pktout
.data
, biglen
+12));
548 pktout
.data
= (pktout
.data
== NULL ?
malloc(biglen
+4) :
549 realloc(pktout
.data
, biglen
+4));
552 fatalbox("Out of memory");
556 pktout
.body
= pktout
.data
+4+pad
+1;
559 static void s_wrpkt(void) {
560 int pad
, len
, biglen
, i
;
563 len
= pktout
.length
+ 5; /* type and CRC */
567 pktout
.body
[-1] = pktout
.type
;
568 for (i
=0; i
<pad
; i
++)
569 pktout
.data
[i
+4] = random_byte();
570 crc
= crc32(pktout
.data
+4, biglen
-4);
571 PUT_32BIT(pktout
.data
+biglen
, crc
);
572 PUT_32BIT(pktout
.data
, len
);
575 cipher
->encrypt(pktout
.data
+4, biglen
);
577 s_write(pktout
.data
, biglen
+4);
581 * Construct a packet with the specified contents and
582 * send it to the server.
584 static void send_packet(int pkttype
, ...)
587 unsigned char *p
, *argp
, argchar
;
588 unsigned long argint
;
589 int pktlen
, argtype
, arglen
;
593 va_start(args
, pkttype
);
594 while ((argtype
= va_arg(args
, int)) != PKT_END
) {
597 (void) va_arg(args
, int);
601 (void) va_arg(args
, char);
605 (void) va_arg(args
, unsigned char *);
606 arglen
= va_arg(args
, int);
610 argp
= va_arg(args
, unsigned char *);
611 arglen
= strlen(argp
);
612 pktlen
+= 4 + arglen
;
615 bn
= va_arg(args
, Bignum
);
616 pktlen
+= ssh1_bignum_length(bn
);
624 s_wrpkt_start(pkttype
, pktlen
);
627 va_start(args
, pkttype
);
628 while ((argtype
= va_arg(args
, int)) != PKT_END
) {
631 argint
= va_arg(args
, int);
632 PUT_32BIT(p
, argint
);
636 argchar
= va_arg(args
, unsigned char);
641 argp
= va_arg(args
, unsigned char *);
642 arglen
= va_arg(args
, int);
643 memcpy(p
, argp
, arglen
);
647 argp
= va_arg(args
, unsigned char *);
648 arglen
= strlen(argp
);
649 PUT_32BIT(p
, arglen
);
650 memcpy(p
+ 4, argp
, arglen
);
654 bn
= va_arg(args
, Bignum
);
655 p
+= ssh1_write_bignum(p
, bn
);
666 * Connect to specified host and port.
667 * Returns an error message, or NULL on success.
668 * Also places the canonical host name into `realhost'.
670 static char *connect_to_host(char *host
, int port
, char **realhost
)
680 savedhost
= malloc(1+strlen(host
));
682 fatalbox("Out of memory");
683 strcpy(savedhost
, host
);
686 port
= 22; /* default ssh port */
698 if ( (a
= inet_addr(host
)) == (unsigned long) INADDR_NONE
) {
699 if ( (h
= gethostbyname(host
)) == NULL
)
700 switch (WSAGetLastError()) {
701 case WSAENETDOWN
: return "Network is down";
702 case WSAHOST_NOT_FOUND
: case WSANO_DATA
:
703 return "Host does not exist";
704 case WSATRY_AGAIN
: return "Host not found";
705 default: return "gethostbyname: unknown error";
707 memcpy (&a
, h
->h_addr
, sizeof(a
));
708 *realhost
= h
->h_name
;
719 s
= socket(AF_INET
, SOCK_STREAM
, 0);
720 if (s
== INVALID_SOCKET
)
721 switch (WSAGetLastError()) {
722 case WSAENETDOWN
: return "Network is down";
723 case WSAEAFNOSUPPORT
: return "TCP/IP support not present";
724 default: return "socket(): unknown error";
728 * Bind to local address.
730 addr
.sin_family
= AF_INET
;
731 addr
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
732 addr
.sin_port
= htons(0);
733 if (bind (s
, (struct sockaddr
*)&addr
, sizeof(addr
)) == SOCKET_ERROR
)
734 switch (WSAGetLastError()) {
735 case WSAENETDOWN
: return "Network is down";
736 default: return "bind(): unknown error";
740 * Connect to remote address.
742 addr
.sin_addr
.s_addr
= htonl(a
);
743 addr
.sin_port
= htons((short)port
);
744 if (connect (s
, (struct sockaddr
*)&addr
, sizeof(addr
)) == SOCKET_ERROR
)
745 switch (WSAGetLastError()) {
746 case WSAENETDOWN
: return "Network is down";
747 case WSAECONNREFUSED
: return "Connection refused";
748 case WSAENETUNREACH
: return "Network is unreachable";
749 case WSAEHOSTUNREACH
: return "No route to host";
750 default: return "connect(): unknown error";
754 send(s
, "connect ", 8, 0);
755 send(s
, FWhost
, strlen(FWhost
), 0);
758 sprintf(buf
, " %d\n", FWport
);
759 send (s
, buf
, strlen(buf
), 0);
766 static int ssh_versioncmp(char *a
, char *b
) {
768 unsigned long av
, bv
;
770 av
= strtoul(a
, &ae
, 10);
771 bv
= strtoul(b
, &be
, 10);
772 if (av
!= bv
) return (av
< bv ?
-1 : +1);
773 if (*ae
== '.') ae
++;
774 if (*be
== '.') be
++;
775 av
= strtoul(ae
, &ae
, 10);
776 bv
= strtoul(be
, &be
, 10);
777 if (av
!= bv
) return (av
< bv ?
-1 : +1);
783 * Utility routine for putting an SSH-protocol `string' into a SHA
787 void sha_string(SHA_State
*s
, void *str
, int len
) {
788 unsigned char lenblk
[4];
789 PUT_32BIT(lenblk
, len
);
790 SHA_Bytes(s
, lenblk
, 4);
791 SHA_Bytes(s
, str
, len
);
795 * SSH2 packet construction functions.
797 void ssh2_pkt_adddata(void *data
, int len
) {
798 pktout
.length
+= len
;
799 if (pktout
.maxlen
< pktout
.length
) {
800 pktout
.maxlen
= pktout
.length
+ 256;
801 pktout
.data
= (pktout
.data
== NULL ?
malloc(pktout
.maxlen
+APIEXTRA
) :
802 realloc(pktout
.data
, pktout
.maxlen
+APIEXTRA
));
804 fatalbox("Out of memory");
806 memcpy(pktout
.data
+pktout
.length
-len
, data
, len
);
808 void ssh2_pkt_addbyte(unsigned char byte
) {
809 ssh2_pkt_adddata(&byte
, 1);
811 void ssh2_pkt_init(int pkt_type
) {
813 ssh2_pkt_addbyte((unsigned char)pkt_type
);
815 void ssh2_pkt_addbool(unsigned char value
) {
816 ssh2_pkt_adddata(&value
, 1);
818 void ssh2_pkt_adduint32(unsigned long value
) {
821 ssh2_pkt_adddata(x
, 4);
823 void ssh2_pkt_addstring_start(void) {
824 ssh2_pkt_adduint32(0);
825 pktout
.savedpos
= pktout
.length
;
827 void ssh2_pkt_addstring_str(char *data
) {
828 ssh2_pkt_adddata(data
, strlen(data
));
829 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
830 pktout
.length
- pktout
.savedpos
);
832 void ssh2_pkt_addstring_data(char *data
, int len
) {
833 ssh2_pkt_adddata(data
, len
);
834 PUT_32BIT(pktout
.data
+ pktout
.savedpos
- 4,
835 pktout
.length
- pktout
.savedpos
);
837 void ssh2_pkt_addstring(char *data
) {
838 ssh2_pkt_addstring_start();
839 ssh2_pkt_addstring_str(data
);
841 char *ssh2_mpint_fmt(Bignum b
, int *len
) {
844 p
= malloc(n
* 2 + 1);
846 fatalbox("out of memory");
848 for (i
= 0; i
< n
; i
++) {
849 p
[i
*2+1] = (b
[n
-i
] >> 8) & 0xFF;
850 p
[i
*2+2] = (b
[n
-i
] ) & 0xFF;
853 while (p
[i
] == 0 && (p
[i
+1] & 0x80) == 0)
855 memmove(p
, p
+i
, n
*2+1-i
);
859 void ssh2_pkt_addmp(Bignum b
) {
862 p
= ssh2_mpint_fmt(b
, &len
);
863 ssh2_pkt_addstring_start();
864 ssh2_pkt_addstring_data(p
, len
);
867 void ssh2_pkt_send(void) {
868 int cipherblk
, maclen
, padding
, i
;
869 static unsigned long outgoing_sequence
= 0;
872 * Add padding. At least four bytes, and must also bring total
873 * length (minus MAC) up to a multiple of the block size.
875 cipherblk
= cipher ? cipher
->blksize
: 8; /* block size */
876 cipherblk
= cipherblk
< 8 ?
8 : cipherblk
; /* or 8 if blksize < 8 */
878 padding
+= (cipherblk
- (pktout
.length
+ padding
) % cipherblk
) % cipherblk
;
879 pktout
.data
[4] = padding
;
880 for (i
= 0; i
< padding
; i
++)
881 pktout
.data
[pktout
.length
+ i
] = random_byte();
882 PUT_32BIT(pktout
.data
, pktout
.length
+ padding
- 4);
884 csmac
->generate(pktout
.data
, pktout
.length
+ padding
,
886 outgoing_sequence
++; /* whether or not we MACed */
889 debug(("Sending packet len=%d\r\n", pktout
.length
+padding
));
890 for (i
= 0; i
< pktout
.length
+padding
; i
++)
891 debug((" %02x", (unsigned char)pktout
.data
[i
]));
896 cscipher
->encrypt(pktout
.data
, pktout
.length
+ padding
);
897 maclen
= csmac ? csmac
->len
: 0;
899 s_write(pktout
.data
, pktout
.length
+ padding
+ maclen
);
903 void bndebug(char *string
, Bignum b
) {
906 p
= ssh2_mpint_fmt(b
, &len
);
907 debug(("%s", string
));
908 for (i
= 0; i
< len
; i
++)
909 debug((" %02x", p
[i
]));
915 void sha_mpint(SHA_State
*s
, Bignum b
) {
918 p
= ssh2_mpint_fmt(b
, &len
);
919 sha_string(s
, p
, len
);
924 * SSH2 packet decode functions.
926 unsigned long ssh2_pkt_getuint32(void) {
928 if (pktin
.length
- pktin
.savedpos
< 4)
929 return 0; /* arrgh, no way to decline (FIXME?) */
930 value
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
934 void ssh2_pkt_getstring(char **p
, int *length
) {
936 if (pktin
.length
- pktin
.savedpos
< 4)
938 *length
= GET_32BIT(pktin
.data
+pktin
.savedpos
);
940 if (pktin
.length
- pktin
.savedpos
< *length
)
942 *p
= pktin
.data
+pktin
.savedpos
;
943 pktin
.savedpos
+= *length
;
945 Bignum
ssh2_pkt_getmp(void) {
950 ssh2_pkt_getstring(&p
, &length
);
954 fatalbox("internal error: Can't handle negative mpints");
955 b
= newbn((length
+1)/2);
956 for (i
= 0; i
< length
; i
++) {
959 b
[j
/2+1] |= ((unsigned char)p
[i
]) << 8;
961 b
[j
/2+1] |= ((unsigned char)p
[i
]);
966 static int do_ssh_init(void) {
970 char vlog
[sizeof(vstring
)+20];
975 while (s_read(&c
, 1) == 1) {
976 if (c
== 'S' && i
< 2) i
++;
977 else if (c
== 'S' && i
== 2) i
= 2;
978 else if (c
== 'H' && i
== 2) break;
982 if (s_read(&c
,1) != 1 || c
!= 'S') return 0;
983 if (s_read(&c
,1) != 1 || c
!= 'S') return 0;
984 if (s_read(&c
,1) != 1 || c
!= 'H') return 0;
986 strcpy(vstring
, "SSH-");
988 if (s_read(&c
,1) != 1 || c
!= '-') return 0;
991 if (s_read(&c
,1) != 1)
993 if (vsp
< vstring
+sizeof(vstring
)-1)
999 } else if (i
< sizeof(version
)-1)
1007 sprintf(vlog
, "Server version: %s", vstring
);
1008 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1012 * Server version "1.99" means we can choose whether we use v1
1013 * or v2 protocol. Choice is based on cfg.sshprot.
1015 if (ssh_versioncmp(version
, cfg
.sshprot
== 1 ?
"2.0" : "1.99") >= 0) {
1017 * This is a v2 server. Begin v2 protocol.
1019 char *verstring
= "SSH-2.0-PuTTY";
1022 * Hash our version string and their version string.
1024 sha_string(&exhash
, verstring
, strlen(verstring
));
1025 sha_string(&exhash
, vstring
, strcspn(vstring
, "\r\n"));
1026 sprintf(vstring
, "%s\n", verstring
);
1027 sprintf(vlog
, "We claim version: %s", verstring
);
1029 logevent("Using SSH protocol version 2");
1030 s_write(vstring
, strlen(vstring
));
1031 ssh_protocol
= ssh2_protocol
;
1033 s_rdpkt
= ssh2_rdpkt
;
1036 * This is a v1 server. Begin v1 protocol.
1038 sprintf(vstring
, "SSH-%s-PuTTY\n",
1039 (ssh_versioncmp(version
, "1.5") <= 0 ? version
: "1.5"));
1040 sprintf(vlog
, "We claim version: %s", vstring
);
1041 vlog
[strcspn(vlog
, "\r\n")] = '\0';
1043 logevent("Using SSH protocol version 1");
1044 s_write(vstring
, strlen(vstring
));
1045 ssh_protocol
= ssh1_protocol
;
1047 s_rdpkt
= ssh1_rdpkt
;
1054 * Handle the key exchange and user authentication phases.
1056 static int do_ssh1_login(unsigned char *in
, int inlen
, int ispkt
)
1059 unsigned char *rsabuf
, *keystr1
, *keystr2
;
1060 unsigned char cookie
[8];
1061 struct RSAKey servkey
, hostkey
;
1062 struct MD5Context md5c
;
1063 static unsigned long supported_ciphers_mask
, supported_auths_mask
;
1064 static int tried_publickey
;
1065 static unsigned char session_id
[16];
1070 if (!ispkt
) crWaitUntil(ispkt
);
1072 if (pktin
.type
!= SSH1_SMSG_PUBLIC_KEY
)
1073 fatalbox("Public key packet not received");
1075 logevent("Received public keys");
1077 memcpy(cookie
, pktin
.body
, 8);
1079 i
= makekey(pktin
.body
+8, &servkey
, &keystr1
, 0);
1080 j
= makekey(pktin
.body
+8+i
, &hostkey
, &keystr2
, 0);
1083 * Hash the host key and print the hash in the log box. Just as
1084 * a last resort in case the registry's host key checking is
1085 * compromised, we'll allow the user some ability to verify
1089 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1090 MD5Final(session_id
, &md5c
);
1094 logevent("Host key MD5 is:");
1095 strcpy(logmsg
, " ");
1096 for (i
= 0; i
< 16; i
++)
1097 sprintf(logmsg
+strlen(logmsg
), "%02x", session_id
[i
]);
1101 supported_ciphers_mask
= GET_32BIT(pktin
.body
+12+i
+j
);
1102 supported_auths_mask
= GET_32BIT(pktin
.body
+16+i
+j
);
1105 MD5Update(&md5c
, keystr2
, hostkey
.bytes
);
1106 MD5Update(&md5c
, keystr1
, servkey
.bytes
);
1107 MD5Update(&md5c
, pktin
.body
, 8);
1108 MD5Final(session_id
, &md5c
);
1110 for (i
=0; i
<32; i
++)
1111 session_key
[i
] = random_byte();
1113 len
= (hostkey
.bytes
> servkey
.bytes ? hostkey
.bytes
: servkey
.bytes
);
1115 rsabuf
= malloc(len
);
1117 fatalbox("Out of memory");
1120 * Verify the host key.
1124 * First format the key into a string.
1126 int len
= rsastr_len(&hostkey
);
1127 char *keystr
= malloc(len
);
1129 fatalbox("Out of memory");
1130 rsastr_fmt(keystr
, &hostkey
);
1131 verify_ssh_host_key(savedhost
, keystr
);
1135 for (i
=0; i
<32; i
++) {
1136 rsabuf
[i
] = session_key
[i
];
1138 rsabuf
[i
] ^= session_id
[i
];
1141 if (hostkey
.bytes
> servkey
.bytes
) {
1142 rsaencrypt(rsabuf
, 32, &servkey
);
1143 rsaencrypt(rsabuf
, servkey
.bytes
, &hostkey
);
1145 rsaencrypt(rsabuf
, 32, &hostkey
);
1146 rsaencrypt(rsabuf
, hostkey
.bytes
, &servkey
);
1149 logevent("Encrypted session key");
1151 cipher_type
= cfg
.cipher
== CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH
:
1152 cfg
.cipher
== CIPHER_DES ? SSH_CIPHER_DES
:
1154 if ((supported_ciphers_mask
& (1 << cipher_type
)) == 0) {
1155 c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
1156 cipher_type
= SSH_CIPHER_3DES
;
1158 switch (cipher_type
) {
1159 case SSH_CIPHER_3DES
: logevent("Using 3DES encryption"); break;
1160 case SSH_CIPHER_DES
: logevent("Using single-DES encryption"); break;
1161 case SSH_CIPHER_BLOWFISH
: logevent("Using Blowfish encryption"); break;
1164 send_packet(SSH1_CMSG_SESSION_KEY
,
1165 PKT_CHAR
, cipher_type
,
1166 PKT_DATA
, cookie
, 8,
1167 PKT_CHAR
, (len
*8) >> 8, PKT_CHAR
, (len
*8) & 0xFF,
1168 PKT_DATA
, rsabuf
, len
,
1172 logevent("Trying to enable encryption...");
1176 cipher
= cipher_type
== SSH_CIPHER_BLOWFISH ?
&ssh_blowfish_ssh1
:
1177 cipher_type
== SSH_CIPHER_DES ?
&ssh_des
:
1179 cipher
->sesskey(session_key
);
1183 if (pktin
.type
!= SSH1_SMSG_SUCCESS
)
1184 fatalbox("Encryption not successfully enabled");
1186 logevent("Successfully started encryption");
1190 static char username
[100];
1193 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
1194 c_write("login as: ", 10);
1197 crWaitUntil(!ispkt
);
1198 while (inlen
--) switch (c
= *in
++) {
1205 c_write("\b \b", 3);
1211 c_write("\b \b", 3);
1220 if (((c
>= ' ' && c
<= '~') ||
1221 ((unsigned char)c
>= 160)) && pos
< 40) {
1222 username
[pos
++] = c
;
1229 username
[strcspn(username
, "\n\r")] = '\0';
1232 strncpy(username
, cfg
.username
, 99);
1233 username
[99] = '\0';
1234 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
1235 sprintf(stuff
, "Sent username \"%s\".\r\n", username
);
1236 c_write(stuff
, strlen(stuff
));
1240 send_packet(SSH1_CMSG_USER
, PKT_STR
, username
, PKT_END
);
1242 char userlog
[20+sizeof(username
)];
1243 sprintf(userlog
, "Sent username \"%s\"", username
);
1250 tried_publickey
= 0;
1252 while (pktin
.type
== SSH1_SMSG_FAILURE
) {
1253 static char password
[100];
1256 static int pwpkt_type
;
1258 * Show password prompt, having first obtained it via a TIS
1259 * or CryptoCard exchange if we're doing TIS or CryptoCard
1262 pwpkt_type
= SSH1_CMSG_AUTH_PASSWORD
;
1263 if (agent_exists()) {
1265 * Attempt RSA authentication using Pageant.
1267 static unsigned char request
[5], *response
, *p
;
1268 static int responselen
;
1269 static int i
, nkeys
;
1270 static int authed
= FALSE
;
1273 logevent("Pageant is running. Requesting keys.");
1275 /* Request the keys held by the agent. */
1276 PUT_32BIT(request
, 1);
1277 request
[4] = SSH_AGENTC_REQUEST_RSA_IDENTITIES
;
1278 agent_query(request
, 5, &r
, &responselen
);
1279 response
= (unsigned char *)r
;
1282 nkeys
= GET_32BIT(p
); p
+= 4;
1283 { char buf
[64]; sprintf(buf
, "Pageant has %d keys", nkeys
);
1285 for (i
= 0; i
< nkeys
; i
++) {
1286 static struct RSAKey key
;
1287 static Bignum challenge
;
1288 static char *commentp
;
1289 static int commentlen
;
1291 { char buf
[64]; sprintf(buf
, "Trying Pageant key #%d", i
);
1294 p
+= ssh1_read_bignum(p
, &key
.exponent
);
1295 p
+= ssh1_read_bignum(p
, &key
.modulus
);
1296 commentlen
= GET_32BIT(p
); p
+= 4;
1297 commentp
= p
; p
+= commentlen
;
1298 send_packet(SSH1_CMSG_AUTH_RSA
,
1299 PKT_BIGNUM
, key
.modulus
, PKT_END
);
1301 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
) {
1302 logevent("Key refused");
1305 logevent("Received RSA challenge");
1306 ssh1_read_bignum(pktin
.body
, &challenge
);
1308 char *agentreq
, *q
, *ret
;
1310 len
= 1 + 4; /* message type, bit count */
1311 len
+= ssh1_bignum_length(key
.exponent
);
1312 len
+= ssh1_bignum_length(key
.modulus
);
1313 len
+= ssh1_bignum_length(challenge
);
1314 len
+= 16; /* session id */
1315 len
+= 4; /* response format */
1316 agentreq
= malloc(4 + len
);
1317 PUT_32BIT(agentreq
, len
);
1319 *q
++ = SSH_AGENTC_RSA_CHALLENGE
;
1320 PUT_32BIT(q
, ssh1_bignum_bitcount(key
.modulus
));
1322 q
+= ssh1_write_bignum(q
, key
.exponent
);
1323 q
+= ssh1_write_bignum(q
, key
.modulus
);
1324 q
+= ssh1_write_bignum(q
, challenge
);
1325 memcpy(q
, session_id
, 16); q
+= 16;
1326 PUT_32BIT(q
, 1); /* response format */
1327 agent_query(agentreq
, len
+4, &ret
, &retlen
);
1330 if (ret
[4] == SSH_AGENT_RSA_RESPONSE
) {
1331 logevent("Sending Pageant's response");
1332 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1333 PKT_DATA
, ret
+5, 16, PKT_END
);
1336 if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1337 logevent("Pageant's response accepted");
1338 c_write("Authenticated using RSA key \"",
1340 c_write(commentp
, commentlen
);
1341 c_write("\" from agent\r\n", 14);
1344 logevent("Pageant's response not accepted");
1346 logevent("Pageant failed to answer challenge");
1350 logevent("No reply received from Pageant");
1353 freebn(key
.exponent
);
1354 freebn(key
.modulus
);
1363 if (*cfg
.keyfile
&& !tried_publickey
)
1364 pwpkt_type
= SSH1_CMSG_AUTH_RSA
;
1366 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
&&
1367 !(flags
& FLAG_INTERACTIVE
)) {
1369 sprintf(prompt
, "%s@%s's password: ", cfg
.username
, savedhost
);
1370 if (!ssh_get_password(prompt
, password
, sizeof(password
))) {
1372 * get_password failed to get a password (for
1373 * example because one was supplied on the command
1374 * line which has already failed to work).
1377 logevent("No more passwords to try");
1378 ssh_state
= SSH_STATE_CLOSED
;
1383 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1385 (supported_auths_mask
& (1<<SSH1_AUTH_TIS
))) {
1386 pwpkt_type
= SSH1_CMSG_AUTH_TIS_RESPONSE
;
1387 logevent("Requested TIS authentication");
1388 send_packet(SSH1_CMSG_AUTH_TIS
, PKT_END
);
1390 if (pktin
.type
!= SSH1_SMSG_AUTH_TIS_CHALLENGE
) {
1391 logevent("TIS authentication declined");
1392 c_write("TIS authentication refused.\r\n", 29);
1394 int challengelen
= ((pktin
.body
[0] << 24) |
1395 (pktin
.body
[1] << 16) |
1396 (pktin
.body
[2] << 8) |
1398 logevent("Received TIS challenge");
1399 c_write(pktin
.body
+4, challengelen
);
1402 if (pktin
.type
== SSH1_SMSG_FAILURE
&&
1404 (supported_auths_mask
& (1<<SSH1_AUTH_CCARD
))) {
1405 pwpkt_type
= SSH1_CMSG_AUTH_CCARD_RESPONSE
;
1406 logevent("Requested CryptoCard authentication");
1407 send_packet(SSH1_CMSG_AUTH_CCARD
, PKT_END
);
1409 if (pktin
.type
!= SSH1_SMSG_AUTH_CCARD_CHALLENGE
) {
1410 logevent("CryptoCard authentication declined");
1411 c_write("CryptoCard authentication refused.\r\n", 29);
1413 int challengelen
= ((pktin
.body
[0] << 24) |
1414 (pktin
.body
[1] << 16) |
1415 (pktin
.body
[2] << 8) |
1417 logevent("Received CryptoCard challenge");
1418 c_write(pktin
.body
+4, challengelen
);
1419 c_write("\r\nResponse : ", 13);
1422 if (pwpkt_type
== SSH1_CMSG_AUTH_PASSWORD
)
1423 c_write("password: ", 10);
1424 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1425 if (flags
& FLAG_VERBOSE
)
1426 c_write("Trying public key authentication.\r\n", 35);
1427 if (!rsakey_encrypted(cfg
.keyfile
)) {
1428 if (flags
& FLAG_VERBOSE
)
1429 c_write("No passphrase required.\r\n", 25);
1432 c_write("passphrase: ", 12);
1438 crWaitUntil(!ispkt
);
1439 while (inlen
--) switch (c
= *in
++) {
1456 if (((c
>= ' ' && c
<= '~') ||
1457 ((unsigned char)c
>= 160)) && pos
< sizeof(password
))
1458 password
[pos
++] = c
;
1467 if (pwpkt_type
== SSH1_CMSG_AUTH_RSA
) {
1469 * Try public key authentication with the specified
1472 static struct RSAKey pubkey
;
1473 static Bignum challenge
, response
;
1475 static unsigned char buffer
[32];
1477 tried_publickey
= 1;
1478 i
= loadrsakey(cfg
.keyfile
, &pubkey
, password
);
1480 c_write("Couldn't load public key from ", 30);
1481 c_write(cfg
.keyfile
, strlen(cfg
.keyfile
));
1482 c_write(".\r\n", 3);
1483 continue; /* go and try password */
1486 c_write("Wrong passphrase.\r\n", 19);
1487 tried_publickey
= 0;
1488 continue; /* try again */
1492 * Send a public key attempt.
1494 send_packet(SSH1_CMSG_AUTH_RSA
,
1495 PKT_BIGNUM
, pubkey
.modulus
, PKT_END
);
1498 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1499 if (flags
& FLAG_VERBOSE
)
1500 c_write("Server refused our public key.\r\n", 32);
1501 continue; /* go and try password */
1503 if (pktin
.type
!= SSH1_SMSG_AUTH_RSA_CHALLENGE
)
1504 fatalbox("Bizarre response to offer of public key");
1505 ssh1_read_bignum(pktin
.body
, &challenge
);
1506 response
= rsadecrypt(challenge
, &pubkey
);
1507 freebn(pubkey
.private_exponent
); /* burn the evidence */
1509 for (i
= 0; i
< 32; i
+= 2) {
1510 buffer
[i
] = response
[16-i
/2] >> 8;
1511 buffer
[i
+1] = response
[16-i
/2] & 0xFF;
1515 MD5Update(&md5c
, buffer
, 32);
1516 MD5Update(&md5c
, session_id
, 16);
1517 MD5Final(buffer
, &md5c
);
1519 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE
,
1520 PKT_DATA
, buffer
, 16, PKT_END
);
1523 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1524 if (flags
& FLAG_VERBOSE
)
1525 c_write("Failed to authenticate with our public key.\r\n",
1527 continue; /* go and try password */
1528 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1529 fatalbox("Bizarre response to RSA authentication response");
1532 break; /* we're through! */
1534 send_packet(pwpkt_type
, PKT_STR
, password
, PKT_END
);
1536 logevent("Sent password");
1537 memset(password
, 0, strlen(password
));
1539 if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1540 if (flags
& FLAG_VERBOSE
)
1541 c_write("Access denied\r\n", 15);
1542 logevent("Authentication refused");
1543 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
1544 logevent("Received disconnect request");
1545 ssh_state
= SSH_STATE_CLOSED
;
1547 } else if (pktin
.type
!= SSH1_SMSG_SUCCESS
) {
1548 fatalbox("Strange packet received, type %d", pktin
.type
);
1552 logevent("Authentication successful");
1557 static void ssh1_protocol(unsigned char *in
, int inlen
, int ispkt
) {
1562 while (!do_ssh1_login(in
, inlen
, ispkt
)) {
1565 if (ssh_state
== SSH_STATE_CLOSED
)
1568 if (cfg
.agentfwd
&& agent_exists()) {
1569 logevent("Requesting agent forwarding");
1570 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING
, PKT_END
);
1571 do { crReturnV
; } while (!ispkt
);
1572 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
1573 fatalbox("Protocol confusion");
1574 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1575 logevent("Agent forwarding refused");
1577 logevent("Agent forwarding enabled");
1581 send_packet(SSH1_CMSG_REQUEST_PTY
,
1582 PKT_STR
, cfg
.termtype
,
1583 PKT_INT
, rows
, PKT_INT
, cols
,
1584 PKT_INT
, 0, PKT_INT
, 0,
1587 ssh_state
= SSH_STATE_INTERMED
;
1588 do { crReturnV
; } while (!ispkt
);
1589 if (pktin
.type
!= SSH1_SMSG_SUCCESS
&& pktin
.type
!= SSH1_SMSG_FAILURE
) {
1590 fatalbox("Protocol confusion");
1591 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1592 c_write("Server refused to allocate pty\r\n", 32);
1594 logevent("Allocated pty");
1597 if (*cfg
.remote_cmd
)
1598 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cfg
.remote_cmd
, PKT_END
);
1600 send_packet(SSH1_CMSG_EXEC_SHELL
, PKT_END
);
1601 logevent("Started session");
1603 ssh_state
= SSH_STATE_SESSION
;
1608 ssh_channels
= newtree234(ssh_channelcmp
);
1612 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
||
1613 pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
1614 long len
= GET_32BIT(pktin
.body
);
1615 c_write(pktin
.body
+4, len
);
1616 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
1617 ssh_state
= SSH_STATE_CLOSED
;
1618 logevent("Received disconnect request");
1619 } else if (pktin
.type
== SSH1_SMSG_AGENT_OPEN
) {
1620 /* Remote side is trying to open a channel to talk to our
1621 * agent. Give them back a local channel number. */
1623 struct ssh_channel
*c
;
1625 for (c
= first234(ssh_channels
, &e
); c
; c
= next234(&e
)) {
1627 break; /* found a free number */
1630 c
= malloc(sizeof(struct ssh_channel
));
1631 c
->remoteid
= GET_32BIT(pktin
.body
);
1634 c
->type
= SSH1_SMSG_AGENT_OPEN
; /* identify channel type */
1635 add234(ssh_channels
, c
);
1636 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION
,
1637 PKT_INT
, c
->remoteid
, PKT_INT
, c
->localid
,
1639 } else if (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE
||
1640 pktin
.type
== SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION
) {
1641 /* Remote side closes a channel. */
1642 unsigned i
= GET_32BIT(pktin
.body
);
1643 struct ssh_channel
*c
;
1644 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
1647 closetype
= (pktin
.type
== SSH1_MSG_CHANNEL_CLOSE ?
1 : 2);
1648 send_packet(pktin
.type
, PKT_INT
, c
->remoteid
, PKT_END
);
1649 c
->closes
|= closetype
;
1650 if (c
->closes
== 3) {
1651 del234(ssh_channels
, c
);
1655 } else if (pktin
.type
== SSH1_MSG_CHANNEL_DATA
) {
1656 /* Data sent down one of our channels. */
1657 int i
= GET_32BIT(pktin
.body
);
1658 int len
= GET_32BIT(pktin
.body
+4);
1659 unsigned char *p
= pktin
.body
+8;
1660 struct ssh_channel
*c
;
1661 c
= find234(ssh_channels
, &i
, ssh_channelfind
);
1664 case SSH1_SMSG_AGENT_OPEN
:
1665 /* Data for an agent message. Buffer it. */
1667 if (c
->u
.a
.lensofar
< 4) {
1668 int l
= min(4 - c
->u
.a
.lensofar
, len
);
1669 memcpy(c
->u
.a
.msglen
+ c
->u
.a
.lensofar
, p
, l
);
1670 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
1672 if (c
->u
.a
.lensofar
== 4) {
1673 c
->u
.a
.totallen
= 4 + GET_32BIT(c
->u
.a
.msglen
);
1674 c
->u
.a
.message
= malloc(c
->u
.a
.totallen
);
1675 memcpy(c
->u
.a
.message
, c
->u
.a
.msglen
, 4);
1677 if (c
->u
.a
.lensofar
>= 4 && len
> 0) {
1678 int l
= min(c
->u
.a
.totallen
- c
->u
.a
.lensofar
, len
);
1679 memcpy(c
->u
.a
.message
+ c
->u
.a
.lensofar
, p
, l
);
1680 p
+= l
; len
-= l
; c
->u
.a
.lensofar
+= l
;
1682 if (c
->u
.a
.lensofar
== c
->u
.a
.totallen
) {
1683 void *reply
, *sentreply
;
1685 agent_query(c
->u
.a
.message
, c
->u
.a
.totallen
,
1690 /* Fake SSH_AGENT_FAILURE. */
1691 sentreply
= "\0\0\0\1\5";
1694 send_packet(SSH1_MSG_CHANNEL_DATA
,
1695 PKT_INT
, c
->remoteid
,
1697 PKT_DATA
, sentreply
, replylen
,
1701 free(c
->u
.a
.message
);
1702 c
->u
.a
.lensofar
= 0;
1708 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
) {
1709 /* may be from EXEC_SHELL on some servers */
1710 } else if (pktin
.type
== SSH1_SMSG_FAILURE
) {
1711 /* may be from EXEC_SHELL on some servers
1712 * if no pty is available or in other odd cases. Ignore */
1713 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
1714 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
1716 fatalbox("Strange packet received: type %d", pktin
.type
);
1719 send_packet(SSH1_CMSG_STDIN_DATA
,
1720 PKT_INT
, inlen
, PKT_DATA
, in
, inlen
, PKT_END
);
1728 * Utility routine for decoding comma-separated strings in KEXINIT.
1730 int in_commasep_string(char *needle
, char *haystack
, int haylen
) {
1731 int needlen
= strlen(needle
);
1734 * Is it at the start of the string?
1736 if (haylen
>= needlen
&& /* haystack is long enough */
1737 !memcmp(needle
, haystack
, needlen
) && /* initial match */
1738 (haylen
== needlen
|| haystack
[needlen
] == ',')
1739 /* either , or EOS follows */
1743 * If not, search for the next comma and resume after that.
1744 * If no comma found, terminate.
1746 while (haylen
> 0 && *haystack
!= ',')
1747 haylen
--, haystack
++;
1750 haylen
--, haystack
++; /* skip over comma itself */
1755 * SSH2 key creation method.
1757 void ssh2_mkkey(Bignum K
, char *H
, char chr
, char *keyspace
) {
1759 /* First 20 bytes. */
1762 SHA_Bytes(&s
, H
, 20);
1763 SHA_Bytes(&s
, &chr
, 1);
1764 SHA_Bytes(&s
, H
, 20);
1765 SHA_Final(&s
, keyspace
);
1766 /* Next 20 bytes. */
1769 SHA_Bytes(&s
, H
, 20);
1770 SHA_Bytes(&s
, keyspace
, 20);
1771 SHA_Final(&s
, keyspace
+20);
1775 * Handle the SSH2 transport layer.
1777 static int do_ssh2_transport(unsigned char *in
, int inlen
, int ispkt
)
1781 static Bignum e
, f
, K
;
1782 static struct ssh_cipher
*cscipher_tobe
= NULL
;
1783 static struct ssh_cipher
*sccipher_tobe
= NULL
;
1784 static struct ssh_mac
*csmac_tobe
= NULL
;
1785 static struct ssh_mac
*scmac_tobe
= NULL
;
1786 static struct ssh_compress
*cscomp_tobe
= NULL
;
1787 static struct ssh_compress
*sccomp_tobe
= NULL
;
1788 static char *hostkeydata
, *sigdata
, *keystr
;
1789 static int hostkeylen
, siglen
;
1790 static unsigned char exchange_hash
[20];
1791 static unsigned char keyspace
[40];
1797 * Set up the preferred cipher.
1799 if (cfg
.cipher
== CIPHER_BLOWFISH
) {
1800 ciphers
[0] = &ssh_blowfish_ssh2
;
1801 } else if (cfg
.cipher
== CIPHER_DES
) {
1802 logevent("Single DES not supported in SSH2; using 3DES");
1803 ciphers
[0] = &ssh_3des_ssh2
;
1804 } else if (cfg
.cipher
== CIPHER_3DES
) {
1805 ciphers
[0] = &ssh_3des_ssh2
;
1807 /* Shouldn't happen, but we do want to initialise to _something_. */
1808 ciphers
[0] = &ssh_3des_ssh2
;
1813 * Construct and send our key exchange packet.
1815 ssh2_pkt_init(SSH2_MSG_KEXINIT
);
1816 for (i
= 0; i
< 16; i
++)
1817 ssh2_pkt_addbyte((unsigned char)random_byte());
1818 /* List key exchange algorithms. */
1819 ssh2_pkt_addstring_start();
1820 for (i
= 0; i
< lenof(kex_algs
); i
++) {
1821 ssh2_pkt_addstring_str(kex_algs
[i
]->name
);
1822 if (i
< lenof(kex_algs
)-1)
1823 ssh2_pkt_addstring_str(",");
1825 /* List server host key algorithms. */
1826 ssh2_pkt_addstring_start();
1827 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
1828 ssh2_pkt_addstring_str(hostkey_algs
[i
]->name
);
1829 if (i
< lenof(hostkey_algs
)-1)
1830 ssh2_pkt_addstring_str(",");
1832 /* List client->server encryption algorithms. */
1833 ssh2_pkt_addstring_start();
1834 for (i
= 0; i
< lenof(ciphers
); i
++) {
1835 ssh2_pkt_addstring_str(ciphers
[i
]->name
);
1836 if (i
< lenof(ciphers
)-1)
1837 ssh2_pkt_addstring_str(",");
1839 /* List server->client encryption algorithms. */
1840 ssh2_pkt_addstring_start();
1841 for (i
= 0; i
< lenof(ciphers
); i
++) {
1842 ssh2_pkt_addstring_str(ciphers
[i
]->name
);
1843 if (i
< lenof(ciphers
)-1)
1844 ssh2_pkt_addstring_str(",");
1846 /* List client->server MAC algorithms. */
1847 ssh2_pkt_addstring_start();
1848 for (i
= 0; i
< lenof(macs
); i
++) {
1849 ssh2_pkt_addstring_str(macs
[i
]->name
);
1850 if (i
< lenof(macs
)-1)
1851 ssh2_pkt_addstring_str(",");
1853 /* List server->client MAC algorithms. */
1854 ssh2_pkt_addstring_start();
1855 for (i
= 0; i
< lenof(macs
); i
++) {
1856 ssh2_pkt_addstring_str(macs
[i
]->name
);
1857 if (i
< lenof(macs
)-1)
1858 ssh2_pkt_addstring_str(",");
1860 /* List client->server compression algorithms. */
1861 ssh2_pkt_addstring_start();
1862 for (i
= 0; i
< lenof(compressions
); i
++) {
1863 ssh2_pkt_addstring_str(compressions
[i
]->name
);
1864 if (i
< lenof(compressions
)-1)
1865 ssh2_pkt_addstring_str(",");
1867 /* List server->client compression algorithms. */
1868 ssh2_pkt_addstring_start();
1869 for (i
= 0; i
< lenof(compressions
); i
++) {
1870 ssh2_pkt_addstring_str(compressions
[i
]->name
);
1871 if (i
< lenof(compressions
)-1)
1872 ssh2_pkt_addstring_str(",");
1874 /* List client->server languages. Empty list. */
1875 ssh2_pkt_addstring_start();
1876 /* List server->client languages. Empty list. */
1877 ssh2_pkt_addstring_start();
1878 /* First KEX packet does _not_ follow, because we're not that brave. */
1879 ssh2_pkt_addbool(FALSE
);
1881 ssh2_pkt_adduint32(0);
1882 sha_string(&exhash
, pktout
.data
+5, pktout
.length
-5);
1885 if (!ispkt
) crWaitUntil(ispkt
);
1886 sha_string(&exhash
, pktin
.data
+5, pktin
.length
-5);
1889 * Now examine the other side's KEXINIT to see what we're up
1892 if (pktin
.type
!= SSH2_MSG_KEXINIT
) {
1893 fatalbox("expected key exchange packet from server");
1895 kex
= NULL
; hostkey
= NULL
; cscipher_tobe
= NULL
; sccipher_tobe
= NULL
;
1896 csmac_tobe
= NULL
; scmac_tobe
= NULL
; cscomp_tobe
= NULL
; sccomp_tobe
= NULL
;
1897 pktin
.savedpos
+= 16; /* skip garbage cookie */
1898 ssh2_pkt_getstring(&str
, &len
); /* key exchange algorithms */
1899 for (i
= 0; i
< lenof(kex_algs
); i
++) {
1900 if (in_commasep_string(kex_algs
[i
]->name
, str
, len
)) {
1905 ssh2_pkt_getstring(&str
, &len
); /* host key algorithms */
1906 for (i
= 0; i
< lenof(hostkey_algs
); i
++) {
1907 if (in_commasep_string(hostkey_algs
[i
]->name
, str
, len
)) {
1908 hostkey
= hostkey_algs
[i
];
1912 ssh2_pkt_getstring(&str
, &len
); /* client->server cipher */
1913 for (i
= 0; i
< lenof(ciphers
); i
++) {
1914 if (in_commasep_string(ciphers
[i
]->name
, str
, len
)) {
1915 cscipher_tobe
= ciphers
[i
];
1919 ssh2_pkt_getstring(&str
, &len
); /* server->client cipher */
1920 for (i
= 0; i
< lenof(ciphers
); i
++) {
1921 if (in_commasep_string(ciphers
[i
]->name
, str
, len
)) {
1922 sccipher_tobe
= ciphers
[i
];
1926 ssh2_pkt_getstring(&str
, &len
); /* client->server mac */
1927 for (i
= 0; i
< lenof(macs
); i
++) {
1928 if (in_commasep_string(macs
[i
]->name
, str
, len
)) {
1929 csmac_tobe
= macs
[i
];
1933 ssh2_pkt_getstring(&str
, &len
); /* server->client mac */
1934 for (i
= 0; i
< lenof(macs
); i
++) {
1935 if (in_commasep_string(macs
[i
]->name
, str
, len
)) {
1936 scmac_tobe
= macs
[i
];
1940 ssh2_pkt_getstring(&str
, &len
); /* client->server compression */
1941 for (i
= 0; i
< lenof(compressions
); i
++) {
1942 if (in_commasep_string(compressions
[i
]->name
, str
, len
)) {
1943 cscomp_tobe
= compressions
[i
];
1947 ssh2_pkt_getstring(&str
, &len
); /* server->client compression */
1948 for (i
= 0; i
< lenof(compressions
); i
++) {
1949 if (in_commasep_string(compressions
[i
]->name
, str
, len
)) {
1950 sccomp_tobe
= compressions
[i
];
1956 * Currently we only support Diffie-Hellman and DSS, so let's
1957 * bomb out if those aren't selected.
1959 if (kex
!= &ssh_diffiehellman
|| hostkey
!= &ssh_dss
)
1960 fatalbox("internal fault: chaos in SSH 2 transport layer");
1963 * Now we begin the fun. Generate and send e for Diffie-Hellman.
1966 ssh2_pkt_init(SSH2_MSG_KEXDH_INIT
);
1971 if (pktin
.type
!= SSH2_MSG_KEXDH_REPLY
) {
1972 fatalbox("expected key exchange packet from server");
1974 ssh2_pkt_getstring(&hostkeydata
, &hostkeylen
);
1975 f
= ssh2_pkt_getmp();
1976 ssh2_pkt_getstring(&sigdata
, &siglen
);
1980 sha_string(&exhash
, hostkeydata
, hostkeylen
);
1981 sha_mpint(&exhash
, e
);
1982 sha_mpint(&exhash
, f
);
1983 sha_mpint(&exhash
, K
);
1984 SHA_Final(&exhash
, exchange_hash
);
1987 debug(("Exchange hash is:\r\n"));
1988 for (i
= 0; i
< 20; i
++)
1989 debug((" %02x", exchange_hash
[i
]));
1993 hostkey
->setkey(hostkeydata
, hostkeylen
);
1994 if (!hostkey
->verifysig(sigdata
, siglen
, exchange_hash
, 20))
1995 fatalbox("Server failed host key check");
1998 * Expect SSH2_MSG_NEWKEYS from server.
2001 if (pktin
.type
!= SSH2_MSG_NEWKEYS
)
2002 fatalbox("expected new-keys packet from server");
2005 * Authenticate remote host: verify host key. (We've already
2006 * checked the signature of the exchange hash.)
2008 keystr
= hostkey
->fmtkey();
2009 verify_ssh_host_key(savedhost
, keystr
);
2013 * Send SSH2_MSG_NEWKEYS.
2015 ssh2_pkt_init(SSH2_MSG_NEWKEYS
);
2019 * Create and initialise session keys.
2021 cscipher
= cscipher_tobe
;
2022 sccipher
= sccipher_tobe
;
2025 cscomp
= cscomp_tobe
;
2026 sccomp
= sccomp_tobe
;
2028 * Set IVs after keys.
2030 ssh2_mkkey(K
, exchange_hash
, 'C', keyspace
); cscipher
->setcskey(keyspace
);
2031 ssh2_mkkey(K
, exchange_hash
, 'D', keyspace
); cscipher
->setsckey(keyspace
);
2032 ssh2_mkkey(K
, exchange_hash
, 'A', keyspace
); cscipher
->setcsiv(keyspace
);
2033 ssh2_mkkey(K
, exchange_hash
, 'B', keyspace
); sccipher
->setsciv(keyspace
);
2034 ssh2_mkkey(K
, exchange_hash
, 'E', keyspace
); csmac
->setcskey(keyspace
);
2035 ssh2_mkkey(K
, exchange_hash
, 'F', keyspace
); scmac
->setsckey(keyspace
);
2038 * Now we're encrypting. Begin returning 1 to the protocol main
2039 * function so that other things can run on top of the
2040 * transport. If we ever see a KEXINIT, we must go back to the
2045 } while (!(ispkt
&& pktin
.type
== SSH2_MSG_KEXINIT
));
2046 goto begin_key_exchange
;
2052 * Handle the SSH2 userauth and connection layers.
2054 static void do_ssh2_authconn(unsigned char *in
, int inlen
, int ispkt
)
2056 static unsigned long remote_winsize
;
2057 static unsigned long remote_maxpkt
;
2062 * Request userauth protocol, and await a response to it.
2064 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST
);
2065 ssh2_pkt_addstring("ssh-userauth");
2067 crWaitUntilV(ispkt
);
2068 if (pktin
.type
!= SSH2_MSG_SERVICE_ACCEPT
)
2069 fatalbox("Server refused user authentication protocol");
2072 * FIXME: currently we support only password authentication.
2073 * (This places us technically in violation of the SSH2 spec.
2074 * We must fix this.)
2078 * Get a username and a password.
2080 static char username
[100];
2081 static char password
[100];
2085 if ((flags
& FLAG_INTERACTIVE
) && !*cfg
.username
) {
2086 c_write("login as: ", 10);
2089 crWaitUntilV(!ispkt
);
2090 while (inlen
--) switch (c
= *in
++) {
2097 c_write("\b \b", 3);
2103 c_write("\b \b", 3);
2112 if (((c
>= ' ' && c
<= '~') ||
2113 ((unsigned char)c
>= 160)) && pos
< 40) {
2114 username
[pos
++] = c
;
2121 username
[strcspn(username
, "\n\r")] = '\0';
2124 strncpy(username
, cfg
.username
, 99);
2125 username
[99] = '\0';
2126 if ((flags
& FLAG_VERBOSE
) || (flags
& FLAG_INTERACTIVE
)) {
2127 sprintf(stuff
, "Using username \"%s\".\r\n", username
);
2128 c_write(stuff
, strlen(stuff
));
2132 if (!(flags
& FLAG_INTERACTIVE
)) {
2134 sprintf(prompt
, "%s@%s's password: ", cfg
.username
, savedhost
);
2135 if (!ssh_get_password(prompt
, password
, sizeof(password
))) {
2137 * get_password failed to get a password (for
2138 * example because one was supplied on the command
2139 * line which has already failed to work).
2142 logevent("No more passwords to try");
2143 ssh_state
= SSH_STATE_CLOSED
;
2147 c_write("password: ", 10);
2152 crWaitUntilV(!ispkt
);
2153 while (inlen
--) switch (c
= *in
++) {
2170 if (((c
>= ' ' && c
<= '~') ||
2171 ((unsigned char)c
>= 160)) && pos
< 40)
2172 password
[pos
++] = c
;
2179 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST
);
2180 ssh2_pkt_addstring(username
);
2181 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2182 ssh2_pkt_addstring("password");
2183 ssh2_pkt_addbool(FALSE
);
2184 ssh2_pkt_addstring(password
);
2187 crWaitUntilV(ispkt
);
2188 if (pktin
.type
!= SSH2_MSG_USERAUTH_SUCCESS
) {
2189 c_write("Access denied\r\n", 15);
2190 logevent("Authentication refused");
2196 * Now we're authenticated for the connection protocol. The
2197 * connection protocol will automatically have started at this
2198 * point; there's no need to send SERVICE_REQUEST.
2202 * So now create a channel with a session in it.
2204 mainchan
= malloc(sizeof(struct ssh_channel
));
2205 mainchan
->localid
= 100; /* as good as any */
2206 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN
);
2207 ssh2_pkt_addstring("session");
2208 ssh2_pkt_adduint32(mainchan
->localid
);
2209 ssh2_pkt_adduint32(0x7FFFFFFFUL
); /* our window size */
2210 ssh2_pkt_adduint32(0x4000UL
); /* our max pkt size */
2212 crWaitUntilV(ispkt
);
2213 if (pktin
.type
!= SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
) {
2214 fatalbox("Server refused to open a session");
2215 /* FIXME: error data comes back in FAILURE packet */
2217 if (ssh2_pkt_getuint32() != mainchan
->localid
) {
2218 fatalbox("Server's channel confirmation cited wrong channel");
2220 mainchan
->remoteid
= ssh2_pkt_getuint32();
2221 mainchan
->u
.v2
.remwindow
= ssh2_pkt_getuint32();
2222 mainchan
->u
.v2
.remmaxpkt
= ssh2_pkt_getuint32();
2223 mainchan
->u
.v2
.outbuffer
= NULL
;
2224 mainchan
->u
.v2
.outbuflen
= mainchan
->u
.v2
.outbufsize
= 0;
2225 logevent("Opened channel for session");
2228 * Now allocate a pty for the session.
2231 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
2232 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
2233 ssh2_pkt_addstring("pty-req");
2234 ssh2_pkt_addbool(1); /* want reply */
2235 ssh2_pkt_addstring(cfg
.termtype
);
2236 ssh2_pkt_adduint32(cols
);
2237 ssh2_pkt_adduint32(rows
);
2238 ssh2_pkt_adduint32(0); /* pixel width */
2239 ssh2_pkt_adduint32(0); /* pixel height */
2240 ssh2_pkt_addstring_start();
2241 ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
2245 crWaitUntilV(ispkt
);
2246 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
2247 /* FIXME: be able to handle other channels here */
2248 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2249 continue; /* wrong channel */
2250 mainchan
->u
.v2
.remwindow
+= ssh2_pkt_getuint32();
2252 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
2254 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
2255 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
2256 fatalbox("Server got confused by pty request");
2258 c_write("Server refused to allocate pty\r\n", 32);
2260 logevent("Allocated pty");
2265 * Start a shell or a remote command.
2267 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST
);
2268 ssh2_pkt_adduint32(mainchan
->remoteid
); /* recipient channel */
2269 if (*cfg
.remote_cmd
) {
2270 ssh2_pkt_addstring("exec");
2271 ssh2_pkt_addbool(1); /* want reply */
2272 ssh2_pkt_addstring(cfg
.remote_cmd
);
2274 ssh2_pkt_addstring("shell");
2275 ssh2_pkt_addbool(1); /* want reply */
2279 crWaitUntilV(ispkt
);
2280 if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
2281 /* FIXME: be able to handle other channels here */
2282 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2283 continue; /* wrong channel */
2284 mainchan
->u
.v2
.remwindow
+= ssh2_pkt_getuint32();
2286 } while (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
2287 if (pktin
.type
!= SSH2_MSG_CHANNEL_SUCCESS
) {
2288 if (pktin
.type
!= SSH2_MSG_CHANNEL_FAILURE
) {
2289 fatalbox("Server got confused by shell request");
2291 fatalbox("Server refused to start a shell");
2293 logevent("Started a shell");
2301 static int try_send
;
2305 if (pktin
.type
== SSH2_MSG_CHANNEL_DATA
||
2306 pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
) {
2309 /* FIXME: be able to handle other channels here */
2310 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2311 continue; /* wrong channel */
2312 if (pktin
.type
== SSH2_MSG_CHANNEL_EXTENDED_DATA
&&
2313 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR
)
2314 continue; /* extended but not stderr */
2315 ssh2_pkt_getstring(&data
, &length
);
2317 c_write(data
, length
);
2319 * Enlarge the window again at the remote side,
2320 * just in case it ever runs down and they fail
2321 * to send us any more data.
2323 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
2324 ssh2_pkt_adduint32(mainchan
->remoteid
);
2325 ssh2_pkt_adduint32(length
);
2328 } else if (pktin
.type
== SSH2_MSG_DISCONNECT
) {
2329 ssh_state
= SSH_STATE_CLOSED
;
2330 logevent("Received disconnect message");
2331 } else if (pktin
.type
== SSH2_MSG_CHANNEL_REQUEST
) {
2332 continue; /* exit status et al; ignore (FIXME?) */
2333 } else if (pktin
.type
== SSH2_MSG_CHANNEL_EOF
) {
2334 continue; /* remote sends EOF; ignore */
2335 } else if (pktin
.type
== SSH2_MSG_CHANNEL_CLOSE
) {
2336 /* FIXME: be able to handle other channels here */
2337 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2338 continue; /* wrong channel */
2339 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE
);
2340 ssh2_pkt_adduint32(mainchan
->remoteid
);
2342 /* FIXME: mark the channel as closed */
2343 if (1 /* FIXME: "all channels are closed" */) {
2344 logevent("All channels closed. Disconnecting");
2345 ssh2_pkt_init(SSH2_MSG_DISCONNECT
);
2348 continue; /* remote sends close; ignore (FIXME) */
2349 } else if (pktin
.type
== SSH2_MSG_CHANNEL_WINDOW_ADJUST
) {
2350 /* FIXME: be able to handle other channels here */
2351 if (ssh2_pkt_getuint32() != mainchan
->localid
)
2352 continue; /* wrong channel */
2353 mainchan
->u
.v2
.remwindow
+= ssh2_pkt_getuint32();
2356 fatalbox("Strange packet received: type %d", pktin
.type
);
2360 * We have spare data. Add it to the channel buffer.
2362 if (mainchan
->u
.v2
.outbufsize
<
2363 mainchan
->u
.v2
.outbuflen
+ inlen
) {
2364 mainchan
->u
.v2
.outbufsize
=
2365 mainchan
->u
.v2
.outbuflen
+ inlen
+ 1024;
2366 mainchan
->u
.v2
.outbuffer
= srealloc(mainchan
->u
.v2
.outbuffer
,
2367 mainchan
->u
.v2
.outbufsize
);
2369 memcpy(mainchan
->u
.v2
.outbuffer
+ mainchan
->u
.v2
.outbuflen
,
2371 mainchan
->u
.v2
.outbuflen
+= inlen
;
2376 * Try to send data on the channel if we can. (FIXME:
2377 * on _all_ channels.)
2379 while (mainchan
->u
.v2
.remwindow
> 0 &&
2380 mainchan
->u
.v2
.outbuflen
> 0) {
2381 unsigned len
= mainchan
->u
.v2
.remwindow
;
2382 if (len
> mainchan
->u
.v2
.outbuflen
)
2383 len
= mainchan
->u
.v2
.outbuflen
;
2384 if (len
> mainchan
->u
.v2
.remmaxpkt
)
2385 len
= mainchan
->u
.v2
.remmaxpkt
;
2386 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA
);
2387 ssh2_pkt_adduint32(mainchan
->remoteid
);
2388 ssh2_pkt_addstring_start();
2389 ssh2_pkt_addstring_data(mainchan
->u
.v2
.outbuffer
, len
);
2391 mainchan
->u
.v2
.outbuflen
-= len
;
2392 memmove(mainchan
->u
.v2
.outbuffer
, mainchan
->u
.v2
.outbuffer
+len
,
2393 mainchan
->u
.v2
.outbuflen
);
2394 mainchan
->u
.v2
.remwindow
-= len
;
2403 * Handle the top-level SSH2 protocol.
2405 static void ssh2_protocol(unsigned char *in
, int inlen
, int ispkt
)
2407 if (do_ssh2_transport(in
, inlen
, ispkt
) == 0)
2409 do_ssh2_authconn(in
, inlen
, ispkt
);
2413 * Called to set up the connection. Will arrange for WM_NETEVENT
2414 * messages to be passed to the specified window, whose window
2415 * procedure should then call telnet_msg().
2417 * Returns an error message, or NULL on success.
2419 static char *ssh_init (HWND hwnd
, char *host
, int port
, char **realhost
) {
2423 if(crypto_startup() == 0)
2424 return "Microsoft high encryption pack not installed!";
2427 p
= connect_to_host(host
, port
, realhost
);
2432 return "Protocol initialisation error";
2434 if (hwnd
&& WSAAsyncSelect (s
, hwnd
, WM_NETEVENT
, FD_READ
| FD_CLOSE
) == SOCKET_ERROR
)
2435 switch (WSAGetLastError()) {
2436 case WSAENETDOWN
: return "Network is down";
2437 default: return "WSAAsyncSelect(): unknown error";
2444 * Process a WM_NETEVENT message. Will return 0 if the connection
2445 * has closed, or <0 for a socket error.
2447 static int ssh_msg (WPARAM wParam
, LPARAM lParam
) {
2452 * Because reading less than the whole of the available pending
2453 * data can generate an FD_READ event, we need to allow for the
2454 * possibility that FD_READ may arrive with FD_CLOSE already in
2455 * the queue; so it's possible that we can get here even with s
2456 * invalid. If so, we return 1 and don't worry about it.
2458 if (s
== INVALID_SOCKET
)
2461 if (WSAGETSELECTERROR(lParam
) != 0)
2462 return -WSAGETSELECTERROR(lParam
);
2464 switch (WSAGETSELECTEVENT(lParam
)) {
2467 ret
= recv(s
, buf
, sizeof(buf
), 0);
2468 if (ret
< 0 && WSAGetLastError() == WSAEWOULDBLOCK
)
2470 if (ret
< 0) /* any _other_ error */
2471 return -10000-WSAGetLastError();
2476 ssh_gotdata (buf
, ret
);
2477 if (ssh_state
== SSH_STATE_CLOSED
) {
2484 return 1; /* shouldn't happen, but WTF */
2488 * Called to send data down the Telnet connection.
2490 static void ssh_send (char *buf
, int len
) {
2491 if (s
== INVALID_SOCKET
)
2494 ssh_protocol(buf
, len
, 0);
2498 * Called to set the size of the window from Telnet's POV.
2500 static void ssh_size(void) {
2501 switch (ssh_state
) {
2502 case SSH_STATE_BEFORE_SIZE
:
2503 case SSH_STATE_CLOSED
:
2504 break; /* do nothing */
2505 case SSH_STATE_INTERMED
:
2506 size_needed
= TRUE
; /* buffer for later */
2508 case SSH_STATE_SESSION
:
2510 send_packet(SSH1_CMSG_WINDOW_SIZE
,
2511 PKT_INT
, rows
, PKT_INT
, cols
,
2512 PKT_INT
, 0, PKT_INT
, 0, PKT_END
);
2518 * Send Telnet special codes. TS_EOF is useful for `plink', so you
2519 * can send an EOF and collect resulting output (e.g. `plink
2522 static void ssh_special (Telnet_Special code
) {
2523 if (code
== TS_EOF
) {
2524 if (ssh_version
== 1) {
2525 send_packet(SSH1_CMSG_EOF
, PKT_END
);
2527 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF
);
2528 ssh2_pkt_adduint32(mainchan
->remoteid
);
2531 logevent("Sent EOF message");
2539 * Read and decrypt one incoming SSH packet.
2540 * (only used by pSCP)
2542 static void get_packet(void)
2544 unsigned char buf
[4096], *p
;
2551 while ((to_read
= s_rdpkt(&p
, &len
)) > 0) {
2552 if (to_read
> sizeof(buf
)) to_read
= sizeof(buf
);
2553 len
= s_read(buf
, to_read
);
2554 if (len
!= to_read
) {
2566 * Receive a block of data over the SSH link. Block until
2567 * all data is available. Return nr of bytes read (0 if lost connection).
2568 * (only used by pSCP)
2570 int ssh_scp_recv(unsigned char *buf
, int len
)
2572 static int pending_input_len
= 0;
2573 static unsigned char *pending_input_ptr
;
2576 if (pending_input_len
>= to_read
) {
2577 memcpy(buf
, pending_input_ptr
, to_read
);
2578 pending_input_ptr
+= to_read
;
2579 pending_input_len
-= to_read
;
2583 if (pending_input_len
> 0) {
2584 memcpy(buf
, pending_input_ptr
, pending_input_len
);
2585 buf
+= pending_input_len
;
2586 to_read
-= pending_input_len
;
2587 pending_input_len
= 0;
2590 if (s
== INVALID_SOCKET
)
2592 while (to_read
> 0) {
2594 if (s
== INVALID_SOCKET
)
2596 if (pktin
.type
== SSH1_SMSG_STDOUT_DATA
) {
2597 int plen
= GET_32BIT(pktin
.body
);
2598 if (plen
<= to_read
) {
2599 memcpy(buf
, pktin
.body
+ 4, plen
);
2603 memcpy(buf
, pktin
.body
+ 4, to_read
);
2604 pending_input_len
= plen
- to_read
;
2605 pending_input_ptr
= pktin
.body
+ 4 + to_read
;
2608 } else if (pktin
.type
== SSH1_SMSG_STDERR_DATA
) {
2609 int plen
= GET_32BIT(pktin
.body
);
2610 fwrite(pktin
.body
+ 4, plen
, 1, stderr
);
2611 } else if (pktin
.type
== SSH1_MSG_DISCONNECT
) {
2612 logevent("Received disconnect request");
2613 } else if (pktin
.type
== SSH1_SMSG_SUCCESS
||
2614 pktin
.type
== SSH1_SMSG_FAILURE
) {
2616 } else if (pktin
.type
== SSH1_SMSG_EXIT_STATUS
) {
2618 sprintf(logbuf
, "Remote exit status: %d", GET_32BIT(pktin
.body
));
2620 send_packet(SSH1_CMSG_EXIT_CONFIRMATION
, PKT_END
);
2621 logevent("Closing connection");
2625 fatalbox("Strange packet received: type %d", pktin
.type
);
2633 * Send a block of data over the SSH link.
2634 * Block until all data is sent.
2635 * (only used by pSCP)
2637 void ssh_scp_send(unsigned char *buf
, int len
)
2639 if (s
== INVALID_SOCKET
)
2641 send_packet(SSH1_CMSG_STDIN_DATA
,
2642 PKT_INT
, len
, PKT_DATA
, buf
, len
, PKT_END
);
2646 * Send an EOF notification to the server.
2647 * (only used by pSCP)
2649 void ssh_scp_send_eof(void)
2651 if (s
== INVALID_SOCKET
)
2653 send_packet(SSH1_CMSG_EOF
, PKT_END
);
2657 * Set up the connection, login on the remote host and
2658 * start execution of a command.
2659 * Returns an error message, or NULL on success.
2660 * (only used by pSCP)
2662 char *ssh_scp_init(char *host
, int port
, char *cmd
, char **realhost
)
2667 if (crypto_startup() == 0)
2668 return "Microsoft high encryption pack not installed!";
2671 p
= connect_to_host(host
, port
, realhost
);
2678 return "Protocol initialisation error";
2680 /* Exchange keys and login */
2683 if (s
== INVALID_SOCKET
)
2684 return "Connection closed by remote host";
2685 } while (!do_ssh1_login(NULL
, 0, 1));
2687 if (ssh_state
== SSH_STATE_CLOSED
) {
2690 return "Session initialisation error";
2693 /* Execute command */
2694 sprintf(buf
, "Sending command: %.100s", cmd
);
2696 send_packet(SSH1_CMSG_EXEC_CMD
, PKT_STR
, cmd
, PKT_END
);
2701 static SOCKET
ssh_socket(void) { return s
; }
2703 static int ssh_sendok(void) { return ssh_send_ok
; }
2705 Backend ssh_backend
= {