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;
147 /* for ssh 2; we miss out single-DES because it isn't supported */
148 struct ssh_cipher *ciphers[] = { &ssh_3des_ssh2, &ssh_blowfish };
150 extern struct ssh_kex ssh_diffiehellman;
151 struct ssh_kex *kex_algs[] = { &ssh_diffiehellman };
153 extern struct ssh_hostkey ssh_dss;
154 struct ssh_hostkey *hostkey_algs[] = { &ssh_dss };
156 extern struct ssh_mac ssh_sha1;
158 static SHA_State exhash;
160 static void nullmac_key(unsigned char *key) { }
161 static void nullmac_generate(unsigned char *blk, int len, unsigned long seq) { }
162 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq) { return 1; }
163 struct ssh_mac ssh_mac_none = {
164 nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
166 struct ssh_mac *macs[] = { &ssh_sha1, &ssh_mac_none };
168 struct ssh_compress ssh_comp_none = {
171 struct ssh_compress *compressions[] = { &ssh_comp_none };
173 static SOCKET s = INVALID_SOCKET;
175 static unsigned char session_key[32];
176 static struct ssh_cipher *cipher = NULL;
177 static struct ssh_cipher *cscipher = NULL;
178 static struct ssh_cipher *sccipher = NULL;
179 static struct ssh_mac *csmac = NULL;
180 static struct ssh_mac *scmac = NULL;
181 static struct ssh_compress *cscomp = NULL;
182 static struct ssh_compress *sccomp = NULL;
183 static struct ssh_kex *kex = NULL;
184 static struct ssh_hostkey *hostkey = NULL;
185 int (*ssh_get_password)(const char *prompt, char *str, int maxlen) = NULL;
187 static char *savedhost;
188 static int ssh_send_ok;
191 * 2-3-4 tree storing channels.
194 unsigned remoteid, localid;
198 struct ssh_agent_channel {
199 unsigned char *message;
200 unsigned char msglen[4];
201 int lensofar, totallen;
203 struct ssh2_data_channel {
204 unsigned char *outbuffer;
205 unsigned outbuflen, outbufsize;
206 unsigned remwindow, remmaxpkt;
210 static tree234 *ssh_channels; /* indexed by local id */
211 static int ssh_channelcmp(void *av, void *bv) {
212 struct ssh_channel *a = (struct ssh_channel *)av;
213 struct ssh_channel *b = (struct ssh_channel *)bv;
214 if (a->localid < b->localid) return -1;
215 if (a->localid > b->localid) return +1;
218 static int ssh_channelfind(void *av, void *bv) {
219 unsigned *a = (unsigned *)av;
220 struct ssh_channel *b = (struct ssh_channel *)bv;
221 if (*a < b->localid) return -1;
222 if (*a > b->localid) return +1;
226 static struct ssh_channel *mainchan; /* primary session channel */
229 SSH_STATE_BEFORE_SIZE,
233 } ssh_state = SSH_STATE_BEFORE_SIZE;
235 static int size_needed = FALSE;
237 static void s_write (char *buf, int len) {
239 int i = send (s, buf, len, 0);
242 fatalbox("Lost connection while sending");
248 static int s_read (char *buf, int len) {
251 int i = recv (s, buf, len, 0);
254 len -= i, buf += i, ret += i;
261 static void c_write (char *buf, int len) {
262 if (!(flags & FLAG_CONNECTION)) {
264 for (i = 0; i < len; i++)
266 fputc(buf[i], stderr);
282 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
283 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
285 static int ssh_version;
286 static void (*ssh_protocol)(unsigned char *in, int inlen, int ispkt);
287 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
288 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
289 static void ssh_size(void);
291 static int (*s_rdpkt)(unsigned char **data, int *datalen);
294 * Collect incoming data in the incoming packet buffer.
295 * Decipher and verify the packet when it is completely read.
296 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
297 * Update the *data and *datalen variables.
298 * Return the additional nr of bytes needed, or 0 when
299 * a complete packet is available.
301 static int ssh1_rdpkt(unsigned char **data, int *datalen)
303 static long len, pad, biglen, to_read;
304 static unsigned long realcrc, gotcrc;
305 static unsigned char *p;
315 for (i = len = 0; i < 4; i++) {
316 while ((*datalen) == 0)
318 len = (len << 8) + **data;
319 (*data)++, (*datalen)--;
323 if (len == 0x52656d6f) { /* "Remo"te server has closed ... */
324 len = 0x300; /* big enough to carry to end */
330 pktin.length = len - 5;
332 if (pktin.maxlen < biglen) {
333 pktin.maxlen = biglen;
334 pktin.data = (pktin.data == NULL ? malloc(biglen+APIEXTRA) :
335 realloc(pktin.data, biglen+APIEXTRA));
337 fatalbox("Out of memory");
342 while (to_read > 0) {
345 while ((*datalen) == 0)
347 if (chunk > (*datalen))
349 memcpy(p, *data, chunk);
357 cipher->decrypt(pktin.data, biglen);
359 pktin.type = pktin.data[pad];
360 pktin.body = pktin.data + pad + 1;
362 realcrc = crc32(pktin.data, biglen-4);
363 gotcrc = GET_32BIT(pktin.data+biglen-4);
364 if (gotcrc != realcrc) {
365 fatalbox("Incorrect CRC received on packet");
368 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
369 pktin.type == SSH1_SMSG_STDERR_DATA ||
370 pktin.type == SSH1_MSG_DEBUG ||
371 pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
372 pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
373 long strlen = GET_32BIT(pktin.body);
374 if (strlen + 4 != pktin.length)
375 fatalbox("Received data packet with bogus string length");
378 if (pktin.type == SSH1_MSG_DEBUG) {
379 /* log debug message */
381 int strlen = GET_32BIT(pktin.body);
382 strcpy(buf, "Remote: ");
383 if (strlen > 70) strlen = 70;
384 memcpy(buf+8, pktin.body+4, strlen);
385 buf[8+strlen] = '\0';
388 } else if (pktin.type == SSH1_MSG_IGNORE) {
396 static int ssh2_rdpkt(unsigned char **data, int *datalen)
398 static long len, pad, payload, packetlen, maclen;
400 static int cipherblk;
401 static unsigned long incoming_sequence = 0;
411 cipherblk = cipher->blksize;
417 if (pktin.maxlen < cipherblk) {
418 pktin.maxlen = cipherblk;
419 pktin.data = (pktin.data == NULL ? malloc(cipherblk+APIEXTRA) :
420 realloc(pktin.data, cipherblk+APIEXTRA));
422 fatalbox("Out of memory");
426 * Acquire and decrypt the first block of the packet. This will
427 * contain the length and padding details.
429 for (i = len = 0; i < cipherblk; i++) {
430 while ((*datalen) == 0)
431 crReturn(cipherblk-i);
432 pktin.data[i] = *(*data)++;
436 if (!memcmp(pktin.data, "Remo", 4)) {/* "Remo"te server has closed ... */
441 sccipher->decrypt(pktin.data, cipherblk);
444 * Now get the length and padding figures.
446 len = GET_32BIT(pktin.data);
450 * This enables us to deduce the payload length.
452 payload = len - pad - 1;
454 pktin.length = payload + 5;
457 * So now we can work out the total packet length.
460 maclen = scmac ? scmac->len : 0;
463 * Adjust memory allocation if packet is too big.
465 if (pktin.maxlen < packetlen+maclen) {
466 pktin.maxlen = packetlen+maclen;
467 pktin.data = (pktin.data == NULL ? malloc(pktin.maxlen+APIEXTRA) :
468 realloc(pktin.data, pktin.maxlen+APIEXTRA));
470 fatalbox("Out of memory");
474 * Read and decrypt the remainder of the packet.
476 for (i = cipherblk; i < packetlen + maclen; i++) {
477 while ((*datalen) == 0)
478 crReturn(packetlen + maclen - i);
479 pktin.data[i] = *(*data)++;
482 /* Decrypt everything _except_ the MAC. */
484 sccipher->decrypt(pktin.data + cipherblk, packetlen - cipherblk);
487 debug(("Got packet len=%d pad=%d\r\n", len, pad));
488 for (i = 0; i < packetlen; i++)
489 debug((" %02x", (unsigned char)pktin.data[i]));
496 if (scmac && !scmac->verify(pktin.data, len+4, incoming_sequence))
497 fatalbox("Incorrect MAC received on packet");
498 incoming_sequence++; /* whether or not we MACed */
501 pktin.type = pktin.data[5];
503 if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
504 goto next_packet; /* FIXME: print DEBUG message */
509 static void ssh_gotdata(unsigned char *data, int datalen)
511 while (datalen > 0) {
512 if ( s_rdpkt(&data, &datalen) == 0 ) {
513 ssh_protocol(NULL, 0, 1);
514 if (ssh_state == SSH_STATE_CLOSED) {
522 static void s_wrpkt_start(int type, int len) {
525 len += 5; /* type and CRC */
529 pktout.length = len-5;
530 if (pktout.maxlen < biglen) {
531 pktout.maxlen = biglen;
533 /* Allocate enough buffer space for extra block
534 * for MS CryptEncrypt() */
535 pktout.data = (pktout.data == NULL ? malloc(biglen+12) :
536 realloc(pktout.data, biglen+12));
538 pktout.data = (pktout.data == NULL ? malloc(biglen+4) :
539 realloc(pktout.data, biglen+4));
542 fatalbox("Out of memory");
546 pktout.body = pktout.data+4+pad+1;
549 static void s_wrpkt(void) {
550 int pad, len, biglen, i;
553 len = pktout.length + 5; /* type and CRC */
557 pktout.body[-1] = pktout.type;
558 for (i=0; i<pad; i++)
559 pktout.data[i+4] = random_byte();
560 crc = crc32(pktout.data+4, biglen-4);
561 PUT_32BIT(pktout.data+biglen, crc);
562 PUT_32BIT(pktout.data, len);
565 cipher->encrypt(pktout.data+4, biglen);
567 s_write(pktout.data, biglen+4);
571 * Construct a packet with the specified contents and
572 * send it to the server.
574 static void send_packet(int pkttype, ...)
577 unsigned char *p, *argp, argchar;
578 unsigned long argint;
579 int pktlen, argtype, arglen;
583 va_start(args, pkttype);
584 while ((argtype = va_arg(args, int)) != PKT_END) {
587 (void) va_arg(args, int);
591 (void) va_arg(args, char);
595 (void) va_arg(args, unsigned char *);
596 arglen = va_arg(args, int);
600 argp = va_arg(args, unsigned char *);
601 arglen = strlen(argp);
602 pktlen += 4 + arglen;
605 bn = va_arg(args, Bignum);
606 pktlen += ssh1_bignum_length(bn);
614 s_wrpkt_start(pkttype, pktlen);
617 va_start(args, pkttype);
618 while ((argtype = va_arg(args, int)) != PKT_END) {
621 argint = va_arg(args, int);
622 PUT_32BIT(p, argint);
626 argchar = va_arg(args, unsigned char);
631 argp = va_arg(args, unsigned char *);
632 arglen = va_arg(args, int);
633 memcpy(p, argp, arglen);
637 argp = va_arg(args, unsigned char *);
638 arglen = strlen(argp);
639 PUT_32BIT(p, arglen);
640 memcpy(p + 4, argp, arglen);
644 bn = va_arg(args, Bignum);
645 p += ssh1_write_bignum(p, bn);
656 * Connect to specified host and port.
657 * Returns an error message, or NULL on success.
658 * Also places the canonical host name into `realhost'.
660 static char *connect_to_host(char *host, int port, char **realhost)
670 savedhost = malloc(1+strlen(host));
672 fatalbox("Out of memory");
673 strcpy(savedhost, host);
676 port = 22; /* default ssh port */
688 if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
689 if ( (h = gethostbyname(host)) == NULL)
690 switch (WSAGetLastError()) {
691 case WSAENETDOWN: return "Network is down";
692 case WSAHOST_NOT_FOUND: case WSANO_DATA:
693 return "Host does not exist";
694 case WSATRY_AGAIN: return "Host not found";
695 default: return "gethostbyname: unknown error";
697 memcpy (&a, h->h_addr, sizeof(a));
698 *realhost = h->h_name;
709 s = socket(AF_INET, SOCK_STREAM, 0);
710 if (s == INVALID_SOCKET)
711 switch (WSAGetLastError()) {
712 case WSAENETDOWN: return "Network is down";
713 case WSAEAFNOSUPPORT: return "TCP/IP support not present";
714 default: return "socket(): unknown error";
718 * Bind to local address.
720 addr.sin_family = AF_INET;
721 addr.sin_addr.s_addr = htonl(INADDR_ANY);
722 addr.sin_port = htons(0);
723 if (bind (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
724 switch (WSAGetLastError()) {
725 case WSAENETDOWN: return "Network is down";
726 default: return "bind(): unknown error";
730 * Connect to remote address.
732 addr.sin_addr.s_addr = htonl(a);
733 addr.sin_port = htons((short)port);
734 if (connect (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
735 switch (WSAGetLastError()) {
736 case WSAENETDOWN: return "Network is down";
737 case WSAECONNREFUSED: return "Connection refused";
738 case WSAENETUNREACH: return "Network is unreachable";
739 case WSAEHOSTUNREACH: return "No route to host";
740 default: return "connect(): unknown error";
744 send(s, "connect ", 8, 0);
745 send(s, FWhost, strlen(FWhost), 0);
748 sprintf(buf, " %d\n", FWport);
749 send (s, buf, strlen(buf), 0);
756 static int ssh_versioncmp(char *a, char *b) {
758 unsigned long av, bv;
760 av = strtoul(a, &ae, 10);
761 bv = strtoul(b, &be, 10);
762 if (av != bv) return (av < bv ? -1 : +1);
763 if (*ae == '.') ae++;
764 if (*be == '.') be++;
765 av = strtoul(ae, &ae, 10);
766 bv = strtoul(be, &be, 10);
767 if (av != bv) return (av < bv ? -1 : +1);
773 * Utility routine for putting an SSH-protocol `string' into a SHA
777 void sha_string(SHA_State *s, void *str, int len) {
778 unsigned char lenblk[4];
779 PUT_32BIT(lenblk, len);
780 SHA_Bytes(s, lenblk, 4);
781 SHA_Bytes(s, str, len);
785 * SSH2 packet construction functions.
787 void ssh2_pkt_adddata(void *data, int len) {
788 pktout.length += len;
789 if (pktout.maxlen < pktout.length) {
790 pktout.maxlen = pktout.length + 256;
791 pktout.data = (pktout.data == NULL ? malloc(pktout.maxlen+APIEXTRA) :
792 realloc(pktout.data, pktout.maxlen+APIEXTRA));
794 fatalbox("Out of memory");
796 memcpy(pktout.data+pktout.length-len, data, len);
798 void ssh2_pkt_addbyte(unsigned char byte) {
799 ssh2_pkt_adddata(&byte, 1);
801 void ssh2_pkt_init(int pkt_type) {
803 ssh2_pkt_addbyte((unsigned char)pkt_type);
805 void ssh2_pkt_addbool(unsigned char value) {
806 ssh2_pkt_adddata(&value, 1);
808 void ssh2_pkt_adduint32(unsigned long value) {
811 ssh2_pkt_adddata(x, 4);
813 void ssh2_pkt_addstring_start(void) {
814 ssh2_pkt_adduint32(0);
815 pktout.savedpos = pktout.length;
817 void ssh2_pkt_addstring_str(char *data) {
818 ssh2_pkt_adddata(data, strlen(data));
819 PUT_32BIT(pktout.data + pktout.savedpos - 4,
820 pktout.length - pktout.savedpos);
822 void ssh2_pkt_addstring_data(char *data, int len) {
823 ssh2_pkt_adddata(data, len);
824 PUT_32BIT(pktout.data + pktout.savedpos - 4,
825 pktout.length - pktout.savedpos);
827 void ssh2_pkt_addstring(char *data) {
828 ssh2_pkt_addstring_start();
829 ssh2_pkt_addstring_str(data);
831 char *ssh2_mpint_fmt(Bignum b, int *len) {
834 p = malloc(n * 2 + 1);
836 fatalbox("out of memory");
838 for (i = 0; i < n; i++) {
839 p[i*2+1] = (b[n-i] >> 8) & 0xFF;
840 p[i*2+2] = (b[n-i] ) & 0xFF;
843 while (p[i] == 0 && (p[i+1] & 0x80) == 0)
845 memmove(p, p+i, n*2+1-i);
849 void ssh2_pkt_addmp(Bignum b) {
852 p = ssh2_mpint_fmt(b, &len);
853 ssh2_pkt_addstring_start();
854 ssh2_pkt_addstring_data(p, len);
857 void ssh2_pkt_send(void) {
858 int cipherblk, maclen, padding, i;
859 static unsigned long outgoing_sequence = 0;
862 * Add padding. At least four bytes, and must also bring total
863 * length (minus MAC) up to a multiple of the block size.
865 cipherblk = cipher ? cipher->blksize : 8; /* block size */
866 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
868 padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
869 pktout.data[4] = padding;
870 for (i = 0; i < padding; i++)
871 pktout.data[pktout.length + i] = random_byte();
872 PUT_32BIT(pktout.data, pktout.length + padding - 4);
874 csmac->generate(pktout.data, pktout.length + padding,
876 outgoing_sequence++; /* whether or not we MACed */
879 debug(("Sending packet len=%d\r\n", pktout.length+padding));
880 for (i = 0; i < pktout.length+padding; i++)
881 debug((" %02x", (unsigned char)pktout.data[i]));
886 cscipher->encrypt(pktout.data, pktout.length + padding);
887 maclen = csmac ? csmac->len : 0;
889 s_write(pktout.data, pktout.length + padding + maclen);
893 void bndebug(char *string, Bignum b) {
896 p = ssh2_mpint_fmt(b, &len);
897 debug(("%s", string));
898 for (i = 0; i < len; i++)
899 debug((" %02x", p[i]));
905 void sha_mpint(SHA_State *s, Bignum b) {
908 p = ssh2_mpint_fmt(b, &len);
909 sha_string(s, p, len);
914 * SSH2 packet decode functions.
916 unsigned long ssh2_pkt_getuint32(void) {
918 if (pktin.length - pktin.savedpos < 4)
919 return 0; /* arrgh, no way to decline (FIXME?) */
920 value = GET_32BIT(pktin.data+pktin.savedpos);
924 void ssh2_pkt_getstring(char **p, int *length) {
926 if (pktin.length - pktin.savedpos < 4)
928 *length = GET_32BIT(pktin.data+pktin.savedpos);
930 if (pktin.length - pktin.savedpos < *length)
932 *p = pktin.data+pktin.savedpos;
933 pktin.savedpos += *length;
935 Bignum ssh2_pkt_getmp(void) {
940 ssh2_pkt_getstring(&p, &length);
944 fatalbox("internal error: Can't handle negative mpints");
945 b = newbn((length+1)/2);
946 for (i = 0; i < length; i++) {
949 b[j/2+1] |= ((unsigned char)p[i]) << 8;
951 b[j/2+1] |= ((unsigned char)p[i]);
956 static int do_ssh_init(void) {
960 char vlog[sizeof(vstring)+20];
965 while (s_read(&c, 1) == 1) {
966 if (c == 'S' && i < 2) i++;
967 else if (c == 'S' && i == 2) i = 2;
968 else if (c == 'H' && i == 2) break;
972 if (s_read(&c,1) != 1 || c != 'S') return 0;
973 if (s_read(&c,1) != 1 || c != 'S') return 0;
974 if (s_read(&c,1) != 1 || c != 'H') return 0;
976 strcpy(vstring, "SSH-");
978 if (s_read(&c,1) != 1 || c != '-') return 0;
981 if (s_read(&c,1) != 1)
983 if (vsp < vstring+sizeof(vstring)-1)
989 } else if (i < sizeof(version)-1)
997 sprintf(vlog, "Server version: %s", vstring);
998 vlog[strcspn(vlog, "\r\n")] = '\0';
1002 * Server version "1.99" means we can choose whether we use v1
1003 * or v2 protocol. Choice is based on cfg.sshprot.
1005 if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
1007 * This is a v2 server. Begin v2 protocol.
1009 char *verstring = "SSH-2.0-PuTTY";
1012 * Hash our version string and their version string.
1014 sha_string(&exhash, verstring, strlen(verstring));
1015 sha_string(&exhash, vstring, strcspn(vstring, "\r\n"));
1016 sprintf(vstring, "%s\n", verstring);
1017 sprintf(vlog, "We claim version: %s", verstring);
1019 logevent("Using SSH protocol version 2");
1020 s_write(vstring, strlen(vstring));
1021 ssh_protocol = ssh2_protocol;
1023 s_rdpkt = ssh2_rdpkt;
1026 * This is a v1 server. Begin v1 protocol.
1028 sprintf(vstring, "SSH-%s-PuTTY\n",
1029 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
1030 sprintf(vlog, "We claim version: %s", vstring);
1031 vlog[strcspn(vlog, "\r\n")] = '\0';
1033 logevent("Using SSH protocol version 1");
1034 s_write(vstring, strlen(vstring));
1035 ssh_protocol = ssh1_protocol;
1037 s_rdpkt = ssh1_rdpkt;
1044 * Handle the key exchange and user authentication phases.
1046 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1049 unsigned char *rsabuf, *keystr1, *keystr2;
1050 unsigned char cookie[8];
1051 struct RSAKey servkey, hostkey;
1052 struct MD5Context md5c;
1053 static unsigned long supported_ciphers_mask, supported_auths_mask;
1054 static int tried_publickey;
1055 static unsigned char session_id[16];
1060 if (!ispkt) crWaitUntil(ispkt);
1062 if (pktin.type != SSH1_SMSG_PUBLIC_KEY)
1063 fatalbox("Public key packet not received");
1065 logevent("Received public keys");
1067 memcpy(cookie, pktin.body, 8);
1069 i = makekey(pktin.body+8, &servkey, &keystr1, 0);
1070 j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
1073 * Hash the host key and print the hash in the log box. Just as
1074 * a last resort in case the registry's host key checking is
1075 * compromised, we'll allow the user some ability to verify
1079 MD5Update(&md5c, keystr2, hostkey.bytes);
1080 MD5Final(session_id, &md5c);
1084 logevent("Host key MD5 is:");
1085 strcpy(logmsg, " ");
1086 for (i = 0; i < 16; i++)
1087 sprintf(logmsg+strlen(logmsg), "%02x", session_id[i]);
1091 supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
1092 supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
1095 MD5Update(&md5c, keystr2, hostkey.bytes);
1096 MD5Update(&md5c, keystr1, servkey.bytes);
1097 MD5Update(&md5c, pktin.body, 8);
1098 MD5Final(session_id, &md5c);
1100 for (i=0; i<32; i++)
1101 session_key[i] = random_byte();
1103 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1105 rsabuf = malloc(len);
1107 fatalbox("Out of memory");
1110 * Verify the host key.
1114 * First format the key into a string.
1116 int len = rsastr_len(&hostkey);
1117 char *keystr = malloc(len);
1119 fatalbox("Out of memory");
1120 rsastr_fmt(keystr, &hostkey);
1121 verify_ssh_host_key(savedhost, keystr);
1125 for (i=0; i<32; i++) {
1126 rsabuf[i] = session_key[i];
1128 rsabuf[i] ^= session_id[i];
1131 if (hostkey.bytes > servkey.bytes) {
1132 rsaencrypt(rsabuf, 32, &servkey);
1133 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1135 rsaencrypt(rsabuf, 32, &hostkey);
1136 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1139 logevent("Encrypted session key");
1141 cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
1142 cfg.cipher == CIPHER_DES ? SSH_CIPHER_DES :
1144 if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1145 c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
1146 cipher_type = SSH_CIPHER_3DES;
1148 switch (cipher_type) {
1149 case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
1150 case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
1151 case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
1154 send_packet(SSH1_CMSG_SESSION_KEY,
1155 PKT_CHAR, cipher_type,
1156 PKT_DATA, cookie, 8,
1157 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
1158 PKT_DATA, rsabuf, len,
1162 logevent("Trying to enable encryption...");
1166 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish :
1167 cipher_type == SSH_CIPHER_DES ? &ssh_des :
1169 cipher->sesskey(session_key);
1173 if (pktin.type != SSH1_SMSG_SUCCESS)
1174 fatalbox("Encryption not successfully enabled");
1176 logevent("Successfully started encryption");
1180 static char username[100];
1183 if ((flags & FLAG_CONNECTION) && !*cfg.username) {
1184 c_write("login as: ", 10);
1186 crWaitUntil(!ispkt);
1187 while (inlen--) switch (c = *in++) {
1194 c_write("\b \b", 3);
1200 c_write("\b \b", 3);
1209 if (((c >= ' ' && c <= '~') ||
1210 ((unsigned char)c >= 160)) && pos < 40) {
1211 username[pos++] = c;
1218 username[strcspn(username, "\n\r")] = '\0';
1221 strncpy(username, cfg.username, 99);
1222 username[99] = '\0';
1223 if (flags & FLAG_VERBOSE) {
1224 sprintf(stuff, "Sent username \"%s\".\r\n", username);
1225 c_write(stuff, strlen(stuff));
1229 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
1231 char userlog[20+sizeof(username)];
1232 sprintf(userlog, "Sent username \"%s\"", username);
1239 tried_publickey = 0;
1241 while (pktin.type == SSH1_SMSG_FAILURE) {
1242 static char password[100];
1245 static int pwpkt_type;
1247 * Show password prompt, having first obtained it via a TIS
1248 * or CryptoCard exchange if we're doing TIS or CryptoCard
1251 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
1252 if (agent_exists()) {
1254 * Attempt RSA authentication using Pageant.
1256 static unsigned char request[5], *response, *p;
1257 static int responselen;
1258 static int i, nkeys;
1259 static int authed = FALSE;
1262 logevent("Pageant is running. Requesting keys.");
1264 /* Request the keys held by the agent. */
1265 PUT_32BIT(request, 1);
1266 request[4] = SSH_AGENTC_REQUEST_RSA_IDENTITIES;
1267 agent_query(request, 5, &r, &responselen);
1268 response = (unsigned char *)r;
1271 nkeys = GET_32BIT(p); p += 4;
1272 { char buf[64]; sprintf(buf, "Pageant has %d keys", nkeys);
1274 for (i = 0; i < nkeys; i++) {
1275 static struct RSAKey key;
1276 static Bignum challenge;
1277 static char *commentp;
1278 static int commentlen;
1280 { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
1283 p += ssh1_read_bignum(p, &key.exponent);
1284 p += ssh1_read_bignum(p, &key.modulus);
1285 commentlen = GET_32BIT(p); p += 4;
1286 commentp = p; p += commentlen;
1287 send_packet(SSH1_CMSG_AUTH_RSA,
1288 PKT_BIGNUM, key.modulus, PKT_END);
1290 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1291 logevent("Key refused");
1294 logevent("Received RSA challenge");
1295 ssh1_read_bignum(pktin.body, &challenge);
1297 char *agentreq, *q, *ret;
1299 len = 1 + 4; /* message type, bit count */
1300 len += ssh1_bignum_length(key.exponent);
1301 len += ssh1_bignum_length(key.modulus);
1302 len += ssh1_bignum_length(challenge);
1303 len += 16; /* session id */
1304 len += 4; /* response format */
1305 agentreq = malloc(4 + len);
1306 PUT_32BIT(agentreq, len);
1308 *q++ = SSH_AGENTC_RSA_CHALLENGE;
1309 PUT_32BIT(q, ssh1_bignum_bitcount(key.modulus));
1311 q += ssh1_write_bignum(q, key.exponent);
1312 q += ssh1_write_bignum(q, key.modulus);
1313 q += ssh1_write_bignum(q, challenge);
1314 memcpy(q, session_id, 16); q += 16;
1315 PUT_32BIT(q, 1); /* response format */
1316 agent_query(agentreq, len+4, &ret, &retlen);
1319 if (ret[4] == SSH_AGENT_RSA_RESPONSE) {
1320 logevent("Sending Pageant's response");
1321 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1322 PKT_DATA, ret+5, 16, PKT_END);
1325 if (pktin.type == SSH1_SMSG_SUCCESS) {
1326 logevent("Pageant's response accepted");
1327 c_write("Authenticated using RSA key \"",
1329 c_write(commentp, commentlen);
1330 c_write("\" from agent\r\n", 14);
1333 logevent("Pageant's response not accepted");
1335 logevent("Pageant failed to answer challenge");
1339 logevent("No reply received from Pageant");
1342 freebn(key.exponent);
1343 freebn(key.modulus);
1352 if (*cfg.keyfile && !tried_publickey)
1353 pwpkt_type = SSH1_CMSG_AUTH_RSA;
1355 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD && !FLAG_WINDOWED) {
1357 sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
1358 if (!ssh_get_password(prompt, password, sizeof(password))) {
1360 * get_password failed to get a password (for
1361 * example because one was supplied on the command
1362 * line which has already failed to work).
1365 logevent("No more passwords to try");
1366 ssh_state = SSH_STATE_CLOSED;
1371 if (pktin.type == SSH1_SMSG_FAILURE &&
1373 (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1374 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1375 logevent("Requested TIS authentication");
1376 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1378 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1379 logevent("TIS authentication declined");
1380 c_write("TIS authentication refused.\r\n", 29);
1382 int challengelen = ((pktin.body[0] << 24) |
1383 (pktin.body[1] << 16) |
1384 (pktin.body[2] << 8) |
1386 logevent("Received TIS challenge");
1387 c_write(pktin.body+4, challengelen);
1390 if (pktin.type == SSH1_SMSG_FAILURE &&
1392 (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
1393 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
1394 logevent("Requested CryptoCard authentication");
1395 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
1397 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
1398 logevent("CryptoCard authentication declined");
1399 c_write("CryptoCard authentication refused.\r\n", 29);
1401 int challengelen = ((pktin.body[0] << 24) |
1402 (pktin.body[1] << 16) |
1403 (pktin.body[2] << 8) |
1405 logevent("Received CryptoCard challenge");
1406 c_write(pktin.body+4, challengelen);
1407 c_write("\r\nResponse : ", 13);
1410 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD)
1411 c_write("password: ", 10);
1412 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1413 if (flags & FLAG_VERBOSE)
1414 c_write("Trying public key authentication.\r\n", 35);
1415 if (!rsakey_encrypted(cfg.keyfile)) {
1416 if (flags & FLAG_VERBOSE)
1417 c_write("No passphrase required.\r\n", 25);
1420 c_write("passphrase: ", 12);
1425 crWaitUntil(!ispkt);
1426 while (inlen--) switch (c = *in++) {
1443 if (((c >= ' ' && c <= '~') ||
1444 ((unsigned char)c >= 160)) && pos < sizeof(password))
1445 password[pos++] = c;
1454 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1456 * Try public key authentication with the specified
1459 static struct RSAKey pubkey;
1460 static Bignum challenge, response;
1462 static unsigned char buffer[32];
1464 tried_publickey = 1;
1465 i = loadrsakey(cfg.keyfile, &pubkey, password);
1467 c_write("Couldn't load public key from ", 30);
1468 c_write(cfg.keyfile, strlen(cfg.keyfile));
1469 c_write(".\r\n", 3);
1470 continue; /* go and try password */
1473 c_write("Wrong passphrase.\r\n", 19);
1474 tried_publickey = 0;
1475 continue; /* try again */
1479 * Send a public key attempt.
1481 send_packet(SSH1_CMSG_AUTH_RSA,
1482 PKT_BIGNUM, pubkey.modulus, PKT_END);
1485 if (pktin.type == SSH1_SMSG_FAILURE) {
1486 if (flags & FLAG_VERBOSE)
1487 c_write("Server refused our public key.\r\n", 32);
1488 continue; /* go and try password */
1490 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE)
1491 fatalbox("Bizarre response to offer of public key");
1492 ssh1_read_bignum(pktin.body, &challenge);
1493 response = rsadecrypt(challenge, &pubkey);
1494 freebn(pubkey.private_exponent); /* burn the evidence */
1496 for (i = 0; i < 32; i += 2) {
1497 buffer[i] = response[16-i/2] >> 8;
1498 buffer[i+1] = response[16-i/2] & 0xFF;
1502 MD5Update(&md5c, buffer, 32);
1503 MD5Update(&md5c, session_id, 16);
1504 MD5Final(buffer, &md5c);
1506 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1507 PKT_DATA, buffer, 16, PKT_END);
1510 if (pktin.type == SSH1_SMSG_FAILURE) {
1511 if (flags & FLAG_VERBOSE)
1512 c_write("Failed to authenticate with our public key.\r\n",
1514 continue; /* go and try password */
1515 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1516 fatalbox("Bizarre response to RSA authentication response");
1519 break; /* we're through! */
1521 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1523 logevent("Sent password");
1524 memset(password, 0, strlen(password));
1526 if (pktin.type == SSH1_SMSG_FAILURE) {
1527 if (flags & FLAG_VERBOSE)
1528 c_write("Access denied\r\n", 15);
1529 logevent("Authentication refused");
1530 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1531 logevent("Received disconnect request");
1532 ssh_state = SSH_STATE_CLOSED;
1534 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1535 fatalbox("Strange packet received, type %d", pktin.type);
1539 logevent("Authentication successful");
1544 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
1549 while (!do_ssh1_login(in, inlen, ispkt)) {
1552 if (ssh_state == SSH_STATE_CLOSED)
1555 if (cfg.agentfwd && agent_exists()) {
1556 logevent("Requesting agent forwarding");
1557 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
1558 do { crReturnV; } while (!ispkt);
1559 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1560 fatalbox("Protocol confusion");
1561 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1562 logevent("Agent forwarding refused");
1564 logevent("Agent forwarding enabled");
1568 send_packet(SSH1_CMSG_REQUEST_PTY,
1569 PKT_STR, cfg.termtype,
1570 PKT_INT, rows, PKT_INT, cols,
1571 PKT_INT, 0, PKT_INT, 0,
1574 ssh_state = SSH_STATE_INTERMED;
1575 do { crReturnV; } while (!ispkt);
1576 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1577 fatalbox("Protocol confusion");
1578 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1579 c_write("Server refused to allocate pty\r\n", 32);
1581 logevent("Allocated pty");
1584 if (*cfg.remote_cmd)
1585 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
1587 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
1588 logevent("Started session");
1590 ssh_state = SSH_STATE_SESSION;
1595 ssh_channels = newtree234(ssh_channelcmp);
1599 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
1600 pktin.type == SSH1_SMSG_STDERR_DATA) {
1601 long len = GET_32BIT(pktin.body);
1602 c_write(pktin.body+4, len);
1603 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1604 ssh_state = SSH_STATE_CLOSED;
1605 logevent("Received disconnect request");
1606 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
1607 /* Remote side is trying to open a channel to talk to our
1608 * agent. Give them back a local channel number. */
1610 struct ssh_channel *c;
1612 for (c = first234(ssh_channels, &e); c; c = next234(&e)) {
1614 break; /* found a free number */
1617 c = malloc(sizeof(struct ssh_channel));
1618 c->remoteid = GET_32BIT(pktin.body);
1621 c->type = SSH1_SMSG_AGENT_OPEN; /* identify channel type */
1622 add234(ssh_channels, c);
1623 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
1624 PKT_INT, c->remoteid, PKT_INT, c->localid,
1626 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
1627 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
1628 /* Remote side closes a channel. */
1629 unsigned i = GET_32BIT(pktin.body);
1630 struct ssh_channel *c;
1631 c = find234(ssh_channels, &i, ssh_channelfind);
1634 closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
1635 send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
1636 c->closes |= closetype;
1637 if (c->closes == 3) {
1638 del234(ssh_channels, c);
1642 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
1643 /* Data sent down one of our channels. */
1644 int i = GET_32BIT(pktin.body);
1645 int len = GET_32BIT(pktin.body+4);
1646 unsigned char *p = pktin.body+8;
1647 struct ssh_channel *c;
1648 c = find234(ssh_channels, &i, ssh_channelfind);
1651 case SSH1_SMSG_AGENT_OPEN:
1652 /* Data for an agent message. Buffer it. */
1654 if (c->u.a.lensofar < 4) {
1655 int l = min(4 - c->u.a.lensofar, len);
1656 memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
1657 p += l; len -= l; c->u.a.lensofar += l;
1659 if (c->u.a.lensofar == 4) {
1660 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
1661 c->u.a.message = malloc(c->u.a.totallen);
1662 memcpy(c->u.a.message, c->u.a.msglen, 4);
1664 if (c->u.a.lensofar >= 4 && len > 0) {
1665 int l = min(c->u.a.totallen - c->u.a.lensofar, len);
1666 memcpy(c->u.a.message + c->u.a.lensofar, p, l);
1667 p += l; len -= l; c->u.a.lensofar += l;
1669 if (c->u.a.lensofar == c->u.a.totallen) {
1670 void *reply, *sentreply;
1672 agent_query(c->u.a.message, c->u.a.totallen,
1677 /* Fake SSH_AGENT_FAILURE. */
1678 sentreply = "\0\0\0\1\5";
1681 send_packet(SSH1_MSG_CHANNEL_DATA,
1682 PKT_INT, c->remoteid,
1684 PKT_DATA, sentreply, replylen,
1688 free(c->u.a.message);
1689 c->u.a.lensofar = 0;
1695 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
1696 /* may be from EXEC_SHELL on some servers */
1697 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1698 /* may be from EXEC_SHELL on some servers
1699 * if no pty is available or in other odd cases. Ignore */
1700 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
1701 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
1703 fatalbox("Strange packet received: type %d", pktin.type);
1706 send_packet(SSH1_CMSG_STDIN_DATA,
1707 PKT_INT, inlen, PKT_DATA, in, inlen, PKT_END);
1715 * Utility routine for decoding comma-separated strings in KEXINIT.
1717 int in_commasep_string(char *needle, char *haystack, int haylen) {
1718 int needlen = strlen(needle);
1721 * Is it at the start of the string?
1723 if (haylen >= needlen && /* haystack is long enough */
1724 !memcmp(needle, haystack, needlen) && /* initial match */
1725 (haylen == needlen || haystack[needlen] == ',')
1726 /* either , or EOS follows */
1730 * If not, search for the next comma and resume after that.
1731 * If no comma found, terminate.
1733 while (haylen > 0 && *haystack != ',')
1734 haylen--, haystack++;
1737 haylen--, haystack++; /* skip over comma itself */
1742 * SSH2 key creation method.
1744 void ssh2_mkkey(Bignum K, char *H, char chr, char *keyspace) {
1746 /* First 20 bytes. */
1749 SHA_Bytes(&s, H, 20);
1750 SHA_Bytes(&s, &chr, 1);
1751 SHA_Bytes(&s, H, 20);
1752 SHA_Final(&s, keyspace);
1753 /* Next 20 bytes. */
1756 SHA_Bytes(&s, H, 20);
1757 SHA_Bytes(&s, keyspace, 20);
1758 SHA_Final(&s, keyspace+20);
1762 * Handle the SSH2 transport layer.
1764 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
1768 static Bignum e, f, K;
1769 static struct ssh_cipher *cscipher_tobe = NULL;
1770 static struct ssh_cipher *sccipher_tobe = NULL;
1771 static struct ssh_mac *csmac_tobe = NULL;
1772 static struct ssh_mac *scmac_tobe = NULL;
1773 static struct ssh_compress *cscomp_tobe = NULL;
1774 static struct ssh_compress *sccomp_tobe = NULL;
1775 static char *hostkeydata, *sigdata, *keystr;
1776 static int hostkeylen, siglen;
1777 static unsigned char exchange_hash[20];
1778 static unsigned char keyspace[40];
1785 * Construct and send our key exchange packet.
1787 ssh2_pkt_init(SSH2_MSG_KEXINIT);
1788 for (i = 0; i < 16; i++)
1789 ssh2_pkt_addbyte((unsigned char)random_byte());
1790 /* List key exchange algorithms. */
1791 ssh2_pkt_addstring_start();
1792 for (i = 0; i < lenof(kex_algs); i++) {
1793 ssh2_pkt_addstring_str(kex_algs[i]->name);
1794 if (i < lenof(kex_algs)-1)
1795 ssh2_pkt_addstring_str(",");
1797 /* List server host key algorithms. */
1798 ssh2_pkt_addstring_start();
1799 for (i = 0; i < lenof(hostkey_algs); i++) {
1800 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
1801 if (i < lenof(hostkey_algs)-1)
1802 ssh2_pkt_addstring_str(",");
1804 /* List client->server encryption algorithms. */
1805 ssh2_pkt_addstring_start();
1806 for (i = 0; i < lenof(ciphers); i++) {
1807 ssh2_pkt_addstring_str(ciphers[i]->name);
1808 if (i < lenof(ciphers)-1)
1809 ssh2_pkt_addstring_str(",");
1811 /* List server->client encryption algorithms. */
1812 ssh2_pkt_addstring_start();
1813 for (i = 0; i < lenof(ciphers); i++) {
1814 ssh2_pkt_addstring_str(ciphers[i]->name);
1815 if (i < lenof(ciphers)-1)
1816 ssh2_pkt_addstring_str(",");
1818 /* List client->server MAC algorithms. */
1819 ssh2_pkt_addstring_start();
1820 for (i = 0; i < lenof(macs); i++) {
1821 ssh2_pkt_addstring_str(macs[i]->name);
1822 if (i < lenof(macs)-1)
1823 ssh2_pkt_addstring_str(",");
1825 /* List server->client MAC algorithms. */
1826 ssh2_pkt_addstring_start();
1827 for (i = 0; i < lenof(macs); i++) {
1828 ssh2_pkt_addstring_str(macs[i]->name);
1829 if (i < lenof(macs)-1)
1830 ssh2_pkt_addstring_str(",");
1832 /* List client->server compression algorithms. */
1833 ssh2_pkt_addstring_start();
1834 for (i = 0; i < lenof(compressions); i++) {
1835 ssh2_pkt_addstring_str(compressions[i]->name);
1836 if (i < lenof(compressions)-1)
1837 ssh2_pkt_addstring_str(",");
1839 /* List server->client compression algorithms. */
1840 ssh2_pkt_addstring_start();
1841 for (i = 0; i < lenof(compressions); i++) {
1842 ssh2_pkt_addstring_str(compressions[i]->name);
1843 if (i < lenof(compressions)-1)
1844 ssh2_pkt_addstring_str(",");
1846 /* List client->server languages. Empty list. */
1847 ssh2_pkt_addstring_start();
1848 /* List server->client languages. Empty list. */
1849 ssh2_pkt_addstring_start();
1850 /* First KEX packet does _not_ follow, because we're not that brave. */
1851 ssh2_pkt_addbool(FALSE);
1853 ssh2_pkt_adduint32(0);
1854 sha_string(&exhash, pktout.data+5, pktout.length-5);
1857 if (!ispkt) crWaitUntil(ispkt);
1858 sha_string(&exhash, pktin.data+5, pktin.length-5);
1861 * Now examine the other side's KEXINIT to see what we're up
1864 if (pktin.type != SSH2_MSG_KEXINIT) {
1865 fatalbox("expected key exchange packet from server");
1867 kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
1868 csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
1869 pktin.savedpos += 16; /* skip garbage cookie */
1870 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
1871 for (i = 0; i < lenof(kex_algs); i++) {
1872 if (in_commasep_string(kex_algs[i]->name, str, len)) {
1877 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
1878 for (i = 0; i < lenof(hostkey_algs); i++) {
1879 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
1880 hostkey = hostkey_algs[i];
1884 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
1885 for (i = 0; i < lenof(ciphers); i++) {
1886 if (in_commasep_string(ciphers[i]->name, str, len)) {
1887 cscipher_tobe = ciphers[i];
1891 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
1892 for (i = 0; i < lenof(ciphers); i++) {
1893 if (in_commasep_string(ciphers[i]->name, str, len)) {
1894 sccipher_tobe = ciphers[i];
1898 ssh2_pkt_getstring(&str, &len); /* client->server mac */
1899 for (i = 0; i < lenof(macs); i++) {
1900 if (in_commasep_string(macs[i]->name, str, len)) {
1901 csmac_tobe = macs[i];
1905 ssh2_pkt_getstring(&str, &len); /* server->client mac */
1906 for (i = 0; i < lenof(macs); i++) {
1907 if (in_commasep_string(macs[i]->name, str, len)) {
1908 scmac_tobe = macs[i];
1912 ssh2_pkt_getstring(&str, &len); /* client->server compression */
1913 for (i = 0; i < lenof(compressions); i++) {
1914 if (in_commasep_string(compressions[i]->name, str, len)) {
1915 cscomp_tobe = compressions[i];
1919 ssh2_pkt_getstring(&str, &len); /* server->client compression */
1920 for (i = 0; i < lenof(compressions); i++) {
1921 if (in_commasep_string(compressions[i]->name, str, len)) {
1922 sccomp_tobe = compressions[i];
1928 * Currently we only support Diffie-Hellman and DSS, so let's
1929 * bomb out if those aren't selected.
1931 if (kex != &ssh_diffiehellman || hostkey != &ssh_dss)
1932 fatalbox("internal fault: chaos in SSH 2 transport layer");
1935 * Now we begin the fun. Generate and send e for Diffie-Hellman.
1938 ssh2_pkt_init(SSH2_MSG_KEXDH_INIT);
1943 if (pktin.type != SSH2_MSG_KEXDH_REPLY) {
1944 fatalbox("expected key exchange packet from server");
1946 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
1947 f = ssh2_pkt_getmp();
1948 ssh2_pkt_getstring(&sigdata, &siglen);
1952 sha_string(&exhash, hostkeydata, hostkeylen);
1953 sha_mpint(&exhash, e);
1954 sha_mpint(&exhash, f);
1955 sha_mpint(&exhash, K);
1956 SHA_Final(&exhash, exchange_hash);
1959 debug(("Exchange hash is:\r\n"));
1960 for (i = 0; i < 20; i++)
1961 debug((" %02x", exchange_hash[i]));
1965 hostkey->setkey(hostkeydata, hostkeylen);
1966 if (!hostkey->verifysig(sigdata, siglen, exchange_hash, 20))
1967 fatalbox("Server failed host key check");
1970 * Expect SSH2_MSG_NEWKEYS from server.
1973 if (pktin.type != SSH2_MSG_NEWKEYS)
1974 fatalbox("expected new-keys packet from server");
1977 * Authenticate remote host: verify host key. (We've already
1978 * checked the signature of the exchange hash.)
1980 keystr = hostkey->fmtkey();
1981 verify_ssh_host_key(savedhost, keystr);
1985 * Send SSH2_MSG_NEWKEYS.
1987 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
1991 * Create and initialise session keys.
1993 cscipher = cscipher_tobe;
1994 sccipher = sccipher_tobe;
1997 cscomp = cscomp_tobe;
1998 sccomp = sccomp_tobe;
2000 * Set IVs after keys.
2002 ssh2_mkkey(K, exchange_hash, 'C', keyspace); cscipher->setcskey(keyspace);
2003 ssh2_mkkey(K, exchange_hash, 'D', keyspace); cscipher->setsckey(keyspace);
2004 ssh2_mkkey(K, exchange_hash, 'A', keyspace); cscipher->setcsiv(keyspace);
2005 ssh2_mkkey(K, exchange_hash, 'B', keyspace); sccipher->setsciv(keyspace);
2006 ssh2_mkkey(K, exchange_hash, 'E', keyspace); csmac->setcskey(keyspace);
2007 ssh2_mkkey(K, exchange_hash, 'F', keyspace); scmac->setsckey(keyspace);
2010 * Now we're encrypting. Begin returning 1 to the protocol main
2011 * function so that other things can run on top of the
2012 * transport. If we ever see a KEXINIT, we must go back to the
2017 } while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT));
2018 goto begin_key_exchange;
2024 * Handle the SSH2 userauth and connection layers.
2026 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
2028 static unsigned long remote_winsize;
2029 static unsigned long remote_maxpkt;
2034 * Request userauth protocol, and await a response to it.
2036 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
2037 ssh2_pkt_addstring("ssh-userauth");
2039 crWaitUntilV(ispkt);
2040 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT)
2041 fatalbox("Server refused user authentication protocol");
2044 * FIXME: currently we support only password authentication.
2045 * (This places us technically in violation of the SSH2 spec.
2046 * We must fix this.)
2050 * Get a username and a password.
2052 static char username[100];
2053 static char password[100];
2057 if ((flags & FLAG_CONNECTION) && !*cfg.username) {
2058 c_write("login as: ", 10);
2060 crWaitUntilV(!ispkt);
2061 while (inlen--) switch (c = *in++) {
2068 c_write("\b \b", 3);
2074 c_write("\b \b", 3);
2083 if (((c >= ' ' && c <= '~') ||
2084 ((unsigned char)c >= 160)) && pos < 40) {
2085 username[pos++] = c;
2092 username[strcspn(username, "\n\r")] = '\0';
2095 strncpy(username, cfg.username, 99);
2096 username[99] = '\0';
2097 if (flags & FLAG_VERBOSE) {
2098 sprintf(stuff, "Using username \"%s\".\r\n", username);
2099 c_write(stuff, strlen(stuff));
2103 if (!(flags & FLAG_WINDOWED)) {
2105 sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
2106 if (!ssh_get_password(prompt, password, sizeof(password))) {
2108 * get_password failed to get a password (for
2109 * example because one was supplied on the command
2110 * line which has already failed to work).
2113 logevent("No more passwords to try");
2114 ssh_state = SSH_STATE_CLOSED;
2118 c_write("password: ", 10);
2122 crWaitUntilV(!ispkt);
2123 while (inlen--) switch (c = *in++) {
2140 if (((c >= ' ' && c <= '~') ||
2141 ((unsigned char)c >= 160)) && pos < 40)
2142 password[pos++] = c;
2149 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2150 ssh2_pkt_addstring(username);
2151 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2152 ssh2_pkt_addstring("password");
2153 ssh2_pkt_addbool(FALSE);
2154 ssh2_pkt_addstring(password);
2157 crWaitUntilV(ispkt);
2158 if (pktin.type != SSH2_MSG_USERAUTH_SUCCESS) {
2159 c_write("Access denied\r\n", 15);
2160 logevent("Authentication refused");
2166 * Now we're authenticated for the connection protocol. The
2167 * connection protocol will automatically have started at this
2168 * point; there's no need to send SERVICE_REQUEST.
2172 * So now create a channel with a session in it.
2174 mainchan = malloc(sizeof(struct ssh_channel));
2175 mainchan->localid = 100; /* as good as any */
2176 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
2177 ssh2_pkt_addstring("session");
2178 ssh2_pkt_adduint32(mainchan->localid);
2179 ssh2_pkt_adduint32(0x7FFFFFFFUL); /* our window size */
2180 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
2182 crWaitUntilV(ispkt);
2183 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
2184 fatalbox("Server refused to open a session");
2185 /* FIXME: error data comes back in FAILURE packet */
2187 if (ssh2_pkt_getuint32() != mainchan->localid) {
2188 fatalbox("Server's channel confirmation cited wrong channel");
2190 mainchan->remoteid = ssh2_pkt_getuint32();
2191 mainchan->u.v2.remwindow = ssh2_pkt_getuint32();
2192 mainchan->u.v2.remmaxpkt = ssh2_pkt_getuint32();
2193 mainchan->u.v2.outbuffer = NULL;
2194 mainchan->u.v2.outbuflen = mainchan->u.v2.outbufsize = 0;
2195 logevent("Opened channel for session");
2198 * Now allocate a pty for the session.
2200 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2201 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
2202 ssh2_pkt_addstring("pty-req");
2203 ssh2_pkt_addbool(1); /* want reply */
2204 ssh2_pkt_addstring(cfg.termtype);
2205 ssh2_pkt_adduint32(cols);
2206 ssh2_pkt_adduint32(rows);
2207 ssh2_pkt_adduint32(0); /* pixel width */
2208 ssh2_pkt_adduint32(0); /* pixel height */
2209 ssh2_pkt_addstring_start();
2210 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
2213 do { /* FIXME: pay attention to these */
2214 crWaitUntilV(ispkt);
2215 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2217 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2218 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2219 fatalbox("Server got confused by pty request");
2221 c_write("Server refused to allocate pty\r\n", 32);
2223 logevent("Allocated pty");
2229 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2230 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
2231 ssh2_pkt_addstring("shell");
2232 ssh2_pkt_addbool(1); /* want reply */
2235 crWaitUntilV(ispkt);
2236 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2237 /* FIXME: be able to handle other channels here */
2238 if (ssh2_pkt_getuint32() != mainchan->localid)
2239 continue; /* wrong channel */
2240 mainchan->u.v2.remwindow += ssh2_pkt_getuint32();
2242 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2243 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2244 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2245 fatalbox("Server got confused by shell request");
2247 fatalbox("Server refused to start a shell");
2249 logevent("Started a shell");
2257 static int try_send;
2261 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
2262 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
2265 /* FIXME: be able to handle other channels here */
2266 if (ssh2_pkt_getuint32() != mainchan->localid)
2267 continue; /* wrong channel */
2268 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
2269 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
2270 continue; /* extended but not stderr */
2271 ssh2_pkt_getstring(&data, &length);
2273 c_write(data, length);
2275 * Enlarge the window again at the remote side,
2276 * just in case it ever runs down and they fail
2277 * to send us any more data.
2279 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2280 ssh2_pkt_adduint32(mainchan->remoteid);
2281 ssh2_pkt_adduint32(length);
2284 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
2285 ssh_state = SSH_STATE_CLOSED;
2286 logevent("Received disconnect message");
2287 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
2288 continue; /* exit status et al; ignore (FIXME?) */
2289 } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
2290 continue; /* remote sends EOF; ignore */
2291 } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
2292 /* FIXME: be able to handle other channels here */
2293 if (ssh2_pkt_getuint32() != mainchan->localid)
2294 continue; /* wrong channel */
2295 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2296 ssh2_pkt_adduint32(mainchan->remoteid);
2298 /* FIXME: mark the channel as closed */
2299 if (1 /* FIXME: "all channels are closed" */) {
2300 logevent("All channels closed. Disconnecting");
2301 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
2304 continue; /* remote sends close; ignore (FIXME) */
2305 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2306 /* FIXME: be able to handle other channels here */
2307 if (ssh2_pkt_getuint32() != mainchan->localid)
2308 continue; /* wrong channel */
2309 mainchan->u.v2.remwindow += ssh2_pkt_getuint32();
2312 fatalbox("Strange packet received: type %d", pktin.type);
2316 * We have spare data. Add it to the channel buffer.
2318 if (mainchan->u.v2.outbufsize <
2319 mainchan->u.v2.outbuflen + inlen) {
2320 mainchan->u.v2.outbufsize =
2321 mainchan->u.v2.outbuflen + inlen + 1024;
2322 mainchan->u.v2.outbuffer = srealloc(mainchan->u.v2.outbuffer,
2323 mainchan->u.v2.outbufsize);
2325 memcpy(mainchan->u.v2.outbuffer + mainchan->u.v2.outbuflen,
2327 mainchan->u.v2.outbuflen += inlen;
2332 * Try to send data on the channel if we can. (FIXME:
2333 * on _all_ channels.)
2335 while (mainchan->u.v2.remwindow > 0 &&
2336 mainchan->u.v2.outbuflen > 0) {
2337 unsigned len = mainchan->u.v2.remwindow;
2338 if (len > mainchan->u.v2.outbuflen)
2339 len = mainchan->u.v2.outbuflen;
2340 if (len > mainchan->u.v2.remmaxpkt)
2341 len = mainchan->u.v2.remmaxpkt;
2342 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2343 ssh2_pkt_adduint32(mainchan->remoteid);
2344 ssh2_pkt_addstring_start();
2345 ssh2_pkt_addstring_data(mainchan->u.v2.outbuffer, len);
2347 mainchan->u.v2.outbuflen -= len;
2348 memmove(mainchan->u.v2.outbuffer, mainchan->u.v2.outbuffer+len,
2349 mainchan->u.v2.outbuflen);
2350 mainchan->u.v2.remwindow -= len;
2359 * Handle the top-level SSH2 protocol.
2361 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
2363 if (do_ssh2_transport(in, inlen, ispkt) == 0)
2365 do_ssh2_authconn(in, inlen, ispkt);
2369 * Called to set up the connection. Will arrange for WM_NETEVENT
2370 * messages to be passed to the specified window, whose window
2371 * procedure should then call telnet_msg().
2373 * Returns an error message, or NULL on success.
2375 static char *ssh_init (HWND hwnd, char *host, int port, char **realhost) {
2379 if(crypto_startup() == 0)
2380 return "Microsoft high encryption pack not installed!";
2383 p = connect_to_host(host, port, realhost);
2388 return "Protocol initialisation error";
2390 if (hwnd && WSAAsyncSelect (s, hwnd, WM_NETEVENT, FD_READ | FD_CLOSE) == SOCKET_ERROR)
2391 switch (WSAGetLastError()) {
2392 case WSAENETDOWN: return "Network is down";
2393 default: return "WSAAsyncSelect(): unknown error";
2400 * Process a WM_NETEVENT message. Will return 0 if the connection
2401 * has closed, or <0 for a socket error.
2403 static int ssh_msg (WPARAM wParam, LPARAM lParam) {
2408 * Because reading less than the whole of the available pending
2409 * data can generate an FD_READ event, we need to allow for the
2410 * possibility that FD_READ may arrive with FD_CLOSE already in
2411 * the queue; so it's possible that we can get here even with s
2412 * invalid. If so, we return 1 and don't worry about it.
2414 if (s == INVALID_SOCKET)
2417 if (WSAGETSELECTERROR(lParam) != 0)
2418 return -WSAGETSELECTERROR(lParam);
2420 switch (WSAGETSELECTEVENT(lParam)) {
2423 ret = recv(s, buf, sizeof(buf), 0);
2424 if (ret < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
2426 if (ret < 0) /* any _other_ error */
2427 return -10000-WSAGetLastError();
2432 ssh_gotdata (buf, ret);
2433 if (ssh_state == SSH_STATE_CLOSED) {
2440 return 1; /* shouldn't happen, but WTF */
2444 * Called to send data down the Telnet connection.
2446 static void ssh_send (char *buf, int len) {
2447 if (s == INVALID_SOCKET)
2450 ssh_protocol(buf, len, 0);
2454 * Called to set the size of the window from Telnet's POV.
2456 static void ssh_size(void) {
2457 switch (ssh_state) {
2458 case SSH_STATE_BEFORE_SIZE:
2459 case SSH_STATE_CLOSED:
2460 break; /* do nothing */
2461 case SSH_STATE_INTERMED:
2462 size_needed = TRUE; /* buffer for later */
2464 case SSH_STATE_SESSION:
2466 send_packet(SSH1_CMSG_WINDOW_SIZE,
2467 PKT_INT, rows, PKT_INT, cols,
2468 PKT_INT, 0, PKT_INT, 0, PKT_END);
2474 * Send Telnet special codes. TS_EOF is useful for `plink', so you
2475 * can send an EOF and collect resulting output (e.g. `plink
2478 static void ssh_special (Telnet_Special code) {
2479 if (code == TS_EOF) {
2480 if (ssh_version = 1) {
2481 send_packet(SSH1_CMSG_EOF, PKT_END);
2483 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
2484 ssh2_pkt_adduint32(mainchan->remoteid);
2494 * Read and decrypt one incoming SSH packet.
2495 * (only used by pSCP)
2497 static void get_packet(void)
2499 unsigned char buf[4096], *p;
2506 while ((to_read = s_rdpkt(&p, &len)) > 0) {
2507 if (to_read > sizeof(buf)) to_read = sizeof(buf);
2508 len = s_read(buf, to_read);
2509 if (len != to_read) {
2521 * Receive a block of data over the SSH link. Block until
2522 * all data is available. Return nr of bytes read (0 if lost connection).
2523 * (only used by pSCP)
2525 int ssh_scp_recv(unsigned char *buf, int len)
2527 static int pending_input_len = 0;
2528 static unsigned char *pending_input_ptr;
2531 if (pending_input_len >= to_read) {
2532 memcpy(buf, pending_input_ptr, to_read);
2533 pending_input_ptr += to_read;
2534 pending_input_len -= to_read;
2538 if (pending_input_len > 0) {
2539 memcpy(buf, pending_input_ptr, pending_input_len);
2540 buf += pending_input_len;
2541 to_read -= pending_input_len;
2542 pending_input_len = 0;
2545 if (s == INVALID_SOCKET)
2547 while (to_read > 0) {
2549 if (s == INVALID_SOCKET)
2551 if (pktin.type == SSH1_SMSG_STDOUT_DATA) {
2552 int plen = GET_32BIT(pktin.body);
2553 if (plen <= to_read) {
2554 memcpy(buf, pktin.body + 4, plen);
2558 memcpy(buf, pktin.body + 4, to_read);
2559 pending_input_len = plen - to_read;
2560 pending_input_ptr = pktin.body + 4 + to_read;
2563 } else if (pktin.type == SSH1_SMSG_STDERR_DATA) {
2564 int plen = GET_32BIT(pktin.body);
2565 fwrite(pktin.body + 4, plen, 1, stderr);
2566 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2567 logevent("Received disconnect request");
2568 } else if (pktin.type == SSH1_SMSG_SUCCESS ||
2569 pktin.type == SSH1_SMSG_FAILURE) {
2571 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2573 sprintf(logbuf, "Remote exit status: %d", GET_32BIT(pktin.body));
2575 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
2576 logevent("Closing connection");
2580 fatalbox("Strange packet received: type %d", pktin.type);
2588 * Send a block of data over the SSH link.
2589 * Block until all data is sent.
2590 * (only used by pSCP)
2592 void ssh_scp_send(unsigned char *buf, int len)
2594 if (s == INVALID_SOCKET)
2596 send_packet(SSH1_CMSG_STDIN_DATA,
2597 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2601 * Send an EOF notification to the server.
2602 * (only used by pSCP)
2604 void ssh_scp_send_eof(void)
2606 if (s == INVALID_SOCKET)
2608 send_packet(SSH1_CMSG_EOF, PKT_END);
2612 * Set up the connection, login on the remote host and
2613 * start execution of a command.
2614 * Returns an error message, or NULL on success.
2615 * (only used by pSCP)
2617 char *ssh_scp_init(char *host, int port, char *cmd, char **realhost)
2622 if (crypto_startup() == 0)
2623 return "Microsoft high encryption pack not installed!";
2626 p = connect_to_host(host, port, realhost);
2633 return "Protocol initialisation error";
2635 /* Exchange keys and login */
2638 if (s == INVALID_SOCKET)
2639 return "Connection closed by remote host";
2640 } while (!do_ssh1_login(NULL, 0, 1));
2642 if (ssh_state == SSH_STATE_CLOSED) {
2645 return "Session initialisation error";
2648 /* Execute command */
2649 sprintf(buf, "Sending command: %.100s", cmd);
2651 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
2656 static SOCKET ssh_socket(void) { return s; }
2658 static int ssh_sendok(void) { return ssh_send_ok; }
2660 Backend ssh_backend = {