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