19 #define logevent(s) { logevent(s); \
20 if (!(flags & FLAG_CONNECTION) && (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_CONNECTION)) {
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_CONNECTION) && !*cfg.username) {
1194 c_write("login as: ", 10);
1196 crWaitUntil(!ispkt);
1197 while (inlen--) switch (c = *in++) {
1204 c_write("\b \b", 3);
1210 c_write("\b \b", 3);
1219 if (((c >= ' ' && c <= '~') ||
1220 ((unsigned char)c >= 160)) && pos < 40) {
1221 username[pos++] = c;
1228 username[strcspn(username, "\n\r")] = '\0';
1231 strncpy(username, cfg.username, 99);
1232 username[99] = '\0';
1233 if (flags & FLAG_VERBOSE) {
1234 sprintf(stuff, "Sent username \"%s\".\r\n", username);
1235 c_write(stuff, strlen(stuff));
1239 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
1241 char userlog[20+sizeof(username)];
1242 sprintf(userlog, "Sent username \"%s\"", username);
1249 tried_publickey = 0;
1251 while (pktin.type == SSH1_SMSG_FAILURE) {
1252 static char password[100];
1255 static int pwpkt_type;
1257 * Show password prompt, having first obtained it via a TIS
1258 * or CryptoCard exchange if we're doing TIS or CryptoCard
1261 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
1262 if (agent_exists()) {
1264 * Attempt RSA authentication using Pageant.
1266 static unsigned char request[5], *response, *p;
1267 static int responselen;
1268 static int i, nkeys;
1269 static int authed = FALSE;
1272 logevent("Pageant is running. Requesting keys.");
1274 /* Request the keys held by the agent. */
1275 PUT_32BIT(request, 1);
1276 request[4] = SSH_AGENTC_REQUEST_RSA_IDENTITIES;
1277 agent_query(request, 5, &r, &responselen);
1278 response = (unsigned char *)r;
1281 nkeys = GET_32BIT(p); p += 4;
1282 { char buf[64]; sprintf(buf, "Pageant has %d keys", nkeys);
1284 for (i = 0; i < nkeys; i++) {
1285 static struct RSAKey key;
1286 static Bignum challenge;
1287 static char *commentp;
1288 static int commentlen;
1290 { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
1293 p += ssh1_read_bignum(p, &key.exponent);
1294 p += ssh1_read_bignum(p, &key.modulus);
1295 commentlen = GET_32BIT(p); p += 4;
1296 commentp = p; p += commentlen;
1297 send_packet(SSH1_CMSG_AUTH_RSA,
1298 PKT_BIGNUM, key.modulus, PKT_END);
1300 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1301 logevent("Key refused");
1304 logevent("Received RSA challenge");
1305 ssh1_read_bignum(pktin.body, &challenge);
1307 char *agentreq, *q, *ret;
1309 len = 1 + 4; /* message type, bit count */
1310 len += ssh1_bignum_length(key.exponent);
1311 len += ssh1_bignum_length(key.modulus);
1312 len += ssh1_bignum_length(challenge);
1313 len += 16; /* session id */
1314 len += 4; /* response format */
1315 agentreq = malloc(4 + len);
1316 PUT_32BIT(agentreq, len);
1318 *q++ = SSH_AGENTC_RSA_CHALLENGE;
1319 PUT_32BIT(q, ssh1_bignum_bitcount(key.modulus));
1321 q += ssh1_write_bignum(q, key.exponent);
1322 q += ssh1_write_bignum(q, key.modulus);
1323 q += ssh1_write_bignum(q, challenge);
1324 memcpy(q, session_id, 16); q += 16;
1325 PUT_32BIT(q, 1); /* response format */
1326 agent_query(agentreq, len+4, &ret, &retlen);
1329 if (ret[4] == SSH_AGENT_RSA_RESPONSE) {
1330 logevent("Sending Pageant's response");
1331 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1332 PKT_DATA, ret+5, 16, PKT_END);
1335 if (pktin.type == SSH1_SMSG_SUCCESS) {
1336 logevent("Pageant's response accepted");
1337 c_write("Authenticated using RSA key \"",
1339 c_write(commentp, commentlen);
1340 c_write("\" from agent\r\n", 14);
1343 logevent("Pageant's response not accepted");
1345 logevent("Pageant failed to answer challenge");
1349 logevent("No reply received from Pageant");
1352 freebn(key.exponent);
1353 freebn(key.modulus);
1362 if (*cfg.keyfile && !tried_publickey)
1363 pwpkt_type = SSH1_CMSG_AUTH_RSA;
1365 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD && !FLAG_WINDOWED) {
1367 sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
1368 if (!ssh_get_password(prompt, password, sizeof(password))) {
1370 * get_password failed to get a password (for
1371 * example because one was supplied on the command
1372 * line which has already failed to work).
1375 logevent("No more passwords to try");
1376 ssh_state = SSH_STATE_CLOSED;
1381 if (pktin.type == SSH1_SMSG_FAILURE &&
1383 (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1384 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1385 logevent("Requested TIS authentication");
1386 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1388 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1389 logevent("TIS authentication declined");
1390 c_write("TIS authentication refused.\r\n", 29);
1392 int challengelen = ((pktin.body[0] << 24) |
1393 (pktin.body[1] << 16) |
1394 (pktin.body[2] << 8) |
1396 logevent("Received TIS challenge");
1397 c_write(pktin.body+4, challengelen);
1400 if (pktin.type == SSH1_SMSG_FAILURE &&
1402 (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
1403 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
1404 logevent("Requested CryptoCard authentication");
1405 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
1407 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
1408 logevent("CryptoCard authentication declined");
1409 c_write("CryptoCard authentication refused.\r\n", 29);
1411 int challengelen = ((pktin.body[0] << 24) |
1412 (pktin.body[1] << 16) |
1413 (pktin.body[2] << 8) |
1415 logevent("Received CryptoCard challenge");
1416 c_write(pktin.body+4, challengelen);
1417 c_write("\r\nResponse : ", 13);
1420 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD)
1421 c_write("password: ", 10);
1422 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1423 if (flags & FLAG_VERBOSE)
1424 c_write("Trying public key authentication.\r\n", 35);
1425 if (!rsakey_encrypted(cfg.keyfile)) {
1426 if (flags & FLAG_VERBOSE)
1427 c_write("No passphrase required.\r\n", 25);
1430 c_write("passphrase: ", 12);
1435 crWaitUntil(!ispkt);
1436 while (inlen--) switch (c = *in++) {
1453 if (((c >= ' ' && c <= '~') ||
1454 ((unsigned char)c >= 160)) && pos < sizeof(password))
1455 password[pos++] = c;
1464 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1466 * Try public key authentication with the specified
1469 static struct RSAKey pubkey;
1470 static Bignum challenge, response;
1472 static unsigned char buffer[32];
1474 tried_publickey = 1;
1475 i = loadrsakey(cfg.keyfile, &pubkey, password);
1477 c_write("Couldn't load public key from ", 30);
1478 c_write(cfg.keyfile, strlen(cfg.keyfile));
1479 c_write(".\r\n", 3);
1480 continue; /* go and try password */
1483 c_write("Wrong passphrase.\r\n", 19);
1484 tried_publickey = 0;
1485 continue; /* try again */
1489 * Send a public key attempt.
1491 send_packet(SSH1_CMSG_AUTH_RSA,
1492 PKT_BIGNUM, pubkey.modulus, PKT_END);
1495 if (pktin.type == SSH1_SMSG_FAILURE) {
1496 if (flags & FLAG_VERBOSE)
1497 c_write("Server refused our public key.\r\n", 32);
1498 continue; /* go and try password */
1500 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE)
1501 fatalbox("Bizarre response to offer of public key");
1502 ssh1_read_bignum(pktin.body, &challenge);
1503 response = rsadecrypt(challenge, &pubkey);
1504 freebn(pubkey.private_exponent); /* burn the evidence */
1506 for (i = 0; i < 32; i += 2) {
1507 buffer[i] = response[16-i/2] >> 8;
1508 buffer[i+1] = response[16-i/2] & 0xFF;
1512 MD5Update(&md5c, buffer, 32);
1513 MD5Update(&md5c, session_id, 16);
1514 MD5Final(buffer, &md5c);
1516 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1517 PKT_DATA, buffer, 16, PKT_END);
1520 if (pktin.type == SSH1_SMSG_FAILURE) {
1521 if (flags & FLAG_VERBOSE)
1522 c_write("Failed to authenticate with our public key.\r\n",
1524 continue; /* go and try password */
1525 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1526 fatalbox("Bizarre response to RSA authentication response");
1529 break; /* we're through! */
1531 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1533 logevent("Sent password");
1534 memset(password, 0, strlen(password));
1536 if (pktin.type == SSH1_SMSG_FAILURE) {
1537 if (flags & FLAG_VERBOSE)
1538 c_write("Access denied\r\n", 15);
1539 logevent("Authentication refused");
1540 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1541 logevent("Received disconnect request");
1542 ssh_state = SSH_STATE_CLOSED;
1544 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1545 fatalbox("Strange packet received, type %d", pktin.type);
1549 logevent("Authentication successful");
1554 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
1559 while (!do_ssh1_login(in, inlen, ispkt)) {
1562 if (ssh_state == SSH_STATE_CLOSED)
1565 if (cfg.agentfwd && agent_exists()) {
1566 logevent("Requesting agent forwarding");
1567 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
1568 do { crReturnV; } while (!ispkt);
1569 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1570 fatalbox("Protocol confusion");
1571 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1572 logevent("Agent forwarding refused");
1574 logevent("Agent forwarding enabled");
1578 send_packet(SSH1_CMSG_REQUEST_PTY,
1579 PKT_STR, cfg.termtype,
1580 PKT_INT, rows, PKT_INT, cols,
1581 PKT_INT, 0, PKT_INT, 0,
1584 ssh_state = SSH_STATE_INTERMED;
1585 do { crReturnV; } while (!ispkt);
1586 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1587 fatalbox("Protocol confusion");
1588 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1589 c_write("Server refused to allocate pty\r\n", 32);
1591 logevent("Allocated pty");
1594 if (*cfg.remote_cmd)
1595 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
1597 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
1598 logevent("Started session");
1600 ssh_state = SSH_STATE_SESSION;
1605 ssh_channels = newtree234(ssh_channelcmp);
1609 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
1610 pktin.type == SSH1_SMSG_STDERR_DATA) {
1611 long len = GET_32BIT(pktin.body);
1612 c_write(pktin.body+4, len);
1613 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1614 ssh_state = SSH_STATE_CLOSED;
1615 logevent("Received disconnect request");
1616 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
1617 /* Remote side is trying to open a channel to talk to our
1618 * agent. Give them back a local channel number. */
1620 struct ssh_channel *c;
1622 for (c = first234(ssh_channels, &e); c; c = next234(&e)) {
1624 break; /* found a free number */
1627 c = malloc(sizeof(struct ssh_channel));
1628 c->remoteid = GET_32BIT(pktin.body);
1631 c->type = SSH1_SMSG_AGENT_OPEN; /* identify channel type */
1632 add234(ssh_channels, c);
1633 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
1634 PKT_INT, c->remoteid, PKT_INT, c->localid,
1636 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
1637 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
1638 /* Remote side closes a channel. */
1639 unsigned i = GET_32BIT(pktin.body);
1640 struct ssh_channel *c;
1641 c = find234(ssh_channels, &i, ssh_channelfind);
1644 closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
1645 send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
1646 c->closes |= closetype;
1647 if (c->closes == 3) {
1648 del234(ssh_channels, c);
1652 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
1653 /* Data sent down one of our channels. */
1654 int i = GET_32BIT(pktin.body);
1655 int len = GET_32BIT(pktin.body+4);
1656 unsigned char *p = pktin.body+8;
1657 struct ssh_channel *c;
1658 c = find234(ssh_channels, &i, ssh_channelfind);
1661 case SSH1_SMSG_AGENT_OPEN:
1662 /* Data for an agent message. Buffer it. */
1664 if (c->u.a.lensofar < 4) {
1665 int l = min(4 - c->u.a.lensofar, len);
1666 memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
1667 p += l; len -= l; c->u.a.lensofar += l;
1669 if (c->u.a.lensofar == 4) {
1670 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
1671 c->u.a.message = malloc(c->u.a.totallen);
1672 memcpy(c->u.a.message, c->u.a.msglen, 4);
1674 if (c->u.a.lensofar >= 4 && len > 0) {
1675 int l = min(c->u.a.totallen - c->u.a.lensofar, len);
1676 memcpy(c->u.a.message + c->u.a.lensofar, p, l);
1677 p += l; len -= l; c->u.a.lensofar += l;
1679 if (c->u.a.lensofar == c->u.a.totallen) {
1680 void *reply, *sentreply;
1682 agent_query(c->u.a.message, c->u.a.totallen,
1687 /* Fake SSH_AGENT_FAILURE. */
1688 sentreply = "\0\0\0\1\5";
1691 send_packet(SSH1_MSG_CHANNEL_DATA,
1692 PKT_INT, c->remoteid,
1694 PKT_DATA, sentreply, replylen,
1698 free(c->u.a.message);
1699 c->u.a.lensofar = 0;
1705 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
1706 /* may be from EXEC_SHELL on some servers */
1707 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1708 /* may be from EXEC_SHELL on some servers
1709 * if no pty is available or in other odd cases. Ignore */
1710 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
1711 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
1713 fatalbox("Strange packet received: type %d", pktin.type);
1716 send_packet(SSH1_CMSG_STDIN_DATA,
1717 PKT_INT, inlen, PKT_DATA, in, inlen, PKT_END);
1725 * Utility routine for decoding comma-separated strings in KEXINIT.
1727 int in_commasep_string(char *needle, char *haystack, int haylen) {
1728 int needlen = strlen(needle);
1731 * Is it at the start of the string?
1733 if (haylen >= needlen && /* haystack is long enough */
1734 !memcmp(needle, haystack, needlen) && /* initial match */
1735 (haylen == needlen || haystack[needlen] == ',')
1736 /* either , or EOS follows */
1740 * If not, search for the next comma and resume after that.
1741 * If no comma found, terminate.
1743 while (haylen > 0 && *haystack != ',')
1744 haylen--, haystack++;
1747 haylen--, haystack++; /* skip over comma itself */
1752 * SSH2 key creation method.
1754 void ssh2_mkkey(Bignum K, char *H, char chr, char *keyspace) {
1756 /* First 20 bytes. */
1759 SHA_Bytes(&s, H, 20);
1760 SHA_Bytes(&s, &chr, 1);
1761 SHA_Bytes(&s, H, 20);
1762 SHA_Final(&s, keyspace);
1763 /* Next 20 bytes. */
1766 SHA_Bytes(&s, H, 20);
1767 SHA_Bytes(&s, keyspace, 20);
1768 SHA_Final(&s, keyspace+20);
1772 * Handle the SSH2 transport layer.
1774 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
1778 static Bignum e, f, K;
1779 static struct ssh_cipher *cscipher_tobe = NULL;
1780 static struct ssh_cipher *sccipher_tobe = NULL;
1781 static struct ssh_mac *csmac_tobe = NULL;
1782 static struct ssh_mac *scmac_tobe = NULL;
1783 static struct ssh_compress *cscomp_tobe = NULL;
1784 static struct ssh_compress *sccomp_tobe = NULL;
1785 static char *hostkeydata, *sigdata, *keystr;
1786 static int hostkeylen, siglen;
1787 static unsigned char exchange_hash[20];
1788 static unsigned char keyspace[40];
1794 * Set up the preferred cipher.
1796 if (cfg.cipher == CIPHER_BLOWFISH) {
1797 ciphers[0] = &ssh_blowfish_ssh2;
1798 } else if (cfg.cipher == CIPHER_DES) {
1799 logevent("Single DES not supported in SSH2; using 3DES");
1800 ciphers[0] = &ssh_3des_ssh2;
1801 } else if (cfg.cipher == CIPHER_3DES) {
1802 ciphers[0] = &ssh_3des_ssh2;
1804 /* Shouldn't happen, but we do want to initialise to _something_. */
1805 ciphers[0] = &ssh_3des_ssh2;
1810 * Construct and send our key exchange packet.
1812 ssh2_pkt_init(SSH2_MSG_KEXINIT);
1813 for (i = 0; i < 16; i++)
1814 ssh2_pkt_addbyte((unsigned char)random_byte());
1815 /* List key exchange algorithms. */
1816 ssh2_pkt_addstring_start();
1817 for (i = 0; i < lenof(kex_algs); i++) {
1818 ssh2_pkt_addstring_str(kex_algs[i]->name);
1819 if (i < lenof(kex_algs)-1)
1820 ssh2_pkt_addstring_str(",");
1822 /* List server host key algorithms. */
1823 ssh2_pkt_addstring_start();
1824 for (i = 0; i < lenof(hostkey_algs); i++) {
1825 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
1826 if (i < lenof(hostkey_algs)-1)
1827 ssh2_pkt_addstring_str(",");
1829 /* List client->server encryption algorithms. */
1830 ssh2_pkt_addstring_start();
1831 for (i = 0; i < lenof(ciphers); i++) {
1832 ssh2_pkt_addstring_str(ciphers[i]->name);
1833 if (i < lenof(ciphers)-1)
1834 ssh2_pkt_addstring_str(",");
1836 /* List server->client encryption algorithms. */
1837 ssh2_pkt_addstring_start();
1838 for (i = 0; i < lenof(ciphers); i++) {
1839 ssh2_pkt_addstring_str(ciphers[i]->name);
1840 if (i < lenof(ciphers)-1)
1841 ssh2_pkt_addstring_str(",");
1843 /* List client->server MAC algorithms. */
1844 ssh2_pkt_addstring_start();
1845 for (i = 0; i < lenof(macs); i++) {
1846 ssh2_pkt_addstring_str(macs[i]->name);
1847 if (i < lenof(macs)-1)
1848 ssh2_pkt_addstring_str(",");
1850 /* List server->client MAC algorithms. */
1851 ssh2_pkt_addstring_start();
1852 for (i = 0; i < lenof(macs); i++) {
1853 ssh2_pkt_addstring_str(macs[i]->name);
1854 if (i < lenof(macs)-1)
1855 ssh2_pkt_addstring_str(",");
1857 /* List client->server compression algorithms. */
1858 ssh2_pkt_addstring_start();
1859 for (i = 0; i < lenof(compressions); i++) {
1860 ssh2_pkt_addstring_str(compressions[i]->name);
1861 if (i < lenof(compressions)-1)
1862 ssh2_pkt_addstring_str(",");
1864 /* List server->client compression algorithms. */
1865 ssh2_pkt_addstring_start();
1866 for (i = 0; i < lenof(compressions); i++) {
1867 ssh2_pkt_addstring_str(compressions[i]->name);
1868 if (i < lenof(compressions)-1)
1869 ssh2_pkt_addstring_str(",");
1871 /* List client->server languages. Empty list. */
1872 ssh2_pkt_addstring_start();
1873 /* List server->client languages. Empty list. */
1874 ssh2_pkt_addstring_start();
1875 /* First KEX packet does _not_ follow, because we're not that brave. */
1876 ssh2_pkt_addbool(FALSE);
1878 ssh2_pkt_adduint32(0);
1879 sha_string(&exhash, pktout.data+5, pktout.length-5);
1882 if (!ispkt) crWaitUntil(ispkt);
1883 sha_string(&exhash, pktin.data+5, pktin.length-5);
1886 * Now examine the other side's KEXINIT to see what we're up
1889 if (pktin.type != SSH2_MSG_KEXINIT) {
1890 fatalbox("expected key exchange packet from server");
1892 kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
1893 csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
1894 pktin.savedpos += 16; /* skip garbage cookie */
1895 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
1896 for (i = 0; i < lenof(kex_algs); i++) {
1897 if (in_commasep_string(kex_algs[i]->name, str, len)) {
1902 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
1903 for (i = 0; i < lenof(hostkey_algs); i++) {
1904 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
1905 hostkey = hostkey_algs[i];
1909 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
1910 for (i = 0; i < lenof(ciphers); i++) {
1911 if (in_commasep_string(ciphers[i]->name, str, len)) {
1912 cscipher_tobe = ciphers[i];
1916 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
1917 for (i = 0; i < lenof(ciphers); i++) {
1918 if (in_commasep_string(ciphers[i]->name, str, len)) {
1919 sccipher_tobe = ciphers[i];
1923 ssh2_pkt_getstring(&str, &len); /* client->server mac */
1924 for (i = 0; i < lenof(macs); i++) {
1925 if (in_commasep_string(macs[i]->name, str, len)) {
1926 csmac_tobe = macs[i];
1930 ssh2_pkt_getstring(&str, &len); /* server->client mac */
1931 for (i = 0; i < lenof(macs); i++) {
1932 if (in_commasep_string(macs[i]->name, str, len)) {
1933 scmac_tobe = macs[i];
1937 ssh2_pkt_getstring(&str, &len); /* client->server compression */
1938 for (i = 0; i < lenof(compressions); i++) {
1939 if (in_commasep_string(compressions[i]->name, str, len)) {
1940 cscomp_tobe = compressions[i];
1944 ssh2_pkt_getstring(&str, &len); /* server->client compression */
1945 for (i = 0; i < lenof(compressions); i++) {
1946 if (in_commasep_string(compressions[i]->name, str, len)) {
1947 sccomp_tobe = compressions[i];
1953 * Currently we only support Diffie-Hellman and DSS, so let's
1954 * bomb out if those aren't selected.
1956 if (kex != &ssh_diffiehellman || hostkey != &ssh_dss)
1957 fatalbox("internal fault: chaos in SSH 2 transport layer");
1960 * Now we begin the fun. Generate and send e for Diffie-Hellman.
1963 ssh2_pkt_init(SSH2_MSG_KEXDH_INIT);
1968 if (pktin.type != SSH2_MSG_KEXDH_REPLY) {
1969 fatalbox("expected key exchange packet from server");
1971 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
1972 f = ssh2_pkt_getmp();
1973 ssh2_pkt_getstring(&sigdata, &siglen);
1977 sha_string(&exhash, hostkeydata, hostkeylen);
1978 sha_mpint(&exhash, e);
1979 sha_mpint(&exhash, f);
1980 sha_mpint(&exhash, K);
1981 SHA_Final(&exhash, exchange_hash);
1984 debug(("Exchange hash is:\r\n"));
1985 for (i = 0; i < 20; i++)
1986 debug((" %02x", exchange_hash[i]));
1990 hostkey->setkey(hostkeydata, hostkeylen);
1991 if (!hostkey->verifysig(sigdata, siglen, exchange_hash, 20))
1992 fatalbox("Server failed host key check");
1995 * Expect SSH2_MSG_NEWKEYS from server.
1998 if (pktin.type != SSH2_MSG_NEWKEYS)
1999 fatalbox("expected new-keys packet from server");
2002 * Authenticate remote host: verify host key. (We've already
2003 * checked the signature of the exchange hash.)
2005 keystr = hostkey->fmtkey();
2006 verify_ssh_host_key(savedhost, keystr);
2010 * Send SSH2_MSG_NEWKEYS.
2012 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
2016 * Create and initialise session keys.
2018 cscipher = cscipher_tobe;
2019 sccipher = sccipher_tobe;
2022 cscomp = cscomp_tobe;
2023 sccomp = sccomp_tobe;
2025 * Set IVs after keys.
2027 ssh2_mkkey(K, exchange_hash, 'C', keyspace); cscipher->setcskey(keyspace);
2028 ssh2_mkkey(K, exchange_hash, 'D', keyspace); cscipher->setsckey(keyspace);
2029 ssh2_mkkey(K, exchange_hash, 'A', keyspace); cscipher->setcsiv(keyspace);
2030 ssh2_mkkey(K, exchange_hash, 'B', keyspace); sccipher->setsciv(keyspace);
2031 ssh2_mkkey(K, exchange_hash, 'E', keyspace); csmac->setcskey(keyspace);
2032 ssh2_mkkey(K, exchange_hash, 'F', keyspace); scmac->setsckey(keyspace);
2035 * Now we're encrypting. Begin returning 1 to the protocol main
2036 * function so that other things can run on top of the
2037 * transport. If we ever see a KEXINIT, we must go back to the
2042 } while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT));
2043 goto begin_key_exchange;
2049 * Handle the SSH2 userauth and connection layers.
2051 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
2053 static unsigned long remote_winsize;
2054 static unsigned long remote_maxpkt;
2059 * Request userauth protocol, and await a response to it.
2061 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
2062 ssh2_pkt_addstring("ssh-userauth");
2064 crWaitUntilV(ispkt);
2065 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT)
2066 fatalbox("Server refused user authentication protocol");
2069 * FIXME: currently we support only password authentication.
2070 * (This places us technically in violation of the SSH2 spec.
2071 * We must fix this.)
2075 * Get a username and a password.
2077 static char username[100];
2078 static char password[100];
2082 if ((flags & FLAG_CONNECTION) && !*cfg.username) {
2083 c_write("login as: ", 10);
2085 crWaitUntilV(!ispkt);
2086 while (inlen--) switch (c = *in++) {
2093 c_write("\b \b", 3);
2099 c_write("\b \b", 3);
2108 if (((c >= ' ' && c <= '~') ||
2109 ((unsigned char)c >= 160)) && pos < 40) {
2110 username[pos++] = c;
2117 username[strcspn(username, "\n\r")] = '\0';
2120 strncpy(username, cfg.username, 99);
2121 username[99] = '\0';
2122 if (flags & FLAG_VERBOSE) {
2123 sprintf(stuff, "Using username \"%s\".\r\n", username);
2124 c_write(stuff, strlen(stuff));
2128 if (!(flags & FLAG_WINDOWED)) {
2130 sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
2131 if (!ssh_get_password(prompt, password, sizeof(password))) {
2133 * get_password failed to get a password (for
2134 * example because one was supplied on the command
2135 * line which has already failed to work).
2138 logevent("No more passwords to try");
2139 ssh_state = SSH_STATE_CLOSED;
2143 c_write("password: ", 10);
2147 crWaitUntilV(!ispkt);
2148 while (inlen--) switch (c = *in++) {
2165 if (((c >= ' ' && c <= '~') ||
2166 ((unsigned char)c >= 160)) && pos < 40)
2167 password[pos++] = c;
2174 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2175 ssh2_pkt_addstring(username);
2176 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2177 ssh2_pkt_addstring("password");
2178 ssh2_pkt_addbool(FALSE);
2179 ssh2_pkt_addstring(password);
2182 crWaitUntilV(ispkt);
2183 if (pktin.type != SSH2_MSG_USERAUTH_SUCCESS) {
2184 c_write("Access denied\r\n", 15);
2185 logevent("Authentication refused");
2191 * Now we're authenticated for the connection protocol. The
2192 * connection protocol will automatically have started at this
2193 * point; there's no need to send SERVICE_REQUEST.
2197 * So now create a channel with a session in it.
2199 mainchan = malloc(sizeof(struct ssh_channel));
2200 mainchan->localid = 100; /* as good as any */
2201 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
2202 ssh2_pkt_addstring("session");
2203 ssh2_pkt_adduint32(mainchan->localid);
2204 ssh2_pkt_adduint32(0x7FFFFFFFUL); /* our window size */
2205 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
2207 crWaitUntilV(ispkt);
2208 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
2209 fatalbox("Server refused to open a session");
2210 /* FIXME: error data comes back in FAILURE packet */
2212 if (ssh2_pkt_getuint32() != mainchan->localid) {
2213 fatalbox("Server's channel confirmation cited wrong channel");
2215 mainchan->remoteid = ssh2_pkt_getuint32();
2216 mainchan->u.v2.remwindow = ssh2_pkt_getuint32();
2217 mainchan->u.v2.remmaxpkt = ssh2_pkt_getuint32();
2218 mainchan->u.v2.outbuffer = NULL;
2219 mainchan->u.v2.outbuflen = mainchan->u.v2.outbufsize = 0;
2220 logevent("Opened channel for session");
2223 * Now allocate a pty for the session.
2225 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2226 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
2227 ssh2_pkt_addstring("pty-req");
2228 ssh2_pkt_addbool(1); /* want reply */
2229 ssh2_pkt_addstring(cfg.termtype);
2230 ssh2_pkt_adduint32(cols);
2231 ssh2_pkt_adduint32(rows);
2232 ssh2_pkt_adduint32(0); /* pixel width */
2233 ssh2_pkt_adduint32(0); /* pixel height */
2234 ssh2_pkt_addstring_start();
2235 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
2238 do { /* FIXME: pay attention to these */
2239 crWaitUntilV(ispkt);
2240 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2242 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2243 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2244 fatalbox("Server got confused by pty request");
2246 c_write("Server refused to allocate pty\r\n", 32);
2248 logevent("Allocated pty");
2254 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2255 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
2256 ssh2_pkt_addstring("shell");
2257 ssh2_pkt_addbool(1); /* want reply */
2260 crWaitUntilV(ispkt);
2261 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2262 /* FIXME: be able to handle other channels here */
2263 if (ssh2_pkt_getuint32() != mainchan->localid)
2264 continue; /* wrong channel */
2265 mainchan->u.v2.remwindow += ssh2_pkt_getuint32();
2267 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2268 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2269 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2270 fatalbox("Server got confused by shell request");
2272 fatalbox("Server refused to start a shell");
2274 logevent("Started a shell");
2282 static int try_send;
2286 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
2287 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
2290 /* FIXME: be able to handle other channels here */
2291 if (ssh2_pkt_getuint32() != mainchan->localid)
2292 continue; /* wrong channel */
2293 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
2294 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
2295 continue; /* extended but not stderr */
2296 ssh2_pkt_getstring(&data, &length);
2298 c_write(data, length);
2300 * Enlarge the window again at the remote side,
2301 * just in case it ever runs down and they fail
2302 * to send us any more data.
2304 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2305 ssh2_pkt_adduint32(mainchan->remoteid);
2306 ssh2_pkt_adduint32(length);
2309 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
2310 ssh_state = SSH_STATE_CLOSED;
2311 logevent("Received disconnect message");
2312 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
2313 continue; /* exit status et al; ignore (FIXME?) */
2314 } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
2315 continue; /* remote sends EOF; ignore */
2316 } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
2317 /* FIXME: be able to handle other channels here */
2318 if (ssh2_pkt_getuint32() != mainchan->localid)
2319 continue; /* wrong channel */
2320 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2321 ssh2_pkt_adduint32(mainchan->remoteid);
2323 /* FIXME: mark the channel as closed */
2324 if (1 /* FIXME: "all channels are closed" */) {
2325 logevent("All channels closed. Disconnecting");
2326 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
2329 continue; /* remote sends close; ignore (FIXME) */
2330 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2331 /* FIXME: be able to handle other channels here */
2332 if (ssh2_pkt_getuint32() != mainchan->localid)
2333 continue; /* wrong channel */
2334 mainchan->u.v2.remwindow += ssh2_pkt_getuint32();
2337 fatalbox("Strange packet received: type %d", pktin.type);
2341 * We have spare data. Add it to the channel buffer.
2343 if (mainchan->u.v2.outbufsize <
2344 mainchan->u.v2.outbuflen + inlen) {
2345 mainchan->u.v2.outbufsize =
2346 mainchan->u.v2.outbuflen + inlen + 1024;
2347 mainchan->u.v2.outbuffer = srealloc(mainchan->u.v2.outbuffer,
2348 mainchan->u.v2.outbufsize);
2350 memcpy(mainchan->u.v2.outbuffer + mainchan->u.v2.outbuflen,
2352 mainchan->u.v2.outbuflen += inlen;
2357 * Try to send data on the channel if we can. (FIXME:
2358 * on _all_ channels.)
2360 while (mainchan->u.v2.remwindow > 0 &&
2361 mainchan->u.v2.outbuflen > 0) {
2362 unsigned len = mainchan->u.v2.remwindow;
2363 if (len > mainchan->u.v2.outbuflen)
2364 len = mainchan->u.v2.outbuflen;
2365 if (len > mainchan->u.v2.remmaxpkt)
2366 len = mainchan->u.v2.remmaxpkt;
2367 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2368 ssh2_pkt_adduint32(mainchan->remoteid);
2369 ssh2_pkt_addstring_start();
2370 ssh2_pkt_addstring_data(mainchan->u.v2.outbuffer, len);
2372 mainchan->u.v2.outbuflen -= len;
2373 memmove(mainchan->u.v2.outbuffer, mainchan->u.v2.outbuffer+len,
2374 mainchan->u.v2.outbuflen);
2375 mainchan->u.v2.remwindow -= len;
2384 * Handle the top-level SSH2 protocol.
2386 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
2388 if (do_ssh2_transport(in, inlen, ispkt) == 0)
2390 do_ssh2_authconn(in, inlen, ispkt);
2394 * Called to set up the connection. Will arrange for WM_NETEVENT
2395 * messages to be passed to the specified window, whose window
2396 * procedure should then call telnet_msg().
2398 * Returns an error message, or NULL on success.
2400 static char *ssh_init (HWND hwnd, char *host, int port, char **realhost) {
2404 if(crypto_startup() == 0)
2405 return "Microsoft high encryption pack not installed!";
2408 p = connect_to_host(host, port, realhost);
2413 return "Protocol initialisation error";
2415 if (hwnd && WSAAsyncSelect (s, hwnd, WM_NETEVENT, FD_READ | FD_CLOSE) == SOCKET_ERROR)
2416 switch (WSAGetLastError()) {
2417 case WSAENETDOWN: return "Network is down";
2418 default: return "WSAAsyncSelect(): unknown error";
2425 * Process a WM_NETEVENT message. Will return 0 if the connection
2426 * has closed, or <0 for a socket error.
2428 static int ssh_msg (WPARAM wParam, LPARAM lParam) {
2433 * Because reading less than the whole of the available pending
2434 * data can generate an FD_READ event, we need to allow for the
2435 * possibility that FD_READ may arrive with FD_CLOSE already in
2436 * the queue; so it's possible that we can get here even with s
2437 * invalid. If so, we return 1 and don't worry about it.
2439 if (s == INVALID_SOCKET)
2442 if (WSAGETSELECTERROR(lParam) != 0)
2443 return -WSAGETSELECTERROR(lParam);
2445 switch (WSAGETSELECTEVENT(lParam)) {
2448 ret = recv(s, buf, sizeof(buf), 0);
2449 if (ret < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
2451 if (ret < 0) /* any _other_ error */
2452 return -10000-WSAGetLastError();
2457 ssh_gotdata (buf, ret);
2458 if (ssh_state == SSH_STATE_CLOSED) {
2465 return 1; /* shouldn't happen, but WTF */
2469 * Called to send data down the Telnet connection.
2471 static void ssh_send (char *buf, int len) {
2472 if (s == INVALID_SOCKET)
2475 ssh_protocol(buf, len, 0);
2479 * Called to set the size of the window from Telnet's POV.
2481 static void ssh_size(void) {
2482 switch (ssh_state) {
2483 case SSH_STATE_BEFORE_SIZE:
2484 case SSH_STATE_CLOSED:
2485 break; /* do nothing */
2486 case SSH_STATE_INTERMED:
2487 size_needed = TRUE; /* buffer for later */
2489 case SSH_STATE_SESSION:
2491 send_packet(SSH1_CMSG_WINDOW_SIZE,
2492 PKT_INT, rows, PKT_INT, cols,
2493 PKT_INT, 0, PKT_INT, 0, PKT_END);
2499 * Send Telnet special codes. TS_EOF is useful for `plink', so you
2500 * can send an EOF and collect resulting output (e.g. `plink
2503 static void ssh_special (Telnet_Special code) {
2504 if (code == TS_EOF) {
2505 if (ssh_version = 1) {
2506 send_packet(SSH1_CMSG_EOF, PKT_END);
2508 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
2509 ssh2_pkt_adduint32(mainchan->remoteid);
2519 * Read and decrypt one incoming SSH packet.
2520 * (only used by pSCP)
2522 static void get_packet(void)
2524 unsigned char buf[4096], *p;
2531 while ((to_read = s_rdpkt(&p, &len)) > 0) {
2532 if (to_read > sizeof(buf)) to_read = sizeof(buf);
2533 len = s_read(buf, to_read);
2534 if (len != to_read) {
2546 * Receive a block of data over the SSH link. Block until
2547 * all data is available. Return nr of bytes read (0 if lost connection).
2548 * (only used by pSCP)
2550 int ssh_scp_recv(unsigned char *buf, int len)
2552 static int pending_input_len = 0;
2553 static unsigned char *pending_input_ptr;
2556 if (pending_input_len >= to_read) {
2557 memcpy(buf, pending_input_ptr, to_read);
2558 pending_input_ptr += to_read;
2559 pending_input_len -= to_read;
2563 if (pending_input_len > 0) {
2564 memcpy(buf, pending_input_ptr, pending_input_len);
2565 buf += pending_input_len;
2566 to_read -= pending_input_len;
2567 pending_input_len = 0;
2570 if (s == INVALID_SOCKET)
2572 while (to_read > 0) {
2574 if (s == INVALID_SOCKET)
2576 if (pktin.type == SSH1_SMSG_STDOUT_DATA) {
2577 int plen = GET_32BIT(pktin.body);
2578 if (plen <= to_read) {
2579 memcpy(buf, pktin.body + 4, plen);
2583 memcpy(buf, pktin.body + 4, to_read);
2584 pending_input_len = plen - to_read;
2585 pending_input_ptr = pktin.body + 4 + to_read;
2588 } else if (pktin.type == SSH1_SMSG_STDERR_DATA) {
2589 int plen = GET_32BIT(pktin.body);
2590 fwrite(pktin.body + 4, plen, 1, stderr);
2591 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2592 logevent("Received disconnect request");
2593 } else if (pktin.type == SSH1_SMSG_SUCCESS ||
2594 pktin.type == SSH1_SMSG_FAILURE) {
2596 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2598 sprintf(logbuf, "Remote exit status: %d", GET_32BIT(pktin.body));
2600 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
2601 logevent("Closing connection");
2605 fatalbox("Strange packet received: type %d", pktin.type);
2613 * Send a block of data over the SSH link.
2614 * Block until all data is sent.
2615 * (only used by pSCP)
2617 void ssh_scp_send(unsigned char *buf, int len)
2619 if (s == INVALID_SOCKET)
2621 send_packet(SSH1_CMSG_STDIN_DATA,
2622 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2626 * Send an EOF notification to the server.
2627 * (only used by pSCP)
2629 void ssh_scp_send_eof(void)
2631 if (s == INVALID_SOCKET)
2633 send_packet(SSH1_CMSG_EOF, PKT_END);
2637 * Set up the connection, login on the remote host and
2638 * start execution of a command.
2639 * Returns an error message, or NULL on success.
2640 * (only used by pSCP)
2642 char *ssh_scp_init(char *host, int port, char *cmd, char **realhost)
2647 if (crypto_startup() == 0)
2648 return "Microsoft high encryption pack not installed!";
2651 p = connect_to_host(host, port, realhost);
2658 return "Protocol initialisation error";
2660 /* Exchange keys and login */
2663 if (s == INVALID_SOCKET)
2664 return "Connection closed by remote host";
2665 } while (!do_ssh1_login(NULL, 0, 1));
2667 if (ssh_state == SSH_STATE_CLOSED) {
2670 return "Session initialisation error";
2673 /* Execute command */
2674 sprintf(buf, "Sending command: %.100s", cmd);
2676 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
2681 static SOCKET ssh_socket(void) { return s; }
2683 static int ssh_sendok(void) { return ssh_send_ok; }
2685 Backend ssh_backend = {