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
24 #define SSH1_SMSG_PUBLIC_KEY 2
25 #define SSH1_CMSG_SESSION_KEY 3
26 #define SSH1_CMSG_USER 4
27 #define SSH1_CMSG_AUTH_RSA 6
28 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7
29 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8
30 #define SSH1_CMSG_AUTH_PASSWORD 9
31 #define SSH1_CMSG_REQUEST_PTY 10
32 #define SSH1_CMSG_WINDOW_SIZE 11
33 #define SSH1_CMSG_EXEC_SHELL 12
34 #define SSH1_CMSG_EXEC_CMD 13
35 #define SSH1_SMSG_SUCCESS 14
36 #define SSH1_SMSG_FAILURE 15
37 #define SSH1_CMSG_STDIN_DATA 16
38 #define SSH1_SMSG_STDOUT_DATA 17
39 #define SSH1_SMSG_STDERR_DATA 18
40 #define SSH1_CMSG_EOF 19
41 #define SSH1_SMSG_EXIT_STATUS 20
42 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21
43 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22
44 #define SSH1_MSG_CHANNEL_DATA 23
45 #define SSH1_MSG_CHANNEL_CLOSE 24
46 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25
47 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30
48 #define SSH1_SMSG_AGENT_OPEN 31
49 #define SSH1_CMSG_EXIT_CONFIRMATION 33
50 #define SSH1_MSG_IGNORE 32
51 #define SSH1_MSG_DEBUG 36
52 #define SSH1_CMSG_AUTH_TIS 39
53 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40
54 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41
55 #define SSH1_CMSG_AUTH_CCARD 70
56 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71
57 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72
59 #define SSH1_AUTH_TIS 5
60 #define SSH1_AUTH_CCARD 16
62 #define SSH_AGENTC_REQUEST_RSA_IDENTITIES 1
63 #define SSH_AGENT_RSA_IDENTITIES_ANSWER 2
64 #define SSH_AGENTC_RSA_CHALLENGE 3
65 #define SSH_AGENT_RSA_RESPONSE 4
66 #define SSH_AGENT_FAILURE 5
67 #define SSH_AGENT_SUCCESS 6
68 #define SSH_AGENTC_ADD_RSA_IDENTITY 7
69 #define SSH_AGENTC_REMOVE_RSA_IDENTITY 8
71 #define SSH2_MSG_DISCONNECT 1
72 #define SSH2_MSG_IGNORE 2
73 #define SSH2_MSG_UNIMPLEMENTED 3
74 #define SSH2_MSG_DEBUG 4
75 #define SSH2_MSG_SERVICE_REQUEST 5
76 #define SSH2_MSG_SERVICE_ACCEPT 6
77 #define SSH2_MSG_KEXINIT 20
78 #define SSH2_MSG_NEWKEYS 21
79 #define SSH2_MSG_KEXDH_INIT 30
80 #define SSH2_MSG_KEXDH_REPLY 31
81 #define SSH2_MSG_USERAUTH_REQUEST 50
82 #define SSH2_MSG_USERAUTH_FAILURE 51
83 #define SSH2_MSG_USERAUTH_SUCCESS 52
84 #define SSH2_MSG_USERAUTH_BANNER 53
85 #define SSH2_MSG_USERAUTH_PK_OK 60
86 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60
87 #define SSH2_MSG_GLOBAL_REQUEST 80
88 #define SSH2_MSG_REQUEST_SUCCESS 81
89 #define SSH2_MSG_REQUEST_FAILURE 82
90 #define SSH2_MSG_CHANNEL_OPEN 90
91 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91
92 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92
93 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93
94 #define SSH2_MSG_CHANNEL_DATA 94
95 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95
96 #define SSH2_MSG_CHANNEL_EOF 96
97 #define SSH2_MSG_CHANNEL_CLOSE 97
98 #define SSH2_MSG_CHANNEL_REQUEST 98
99 #define SSH2_MSG_CHANNEL_SUCCESS 99
100 #define SSH2_MSG_CHANNEL_FAILURE 100
102 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1
103 #define SSH2_OPEN_CONNECT_FAILED 2
104 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3
105 #define SSH2_OPEN_RESOURCE_SHORTAGE 4
106 #define SSH2_EXTENDED_DATA_STDERR 1
108 #define GET_32BIT(cp) \
109 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
110 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
111 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
112 ((unsigned long)(unsigned char)(cp)[3]))
114 #define PUT_32BIT(cp, value) { \
115 (cp)[0] = (unsigned char)((value) >> 24); \
116 (cp)[1] = (unsigned char)((value) >> 16); \
117 (cp)[2] = (unsigned char)((value) >> 8); \
118 (cp)[3] = (unsigned char)(value); }
120 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
122 /* Coroutine mechanics for the sillier bits of the code */
123 #define crBegin1 static int crLine = 0;
124 #define crBegin2 switch(crLine) { case 0:;
125 #define crBegin crBegin1; crBegin2;
126 #define crFinish(z) } crLine = 0; return (z)
127 #define crFinishV } crLine = 0; return
128 #define crReturn(z) \
130 crLine=__LINE__; return (z); case __LINE__:;\
134 crLine=__LINE__; return; case __LINE__:;\
136 #define crStop(z) do{ crLine = 0; return (z); }while(0)
137 #define crStopV do{ crLine = 0; return; }while(0)
138 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
139 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
141 extern struct ssh_cipher ssh_3des;
142 extern struct ssh_cipher ssh_3des_ssh2;
143 extern struct ssh_cipher ssh_des;
144 extern struct ssh_cipher ssh_blowfish;
146 /* for ssh 2; we miss out single-DES because it isn't supported */
147 struct ssh_cipher *ciphers[] = { &ssh_3des_ssh2, &ssh_blowfish };
149 extern struct ssh_kex ssh_diffiehellman;
150 struct ssh_kex *kex_algs[] = { &ssh_diffiehellman };
152 extern struct ssh_hostkey ssh_dss;
153 struct ssh_hostkey *hostkey_algs[] = { &ssh_dss };
155 extern struct ssh_mac ssh_sha1;
157 static SHA_State exhash;
159 static void nullmac_key(unsigned char *key) { }
160 static void nullmac_generate(unsigned char *blk, int len, unsigned long seq) { }
161 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq) { return 1; }
162 struct ssh_mac ssh_mac_none = {
163 nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
165 struct ssh_mac *macs[] = { &ssh_sha1, &ssh_mac_none };
167 struct ssh_compress ssh_comp_none = {
170 struct ssh_compress *compressions[] = { &ssh_comp_none };
172 static SOCKET s = INVALID_SOCKET;
174 static unsigned char session_key[32];
175 static struct ssh_cipher *cipher = NULL;
176 static struct ssh_cipher *cscipher = NULL;
177 static struct ssh_cipher *sccipher = NULL;
178 static struct ssh_mac *csmac = NULL;
179 static struct ssh_mac *scmac = NULL;
180 static struct ssh_compress *cscomp = NULL;
181 static struct ssh_compress *sccomp = NULL;
182 static struct ssh_kex *kex = NULL;
183 static struct ssh_hostkey *hostkey = NULL;
184 int (*ssh_get_password)(const char *prompt, char *str, int maxlen) = NULL;
186 static char *savedhost;
187 static int ssh_send_ok;
190 * 2-3-4 tree storing channels.
193 int remoteid, localid;
197 struct ssh_agent_channel {
198 unsigned char *message;
199 unsigned char msglen[4];
200 int lensofar, totallen;
204 static tree234 *ssh_channels; /* indexed by local id */
205 static int ssh_channelcmp(void *av, void *bv) {
206 struct ssh_channel *a = (struct ssh_channel *)av;
207 struct ssh_channel *b = (struct ssh_channel *)bv;
208 if (a->localid < b->localid) return -1;
209 if (a->localid > b->localid) return +1;
212 static int ssh_channelfind(void *av, void *bv) {
214 struct ssh_channel *b = (struct ssh_channel *)bv;
215 if (*a < b->localid) return -1;
216 if (*a > b->localid) return +1;
221 SSH_STATE_BEFORE_SIZE,
225 } ssh_state = SSH_STATE_BEFORE_SIZE;
227 static int size_needed = FALSE;
229 static void s_write (char *buf, int len) {
231 int i = send (s, buf, len, 0);
234 fatalbox("Lost connection while sending");
240 static int s_read (char *buf, int len) {
243 int i = recv (s, buf, len, 0);
246 len -= i, buf += i, ret += i;
253 static void c_write (char *buf, int len) {
254 if (!(flags & FLAG_CONNECTION)) {
256 for (i = 0; i < len; i++)
258 fputc(buf[i], stderr);
274 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
275 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
277 static int ssh_version;
278 static void (*ssh_protocol)(unsigned char *in, int inlen, int ispkt);
279 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
280 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
281 static void ssh_size(void);
283 static int (*s_rdpkt)(unsigned char **data, int *datalen);
286 * Collect incoming data in the incoming packet buffer.
287 * Decipher and verify the packet when it is completely read.
288 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
289 * Update the *data and *datalen variables.
290 * Return the additional nr of bytes needed, or 0 when
291 * a complete packet is available.
293 static int ssh1_rdpkt(unsigned char **data, int *datalen)
295 static long len, pad, biglen, to_read;
296 static unsigned long realcrc, gotcrc;
297 static unsigned char *p;
307 for (i = len = 0; i < 4; i++) {
308 while ((*datalen) == 0)
310 len = (len << 8) + **data;
311 (*data)++, (*datalen)--;
315 if (len == 0x52656d6f) { /* "Remo"te server has closed ... */
316 len = 0x300; /* big enough to carry to end */
322 pktin.length = len - 5;
324 if (pktin.maxlen < biglen) {
325 pktin.maxlen = biglen;
326 pktin.data = (pktin.data == NULL ? malloc(biglen+APIEXTRA) :
327 realloc(pktin.data, biglen+APIEXTRA));
329 fatalbox("Out of memory");
334 while (to_read > 0) {
337 while ((*datalen) == 0)
339 if (chunk > (*datalen))
341 memcpy(p, *data, chunk);
349 cipher->decrypt(pktin.data, biglen);
351 pktin.type = pktin.data[pad];
352 pktin.body = pktin.data + pad + 1;
354 realcrc = crc32(pktin.data, biglen-4);
355 gotcrc = GET_32BIT(pktin.data+biglen-4);
356 if (gotcrc != realcrc) {
357 fatalbox("Incorrect CRC received on packet");
360 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
361 pktin.type == SSH1_SMSG_STDERR_DATA ||
362 pktin.type == SSH1_MSG_DEBUG ||
363 pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
364 pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
365 long strlen = GET_32BIT(pktin.body);
366 if (strlen + 4 != pktin.length)
367 fatalbox("Received data packet with bogus string length");
370 if (pktin.type == SSH1_MSG_DEBUG) {
371 /* log debug message */
373 int strlen = GET_32BIT(pktin.body);
374 strcpy(buf, "Remote: ");
375 if (strlen > 70) strlen = 70;
376 memcpy(buf+8, pktin.body+4, strlen);
377 buf[8+strlen] = '\0';
380 } else if (pktin.type == SSH1_MSG_IGNORE) {
388 static int ssh2_rdpkt(unsigned char **data, int *datalen)
390 static long len, pad, payload, packetlen, maclen;
392 static int cipherblk;
393 static unsigned long incoming_sequence = 0;
403 cipherblk = cipher->blksize;
409 if (pktin.maxlen < cipherblk) {
410 pktin.maxlen = cipherblk;
411 pktin.data = (pktin.data == NULL ? malloc(cipherblk+APIEXTRA) :
412 realloc(pktin.data, cipherblk+APIEXTRA));
414 fatalbox("Out of memory");
418 * Acquire and decrypt the first block of the packet. This will
419 * contain the length and padding details.
421 for (i = len = 0; i < cipherblk; i++) {
422 while ((*datalen) == 0)
423 crReturn(cipherblk-i);
424 pktin.data[i] = *(*data)++;
428 if (!memcmp(pktin.data, "Remo", 4)) {/* "Remo"te server has closed ... */
433 sccipher->decrypt(pktin.data, cipherblk);
436 * Now get the length and padding figures.
438 len = GET_32BIT(pktin.data);
442 * This enables us to deduce the payload length.
444 payload = len - pad - 1;
446 pktin.length = payload + 5;
449 * So now we can work out the total packet length.
452 maclen = scmac ? scmac->len : 0;
455 * Adjust memory allocation if packet is too big.
457 if (pktin.maxlen < packetlen) {
458 pktin.maxlen = packetlen;
459 pktin.data = (pktin.data == NULL ? malloc(packetlen+APIEXTRA) :
460 realloc(pktin.data, packetlen+APIEXTRA));
462 fatalbox("Out of memory");
466 * Read and decrypt the remainder of the packet.
468 for (i = cipherblk; i < packetlen + maclen; i++) {
469 while ((*datalen) == 0)
470 crReturn(packetlen + maclen - i);
471 pktin.data[i] = *(*data)++;
474 /* Decrypt everything _except_ the MAC. */
476 sccipher->decrypt(pktin.data + cipherblk, packetlen - cipherblk);
479 debug(("Got packet len=%d pad=%d\r\n", len, pad));
480 for (i = 0; i < packetlen; i++)
481 debug((" %02x", (unsigned char)pktin.data[i]));
488 if (scmac && !scmac->verify(pktin.data, len+4, incoming_sequence))
489 fatalbox("Incorrect MAC received on packet");
490 incoming_sequence++; /* whether or not we MACed */
493 pktin.type = pktin.data[5];
495 if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
496 goto next_packet; /* FIXME: print DEBUG message */
501 static void ssh_gotdata(unsigned char *data, int datalen)
503 while (datalen > 0) {
504 if ( s_rdpkt(&data, &datalen) == 0 ) {
505 ssh_protocol(NULL, 0, 1);
506 if (ssh_state == SSH_STATE_CLOSED) {
514 static void s_wrpkt_start(int type, int len) {
517 len += 5; /* type and CRC */
521 pktout.length = len-5;
522 if (pktout.maxlen < biglen) {
523 pktout.maxlen = biglen;
525 /* Allocate enough buffer space for extra block
526 * for MS CryptEncrypt() */
527 pktout.data = (pktout.data == NULL ? malloc(biglen+12) :
528 realloc(pktout.data, biglen+12));
530 pktout.data = (pktout.data == NULL ? malloc(biglen+4) :
531 realloc(pktout.data, biglen+4));
534 fatalbox("Out of memory");
538 pktout.body = pktout.data+4+pad+1;
541 static void s_wrpkt(void) {
542 int pad, len, biglen, i;
545 len = pktout.length + 5; /* type and CRC */
549 pktout.body[-1] = pktout.type;
550 for (i=0; i<pad; i++)
551 pktout.data[i+4] = random_byte();
552 crc = crc32(pktout.data+4, biglen-4);
553 PUT_32BIT(pktout.data+biglen, crc);
554 PUT_32BIT(pktout.data, len);
557 cipher->encrypt(pktout.data+4, biglen);
559 s_write(pktout.data, biglen+4);
563 * Construct a packet with the specified contents and
564 * send it to the server.
566 static void send_packet(int pkttype, ...)
569 unsigned char *p, *argp, argchar;
570 unsigned long argint;
571 int pktlen, argtype, arglen;
575 va_start(args, pkttype);
576 while ((argtype = va_arg(args, int)) != PKT_END) {
579 (void) va_arg(args, int);
583 (void) va_arg(args, char);
587 (void) va_arg(args, unsigned char *);
588 arglen = va_arg(args, int);
592 argp = va_arg(args, unsigned char *);
593 arglen = strlen(argp);
594 pktlen += 4 + arglen;
597 bn = va_arg(args, Bignum);
598 pktlen += ssh1_bignum_length(bn);
606 s_wrpkt_start(pkttype, pktlen);
609 va_start(args, pkttype);
610 while ((argtype = va_arg(args, int)) != PKT_END) {
613 argint = va_arg(args, int);
614 PUT_32BIT(p, argint);
618 argchar = va_arg(args, unsigned char);
623 argp = va_arg(args, unsigned char *);
624 arglen = va_arg(args, int);
625 memcpy(p, argp, arglen);
629 argp = va_arg(args, unsigned char *);
630 arglen = strlen(argp);
631 PUT_32BIT(p, arglen);
632 memcpy(p + 4, argp, arglen);
636 bn = va_arg(args, Bignum);
637 p += ssh1_write_bignum(p, bn);
648 * Connect to specified host and port.
649 * Returns an error message, or NULL on success.
650 * Also places the canonical host name into `realhost'.
652 static char *connect_to_host(char *host, int port, char **realhost)
662 savedhost = malloc(1+strlen(host));
664 fatalbox("Out of memory");
665 strcpy(savedhost, host);
668 port = 22; /* default ssh port */
680 if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
681 if ( (h = gethostbyname(host)) == NULL)
682 switch (WSAGetLastError()) {
683 case WSAENETDOWN: return "Network is down";
684 case WSAHOST_NOT_FOUND: case WSANO_DATA:
685 return "Host does not exist";
686 case WSATRY_AGAIN: return "Host not found";
687 default: return "gethostbyname: unknown error";
689 memcpy (&a, h->h_addr, sizeof(a));
690 *realhost = h->h_name;
701 s = socket(AF_INET, SOCK_STREAM, 0);
702 if (s == INVALID_SOCKET)
703 switch (WSAGetLastError()) {
704 case WSAENETDOWN: return "Network is down";
705 case WSAEAFNOSUPPORT: return "TCP/IP support not present";
706 default: return "socket(): unknown error";
710 * Bind to local address.
712 addr.sin_family = AF_INET;
713 addr.sin_addr.s_addr = htonl(INADDR_ANY);
714 addr.sin_port = htons(0);
715 if (bind (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
716 switch (WSAGetLastError()) {
717 case WSAENETDOWN: return "Network is down";
718 default: return "bind(): unknown error";
722 * Connect to remote address.
724 addr.sin_addr.s_addr = htonl(a);
725 addr.sin_port = htons((short)port);
726 if (connect (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
727 switch (WSAGetLastError()) {
728 case WSAENETDOWN: return "Network is down";
729 case WSAECONNREFUSED: return "Connection refused";
730 case WSAENETUNREACH: return "Network is unreachable";
731 case WSAEHOSTUNREACH: return "No route to host";
732 default: return "connect(): unknown error";
736 send(s, "connect ", 8, 0);
737 send(s, FWhost, strlen(FWhost), 0);
740 sprintf(buf, " %d\n", FWport);
741 send (s, buf, strlen(buf), 0);
748 static int ssh_versioncmp(char *a, char *b) {
750 unsigned long av, bv;
752 av = strtoul(a, &ae, 10);
753 bv = strtoul(b, &be, 10);
754 if (av != bv) return (av < bv ? -1 : +1);
755 if (*ae == '.') ae++;
756 if (*be == '.') be++;
757 av = strtoul(ae, &ae, 10);
758 bv = strtoul(be, &be, 10);
759 if (av != bv) return (av < bv ? -1 : +1);
765 * Utility routine for putting an SSH-protocol `string' into a SHA
769 void sha_string(SHA_State *s, void *str, int len) {
770 unsigned char lenblk[4];
771 PUT_32BIT(lenblk, len);
772 SHA_Bytes(s, lenblk, 4);
773 SHA_Bytes(s, str, len);
777 * SSH2 packet construction functions.
779 void ssh2_pkt_adddata(void *data, int len) {
780 pktout.length += len;
781 if (pktout.maxlen < pktout.length) {
782 pktout.maxlen = pktout.length + 256;
783 pktout.data = (pktout.data == NULL ? malloc(pktout.maxlen+APIEXTRA) :
784 realloc(pktout.data, pktout.maxlen+APIEXTRA));
786 fatalbox("Out of memory");
788 memcpy(pktout.data+pktout.length-len, data, len);
790 void ssh2_pkt_addbyte(unsigned char byte) {
791 ssh2_pkt_adddata(&byte, 1);
793 void ssh2_pkt_init(int pkt_type) {
795 ssh2_pkt_addbyte((unsigned char)pkt_type);
797 void ssh2_pkt_addbool(unsigned char value) {
798 ssh2_pkt_adddata(&value, 1);
800 void ssh2_pkt_adduint32(unsigned long value) {
803 ssh2_pkt_adddata(x, 4);
805 void ssh2_pkt_addstring_start(void) {
806 ssh2_pkt_adduint32(0);
807 pktout.savedpos = pktout.length;
809 void ssh2_pkt_addstring_str(char *data) {
810 ssh2_pkt_adddata(data, strlen(data));
811 PUT_32BIT(pktout.data + pktout.savedpos - 4,
812 pktout.length - pktout.savedpos);
814 void ssh2_pkt_addstring_data(char *data, int len) {
815 ssh2_pkt_adddata(data, len);
816 PUT_32BIT(pktout.data + pktout.savedpos - 4,
817 pktout.length - pktout.savedpos);
819 void ssh2_pkt_addstring(char *data) {
820 ssh2_pkt_addstring_start();
821 ssh2_pkt_addstring_str(data);
823 char *ssh2_mpint_fmt(Bignum b, int *len) {
826 p = malloc(n * 2 + 1);
828 fatalbox("out of memory");
830 for (i = 0; i < n; i++) {
831 p[i*2+1] = (b[n-i] >> 8) & 0xFF;
832 p[i*2+2] = (b[n-i] ) & 0xFF;
835 while (p[i] == 0 && (p[i+1] & 0x80) == 0)
837 memmove(p, p+i, n*2+1-i);
841 void ssh2_pkt_addmp(Bignum b) {
844 p = ssh2_mpint_fmt(b, &len);
845 ssh2_pkt_addstring_start();
846 ssh2_pkt_addstring_data(p, len);
849 void ssh2_pkt_send(void) {
850 int cipherblk, maclen, padding, i;
851 static unsigned long outgoing_sequence = 0;
854 * Add padding. At least four bytes, and must also bring total
855 * length (minus MAC) up to a multiple of the block size.
857 cipherblk = cipher ? cipher->blksize : 8; /* block size */
858 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
860 padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
861 pktout.data[4] = padding;
862 for (i = 0; i < padding; i++)
863 pktout.data[pktout.length + i] = random_byte();
864 PUT_32BIT(pktout.data, pktout.length + padding - 4);
866 csmac->generate(pktout.data, pktout.length + padding,
868 outgoing_sequence++; /* whether or not we MACed */
871 debug(("Sending packet len=%d\r\n", pktout.length+padding));
872 for (i = 0; i < pktout.length+padding; i++)
873 debug((" %02x", (unsigned char)pktout.data[i]));
878 cscipher->encrypt(pktout.data, pktout.length + padding);
879 maclen = csmac ? csmac->len : 0;
881 s_write(pktout.data, pktout.length + padding + maclen);
885 void bndebug(char *string, Bignum b) {
888 p = ssh2_mpint_fmt(b, &len);
889 debug(("%s", string));
890 for (i = 0; i < len; i++)
891 debug((" %02x", p[i]));
897 void sha_mpint(SHA_State *s, Bignum b) {
900 p = ssh2_mpint_fmt(b, &len);
901 sha_string(s, p, len);
906 * SSH2 packet decode functions.
908 unsigned long ssh2_pkt_getuint32(void) {
910 if (pktin.length - pktin.savedpos < 4)
911 return 0; /* arrgh, no way to decline (FIXME?) */
912 value = GET_32BIT(pktin.data+pktin.savedpos);
916 void ssh2_pkt_getstring(char **p, int *length) {
918 if (pktin.length - pktin.savedpos < 4)
920 *length = GET_32BIT(pktin.data+pktin.savedpos);
922 if (pktin.length - pktin.savedpos < *length)
924 *p = pktin.data+pktin.savedpos;
925 pktin.savedpos += *length;
927 Bignum ssh2_pkt_getmp(void) {
932 ssh2_pkt_getstring(&p, &length);
936 fatalbox("internal error: Can't handle negative mpints");
937 b = newbn((length+1)/2);
938 for (i = 0; i < length; i++) {
941 b[j/2+1] |= ((unsigned char)p[i]) << 8;
943 b[j/2+1] |= ((unsigned char)p[i]);
948 static int do_ssh_init(void) {
952 char vlog[sizeof(vstring)+20];
957 while (s_read(&c, 1) == 1) {
958 if (c == 'S' && i < 2) i++;
959 else if (c == 'S' && i == 2) i = 2;
960 else if (c == 'H' && i == 2) break;
964 if (s_read(&c,1) != 1 || c != 'S') return 0;
965 if (s_read(&c,1) != 1 || c != 'S') return 0;
966 if (s_read(&c,1) != 1 || c != 'H') return 0;
968 strcpy(vstring, "SSH-");
970 if (s_read(&c,1) != 1 || c != '-') return 0;
973 if (s_read(&c,1) != 1)
975 if (vsp < vstring+sizeof(vstring)-1)
981 } else if (i < sizeof(version)-1)
989 sprintf(vlog, "Server version: %s", vstring);
990 vlog[strcspn(vlog, "\r\n")] = '\0';
994 * Server version "1.99" means we can choose whether we use v1
995 * or v2 protocol. Choice is based on cfg.sshprot.
997 if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
999 * This is a v2 server. Begin v2 protocol.
1001 char *verstring = "SSH-2.0-PuTTY";
1004 * Hash our version string and their version string.
1006 sha_string(&exhash, verstring, strlen(verstring));
1007 sha_string(&exhash, vstring, strcspn(vstring, "\r\n"));
1008 sprintf(vstring, "%s\n", verstring);
1009 sprintf(vlog, "We claim version: %s", verstring);
1011 logevent("Using SSH protocol version 2");
1012 s_write(vstring, strlen(vstring));
1013 ssh_protocol = ssh2_protocol;
1015 s_rdpkt = ssh2_rdpkt;
1018 * This is a v1 server. Begin v1 protocol.
1020 sprintf(vstring, "SSH-%s-PuTTY\n",
1021 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
1022 sprintf(vlog, "We claim version: %s", vstring);
1023 vlog[strcspn(vlog, "\r\n")] = '\0';
1025 logevent("Using SSH protocol version 1");
1026 s_write(vstring, strlen(vstring));
1027 ssh_protocol = ssh1_protocol;
1029 s_rdpkt = ssh1_rdpkt;
1036 * Handle the key exchange and user authentication phases.
1038 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1041 unsigned char *rsabuf, *keystr1, *keystr2;
1042 unsigned char cookie[8];
1043 struct RSAKey servkey, hostkey;
1044 struct MD5Context md5c;
1045 static unsigned long supported_ciphers_mask, supported_auths_mask;
1046 static int tried_publickey;
1047 static unsigned char session_id[16];
1052 if (!ispkt) crWaitUntil(ispkt);
1054 if (pktin.type != SSH1_SMSG_PUBLIC_KEY)
1055 fatalbox("Public key packet not received");
1057 logevent("Received public keys");
1059 memcpy(cookie, pktin.body, 8);
1061 i = makekey(pktin.body+8, &servkey, &keystr1, 0);
1062 j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
1065 * Hash the host key and print the hash in the log box. Just as
1066 * a last resort in case the registry's host key checking is
1067 * compromised, we'll allow the user some ability to verify
1071 MD5Update(&md5c, keystr2, hostkey.bytes);
1072 MD5Final(session_id, &md5c);
1076 logevent("Host key MD5 is:");
1077 strcpy(logmsg, " ");
1078 for (i = 0; i < 16; i++)
1079 sprintf(logmsg+strlen(logmsg), "%02x", session_id[i]);
1083 supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
1084 supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
1087 MD5Update(&md5c, keystr2, hostkey.bytes);
1088 MD5Update(&md5c, keystr1, servkey.bytes);
1089 MD5Update(&md5c, pktin.body, 8);
1090 MD5Final(session_id, &md5c);
1092 for (i=0; i<32; i++)
1093 session_key[i] = random_byte();
1095 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1097 rsabuf = malloc(len);
1099 fatalbox("Out of memory");
1102 * Verify the host key.
1106 * First format the key into a string.
1108 int len = rsastr_len(&hostkey);
1109 char *keystr = malloc(len);
1111 fatalbox("Out of memory");
1112 rsastr_fmt(keystr, &hostkey);
1113 verify_ssh_host_key(savedhost, keystr);
1117 for (i=0; i<32; i++) {
1118 rsabuf[i] = session_key[i];
1120 rsabuf[i] ^= session_id[i];
1123 if (hostkey.bytes > servkey.bytes) {
1124 rsaencrypt(rsabuf, 32, &servkey);
1125 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1127 rsaencrypt(rsabuf, 32, &hostkey);
1128 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1131 logevent("Encrypted session key");
1133 cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
1134 cfg.cipher == CIPHER_DES ? SSH_CIPHER_DES :
1136 if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1137 c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
1138 cipher_type = SSH_CIPHER_3DES;
1140 switch (cipher_type) {
1141 case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
1142 case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
1143 case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
1146 send_packet(SSH1_CMSG_SESSION_KEY,
1147 PKT_CHAR, cipher_type,
1148 PKT_DATA, cookie, 8,
1149 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
1150 PKT_DATA, rsabuf, len,
1154 logevent("Trying to enable encryption...");
1158 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish :
1159 cipher_type == SSH_CIPHER_DES ? &ssh_des :
1161 cipher->sesskey(session_key);
1165 if (pktin.type != SSH1_SMSG_SUCCESS)
1166 fatalbox("Encryption not successfully enabled");
1168 logevent("Successfully started encryption");
1172 static char username[100];
1175 if ((flags & FLAG_CONNECTION) && !*cfg.username) {
1176 c_write("login as: ", 10);
1178 crWaitUntil(!ispkt);
1179 while (inlen--) switch (c = *in++) {
1186 c_write("\b \b", 3);
1192 c_write("\b \b", 3);
1201 if (((c >= ' ' && c <= '~') ||
1202 ((unsigned char)c >= 160)) && pos < 40) {
1203 username[pos++] = c;
1210 username[strcspn(username, "\n\r")] = '\0';
1213 strncpy(username, cfg.username, 99);
1214 username[99] = '\0';
1215 if (flags & FLAG_VERBOSE) {
1216 sprintf(stuff, "Sent username \"%s\".\r\n", username);
1217 c_write(stuff, strlen(stuff));
1221 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
1223 char userlog[20+sizeof(username)];
1224 sprintf(userlog, "Sent username \"%s\"", username);
1231 tried_publickey = 0;
1233 while (pktin.type == SSH1_SMSG_FAILURE) {
1234 static char password[100];
1237 static int pwpkt_type;
1239 * Show password prompt, having first obtained it via a TIS
1240 * or CryptoCard exchange if we're doing TIS or CryptoCard
1243 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
1244 if (agent_exists()) {
1246 * Attempt RSA authentication using Pageant.
1248 static unsigned char request[5], *response, *p;
1249 static int responselen;
1250 static int i, nkeys;
1251 static int authed = FALSE;
1254 logevent("Pageant is running. Requesting keys.");
1256 /* Request the keys held by the agent. */
1257 PUT_32BIT(request, 1);
1258 request[4] = SSH_AGENTC_REQUEST_RSA_IDENTITIES;
1259 agent_query(request, 5, &r, &responselen);
1260 response = (unsigned char *)r;
1263 nkeys = GET_32BIT(p); p += 4;
1264 { char buf[64]; sprintf(buf, "Pageant has %d keys", nkeys);
1266 for (i = 0; i < nkeys; i++) {
1267 static struct RSAKey key;
1268 static Bignum challenge;
1269 static char *commentp;
1270 static int commentlen;
1272 { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
1275 p += ssh1_read_bignum(p, &key.exponent);
1276 p += ssh1_read_bignum(p, &key.modulus);
1277 commentlen = GET_32BIT(p); p += 4;
1278 commentp = p; p += commentlen;
1279 send_packet(SSH1_CMSG_AUTH_RSA,
1280 PKT_BIGNUM, key.modulus, PKT_END);
1282 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1283 logevent("Key refused");
1286 logevent("Received RSA challenge");
1287 ssh1_read_bignum(pktin.body, &challenge);
1289 char *agentreq, *q, *ret;
1291 len = 1 + 4; /* message type, bit count */
1292 len += ssh1_bignum_length(key.exponent);
1293 len += ssh1_bignum_length(key.modulus);
1294 len += ssh1_bignum_length(challenge);
1295 len += 16; /* session id */
1296 len += 4; /* response format */
1297 agentreq = malloc(4 + len);
1298 PUT_32BIT(agentreq, len);
1300 *q++ = SSH_AGENTC_RSA_CHALLENGE;
1301 PUT_32BIT(q, ssh1_bignum_bitcount(key.modulus));
1303 q += ssh1_write_bignum(q, key.exponent);
1304 q += ssh1_write_bignum(q, key.modulus);
1305 q += ssh1_write_bignum(q, challenge);
1306 memcpy(q, session_id, 16); q += 16;
1307 PUT_32BIT(q, 1); /* response format */
1308 agent_query(agentreq, len+4, &ret, &retlen);
1311 if (ret[4] == SSH_AGENT_RSA_RESPONSE) {
1312 logevent("Sending Pageant's response");
1313 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1314 PKT_DATA, ret+5, 16, PKT_END);
1317 if (pktin.type == SSH1_SMSG_SUCCESS) {
1318 logevent("Pageant's response accepted");
1319 c_write("Authenticated using RSA key \"",
1321 c_write(commentp, commentlen);
1322 c_write("\" from agent\r\n", 14);
1325 logevent("Pageant's response not accepted");
1327 logevent("Pageant failed to answer challenge");
1331 logevent("No reply received from Pageant");
1334 freebn(key.exponent);
1335 freebn(key.modulus);
1344 if (*cfg.keyfile && !tried_publickey)
1345 pwpkt_type = SSH1_CMSG_AUTH_RSA;
1347 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD && !FLAG_WINDOWED) {
1349 sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
1350 if (!ssh_get_password(prompt, password, sizeof(password))) {
1352 * get_password failed to get a password (for
1353 * example because one was supplied on the command
1354 * line which has already failed to work).
1357 logevent("No more passwords to try");
1358 ssh_state = SSH_STATE_CLOSED;
1363 if (pktin.type == SSH1_SMSG_FAILURE &&
1365 (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1366 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1367 logevent("Requested TIS authentication");
1368 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1370 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1371 logevent("TIS authentication declined");
1372 c_write("TIS authentication refused.\r\n", 29);
1374 int challengelen = ((pktin.body[0] << 24) |
1375 (pktin.body[1] << 16) |
1376 (pktin.body[2] << 8) |
1378 logevent("Received TIS challenge");
1379 c_write(pktin.body+4, challengelen);
1382 if (pktin.type == SSH1_SMSG_FAILURE &&
1384 (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
1385 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
1386 logevent("Requested CryptoCard authentication");
1387 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
1389 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
1390 logevent("CryptoCard authentication declined");
1391 c_write("CryptoCard authentication refused.\r\n", 29);
1393 int challengelen = ((pktin.body[0] << 24) |
1394 (pktin.body[1] << 16) |
1395 (pktin.body[2] << 8) |
1397 logevent("Received CryptoCard challenge");
1398 c_write(pktin.body+4, challengelen);
1399 c_write("\r\nResponse : ", 13);
1402 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD)
1403 c_write("password: ", 10);
1404 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1405 if (flags & FLAG_VERBOSE)
1406 c_write("Trying public key authentication.\r\n", 35);
1407 if (!rsakey_encrypted(cfg.keyfile)) {
1408 if (flags & FLAG_VERBOSE)
1409 c_write("No passphrase required.\r\n", 25);
1412 c_write("passphrase: ", 12);
1417 crWaitUntil(!ispkt);
1418 while (inlen--) switch (c = *in++) {
1435 if (((c >= ' ' && c <= '~') ||
1436 ((unsigned char)c >= 160)) && pos < sizeof(password))
1437 password[pos++] = c;
1446 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1448 * Try public key authentication with the specified
1451 static struct RSAKey pubkey;
1452 static Bignum challenge, response;
1454 static unsigned char buffer[32];
1456 tried_publickey = 1;
1457 i = loadrsakey(cfg.keyfile, &pubkey, password);
1459 c_write("Couldn't load public key from ", 30);
1460 c_write(cfg.keyfile, strlen(cfg.keyfile));
1461 c_write(".\r\n", 3);
1462 continue; /* go and try password */
1465 c_write("Wrong passphrase.\r\n", 19);
1466 tried_publickey = 0;
1467 continue; /* try again */
1471 * Send a public key attempt.
1473 send_packet(SSH1_CMSG_AUTH_RSA,
1474 PKT_BIGNUM, pubkey.modulus, PKT_END);
1477 if (pktin.type == SSH1_SMSG_FAILURE) {
1478 if (flags & FLAG_VERBOSE)
1479 c_write("Server refused our public key.\r\n", 32);
1480 continue; /* go and try password */
1482 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE)
1483 fatalbox("Bizarre response to offer of public key");
1484 ssh1_read_bignum(pktin.body, &challenge);
1485 response = rsadecrypt(challenge, &pubkey);
1486 freebn(pubkey.private_exponent); /* burn the evidence */
1488 for (i = 0; i < 32; i += 2) {
1489 buffer[i] = response[16-i/2] >> 8;
1490 buffer[i+1] = response[16-i/2] & 0xFF;
1494 MD5Update(&md5c, buffer, 32);
1495 MD5Update(&md5c, session_id, 16);
1496 MD5Final(buffer, &md5c);
1498 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1499 PKT_DATA, buffer, 16, PKT_END);
1502 if (pktin.type == SSH1_SMSG_FAILURE) {
1503 if (flags & FLAG_VERBOSE)
1504 c_write("Failed to authenticate with our public key.\r\n",
1506 continue; /* go and try password */
1507 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1508 fatalbox("Bizarre response to RSA authentication response");
1511 break; /* we're through! */
1513 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1515 logevent("Sent password");
1516 memset(password, 0, strlen(password));
1518 if (pktin.type == SSH1_SMSG_FAILURE) {
1519 if (flags & FLAG_VERBOSE)
1520 c_write("Access denied\r\n", 15);
1521 logevent("Authentication refused");
1522 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1523 logevent("Received disconnect request");
1524 ssh_state = SSH_STATE_CLOSED;
1526 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1527 fatalbox("Strange packet received, type %d", pktin.type);
1531 logevent("Authentication successful");
1536 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
1541 while (!do_ssh1_login(in, inlen, ispkt)) {
1544 if (ssh_state == SSH_STATE_CLOSED)
1547 if (cfg.agentfwd && agent_exists()) {
1548 logevent("Requesting agent forwarding");
1549 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
1550 do { crReturnV; } while (!ispkt);
1551 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1552 fatalbox("Protocol confusion");
1553 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1554 logevent("Agent forwarding refused");
1556 logevent("Agent forwarding enabled");
1560 send_packet(SSH1_CMSG_REQUEST_PTY,
1561 PKT_STR, cfg.termtype,
1562 PKT_INT, rows, PKT_INT, cols,
1563 PKT_INT, 0, PKT_INT, 0,
1566 ssh_state = SSH_STATE_INTERMED;
1567 do { crReturnV; } while (!ispkt);
1568 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1569 fatalbox("Protocol confusion");
1570 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1571 c_write("Server refused to allocate pty\r\n", 32);
1573 logevent("Allocated pty");
1576 if (*cfg.remote_cmd)
1577 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
1579 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
1580 logevent("Started session");
1582 ssh_state = SSH_STATE_SESSION;
1587 ssh_channels = newtree234(ssh_channelcmp);
1591 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
1592 pktin.type == SSH1_SMSG_STDERR_DATA) {
1593 long len = GET_32BIT(pktin.body);
1594 c_write(pktin.body+4, len);
1595 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1596 ssh_state = SSH_STATE_CLOSED;
1597 logevent("Received disconnect request");
1598 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
1599 /* Remote side is trying to open a channel to talk to our
1600 * agent. Give them back a local channel number. */
1602 struct ssh_channel *c;
1604 for (c = first234(ssh_channels, &e); c; c = next234(&e)) {
1606 break; /* found a free number */
1609 c = malloc(sizeof(struct ssh_channel));
1610 c->remoteid = GET_32BIT(pktin.body);
1613 c->type = SSH1_SMSG_AGENT_OPEN; /* identify channel type */
1614 add234(ssh_channels, c);
1615 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
1616 PKT_INT, c->remoteid, PKT_INT, c->localid,
1618 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
1619 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
1620 /* Remote side closes a channel. */
1621 int i = GET_32BIT(pktin.body);
1622 struct ssh_channel *c;
1623 c = find234(ssh_channels, &i, ssh_channelfind);
1626 closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
1627 send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
1628 c->closes |= closetype;
1629 if (c->closes == 3) {
1630 del234(ssh_channels, c);
1634 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
1635 /* Data sent down one of our channels. */
1636 int i = GET_32BIT(pktin.body);
1637 int len = GET_32BIT(pktin.body+4);
1638 unsigned char *p = pktin.body+8;
1639 struct ssh_channel *c;
1640 c = find234(ssh_channels, &i, ssh_channelfind);
1643 case SSH1_SMSG_AGENT_OPEN:
1644 /* Data for an agent message. Buffer it. */
1646 if (c->u.a.lensofar < 4) {
1647 int l = min(4 - c->u.a.lensofar, len);
1648 memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
1649 p += l; len -= l; c->u.a.lensofar += l;
1651 if (c->u.a.lensofar == 4) {
1652 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
1653 c->u.a.message = malloc(c->u.a.totallen);
1654 memcpy(c->u.a.message, c->u.a.msglen, 4);
1656 if (c->u.a.lensofar >= 4 && len > 0) {
1657 int l = min(c->u.a.totallen - c->u.a.lensofar, len);
1658 memcpy(c->u.a.message + c->u.a.lensofar, p, l);
1659 p += l; len -= l; c->u.a.lensofar += l;
1661 if (c->u.a.lensofar == c->u.a.totallen) {
1662 void *reply, *sentreply;
1664 agent_query(c->u.a.message, c->u.a.totallen,
1669 /* Fake SSH_AGENT_FAILURE. */
1670 sentreply = "\0\0\0\1\5";
1673 send_packet(SSH1_MSG_CHANNEL_DATA,
1674 PKT_INT, c->remoteid,
1676 PKT_DATA, sentreply, replylen,
1680 free(c->u.a.message);
1681 c->u.a.lensofar = 0;
1687 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
1688 /* may be from EXEC_SHELL on some servers */
1689 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1690 /* may be from EXEC_SHELL on some servers
1691 * if no pty is available or in other odd cases. Ignore */
1692 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
1693 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
1695 fatalbox("Strange packet received: type %d", pktin.type);
1698 send_packet(SSH1_CMSG_STDIN_DATA,
1699 PKT_INT, inlen, PKT_DATA, in, inlen, PKT_END);
1707 * Utility routine for decoding comma-separated strings in KEXINIT.
1709 int in_commasep_string(char *needle, char *haystack, int haylen) {
1710 int needlen = strlen(needle);
1713 * Is it at the start of the string?
1715 if (haylen >= needlen && /* haystack is long enough */
1716 !memcmp(needle, haystack, needlen) && /* initial match */
1717 (haylen == needlen || haystack[needlen] == ',')
1718 /* either , or EOS follows */
1722 * If not, search for the next comma and resume after that.
1723 * If no comma found, terminate.
1725 while (haylen > 0 && *haystack != ',')
1726 haylen--, haystack++;
1729 haylen--, haystack++; /* skip over comma itself */
1734 * SSH2 key creation method.
1736 void ssh2_mkkey(Bignum K, char *H, char chr, char *keyspace) {
1738 /* First 20 bytes. */
1741 SHA_Bytes(&s, H, 20);
1742 SHA_Bytes(&s, &chr, 1);
1743 SHA_Bytes(&s, H, 20);
1744 SHA_Final(&s, keyspace);
1745 /* Next 20 bytes. */
1748 SHA_Bytes(&s, H, 20);
1749 SHA_Bytes(&s, keyspace, 20);
1750 SHA_Final(&s, keyspace+20);
1754 * Handle the SSH2 transport layer.
1756 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
1760 static Bignum e, f, K;
1761 static struct ssh_cipher *cscipher_tobe = NULL;
1762 static struct ssh_cipher *sccipher_tobe = NULL;
1763 static struct ssh_mac *csmac_tobe = NULL;
1764 static struct ssh_mac *scmac_tobe = NULL;
1765 static struct ssh_compress *cscomp_tobe = NULL;
1766 static struct ssh_compress *sccomp_tobe = NULL;
1767 static char *hostkeydata, *sigdata, *keystr;
1768 static int hostkeylen, siglen;
1769 static unsigned char exchange_hash[20];
1770 static unsigned char keyspace[40];
1777 * Construct and send our key exchange packet.
1779 ssh2_pkt_init(SSH2_MSG_KEXINIT);
1780 for (i = 0; i < 16; i++)
1781 ssh2_pkt_addbyte((unsigned char)random_byte());
1782 /* List key exchange algorithms. */
1783 ssh2_pkt_addstring_start();
1784 for (i = 0; i < lenof(kex_algs); i++) {
1785 ssh2_pkt_addstring_str(kex_algs[i]->name);
1786 if (i < lenof(kex_algs)-1)
1787 ssh2_pkt_addstring_str(",");
1789 /* List server host key algorithms. */
1790 ssh2_pkt_addstring_start();
1791 for (i = 0; i < lenof(hostkey_algs); i++) {
1792 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
1793 if (i < lenof(hostkey_algs)-1)
1794 ssh2_pkt_addstring_str(",");
1796 /* List client->server encryption algorithms. */
1797 ssh2_pkt_addstring_start();
1798 for (i = 0; i < lenof(ciphers); i++) {
1799 ssh2_pkt_addstring_str(ciphers[i]->name);
1800 if (i < lenof(ciphers)-1)
1801 ssh2_pkt_addstring_str(",");
1803 /* List server->client encryption algorithms. */
1804 ssh2_pkt_addstring_start();
1805 for (i = 0; i < lenof(ciphers); i++) {
1806 ssh2_pkt_addstring_str(ciphers[i]->name);
1807 if (i < lenof(ciphers)-1)
1808 ssh2_pkt_addstring_str(",");
1810 /* List client->server MAC algorithms. */
1811 ssh2_pkt_addstring_start();
1812 for (i = 0; i < lenof(macs); i++) {
1813 ssh2_pkt_addstring_str(macs[i]->name);
1814 if (i < lenof(macs)-1)
1815 ssh2_pkt_addstring_str(",");
1817 /* List server->client MAC algorithms. */
1818 ssh2_pkt_addstring_start();
1819 for (i = 0; i < lenof(macs); i++) {
1820 ssh2_pkt_addstring_str(macs[i]->name);
1821 if (i < lenof(macs)-1)
1822 ssh2_pkt_addstring_str(",");
1824 /* List client->server compression algorithms. */
1825 ssh2_pkt_addstring_start();
1826 for (i = 0; i < lenof(compressions); i++) {
1827 ssh2_pkt_addstring_str(compressions[i]->name);
1828 if (i < lenof(compressions)-1)
1829 ssh2_pkt_addstring_str(",");
1831 /* List server->client compression algorithms. */
1832 ssh2_pkt_addstring_start();
1833 for (i = 0; i < lenof(compressions); i++) {
1834 ssh2_pkt_addstring_str(compressions[i]->name);
1835 if (i < lenof(compressions)-1)
1836 ssh2_pkt_addstring_str(",");
1838 /* List client->server languages. Empty list. */
1839 ssh2_pkt_addstring_start();
1840 /* List server->client languages. Empty list. */
1841 ssh2_pkt_addstring_start();
1842 /* First KEX packet does _not_ follow, because we're not that brave. */
1843 ssh2_pkt_addbool(FALSE);
1845 ssh2_pkt_adduint32(0);
1846 sha_string(&exhash, pktout.data+5, pktout.length-5);
1849 if (!ispkt) crWaitUntil(ispkt);
1850 sha_string(&exhash, pktin.data+5, pktin.length-5);
1853 * Now examine the other side's KEXINIT to see what we're up
1856 if (pktin.type != SSH2_MSG_KEXINIT) {
1857 fatalbox("expected key exchange packet from server");
1859 kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
1860 csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
1861 pktin.savedpos += 16; /* skip garbage cookie */
1862 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
1863 for (i = 0; i < lenof(kex_algs); i++) {
1864 if (in_commasep_string(kex_algs[i]->name, str, len)) {
1869 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
1870 for (i = 0; i < lenof(hostkey_algs); i++) {
1871 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
1872 hostkey = hostkey_algs[i];
1876 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
1877 for (i = 0; i < lenof(ciphers); i++) {
1878 if (in_commasep_string(ciphers[i]->name, str, len)) {
1879 cscipher_tobe = ciphers[i];
1883 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
1884 for (i = 0; i < lenof(ciphers); i++) {
1885 if (in_commasep_string(ciphers[i]->name, str, len)) {
1886 sccipher_tobe = ciphers[i];
1890 ssh2_pkt_getstring(&str, &len); /* client->server mac */
1891 for (i = 0; i < lenof(macs); i++) {
1892 if (in_commasep_string(macs[i]->name, str, len)) {
1893 csmac_tobe = macs[i];
1897 ssh2_pkt_getstring(&str, &len); /* server->client mac */
1898 for (i = 0; i < lenof(macs); i++) {
1899 if (in_commasep_string(macs[i]->name, str, len)) {
1900 scmac_tobe = macs[i];
1904 ssh2_pkt_getstring(&str, &len); /* client->server compression */
1905 for (i = 0; i < lenof(compressions); i++) {
1906 if (in_commasep_string(compressions[i]->name, str, len)) {
1907 cscomp_tobe = compressions[i];
1911 ssh2_pkt_getstring(&str, &len); /* server->client compression */
1912 for (i = 0; i < lenof(compressions); i++) {
1913 if (in_commasep_string(compressions[i]->name, str, len)) {
1914 sccomp_tobe = compressions[i];
1920 * Currently we only support Diffie-Hellman and DSS, so let's
1921 * bomb out if those aren't selected.
1923 if (kex != &ssh_diffiehellman || hostkey != &ssh_dss)
1924 fatalbox("internal fault: chaos in SSH 2 transport layer");
1927 * Now we begin the fun. Generate and send e for Diffie-Hellman.
1930 ssh2_pkt_init(SSH2_MSG_KEXDH_INIT);
1935 if (pktin.type != SSH2_MSG_KEXDH_REPLY) {
1936 fatalbox("expected key exchange packet from server");
1938 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
1939 f = ssh2_pkt_getmp();
1940 ssh2_pkt_getstring(&sigdata, &siglen);
1944 sha_string(&exhash, hostkeydata, hostkeylen);
1945 sha_mpint(&exhash, e);
1946 sha_mpint(&exhash, f);
1947 sha_mpint(&exhash, K);
1948 SHA_Final(&exhash, exchange_hash);
1951 debug(("Exchange hash is:\r\n"));
1952 for (i = 0; i < 20; i++)
1953 debug((" %02x", exchange_hash[i]));
1957 hostkey->setkey(hostkeydata, hostkeylen);
1958 if (!hostkey->verifysig(sigdata, siglen, exchange_hash, 20))
1959 fatalbox("Server failed host key check");
1962 * Expect SSH2_MSG_NEWKEYS from server.
1965 if (pktin.type != SSH2_MSG_NEWKEYS)
1966 fatalbox("expected new-keys packet from server");
1969 * Authenticate remote host: verify host key. (We've already
1970 * checked the signature of the exchange hash.)
1972 keystr = hostkey->fmtkey();
1973 verify_ssh_host_key(savedhost, keystr);
1977 * Send SSH2_MSG_NEWKEYS.
1979 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
1983 * Create and initialise session keys.
1985 cscipher = cscipher_tobe;
1986 sccipher = sccipher_tobe;
1989 cscomp = cscomp_tobe;
1990 sccomp = sccomp_tobe;
1992 * Set IVs after keys.
1994 ssh2_mkkey(K, exchange_hash, 'C', keyspace); cscipher->setcskey(keyspace);
1995 ssh2_mkkey(K, exchange_hash, 'D', keyspace); cscipher->setsckey(keyspace);
1996 ssh2_mkkey(K, exchange_hash, 'A', keyspace); cscipher->setcsiv(keyspace);
1997 ssh2_mkkey(K, exchange_hash, 'B', keyspace); sccipher->setsciv(keyspace);
1998 ssh2_mkkey(K, exchange_hash, 'E', keyspace); csmac->setcskey(keyspace);
1999 ssh2_mkkey(K, exchange_hash, 'F', keyspace); scmac->setsckey(keyspace);
2002 * Now we're encrypting. Begin returning 1 to the protocol main
2003 * function so that other things can run on top of the
2004 * transport. If we ever see a KEXINIT, we must go back to the
2009 } while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT));
2010 goto begin_key_exchange;
2016 * SSH2: remote identifier for the main session channel.
2018 static unsigned long ssh_remote_channel;
2021 * Handle the SSH2 userauth and connection layers.
2023 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
2025 static unsigned long remote_winsize;
2026 static unsigned long remote_maxpkt;
2031 * Request userauth protocol, and await a response to it.
2033 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
2034 ssh2_pkt_addstring("ssh-userauth");
2036 crWaitUntilV(ispkt);
2037 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT)
2038 fatalbox("Server refused user authentication protocol");
2041 * FIXME: currently we support only password authentication.
2042 * (This places us technically in violation of the SSH2 spec.
2043 * We must fix this.)
2047 * Get a username and a password.
2049 static char username[100];
2050 static char password[100];
2054 if ((flags & FLAG_CONNECTION) && !*cfg.username) {
2055 c_write("login as: ", 10);
2057 crWaitUntilV(!ispkt);
2058 while (inlen--) switch (c = *in++) {
2065 c_write("\b \b", 3);
2071 c_write("\b \b", 3);
2080 if (((c >= ' ' && c <= '~') ||
2081 ((unsigned char)c >= 160)) && pos < 40) {
2082 username[pos++] = c;
2089 username[strcspn(username, "\n\r")] = '\0';
2092 strncpy(username, cfg.username, 99);
2093 username[99] = '\0';
2094 if (flags & FLAG_VERBOSE) {
2095 sprintf(stuff, "Using username \"%s\".\r\n", username);
2096 c_write(stuff, strlen(stuff));
2100 if (!(flags & FLAG_WINDOWED)) {
2102 sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
2103 if (!ssh_get_password(prompt, password, sizeof(password))) {
2105 * get_password failed to get a password (for
2106 * example because one was supplied on the command
2107 * line which has already failed to work).
2110 logevent("No more passwords to try");
2111 ssh_state = SSH_STATE_CLOSED;
2115 c_write("password: ", 10);
2119 crWaitUntilV(!ispkt);
2120 while (inlen--) switch (c = *in++) {
2137 if (((c >= ' ' && c <= '~') ||
2138 ((unsigned char)c >= 160)) && pos < 40)
2139 password[pos++] = c;
2146 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2147 ssh2_pkt_addstring(username);
2148 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2149 ssh2_pkt_addstring("password");
2150 ssh2_pkt_addbool(FALSE);
2151 ssh2_pkt_addstring(password);
2154 crWaitUntilV(ispkt);
2155 if (pktin.type != SSH2_MSG_USERAUTH_SUCCESS) {
2156 c_write("Access denied\r\n", 15);
2157 logevent("Authentication refused");
2163 * Now we're authenticated for the connection protocol. The
2164 * connection protocol will automatically have started at this
2165 * point; there's no need to send SERVICE_REQUEST.
2169 * So now create a channel with a session in it.
2171 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
2172 ssh2_pkt_addstring("session");
2173 ssh2_pkt_adduint32(100); /* as good as any */
2174 ssh2_pkt_adduint32(0xFFFFFFFFUL); /* very big window which we ignore */
2175 ssh2_pkt_adduint32(0xFFFFFFFFUL); /* very big max pkt size */
2177 crWaitUntilV(ispkt);
2178 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
2179 fatalbox("Server refused to open a session");
2180 /* FIXME: error data comes back in FAILURE packet */
2182 if (ssh2_pkt_getuint32() != 100) {
2183 fatalbox("Server's channel confirmation cited wrong channel");
2185 ssh_remote_channel = ssh2_pkt_getuint32();
2186 remote_winsize = ssh2_pkt_getuint32();
2187 remote_maxpkt = ssh2_pkt_getuint32();
2188 logevent("Opened channel for session");
2191 * Now allocate a pty for the session.
2193 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2194 ssh2_pkt_adduint32(ssh_remote_channel); /* recipient channel */
2195 ssh2_pkt_addstring("pty-req");
2196 ssh2_pkt_addbool(1); /* want reply */
2197 ssh2_pkt_addstring(cfg.termtype);
2198 ssh2_pkt_adduint32(cols);
2199 ssh2_pkt_adduint32(rows);
2200 ssh2_pkt_adduint32(0); /* pixel width */
2201 ssh2_pkt_adduint32(0); /* pixel height */
2202 ssh2_pkt_addstring_start();
2203 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
2206 do { /* FIXME: pay attention to these */
2207 crWaitUntilV(ispkt);
2208 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2210 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2211 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2212 fatalbox("Server got confused by pty request");
2214 c_write("Server refused to allocate pty\r\n", 32);
2216 logevent("Allocated pty");
2222 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2223 ssh2_pkt_adduint32(ssh_remote_channel); /* recipient channel */
2224 ssh2_pkt_addstring("shell");
2225 ssh2_pkt_addbool(1); /* want reply */
2227 do { /* FIXME: pay attention to these */
2228 crWaitUntilV(ispkt);
2229 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2230 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2231 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2232 fatalbox("Server got confused by shell request");
2234 fatalbox("Server refused to start a shell");
2236 logevent("Started a shell");
2246 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
2247 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
2250 if (ssh2_pkt_getuint32() != 100)
2251 continue; /* wrong channel */
2252 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
2253 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
2254 continue; /* extended but not stderr */
2255 ssh2_pkt_getstring(&data, &length);
2257 c_write(data, length);
2258 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
2259 ssh_state = SSH_STATE_CLOSED;
2260 logevent("Received disconnect request");
2261 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
2262 continue; /* exit status et al; ignore (FIXME?) */
2263 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2264 continue; /* ignore for now (FIXME!) */
2266 fatalbox("Strange packet received: type %d", pktin.type);
2269 /* FIXME: for now, ignore window size */
2270 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2271 ssh2_pkt_adduint32(ssh_remote_channel);
2272 ssh2_pkt_addstring_start();
2273 ssh2_pkt_addstring_data(in, inlen);
2282 * Handle the top-level SSH2 protocol.
2284 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
2286 if (do_ssh2_transport(in, inlen, ispkt) == 0)
2288 do_ssh2_authconn(in, inlen, ispkt);
2292 * Called to set up the connection. Will arrange for WM_NETEVENT
2293 * messages to be passed to the specified window, whose window
2294 * procedure should then call telnet_msg().
2296 * Returns an error message, or NULL on success.
2298 static char *ssh_init (HWND hwnd, char *host, int port, char **realhost) {
2302 if(crypto_startup() == 0)
2303 return "Microsoft high encryption pack not installed!";
2306 p = connect_to_host(host, port, realhost);
2311 return "Protocol initialisation error";
2313 if (hwnd && WSAAsyncSelect (s, hwnd, WM_NETEVENT, FD_READ | FD_CLOSE) == SOCKET_ERROR)
2314 switch (WSAGetLastError()) {
2315 case WSAENETDOWN: return "Network is down";
2316 default: return "WSAAsyncSelect(): unknown error";
2323 * Process a WM_NETEVENT message. Will return 0 if the connection
2324 * has closed, or <0 for a socket error.
2326 static int ssh_msg (WPARAM wParam, LPARAM lParam) {
2331 * Because reading less than the whole of the available pending
2332 * data can generate an FD_READ event, we need to allow for the
2333 * possibility that FD_READ may arrive with FD_CLOSE already in
2334 * the queue; so it's possible that we can get here even with s
2335 * invalid. If so, we return 1 and don't worry about it.
2337 if (s == INVALID_SOCKET)
2340 if (WSAGETSELECTERROR(lParam) != 0)
2341 return -WSAGETSELECTERROR(lParam);
2343 switch (WSAGETSELECTEVENT(lParam)) {
2346 ret = recv(s, buf, sizeof(buf), 0);
2347 if (ret < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
2349 if (ret < 0) /* any _other_ error */
2350 return -10000-WSAGetLastError();
2355 ssh_gotdata (buf, ret);
2356 if (ssh_state == SSH_STATE_CLOSED) {
2363 return 1; /* shouldn't happen, but WTF */
2367 * Called to send data down the Telnet connection.
2369 static void ssh_send (char *buf, int len) {
2370 if (s == INVALID_SOCKET)
2373 ssh_protocol(buf, len, 0);
2377 * Called to set the size of the window from Telnet's POV.
2379 static void ssh_size(void) {
2380 switch (ssh_state) {
2381 case SSH_STATE_BEFORE_SIZE:
2382 case SSH_STATE_CLOSED:
2383 break; /* do nothing */
2384 case SSH_STATE_INTERMED:
2385 size_needed = TRUE; /* buffer for later */
2387 case SSH_STATE_SESSION:
2389 send_packet(SSH1_CMSG_WINDOW_SIZE,
2390 PKT_INT, rows, PKT_INT, cols,
2391 PKT_INT, 0, PKT_INT, 0, PKT_END);
2397 * Send Telnet special codes. TS_EOF is useful for `plink', so you
2398 * can send an EOF and collect resulting output (e.g. `plink
2401 static void ssh_special (Telnet_Special code) {
2402 if (code == TS_EOF) {
2403 if (ssh_version = 1) {
2404 send_packet(SSH1_CMSG_EOF, PKT_END);
2406 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
2407 ssh2_pkt_adduint32(ssh_remote_channel);
2417 * Read and decrypt one incoming SSH packet.
2418 * (only used by pSCP)
2420 static void get_packet(void)
2422 unsigned char buf[4096], *p;
2429 while ((to_read = s_rdpkt(&p, &len)) > 0) {
2430 if (to_read > sizeof(buf)) to_read = sizeof(buf);
2431 len = s_read(buf, to_read);
2432 if (len != to_read) {
2444 * Receive a block of data over the SSH link. Block until
2445 * all data is available. Return nr of bytes read (0 if lost connection).
2446 * (only used by pSCP)
2448 int ssh_scp_recv(unsigned char *buf, int len)
2450 static int pending_input_len = 0;
2451 static unsigned char *pending_input_ptr;
2454 if (pending_input_len >= to_read) {
2455 memcpy(buf, pending_input_ptr, to_read);
2456 pending_input_ptr += to_read;
2457 pending_input_len -= to_read;
2461 if (pending_input_len > 0) {
2462 memcpy(buf, pending_input_ptr, pending_input_len);
2463 buf += pending_input_len;
2464 to_read -= pending_input_len;
2465 pending_input_len = 0;
2468 if (s == INVALID_SOCKET)
2470 while (to_read > 0) {
2472 if (s == INVALID_SOCKET)
2474 if (pktin.type == SSH1_SMSG_STDOUT_DATA) {
2475 int plen = GET_32BIT(pktin.body);
2476 if (plen <= to_read) {
2477 memcpy(buf, pktin.body + 4, plen);
2481 memcpy(buf, pktin.body + 4, to_read);
2482 pending_input_len = plen - to_read;
2483 pending_input_ptr = pktin.body + 4 + to_read;
2486 } else if (pktin.type == SSH1_SMSG_STDERR_DATA) {
2487 int plen = GET_32BIT(pktin.body);
2488 fwrite(pktin.body + 4, plen, 1, stderr);
2489 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2490 logevent("Received disconnect request");
2491 } else if (pktin.type == SSH1_SMSG_SUCCESS ||
2492 pktin.type == SSH1_SMSG_FAILURE) {
2494 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2496 sprintf(logbuf, "Remote exit status: %d", GET_32BIT(pktin.body));
2498 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
2499 logevent("Closing connection");
2503 fatalbox("Strange packet received: type %d", pktin.type);
2511 * Send a block of data over the SSH link.
2512 * Block until all data is sent.
2513 * (only used by pSCP)
2515 void ssh_scp_send(unsigned char *buf, int len)
2517 if (s == INVALID_SOCKET)
2519 send_packet(SSH1_CMSG_STDIN_DATA,
2520 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2524 * Send an EOF notification to the server.
2525 * (only used by pSCP)
2527 void ssh_scp_send_eof(void)
2529 if (s == INVALID_SOCKET)
2531 send_packet(SSH1_CMSG_EOF, PKT_END);
2535 * Set up the connection, login on the remote host and
2536 * start execution of a command.
2537 * Returns an error message, or NULL on success.
2538 * (only used by pSCP)
2540 char *ssh_scp_init(char *host, int port, char *cmd, char **realhost)
2545 if (crypto_startup() == 0)
2546 return "Microsoft high encryption pack not installed!";
2549 p = connect_to_host(host, port, realhost);
2556 return "Protocol initialisation error";
2558 /* Exchange keys and login */
2561 if (s == INVALID_SOCKET)
2562 return "Connection closed by remote host";
2563 } while (!do_ssh1_login(NULL, 0, 1));
2565 if (ssh_state == SSH_STATE_CLOSED) {
2568 return "Session initialisation error";
2571 /* Execute command */
2572 sprintf(buf, "Sending command: %.100s", cmd);
2574 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
2579 static SOCKET ssh_socket(void) { return s; }
2581 static int ssh_sendok(void) { return ssh_send_ok; }
2583 Backend ssh_backend = {