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;
1270 { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
1273 p += ssh1_read_bignum(p, &key.exponent);
1274 p += ssh1_read_bignum(p, &key.modulus);
1275 send_packet(SSH1_CMSG_AUTH_RSA,
1276 PKT_BIGNUM, key.modulus, PKT_END);
1278 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1279 logevent("Key refused");
1282 logevent("Received RSA challenge");
1283 ssh1_read_bignum(pktin.body, &challenge);
1285 char *agentreq, *q, *ret;
1287 len = 1 + 4; /* message type, bit count */
1288 len += ssh1_bignum_length(key.exponent);
1289 len += ssh1_bignum_length(key.modulus);
1290 len += ssh1_bignum_length(challenge);
1291 len += 16; /* session id */
1292 len += 4; /* response format */
1293 agentreq = malloc(4 + len);
1294 PUT_32BIT(agentreq, len);
1296 *q++ = SSH_AGENTC_RSA_CHALLENGE;
1297 PUT_32BIT(q, ssh1_bignum_bitcount(key.modulus));
1299 q += ssh1_write_bignum(q, key.exponent);
1300 q += ssh1_write_bignum(q, key.modulus);
1301 q += ssh1_write_bignum(q, challenge);
1302 memcpy(q, session_id, 16); q += 16;
1303 PUT_32BIT(q, 1); /* response format */
1304 agent_query(agentreq, len+4, &ret, &retlen);
1307 if (ret[4] == SSH_AGENT_RSA_RESPONSE) {
1308 logevent("Sending Pageant's response");
1309 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1310 PKT_DATA, ret+5, 16, PKT_END);
1313 if (pktin.type == SSH1_SMSG_SUCCESS) {
1314 logevent("Pageant's response accepted");
1317 logevent("Pageant's response not accepted");
1319 logevent("Pageant failed to answer challenge");
1323 logevent("No reply received from Pageant");
1326 freebn(key.exponent);
1327 freebn(key.modulus);
1336 if (*cfg.keyfile && !tried_publickey)
1337 pwpkt_type = SSH1_CMSG_AUTH_RSA;
1339 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD && !FLAG_WINDOWED) {
1341 sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
1342 if (!ssh_get_password(prompt, password, sizeof(password))) {
1344 * get_password failed to get a password (for
1345 * example because one was supplied on the command
1346 * line which has already failed to work).
1349 logevent("No more passwords to try");
1350 ssh_state = SSH_STATE_CLOSED;
1355 if (pktin.type == SSH1_SMSG_FAILURE &&
1357 (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1358 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1359 logevent("Requested TIS authentication");
1360 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1362 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1363 logevent("TIS authentication declined");
1364 c_write("TIS authentication refused.\r\n", 29);
1366 int challengelen = ((pktin.body[0] << 24) |
1367 (pktin.body[1] << 16) |
1368 (pktin.body[2] << 8) |
1370 logevent("Received TIS challenge");
1371 c_write(pktin.body+4, challengelen);
1374 if (pktin.type == SSH1_SMSG_FAILURE &&
1376 (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
1377 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
1378 logevent("Requested CryptoCard authentication");
1379 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
1381 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
1382 logevent("CryptoCard authentication declined");
1383 c_write("CryptoCard authentication refused.\r\n", 29);
1385 int challengelen = ((pktin.body[0] << 24) |
1386 (pktin.body[1] << 16) |
1387 (pktin.body[2] << 8) |
1389 logevent("Received CryptoCard challenge");
1390 c_write(pktin.body+4, challengelen);
1391 c_write("\r\nResponse : ", 13);
1394 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD)
1395 c_write("password: ", 10);
1396 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1397 if (flags & FLAG_VERBOSE)
1398 c_write("Trying public key authentication.\r\n", 35);
1399 if (!rsakey_encrypted(cfg.keyfile)) {
1400 if (flags & FLAG_VERBOSE)
1401 c_write("No passphrase required.\r\n", 25);
1404 c_write("passphrase: ", 12);
1409 crWaitUntil(!ispkt);
1410 while (inlen--) switch (c = *in++) {
1427 if (((c >= ' ' && c <= '~') ||
1428 ((unsigned char)c >= 160)) && pos < sizeof(password))
1429 password[pos++] = c;
1438 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1440 * Try public key authentication with the specified
1443 static struct RSAKey pubkey;
1444 static Bignum challenge, response;
1446 static unsigned char buffer[32];
1448 tried_publickey = 1;
1449 i = loadrsakey(cfg.keyfile, &pubkey, password);
1451 c_write("Couldn't load public key from ", 30);
1452 c_write(cfg.keyfile, strlen(cfg.keyfile));
1453 c_write(".\r\n", 3);
1454 continue; /* go and try password */
1457 c_write("Wrong passphrase.\r\n", 19);
1458 tried_publickey = 0;
1459 continue; /* try again */
1463 * Send a public key attempt.
1465 send_packet(SSH1_CMSG_AUTH_RSA,
1466 PKT_BIGNUM, pubkey.modulus, PKT_END);
1469 if (pktin.type == SSH1_SMSG_FAILURE) {
1470 if (flags & FLAG_VERBOSE)
1471 c_write("Server refused our public key.\r\n", 32);
1472 continue; /* go and try password */
1474 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE)
1475 fatalbox("Bizarre response to offer of public key");
1476 ssh1_read_bignum(pktin.body, &challenge);
1477 response = rsadecrypt(challenge, &pubkey);
1478 freebn(pubkey.private_exponent); /* burn the evidence */
1480 for (i = 0; i < 32; i += 2) {
1481 buffer[i] = response[16-i/2] >> 8;
1482 buffer[i+1] = response[16-i/2] & 0xFF;
1486 MD5Update(&md5c, buffer, 32);
1487 MD5Update(&md5c, session_id, 16);
1488 MD5Final(buffer, &md5c);
1490 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1491 PKT_DATA, buffer, 16, PKT_END);
1494 if (pktin.type == SSH1_SMSG_FAILURE) {
1495 if (flags & FLAG_VERBOSE)
1496 c_write("Failed to authenticate with our public key.\r\n",
1498 continue; /* go and try password */
1499 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1500 fatalbox("Bizarre response to RSA authentication response");
1503 break; /* we're through! */
1505 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1507 logevent("Sent password");
1508 memset(password, 0, strlen(password));
1510 if (pktin.type == SSH1_SMSG_FAILURE) {
1511 if (flags & FLAG_VERBOSE)
1512 c_write("Access denied\r\n", 15);
1513 logevent("Authentication refused");
1514 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1515 logevent("Received disconnect request");
1516 ssh_state = SSH_STATE_CLOSED;
1518 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1519 fatalbox("Strange packet received, type %d", pktin.type);
1523 logevent("Authentication successful");
1528 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
1533 while (!do_ssh1_login(in, inlen, ispkt)) {
1536 if (ssh_state == SSH_STATE_CLOSED)
1539 if (1 /* FIXME: agent exists && agent forwarding configured */ ) {
1540 logevent("Requesting agent forwarding");
1541 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
1542 do { crReturnV; } while (!ispkt);
1543 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1544 fatalbox("Protocol confusion");
1545 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1546 logevent("Agent forwarding refused");
1548 logevent("Agent forwarding enabled");
1552 send_packet(SSH1_CMSG_REQUEST_PTY,
1553 PKT_STR, cfg.termtype,
1554 PKT_INT, rows, PKT_INT, cols,
1555 PKT_INT, 0, PKT_INT, 0,
1558 ssh_state = SSH_STATE_INTERMED;
1559 do { crReturnV; } while (!ispkt);
1560 if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1561 fatalbox("Protocol confusion");
1562 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1563 c_write("Server refused to allocate pty\r\n", 32);
1565 logevent("Allocated pty");
1568 if (*cfg.remote_cmd)
1569 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
1571 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
1572 logevent("Started session");
1574 ssh_state = SSH_STATE_SESSION;
1579 ssh_channels = newtree234(ssh_channelcmp);
1583 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
1584 pktin.type == SSH1_SMSG_STDERR_DATA) {
1585 long len = GET_32BIT(pktin.body);
1586 c_write(pktin.body+4, len);
1587 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1588 ssh_state = SSH_STATE_CLOSED;
1589 logevent("Received disconnect request");
1590 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
1591 /* Remote side is trying to open a channel to talk to our
1592 * agent. Give them back a local channel number. */
1594 struct ssh_channel *c;
1596 for (c = first234(ssh_channels, &e); c; c = next234(&e)) {
1598 break; /* found a free number */
1601 c = malloc(sizeof(struct ssh_channel));
1602 c->remoteid = GET_32BIT(pktin.body);
1604 c->type = SSH1_SMSG_AGENT_OPEN; /* identify channel type */
1605 add234(ssh_channels, c);
1606 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
1607 PKT_INT, c->remoteid, PKT_INT, c->localid,
1609 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
1610 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
1611 /* Remote side closes a channel. */
1612 int i = GET_32BIT(pktin.body);
1613 struct ssh_channel *c;
1614 c = find234(ssh_channels, &i, ssh_channelfind);
1617 closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
1618 send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
1619 c->closes |= closetype;
1620 if (c->closes == 3) {
1621 del234(ssh_channels, c);
1625 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
1626 /* Data sent down one of our channels. */
1627 int i = GET_32BIT(pktin.body);
1628 int len = GET_32BIT(pktin.body+4);
1629 unsigned char *p = pktin.body+8;
1630 struct ssh_channel *c;
1631 c = find234(ssh_channels, &i, ssh_channelfind);
1634 case SSH1_SMSG_AGENT_OPEN:
1635 /* Data for an agent message. Buffer it. */
1637 if (c->u.a.lensofar < 4) {
1638 int l = min(4 - c->u.a.lensofar, len);
1639 memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
1640 p += l; len -= l; c->u.a.lensofar += l;
1642 if (c->u.a.lensofar == 4) {
1643 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
1644 c->u.a.message = malloc(c->u.a.totallen);
1645 memcpy(c->u.a.message, c->u.a.msglen, 4);
1647 if (c->u.a.lensofar >= 4 && len > 0) {
1648 int l = min(c->u.a.totallen - c->u.a.lensofar, len);
1649 memcpy(c->u.a.message + c->u.a.lensofar, p, l);
1650 p += l; len -= l; c->u.a.lensofar += l;
1652 if (c->u.a.lensofar == c->u.a.totallen) {
1653 void *reply, *sentreply;
1655 agent_query(c->u.a.message, c->u.a.totallen,
1660 /* Fake SSH_AGENT_FAILURE. */
1661 sentreply = "\0\0\0\1\5";
1664 send_packet(SSH1_MSG_CHANNEL_DATA,
1665 PKT_INT, c->remoteid,
1667 PKT_DATA, sentreply, replylen,
1671 free(c->u.a.message);
1672 c->u.a.lensofar = 0;
1678 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
1679 /* may be from EXEC_SHELL on some servers */
1680 } else if (pktin.type == SSH1_SMSG_FAILURE) {
1681 /* may be from EXEC_SHELL on some servers
1682 * if no pty is available or in other odd cases. Ignore */
1683 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
1684 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
1686 fatalbox("Strange packet received: type %d", pktin.type);
1689 send_packet(SSH1_CMSG_STDIN_DATA,
1690 PKT_INT, inlen, PKT_DATA, in, inlen, PKT_END);
1698 * Utility routine for decoding comma-separated strings in KEXINIT.
1700 int in_commasep_string(char *needle, char *haystack, int haylen) {
1701 int needlen = strlen(needle);
1704 * Is it at the start of the string?
1706 if (haylen >= needlen && /* haystack is long enough */
1707 !memcmp(needle, haystack, needlen) && /* initial match */
1708 (haylen == needlen || haystack[needlen] == ',')
1709 /* either , or EOS follows */
1713 * If not, search for the next comma and resume after that.
1714 * If no comma found, terminate.
1716 while (haylen > 0 && *haystack != ',')
1717 haylen--, haystack++;
1720 haylen--, haystack++; /* skip over comma itself */
1725 * SSH2 key creation method.
1727 void ssh2_mkkey(Bignum K, char *H, char chr, char *keyspace) {
1729 /* First 20 bytes. */
1732 SHA_Bytes(&s, H, 20);
1733 SHA_Bytes(&s, &chr, 1);
1734 SHA_Bytes(&s, H, 20);
1735 SHA_Final(&s, keyspace);
1736 /* Next 20 bytes. */
1739 SHA_Bytes(&s, H, 20);
1740 SHA_Bytes(&s, keyspace, 20);
1741 SHA_Final(&s, keyspace+20);
1745 * Handle the SSH2 transport layer.
1747 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
1751 static Bignum e, f, K;
1752 static struct ssh_cipher *cscipher_tobe = NULL;
1753 static struct ssh_cipher *sccipher_tobe = NULL;
1754 static struct ssh_mac *csmac_tobe = NULL;
1755 static struct ssh_mac *scmac_tobe = NULL;
1756 static struct ssh_compress *cscomp_tobe = NULL;
1757 static struct ssh_compress *sccomp_tobe = NULL;
1758 static char *hostkeydata, *sigdata, *keystr;
1759 static int hostkeylen, siglen;
1760 static unsigned char exchange_hash[20];
1761 static unsigned char keyspace[40];
1768 * Construct and send our key exchange packet.
1770 ssh2_pkt_init(SSH2_MSG_KEXINIT);
1771 for (i = 0; i < 16; i++)
1772 ssh2_pkt_addbyte((unsigned char)random_byte());
1773 /* List key exchange algorithms. */
1774 ssh2_pkt_addstring_start();
1775 for (i = 0; i < lenof(kex_algs); i++) {
1776 ssh2_pkt_addstring_str(kex_algs[i]->name);
1777 if (i < lenof(kex_algs)-1)
1778 ssh2_pkt_addstring_str(",");
1780 /* List server host key algorithms. */
1781 ssh2_pkt_addstring_start();
1782 for (i = 0; i < lenof(hostkey_algs); i++) {
1783 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
1784 if (i < lenof(hostkey_algs)-1)
1785 ssh2_pkt_addstring_str(",");
1787 /* List client->server encryption algorithms. */
1788 ssh2_pkt_addstring_start();
1789 for (i = 0; i < lenof(ciphers); i++) {
1790 ssh2_pkt_addstring_str(ciphers[i]->name);
1791 if (i < lenof(ciphers)-1)
1792 ssh2_pkt_addstring_str(",");
1794 /* List server->client encryption algorithms. */
1795 ssh2_pkt_addstring_start();
1796 for (i = 0; i < lenof(ciphers); i++) {
1797 ssh2_pkt_addstring_str(ciphers[i]->name);
1798 if (i < lenof(ciphers)-1)
1799 ssh2_pkt_addstring_str(",");
1801 /* List client->server MAC algorithms. */
1802 ssh2_pkt_addstring_start();
1803 for (i = 0; i < lenof(macs); i++) {
1804 ssh2_pkt_addstring_str(macs[i]->name);
1805 if (i < lenof(macs)-1)
1806 ssh2_pkt_addstring_str(",");
1808 /* List server->client MAC algorithms. */
1809 ssh2_pkt_addstring_start();
1810 for (i = 0; i < lenof(macs); i++) {
1811 ssh2_pkt_addstring_str(macs[i]->name);
1812 if (i < lenof(macs)-1)
1813 ssh2_pkt_addstring_str(",");
1815 /* List client->server compression algorithms. */
1816 ssh2_pkt_addstring_start();
1817 for (i = 0; i < lenof(compressions); i++) {
1818 ssh2_pkt_addstring_str(compressions[i]->name);
1819 if (i < lenof(compressions)-1)
1820 ssh2_pkt_addstring_str(",");
1822 /* List server->client compression algorithms. */
1823 ssh2_pkt_addstring_start();
1824 for (i = 0; i < lenof(compressions); i++) {
1825 ssh2_pkt_addstring_str(compressions[i]->name);
1826 if (i < lenof(compressions)-1)
1827 ssh2_pkt_addstring_str(",");
1829 /* List client->server languages. Empty list. */
1830 ssh2_pkt_addstring_start();
1831 /* List server->client languages. Empty list. */
1832 ssh2_pkt_addstring_start();
1833 /* First KEX packet does _not_ follow, because we're not that brave. */
1834 ssh2_pkt_addbool(FALSE);
1836 ssh2_pkt_adduint32(0);
1837 sha_string(&exhash, pktout.data+5, pktout.length-5);
1840 if (!ispkt) crWaitUntil(ispkt);
1841 sha_string(&exhash, pktin.data+5, pktin.length-5);
1844 * Now examine the other side's KEXINIT to see what we're up
1847 if (pktin.type != SSH2_MSG_KEXINIT) {
1848 fatalbox("expected key exchange packet from server");
1850 kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
1851 csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
1852 pktin.savedpos += 16; /* skip garbage cookie */
1853 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
1854 for (i = 0; i < lenof(kex_algs); i++) {
1855 if (in_commasep_string(kex_algs[i]->name, str, len)) {
1860 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
1861 for (i = 0; i < lenof(hostkey_algs); i++) {
1862 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
1863 hostkey = hostkey_algs[i];
1867 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
1868 for (i = 0; i < lenof(ciphers); i++) {
1869 if (in_commasep_string(ciphers[i]->name, str, len)) {
1870 cscipher_tobe = ciphers[i];
1874 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
1875 for (i = 0; i < lenof(ciphers); i++) {
1876 if (in_commasep_string(ciphers[i]->name, str, len)) {
1877 sccipher_tobe = ciphers[i];
1881 ssh2_pkt_getstring(&str, &len); /* client->server mac */
1882 for (i = 0; i < lenof(macs); i++) {
1883 if (in_commasep_string(macs[i]->name, str, len)) {
1884 csmac_tobe = macs[i];
1888 ssh2_pkt_getstring(&str, &len); /* server->client mac */
1889 for (i = 0; i < lenof(macs); i++) {
1890 if (in_commasep_string(macs[i]->name, str, len)) {
1891 scmac_tobe = macs[i];
1895 ssh2_pkt_getstring(&str, &len); /* client->server compression */
1896 for (i = 0; i < lenof(compressions); i++) {
1897 if (in_commasep_string(compressions[i]->name, str, len)) {
1898 cscomp_tobe = compressions[i];
1902 ssh2_pkt_getstring(&str, &len); /* server->client compression */
1903 for (i = 0; i < lenof(compressions); i++) {
1904 if (in_commasep_string(compressions[i]->name, str, len)) {
1905 sccomp_tobe = compressions[i];
1911 * Currently we only support Diffie-Hellman and DSS, so let's
1912 * bomb out if those aren't selected.
1914 if (kex != &ssh_diffiehellman || hostkey != &ssh_dss)
1915 fatalbox("internal fault: chaos in SSH 2 transport layer");
1918 * Now we begin the fun. Generate and send e for Diffie-Hellman.
1921 ssh2_pkt_init(SSH2_MSG_KEXDH_INIT);
1926 if (pktin.type != SSH2_MSG_KEXDH_REPLY) {
1927 fatalbox("expected key exchange packet from server");
1929 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
1930 f = ssh2_pkt_getmp();
1931 ssh2_pkt_getstring(&sigdata, &siglen);
1935 sha_string(&exhash, hostkeydata, hostkeylen);
1936 sha_mpint(&exhash, e);
1937 sha_mpint(&exhash, f);
1938 sha_mpint(&exhash, K);
1939 SHA_Final(&exhash, exchange_hash);
1942 debug(("Exchange hash is:\r\n"));
1943 for (i = 0; i < 20; i++)
1944 debug((" %02x", exchange_hash[i]));
1948 hostkey->setkey(hostkeydata, hostkeylen);
1949 if (!hostkey->verifysig(sigdata, siglen, exchange_hash, 20))
1950 fatalbox("Server failed host key check");
1953 * Expect SSH2_MSG_NEWKEYS from server.
1956 if (pktin.type != SSH2_MSG_NEWKEYS)
1957 fatalbox("expected new-keys packet from server");
1960 * Authenticate remote host: verify host key. (We've already
1961 * checked the signature of the exchange hash.)
1963 keystr = hostkey->fmtkey();
1964 verify_ssh_host_key(savedhost, keystr);
1968 * Send SSH2_MSG_NEWKEYS.
1970 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
1974 * Create and initialise session keys.
1976 cscipher = cscipher_tobe;
1977 sccipher = sccipher_tobe;
1980 cscomp = cscomp_tobe;
1981 sccomp = sccomp_tobe;
1983 * Set IVs after keys.
1985 ssh2_mkkey(K, exchange_hash, 'C', keyspace); cscipher->setcskey(keyspace);
1986 ssh2_mkkey(K, exchange_hash, 'D', keyspace); cscipher->setsckey(keyspace);
1987 ssh2_mkkey(K, exchange_hash, 'A', keyspace); cscipher->setcsiv(keyspace);
1988 ssh2_mkkey(K, exchange_hash, 'B', keyspace); sccipher->setsciv(keyspace);
1989 ssh2_mkkey(K, exchange_hash, 'E', keyspace); csmac->setcskey(keyspace);
1990 ssh2_mkkey(K, exchange_hash, 'F', keyspace); scmac->setsckey(keyspace);
1993 * Now we're encrypting. Begin returning 1 to the protocol main
1994 * function so that other things can run on top of the
1995 * transport. If we ever see a KEXINIT, we must go back to the
2000 } while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT));
2001 goto begin_key_exchange;
2007 * SSH2: remote identifier for the main session channel.
2009 static unsigned long ssh_remote_channel;
2012 * Handle the SSH2 userauth and connection layers.
2014 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
2016 static unsigned long remote_winsize;
2017 static unsigned long remote_maxpkt;
2022 * Request userauth protocol, and await a response to it.
2024 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
2025 ssh2_pkt_addstring("ssh-userauth");
2027 crWaitUntilV(ispkt);
2028 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT)
2029 fatalbox("Server refused user authentication protocol");
2032 * FIXME: currently we support only password authentication.
2033 * (This places us technically in violation of the SSH2 spec.
2034 * We must fix this.)
2038 * Get a username and a password.
2040 static char username[100];
2041 static char password[100];
2045 if ((flags & FLAG_CONNECTION) && !*cfg.username) {
2046 c_write("login as: ", 10);
2048 crWaitUntilV(!ispkt);
2049 while (inlen--) switch (c = *in++) {
2056 c_write("\b \b", 3);
2062 c_write("\b \b", 3);
2071 if (((c >= ' ' && c <= '~') ||
2072 ((unsigned char)c >= 160)) && pos < 40) {
2073 username[pos++] = c;
2080 username[strcspn(username, "\n\r")] = '\0';
2083 strncpy(username, cfg.username, 99);
2084 username[99] = '\0';
2085 if (flags & FLAG_VERBOSE) {
2086 sprintf(stuff, "Using username \"%s\".\r\n", username);
2087 c_write(stuff, strlen(stuff));
2091 if (!(flags & FLAG_WINDOWED)) {
2093 sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
2094 if (!ssh_get_password(prompt, password, sizeof(password))) {
2096 * get_password failed to get a password (for
2097 * example because one was supplied on the command
2098 * line which has already failed to work).
2101 logevent("No more passwords to try");
2102 ssh_state = SSH_STATE_CLOSED;
2106 c_write("password: ", 10);
2110 crWaitUntilV(!ispkt);
2111 while (inlen--) switch (c = *in++) {
2128 if (((c >= ' ' && c <= '~') ||
2129 ((unsigned char)c >= 160)) && pos < 40)
2130 password[pos++] = c;
2137 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2138 ssh2_pkt_addstring(username);
2139 ssh2_pkt_addstring("ssh-connection"); /* service requested */
2140 ssh2_pkt_addstring("password");
2141 ssh2_pkt_addbool(FALSE);
2142 ssh2_pkt_addstring(password);
2145 crWaitUntilV(ispkt);
2146 if (pktin.type != SSH2_MSG_USERAUTH_SUCCESS) {
2147 c_write("Access denied\r\n", 15);
2148 logevent("Authentication refused");
2154 * Now we're authenticated for the connection protocol. The
2155 * connection protocol will automatically have started at this
2156 * point; there's no need to send SERVICE_REQUEST.
2160 * So now create a channel with a session in it.
2162 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
2163 ssh2_pkt_addstring("session");
2164 ssh2_pkt_adduint32(100); /* as good as any */
2165 ssh2_pkt_adduint32(0xFFFFFFFFUL); /* very big window which we ignore */
2166 ssh2_pkt_adduint32(0xFFFFFFFFUL); /* very big max pkt size */
2168 crWaitUntilV(ispkt);
2169 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
2170 fatalbox("Server refused to open a session");
2171 /* FIXME: error data comes back in FAILURE packet */
2173 if (ssh2_pkt_getuint32() != 100) {
2174 fatalbox("Server's channel confirmation cited wrong channel");
2176 ssh_remote_channel = ssh2_pkt_getuint32();
2177 remote_winsize = ssh2_pkt_getuint32();
2178 remote_maxpkt = ssh2_pkt_getuint32();
2179 logevent("Opened channel for session");
2182 * Now allocate a pty for the session.
2184 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2185 ssh2_pkt_adduint32(ssh_remote_channel); /* recipient channel */
2186 ssh2_pkt_addstring("pty-req");
2187 ssh2_pkt_addbool(1); /* want reply */
2188 ssh2_pkt_addstring(cfg.termtype);
2189 ssh2_pkt_adduint32(cols);
2190 ssh2_pkt_adduint32(rows);
2191 ssh2_pkt_adduint32(0); /* pixel width */
2192 ssh2_pkt_adduint32(0); /* pixel height */
2193 ssh2_pkt_addstring_start();
2194 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
2197 do { /* FIXME: pay attention to these */
2198 crWaitUntilV(ispkt);
2199 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2201 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2202 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2203 fatalbox("Server got confused by pty request");
2205 c_write("Server refused to allocate pty\r\n", 32);
2207 logevent("Allocated pty");
2213 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2214 ssh2_pkt_adduint32(ssh_remote_channel); /* recipient channel */
2215 ssh2_pkt_addstring("shell");
2216 ssh2_pkt_addbool(1); /* want reply */
2218 do { /* FIXME: pay attention to these */
2219 crWaitUntilV(ispkt);
2220 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2221 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2222 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2223 fatalbox("Server got confused by shell request");
2225 fatalbox("Server refused to start a shell");
2227 logevent("Started a shell");
2237 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
2238 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
2241 if (ssh2_pkt_getuint32() != 100)
2242 continue; /* wrong channel */
2243 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
2244 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
2245 continue; /* extended but not stderr */
2246 ssh2_pkt_getstring(&data, &length);
2248 c_write(data, length);
2249 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
2250 ssh_state = SSH_STATE_CLOSED;
2251 logevent("Received disconnect request");
2252 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
2253 continue; /* exit status et al; ignore (FIXME?) */
2254 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2255 continue; /* ignore for now (FIXME!) */
2257 fatalbox("Strange packet received: type %d", pktin.type);
2260 /* FIXME: for now, ignore window size */
2261 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2262 ssh2_pkt_adduint32(ssh_remote_channel);
2263 ssh2_pkt_addstring_start();
2264 ssh2_pkt_addstring_data(in, inlen);
2273 * Handle the top-level SSH2 protocol.
2275 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
2277 if (do_ssh2_transport(in, inlen, ispkt) == 0)
2279 do_ssh2_authconn(in, inlen, ispkt);
2283 * Called to set up the connection. Will arrange for WM_NETEVENT
2284 * messages to be passed to the specified window, whose window
2285 * procedure should then call telnet_msg().
2287 * Returns an error message, or NULL on success.
2289 static char *ssh_init (HWND hwnd, char *host, int port, char **realhost) {
2293 if(crypto_startup() == 0)
2294 return "Microsoft high encryption pack not installed!";
2297 p = connect_to_host(host, port, realhost);
2302 return "Protocol initialisation error";
2304 if (hwnd && WSAAsyncSelect (s, hwnd, WM_NETEVENT, FD_READ | FD_CLOSE) == SOCKET_ERROR)
2305 switch (WSAGetLastError()) {
2306 case WSAENETDOWN: return "Network is down";
2307 default: return "WSAAsyncSelect(): unknown error";
2314 * Process a WM_NETEVENT message. Will return 0 if the connection
2315 * has closed, or <0 for a socket error.
2317 static int ssh_msg (WPARAM wParam, LPARAM lParam) {
2322 * Because reading less than the whole of the available pending
2323 * data can generate an FD_READ event, we need to allow for the
2324 * possibility that FD_READ may arrive with FD_CLOSE already in
2325 * the queue; so it's possible that we can get here even with s
2326 * invalid. If so, we return 1 and don't worry about it.
2328 if (s == INVALID_SOCKET)
2331 if (WSAGETSELECTERROR(lParam) != 0)
2332 return -WSAGETSELECTERROR(lParam);
2334 switch (WSAGETSELECTEVENT(lParam)) {
2337 ret = recv(s, buf, sizeof(buf), 0);
2338 if (ret < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
2340 if (ret < 0) /* any _other_ error */
2341 return -10000-WSAGetLastError();
2346 ssh_gotdata (buf, ret);
2347 if (ssh_state == SSH_STATE_CLOSED) {
2354 return 1; /* shouldn't happen, but WTF */
2358 * Called to send data down the Telnet connection.
2360 static void ssh_send (char *buf, int len) {
2361 if (s == INVALID_SOCKET)
2364 ssh_protocol(buf, len, 0);
2368 * Called to set the size of the window from Telnet's POV.
2370 static void ssh_size(void) {
2371 switch (ssh_state) {
2372 case SSH_STATE_BEFORE_SIZE:
2373 case SSH_STATE_CLOSED:
2374 break; /* do nothing */
2375 case SSH_STATE_INTERMED:
2376 size_needed = TRUE; /* buffer for later */
2378 case SSH_STATE_SESSION:
2380 send_packet(SSH1_CMSG_WINDOW_SIZE,
2381 PKT_INT, rows, PKT_INT, cols,
2382 PKT_INT, 0, PKT_INT, 0, PKT_END);
2388 * Send Telnet special codes. TS_EOF is useful for `plink', so you
2389 * can send an EOF and collect resulting output (e.g. `plink
2392 static void ssh_special (Telnet_Special code) {
2393 if (code == TS_EOF) {
2394 if (ssh_version = 1) {
2395 send_packet(SSH1_CMSG_EOF, PKT_END);
2397 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
2398 ssh2_pkt_adduint32(ssh_remote_channel);
2408 * Read and decrypt one incoming SSH packet.
2409 * (only used by pSCP)
2411 static void get_packet(void)
2413 unsigned char buf[4096], *p;
2420 while ((to_read = s_rdpkt(&p, &len)) > 0) {
2421 if (to_read > sizeof(buf)) to_read = sizeof(buf);
2422 len = s_read(buf, to_read);
2423 if (len != to_read) {
2435 * Receive a block of data over the SSH link. Block until
2436 * all data is available. Return nr of bytes read (0 if lost connection).
2437 * (only used by pSCP)
2439 int ssh_scp_recv(unsigned char *buf, int len)
2441 static int pending_input_len = 0;
2442 static unsigned char *pending_input_ptr;
2445 if (pending_input_len >= to_read) {
2446 memcpy(buf, pending_input_ptr, to_read);
2447 pending_input_ptr += to_read;
2448 pending_input_len -= to_read;
2452 if (pending_input_len > 0) {
2453 memcpy(buf, pending_input_ptr, pending_input_len);
2454 buf += pending_input_len;
2455 to_read -= pending_input_len;
2456 pending_input_len = 0;
2459 if (s == INVALID_SOCKET)
2461 while (to_read > 0) {
2463 if (s == INVALID_SOCKET)
2465 if (pktin.type == SSH1_SMSG_STDOUT_DATA) {
2466 int plen = GET_32BIT(pktin.body);
2467 if (plen <= to_read) {
2468 memcpy(buf, pktin.body + 4, plen);
2472 memcpy(buf, pktin.body + 4, to_read);
2473 pending_input_len = plen - to_read;
2474 pending_input_ptr = pktin.body + 4 + to_read;
2477 } else if (pktin.type == SSH1_SMSG_STDERR_DATA) {
2478 int plen = GET_32BIT(pktin.body);
2479 fwrite(pktin.body + 4, plen, 1, stderr);
2480 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2481 logevent("Received disconnect request");
2482 } else if (pktin.type == SSH1_SMSG_SUCCESS ||
2483 pktin.type == SSH1_SMSG_FAILURE) {
2485 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2487 sprintf(logbuf, "Remote exit status: %d", GET_32BIT(pktin.body));
2489 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
2490 logevent("Closing connection");
2494 fatalbox("Strange packet received: type %d", pktin.type);
2502 * Send a block of data over the SSH link.
2503 * Block until all data is sent.
2504 * (only used by pSCP)
2506 void ssh_scp_send(unsigned char *buf, int len)
2508 if (s == INVALID_SOCKET)
2510 send_packet(SSH1_CMSG_STDIN_DATA,
2511 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2515 * Send an EOF notification to the server.
2516 * (only used by pSCP)
2518 void ssh_scp_send_eof(void)
2520 if (s == INVALID_SOCKET)
2522 send_packet(SSH1_CMSG_EOF, PKT_END);
2526 * Set up the connection, login on the remote host and
2527 * start execution of a command.
2528 * Returns an error message, or NULL on success.
2529 * (only used by pSCP)
2531 char *ssh_scp_init(char *host, int port, char *cmd, char **realhost)
2536 if (crypto_startup() == 0)
2537 return "Microsoft high encryption pack not installed!";
2540 p = connect_to_host(host, port, realhost);
2547 return "Protocol initialisation error";
2549 /* Exchange keys and login */
2552 if (s == INVALID_SOCKET)
2553 return "Connection closed by remote host";
2554 } while (!do_ssh1_login(NULL, 0, 1));
2556 if (ssh_state == SSH_STATE_CLOSED) {
2559 return "Session initialisation error";
2562 /* Execute command */
2563 sprintf(buf, "Sending command: %.100s", cmd);
2565 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
2570 static SOCKET ssh_socket(void) { return s; }
2572 static int ssh_sendok(void) { return ssh_send_ok; }
2574 Backend ssh_backend = {