]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - ssh.c
acc89cfcecce26a896466f218379effa1161dc3a
[PuTTY.git] / ssh.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <stdarg.h>
4 #include <assert.h>
5 #include <winsock.h>
6
7 #include "putty.h"
8 #include "ssh.h"
9 #include "scp.h"
10
11 #ifndef FALSE
12 #define FALSE 0
13 #endif
14 #ifndef TRUE
15 #define TRUE 1
16 #endif
17
18 #define logevent(s) { logevent(s); \
19                       if (IS_SCP && (scp_flags & SCP_VERBOSE) != 0) \
20                       fprintf(stderr, "%s\n", s); }
21
22 #define SSH_MSG_DISCONNECT      1
23 #define SSH_SMSG_PUBLIC_KEY     2
24 #define SSH_CMSG_SESSION_KEY    3
25 #define SSH_CMSG_USER           4
26 #define SSH_CMSG_AUTH_PASSWORD  9
27 #define SSH_CMSG_REQUEST_PTY    10
28 #define SSH_CMSG_WINDOW_SIZE    11
29 #define SSH_CMSG_EXEC_SHELL     12
30 #define SSH_CMSG_EXEC_CMD       13
31 #define SSH_SMSG_SUCCESS        14
32 #define SSH_SMSG_FAILURE        15
33 #define SSH_CMSG_STDIN_DATA     16
34 #define SSH_SMSG_STDOUT_DATA    17
35 #define SSH_SMSG_STDERR_DATA    18
36 #define SSH_CMSG_EOF            19
37 #define SSH_SMSG_EXIT_STATUS    20
38 #define SSH_CMSG_EXIT_CONFIRMATION      33
39 #define SSH_MSG_IGNORE          32
40 #define SSH_MSG_DEBUG           36
41 #define SSH_CMSG_AUTH_TIS       39
42 #define SSH_SMSG_AUTH_TIS_CHALLENGE     40
43 #define SSH_CMSG_AUTH_TIS_RESPONSE      41
44
45 #define SSH_AUTH_TIS            5
46
47 #define GET_32BIT(cp) \
48     (((unsigned long)(unsigned char)(cp)[0] << 24) | \
49     ((unsigned long)(unsigned char)(cp)[1] << 16) | \
50     ((unsigned long)(unsigned char)(cp)[2] << 8) | \
51     ((unsigned long)(unsigned char)(cp)[3]))
52
53 #define PUT_32BIT(cp, value) { \
54     (cp)[0] = (unsigned char)((value) >> 24); \
55     (cp)[1] = (unsigned char)((value) >> 16); \
56     (cp)[2] = (unsigned char)((value) >> 8); \
57     (cp)[3] = (unsigned char)(value); }
58
59 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR };
60
61 /* Coroutine mechanics for the sillier bits of the code */
62 #define crBegin1        static int crLine = 0;
63 #define crBegin2        switch(crLine) { case 0:;
64 #define crBegin         crBegin1; crBegin2;
65 #define crFinish(z)     } crLine = 0; return (z)
66 #define crFinishV       } crLine = 0; return
67 #define crReturn(z)     \
68         do {\
69             crLine=__LINE__; return (z); case __LINE__:;\
70         } while (0)
71 #define crReturnV       \
72         do {\
73             crLine=__LINE__; return; case __LINE__:;\
74         } while (0)
75 #define crStop(z)       do{ crLine = 0; return (z); }while(0)
76 #define crStopV         do{ crLine = 0; return; }while(0)
77 #define crWaitUntil(c)  do { crReturn(0); } while (!(c))
78
79 static SOCKET s = INVALID_SOCKET;
80
81 static unsigned char session_key[32];
82 static struct ssh_cipher *cipher = NULL;
83 int scp_flags = 0;
84 int (*ssh_get_password)(const char *prompt, char *str, int maxlen) = NULL;
85
86 static char *savedhost;
87
88 static enum {
89     SSH_STATE_BEFORE_SIZE,
90     SSH_STATE_INTERMED,
91     SSH_STATE_SESSION,
92     SSH_STATE_CLOSED
93 } ssh_state = SSH_STATE_BEFORE_SIZE;
94
95 static int size_needed = FALSE;
96
97 static void s_write (char *buf, int len) {
98     while (len > 0) {
99         int i = send (s, buf, len, 0);
100         if (IS_SCP) {
101             noise_ultralight(i);
102             if (i <= 0)
103                 fatalbox("Lost connection while sending");
104         }
105         if (i > 0)
106             len -= i, buf += i;
107     }
108 }
109
110 static int s_read (char *buf, int len) {
111     int ret = 0;
112     while (len > 0) {
113         int i = recv (s, buf, len, 0);
114         if (IS_SCP)
115             noise_ultralight(i);
116         if (i > 0)
117             len -= i, buf += i, ret += i;
118         else
119             return i;
120     }
121     return ret;
122 }
123
124 static void c_write (char *buf, int len) {
125     if (IS_SCP) {
126         if (len > 0 && buf[len-1] == '\n') len--;
127         if (len > 0 && buf[len-1] == '\r') len--;
128         if (len > 0) { fwrite(buf, len, 1, stderr); fputc('\n', stderr); }
129         return;
130     }
131     while (len--) {
132         int new_head = (inbuf_head + 1) & INBUF_MASK;
133         if (new_head != inbuf_reap) {
134             inbuf[inbuf_head] = *buf++;
135             inbuf_head = new_head;
136         } else {
137             term_out();
138             if( inbuf_head == inbuf_reap ) len++; else break;
139         }
140     }
141 }
142
143 struct Packet {
144     long length;
145     int type;
146     unsigned char *data;
147     unsigned char *body;
148     long maxlen;
149 };
150
151 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
152 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
153
154 static void ssh_protocol(unsigned char *in, int inlen, int ispkt);
155 static void ssh_size(void);
156
157
158 /*
159  * Collect incoming data in the incoming packet buffer.
160  * Decihper and verify the packet when it is completely read.
161  * Drop SSH_MSG_DEBUG and SSH_MSG_IGNORE packets.
162  * Update the *data and *datalen variables.
163  * Return the additional nr of bytes needed, or 0 when
164  * a complete packet is available.
165  */
166 static int s_rdpkt(unsigned char **data, int *datalen)
167 {
168     static long len, pad, biglen, to_read;
169     static unsigned long realcrc, gotcrc;
170     static unsigned char *p;
171     static int i;
172
173     crBegin;
174
175 next_packet:
176
177     pktin.type = 0;
178     pktin.length = 0;
179
180     for (i = len = 0; i < 4; i++) {
181         while ((*datalen) == 0)
182             crReturn(4-i);
183         len = (len << 8) + **data;
184         (*data)++, (*datalen)--;
185     }
186
187 #ifdef FWHACK
188     if (len == 0x52656d6f) {       /* "Remo"te server has closed ... */
189         len = 0x300;               /* big enough to carry to end */
190     }
191 #endif
192
193     pad = 8 - (len % 8);
194     biglen = len + pad;
195     pktin.length = len - 5;
196
197     if (pktin.maxlen < biglen) {
198         pktin.maxlen = biglen;
199 #ifdef MSCRYPTOAPI
200         /* Allocate enough buffer space for extra block
201          * for MS CryptEncrypt() */
202         pktin.data = (pktin.data == NULL ? malloc(biglen+8) :
203                       realloc(pktin.data, biglen+8));
204 #else
205         pktin.data = (pktin.data == NULL ? malloc(biglen) :
206                       realloc(pktin.data, biglen));
207 #endif
208         if (!pktin.data)
209             fatalbox("Out of memory");
210     }
211
212     to_read = biglen;
213     p = pktin.data;
214     while (to_read > 0) {
215         static int chunk;
216         chunk = to_read;
217         while ((*datalen) == 0)
218             crReturn(to_read);
219         if (chunk > (*datalen))
220             chunk = (*datalen);
221         memcpy(p, *data, chunk);
222         *data += chunk;
223         *datalen -= chunk;
224         p += chunk;
225         to_read -= chunk;
226     }
227
228     if (cipher)
229         cipher->decrypt(pktin.data, biglen);
230
231     pktin.type = pktin.data[pad];
232     pktin.body = pktin.data + pad + 1;
233
234     realcrc = crc32(pktin.data, biglen-4);
235     gotcrc = GET_32BIT(pktin.data+biglen-4);
236     if (gotcrc != realcrc) {
237         fatalbox("Incorrect CRC received on packet");
238     }
239
240     if (pktin.type == SSH_SMSG_STDOUT_DATA ||
241         pktin.type == SSH_SMSG_STDERR_DATA ||
242         pktin.type == SSH_MSG_DEBUG ||
243         pktin.type == SSH_SMSG_AUTH_TIS_CHALLENGE) {
244         long strlen = GET_32BIT(pktin.body);
245         if (strlen + 4 != pktin.length)
246             fatalbox("Received data packet with bogus string length");
247     }
248
249     if (pktin.type == SSH_MSG_DEBUG) {
250         /* log debug message */
251         char buf[80];
252         int strlen = GET_32BIT(pktin.body);
253         strcpy(buf, "Remote: ");
254         if (strlen > 70) strlen = 70;
255         memcpy(buf+8, pktin.body+4, strlen);
256         buf[8+strlen] = '\0';
257         logevent(buf);
258         goto next_packet;
259     } else if (pktin.type == SSH_MSG_IGNORE) {
260         /* do nothing */
261         goto next_packet;
262     }
263
264     crFinish(0);
265 }
266
267 static void ssh_gotdata(unsigned char *data, int datalen)
268 {
269     while (datalen > 0) {
270         if ( s_rdpkt(&data, &datalen) == 0 ) {
271             ssh_protocol(NULL, 0, 1);
272             if (ssh_state == SSH_STATE_CLOSED) {
273                 return;
274             }
275         }
276     }
277 }
278
279
280 static void s_wrpkt_start(int type, int len) {
281     int pad, biglen;
282
283     len += 5;                          /* type and CRC */
284     pad = 8 - (len%8);
285     biglen = len + pad;
286
287     pktout.length = len-5;
288     if (pktout.maxlen < biglen) {
289         pktout.maxlen = biglen;
290 #ifdef MSCRYPTOAPI
291         /* Allocate enough buffer space for extra block
292          * for MS CryptEncrypt() */
293         pktout.data = (pktout.data == NULL ? malloc(biglen+12) :
294                        realloc(pktout.data, biglen+12));
295 #else
296         pktout.data = (pktout.data == NULL ? malloc(biglen+4) :
297                        realloc(pktout.data, biglen+4));
298 #endif
299         if (!pktout.data)
300             fatalbox("Out of memory");
301     }
302
303     pktout.type = type;
304     pktout.body = pktout.data+4+pad+1;
305 }
306
307 static void s_wrpkt(void) {
308     int pad, len, biglen, i;
309     unsigned long crc;
310
311     len = pktout.length + 5;           /* type and CRC */
312     pad = 8 - (len%8);
313     biglen = len + pad;
314
315     pktout.body[-1] = pktout.type;
316     for (i=0; i<pad; i++)
317         pktout.data[i+4] = random_byte();
318     crc = crc32(pktout.data+4, biglen-4);
319     PUT_32BIT(pktout.data+biglen, crc);
320     PUT_32BIT(pktout.data, len);
321
322     if (cipher)
323         cipher->encrypt(pktout.data+4, biglen);
324
325     s_write(pktout.data, biglen+4);
326 }
327
328 /*
329  * Construct a packet with the specified contents and
330  * send it to the server.
331  */
332 static void send_packet(int pkttype, ...)
333 {
334     va_list args;
335     unsigned char *p, *argp, argchar;
336     unsigned long argint;
337     int pktlen, argtype, arglen;
338
339     pktlen = 0;
340     va_start(args, pkttype);
341     while ((argtype = va_arg(args, int)) != PKT_END) {
342         switch (argtype) {
343           case PKT_INT:
344             (void) va_arg(args, int);
345             pktlen += 4;
346             break;
347           case PKT_CHAR:
348             (void) va_arg(args, char);
349             pktlen++;
350             break;
351           case PKT_DATA:
352             (void) va_arg(args, unsigned char *);
353             arglen = va_arg(args, int);
354             pktlen += arglen;
355             break;
356           case PKT_STR:
357             argp = va_arg(args, unsigned char *);
358             arglen = strlen(argp);
359             pktlen += 4 + arglen;
360             break;
361           default:
362             assert(0);
363         }
364     }
365     va_end(args);
366
367     s_wrpkt_start(pkttype, pktlen);
368     p = pktout.body;
369
370     va_start(args, pkttype);
371     while ((argtype = va_arg(args, int)) != PKT_END) {
372         switch (argtype) {
373           case PKT_INT:
374             argint = va_arg(args, int);
375             PUT_32BIT(p, argint);
376             p += 4;
377             break;
378           case PKT_CHAR:
379             argchar = va_arg(args, unsigned char);
380             *p = argchar;
381             p++;
382             break;
383           case PKT_DATA:
384             argp = va_arg(args, unsigned char *);
385             arglen = va_arg(args, int);
386             memcpy(p, argp, arglen);
387             p += arglen;
388             break;
389           case PKT_STR:
390             argp = va_arg(args, unsigned char *);
391             arglen = strlen(argp);
392             PUT_32BIT(p, arglen);
393             memcpy(p + 4, argp, arglen);
394             p += 4 + arglen;
395             break;
396         }
397     }
398     va_end(args);
399
400     s_wrpkt();
401 }
402
403
404 /*
405  * Connect to specified host and port.
406  * Returns an error message, or NULL on success.
407  * Also places the canonical host name into `realhost'.
408  */
409 static char *connect_to_host(char *host, int port, char **realhost)
410 {
411     SOCKADDR_IN addr;
412     struct hostent *h;
413     unsigned long a;
414 #ifdef FWHACK
415     char *FWhost;
416     int FWport;
417 #endif
418
419     savedhost = malloc(1+strlen(host));
420     if (!savedhost)
421         fatalbox("Out of memory");
422     strcpy(savedhost, host);
423
424     if (port < 0)
425         port = 22;                     /* default ssh port */
426
427 #ifdef FWHACK
428     FWhost = host;
429     FWport = port;
430     host = FWSTR;
431     port = 23;
432 #endif
433
434     /*
435      * Try to find host.
436      */
437     if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
438         if ( (h = gethostbyname(host)) == NULL)
439             switch (WSAGetLastError()) {
440               case WSAENETDOWN: return "Network is down";
441               case WSAHOST_NOT_FOUND: case WSANO_DATA:
442                 return "Host does not exist";
443               case WSATRY_AGAIN: return "Host not found";
444               default: return "gethostbyname: unknown error";
445             }
446         memcpy (&a, h->h_addr, sizeof(a));
447         *realhost = h->h_name;
448     } else
449         *realhost = host;
450 #ifdef FWHACK
451     *realhost = FWhost;
452 #endif
453     a = ntohl(a);
454
455     /*
456      * Open socket.
457      */
458     s = socket(AF_INET, SOCK_STREAM, 0);
459     if (s == INVALID_SOCKET)
460         switch (WSAGetLastError()) {
461           case WSAENETDOWN: return "Network is down";
462           case WSAEAFNOSUPPORT: return "TCP/IP support not present";
463           default: return "socket(): unknown error";
464         }
465
466     /*
467      * Bind to local address.
468      */
469     addr.sin_family = AF_INET;
470     addr.sin_addr.s_addr = htonl(INADDR_ANY);
471     addr.sin_port = htons(0);
472     if (bind (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
473         switch (WSAGetLastError()) {
474           case WSAENETDOWN: return "Network is down";
475           default: return "bind(): unknown error";
476         }
477
478     /*
479      * Connect to remote address.
480      */
481     addr.sin_addr.s_addr = htonl(a);
482     addr.sin_port = htons((short)port);
483     if (connect (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
484         switch (WSAGetLastError()) {
485           case WSAENETDOWN: return "Network is down";
486           case WSAECONNREFUSED: return "Connection refused";
487           case WSAENETUNREACH: return "Network is unreachable";
488           case WSAEHOSTUNREACH: return "No route to host";
489           default: return "connect(): unknown error";
490         }
491
492 #ifdef FWHACK
493     send(s, "connect ", 8, 0);
494     send(s, FWhost, strlen(FWhost), 0);
495     {
496         char buf[20];
497         sprintf(buf, " %d\n", FWport);
498         send (s, buf, strlen(buf), 0);
499     }
500 #endif
501
502     return NULL;
503 }
504
505 static int ssh_versioncmp(char *a, char *b) {
506     char *ae, *be;
507     unsigned long av, bv;
508
509     av = strtoul(a, &ae, 10);
510     bv = strtoul(b, &be, 10);
511     if (av != bv) return (av < bv ? -1 : +1);
512     if (*ae == '.') ae++;
513     if (*be == '.') be++;
514     av = strtoul(ae, &ae, 10);
515     bv = strtoul(be, &be, 10);
516     if (av != bv) return (av < bv ? -1 : +1);
517     return 0;
518 }
519
520 static int do_ssh_init(void) {
521     char c, *vsp;
522     char version[10];
523     char vstring[80];
524     char vlog[sizeof(vstring)+20];
525     int i;
526
527 #ifdef FWHACK
528     i = 0;
529     while (s_read(&c, 1) == 1) {
530         if (c == 'S' && i < 2) i++;
531         else if (c == 'S' && i == 2) i = 2;
532         else if (c == 'H' && i == 2) break;
533         else i = 0;
534     }
535 #else
536     if (s_read(&c,1) != 1 || c != 'S') return 0;
537     if (s_read(&c,1) != 1 || c != 'S') return 0;
538     if (s_read(&c,1) != 1 || c != 'H') return 0;
539 #endif
540     strcpy(vstring, "SSH-");
541     vsp = vstring+4;
542     if (s_read(&c,1) != 1 || c != '-') return 0;
543     i = 0;
544     while (1) {
545         if (s_read(&c,1) != 1)
546             return 0;
547         if (vsp < vstring+sizeof(vstring)-1)
548             *vsp++ = c;
549         if (i >= 0) {
550             if (c == '-') {
551                 version[i] = '\0';
552                 i = -1;
553             } else if (i < sizeof(version)-1)
554                 version[i++] = c;
555         }
556         else if (c == '\n')
557             break;
558     }
559
560     *vsp = 0;
561     sprintf(vlog, "Server version: %s", vstring);
562     vlog[strcspn(vlog, "\r\n")] = '\0';
563     logevent(vlog);
564
565     sprintf(vstring, "SSH-%s-PuTTY\n",
566             (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
567     sprintf(vlog, "We claim version: %s", vstring);
568     vlog[strcspn(vlog, "\r\n")] = '\0';
569     logevent(vlog);
570     s_write(vstring, strlen(vstring));
571     return 1;
572 }
573
574 /*
575  * Handle the key exchange and user authentication phases.
576  */
577 static int do_ssh_login(unsigned char *in, int inlen, int ispkt)
578 {
579     int i, j, len;
580     unsigned char session_id[16];
581     unsigned char *rsabuf, *keystr1, *keystr2;
582     unsigned char cookie[8];
583     struct RSAKey servkey, hostkey;
584     struct MD5Context md5c;
585     static unsigned long supported_ciphers_mask, supported_auths_mask;
586     int cipher_type;
587
588     extern struct ssh_cipher ssh_3des;
589     extern struct ssh_cipher ssh_des;
590     extern struct ssh_cipher ssh_blowfish;
591
592     crBegin;
593
594     if (!ispkt) crWaitUntil(ispkt);
595
596     if (pktin.type != SSH_SMSG_PUBLIC_KEY)
597         fatalbox("Public key packet not received");
598
599     logevent("Received public keys");
600
601     memcpy(cookie, pktin.body, 8);
602
603     i = makekey(pktin.body+8, &servkey, &keystr1);
604     j = makekey(pktin.body+8+i, &hostkey, &keystr2);
605
606     /*
607      * Hash the host key and print the hash in the log box. Just as
608      * a last resort in case the registry's host key checking is
609      * compromised, we'll allow the user some ability to verify
610      * host keys by eye.
611      */
612     MD5Init(&md5c);
613     MD5Update(&md5c, keystr2, hostkey.bytes);
614     MD5Final(session_id, &md5c);
615     {
616         char logmsg[80];
617         int i;
618         logevent("Host key MD5 is:");
619         strcpy(logmsg, "      ");
620         for (i = 0; i < 16; i++)
621             sprintf(logmsg+strlen(logmsg), "%02x", session_id[i]);
622         logevent(logmsg);
623     }
624
625     supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
626     supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
627
628     MD5Init(&md5c);
629     MD5Update(&md5c, keystr2, hostkey.bytes);
630     MD5Update(&md5c, keystr1, servkey.bytes);
631     MD5Update(&md5c, pktin.body, 8);
632     MD5Final(session_id, &md5c);
633
634     for (i=0; i<32; i++)
635         session_key[i] = random_byte();
636
637     len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
638
639     rsabuf = malloc(len);
640     if (!rsabuf)
641         fatalbox("Out of memory");
642
643     /*
644      * Verify the host key.
645      */
646     {
647         /*
648          * First format the key into a string.
649          */
650         int len = rsastr_len(&hostkey);
651         char *keystr = malloc(len);
652         if (!keystr)
653             fatalbox("Out of memory");
654         rsastr_fmt(keystr, &hostkey);
655         verify_ssh_host_key(savedhost, keystr);
656         free(keystr);
657     }
658
659     for (i=0; i<32; i++) {
660         rsabuf[i] = session_key[i];
661         if (i < 16)
662             rsabuf[i] ^= session_id[i];
663     }
664
665     if (hostkey.bytes > servkey.bytes) {
666         rsaencrypt(rsabuf, 32, &servkey);
667         rsaencrypt(rsabuf, servkey.bytes, &hostkey);
668     } else {
669         rsaencrypt(rsabuf, 32, &hostkey);
670         rsaencrypt(rsabuf, hostkey.bytes, &servkey);
671     }
672
673     logevent("Encrypted session key");
674
675     cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
676                   cfg.cipher == CIPHER_DES ? SSH_CIPHER_DES : 
677                   SSH_CIPHER_3DES;
678     if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
679         c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
680         cipher_type = SSH_CIPHER_3DES;
681     }
682     switch (cipher_type) {
683       case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
684       case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
685       case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
686     }
687
688     send_packet(SSH_CMSG_SESSION_KEY,
689                 PKT_CHAR, cipher_type,
690                 PKT_DATA, cookie, 8,
691                 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
692                 PKT_DATA, rsabuf, len,
693                 PKT_INT, 0,
694                 PKT_END);
695
696     logevent("Trying to enable encryption...");
697
698     free(rsabuf);
699
700     cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish :
701              cipher_type == SSH_CIPHER_DES ? &ssh_des :
702              &ssh_3des;
703     cipher->sesskey(session_key);
704
705     crWaitUntil(ispkt);
706
707     if (pktin.type != SSH_SMSG_SUCCESS)
708         fatalbox("Encryption not successfully enabled");
709
710     logevent("Successfully started encryption");
711
712     fflush(stdout);
713     {
714         static char username[100];
715         static int pos = 0;
716         static char c;
717         if (!IS_SCP && !*cfg.username) {
718             c_write("login as: ", 10);
719             while (pos >= 0) {
720                 crWaitUntil(!ispkt);
721                 while (inlen--) switch (c = *in++) {
722                   case 10: case 13:
723                     username[pos] = 0;
724                     pos = -1;
725                     break;
726                   case 8: case 127:
727                     if (pos > 0) {
728                         c_write("\b \b", 3);
729                         pos--;
730                     }
731                     break;
732                   case 21: case 27:
733                     while (pos > 0) {
734                         c_write("\b \b", 3);
735                         pos--;
736                     }
737                     break;
738                   case 3: case 4:
739                     random_save_seed();
740                     exit(0);
741                     break;
742                   default:
743                     if (((c >= ' ' && c <= '~') ||
744                          ((unsigned char)c >= 160)) && pos < 40) {
745                         username[pos++] = c;
746                         c_write(&c, 1);
747                     }
748                     break;
749                 }
750             }
751             c_write("\r\n", 2);
752             username[strcspn(username, "\n\r")] = '\0';
753         } else {
754             char stuff[200];
755             strncpy(username, cfg.username, 99);
756             username[99] = '\0';
757             if (!IS_SCP) {
758                 sprintf(stuff, "Sent username \"%s\".\r\n", username);
759                 c_write(stuff, strlen(stuff));
760             }
761         }
762
763         send_packet(SSH_CMSG_USER, PKT_STR, username, PKT_END);
764         {
765             char userlog[20+sizeof(username)];
766             sprintf(userlog, "Sent username \"%s\"", username);
767             logevent(userlog);
768         }
769     }
770
771     crWaitUntil(ispkt);
772
773     while (pktin.type == SSH_SMSG_FAILURE) {
774         static char password[100];
775         static int pos;
776         static char c;
777         static int pwpkt_type;
778
779         /*
780          * Show password prompt, having first obtained it via a TIS
781          * exchange if we're doing TIS authentication.
782          */
783         pwpkt_type = SSH_CMSG_AUTH_PASSWORD;
784
785         if (IS_SCP) {
786             char prompt[200];
787             sprintf(prompt, "%s@%s's password: ", cfg.username, savedhost);
788             if (!ssh_get_password(prompt, password, sizeof(password))) {
789                 /*
790                  * get_password failed to get a password (for
791                  * example because one was supplied on the command
792                  * line which has already failed to work).
793                  * Terminate.
794                  */
795                 logevent("No more passwords to try");
796                 ssh_state = SSH_STATE_CLOSED;
797                 crReturn(1);
798             }
799         } else {
800
801         if (pktin.type == SSH_SMSG_FAILURE &&
802             cfg.try_tis_auth &&
803             (supported_auths_mask & (1<<SSH_AUTH_TIS))) {
804             pwpkt_type = SSH_CMSG_AUTH_TIS_RESPONSE;
805             logevent("Requested TIS authentication");
806             send_packet(SSH_CMSG_AUTH_TIS, PKT_END);
807             crWaitUntil(ispkt);
808             if (pktin.type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
809                 logevent("TIS authentication declined");
810                 c_write("TIS authentication refused.\r\n", 29);
811             } else {
812                 int challengelen = ((pktin.body[0] << 24) |
813                                     (pktin.body[1] << 16) |
814                                     (pktin.body[2] << 8) |
815                                     (pktin.body[3]));
816                 logevent("Received TIS challenge");
817                 c_write(pktin.body+4, challengelen);
818             }
819         }
820         if (pwpkt_type == SSH_CMSG_AUTH_PASSWORD)
821             c_write("password: ", 10);
822
823         pos = 0;
824         while (pos >= 0) {
825             crWaitUntil(!ispkt);
826             while (inlen--) switch (c = *in++) {
827               case 10: case 13:
828                 password[pos] = 0;
829                 pos = -1;
830                 break;
831               case 8: case 127:
832                 if (pos > 0)
833                     pos--;
834                 break;
835               case 21: case 27:
836                 pos = 0;
837                 break;
838               case 3: case 4:
839                 random_save_seed();
840                 exit(0);
841                 break;
842               default:
843                 if (((c >= ' ' && c <= '~') ||
844                      ((unsigned char)c >= 160)) && pos < 40)
845                     password[pos++] = c;
846                 break;
847             }
848         }
849         c_write("\r\n", 2);
850
851         }
852
853         send_packet(pwpkt_type, PKT_STR, password, PKT_END);
854         logevent("Sent password");
855         memset(password, 0, strlen(password));
856         crWaitUntil(ispkt);
857         if (pktin.type == SSH_SMSG_FAILURE) {
858             c_write("Access denied\r\n", 15);
859             logevent("Authentication refused");
860         } else if (pktin.type == SSH_MSG_DISCONNECT) {
861             logevent("Received disconnect request");
862             ssh_state = SSH_STATE_CLOSED;
863             crReturn(1);
864         } else if (pktin.type != SSH_SMSG_SUCCESS) {
865             fatalbox("Strange packet received, type %d", pktin.type);
866         }
867     }
868
869     logevent("Authentication successful");
870
871     crFinish(1);
872 }
873
874 static void ssh_protocol(unsigned char *in, int inlen, int ispkt) {
875     crBegin;
876
877     random_init();
878
879     while (!do_ssh_login(in, inlen, ispkt)) {
880         crReturnV;
881     }
882     if (ssh_state == SSH_STATE_CLOSED)
883         crReturnV;
884
885     if (!cfg.nopty) {
886         send_packet(SSH_CMSG_REQUEST_PTY,
887                     PKT_STR, cfg.termtype,
888                     PKT_INT, rows, PKT_INT, cols,
889                     PKT_INT, 0, PKT_INT, 0,
890                     PKT_CHAR, 0,
891                     PKT_END);
892         ssh_state = SSH_STATE_INTERMED;
893         do { crReturnV; } while (!ispkt);
894         if (pktin.type != SSH_SMSG_SUCCESS && pktin.type != SSH_SMSG_FAILURE) {
895             fatalbox("Protocol confusion");
896         } else if (pktin.type == SSH_SMSG_FAILURE) {
897             c_write("Server refused to allocate pty\r\n", 32);
898         }
899         logevent("Allocated pty");
900     }
901
902     send_packet(SSH_CMSG_EXEC_SHELL, PKT_END);
903     logevent("Started session");
904
905     ssh_state = SSH_STATE_SESSION;
906     if (size_needed)
907         ssh_size();
908
909     while (1) {
910         crReturnV;
911         if (ispkt) {
912             if (pktin.type == SSH_SMSG_STDOUT_DATA ||
913                 pktin.type == SSH_SMSG_STDERR_DATA) {
914                 long len = GET_32BIT(pktin.body);
915                 c_write(pktin.body+4, len);
916             } else if (pktin.type == SSH_MSG_DISCONNECT) {
917                 ssh_state = SSH_STATE_CLOSED;
918                 logevent("Received disconnect request");
919             } else if (pktin.type == SSH_SMSG_SUCCESS) {
920                 /* may be from EXEC_SHELL on some servers */
921             } else if (pktin.type == SSH_SMSG_FAILURE) {
922                 /* may be from EXEC_SHELL on some servers
923                  * if no pty is available or in other odd cases. Ignore */
924             } else if (pktin.type == SSH_SMSG_EXIT_STATUS) {
925                 send_packet(SSH_CMSG_EXIT_CONFIRMATION, PKT_END);
926             } else {
927                 fatalbox("Strange packet received: type %d", pktin.type);
928             }
929         } else {
930             send_packet(SSH_CMSG_STDIN_DATA,
931                         PKT_INT, inlen, PKT_DATA, in, inlen, PKT_END);
932         }
933     }
934
935     crFinishV;
936 }
937
938 /*
939  * Called to set up the connection. Will arrange for WM_NETEVENT
940  * messages to be passed to the specified window, whose window
941  * procedure should then call telnet_msg().
942  *
943  * Returns an error message, or NULL on success.
944  */
945 static char *ssh_init (HWND hwnd, char *host, int port, char **realhost) {
946     char *p;
947         
948 #ifdef MSCRYPTOAPI
949     if(crypto_startup() == 0)
950         return "Microsoft high encryption pack not installed!";
951 #endif
952
953     p = connect_to_host(host, port, realhost);
954     if (p != NULL)
955         return p;
956
957     if (!do_ssh_init())
958         return "Protocol initialisation error";
959
960     if (WSAAsyncSelect (s, hwnd, WM_NETEVENT, FD_READ | FD_CLOSE) == SOCKET_ERROR)
961         switch (WSAGetLastError()) {
962           case WSAENETDOWN: return "Network is down";
963           default: return "WSAAsyncSelect(): unknown error";
964         }
965
966     return NULL;
967 }
968
969 /*
970  * Process a WM_NETEVENT message. Will return 0 if the connection
971  * has closed, or <0 for a socket error.
972  */
973 static int ssh_msg (WPARAM wParam, LPARAM lParam) {
974     int ret;
975     char buf[256];
976
977     /*
978      * Because reading less than the whole of the available pending
979      * data can generate an FD_READ event, we need to allow for the
980      * possibility that FD_READ may arrive with FD_CLOSE already in
981      * the queue; so it's possible that we can get here even with s
982      * invalid. If so, we return 1 and don't worry about it.
983      */
984     if (s == INVALID_SOCKET)
985         return 1;
986
987     if (WSAGETSELECTERROR(lParam) != 0)
988         return -WSAGETSELECTERROR(lParam);
989
990     switch (WSAGETSELECTEVENT(lParam)) {
991       case FD_READ:
992       case FD_CLOSE:
993         ret = recv(s, buf, sizeof(buf), 0);
994         if (ret < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
995             return 1;
996         if (ret < 0)                   /* any _other_ error */
997             return -10000-WSAGetLastError();
998         if (ret == 0) {
999             s = INVALID_SOCKET;
1000             return 0;
1001         }
1002         ssh_gotdata (buf, ret);
1003         if (ssh_state == SSH_STATE_CLOSED) {
1004             closesocket(s);
1005             s = INVALID_SOCKET;
1006             return 0;
1007         }
1008         return 1;
1009     }
1010     return 1;                          /* shouldn't happen, but WTF */
1011 }
1012
1013 /*
1014  * Called to send data down the Telnet connection.
1015  */
1016 static void ssh_send (char *buf, int len) {
1017     if (s == INVALID_SOCKET)
1018         return;
1019
1020     ssh_protocol(buf, len, 0);
1021 }
1022
1023 /*
1024  * Called to set the size of the window from Telnet's POV.
1025  */
1026 static void ssh_size(void) {
1027     switch (ssh_state) {
1028       case SSH_STATE_BEFORE_SIZE:
1029       case SSH_STATE_CLOSED:
1030         break;                         /* do nothing */
1031       case SSH_STATE_INTERMED:
1032         size_needed = TRUE;            /* buffer for later */
1033         break;
1034       case SSH_STATE_SESSION:
1035         if (!cfg.nopty) {
1036             send_packet(SSH_CMSG_WINDOW_SIZE,
1037                         PKT_INT, rows, PKT_INT, cols,
1038                         PKT_INT, 0, PKT_INT, 0, PKT_END);
1039         }
1040     }
1041 }
1042
1043 /*
1044  * (Send Telnet special codes)
1045  */
1046 static void ssh_special (Telnet_Special code) {
1047     /* do nothing */
1048 }
1049
1050
1051 /*
1052  * Read and decrypt one incoming SSH packet.
1053  * (only used by pSCP)
1054  */
1055 static void get_packet(void)
1056 {
1057     unsigned char buf[4096], *p;
1058     long to_read;
1059     int len;
1060
1061     assert(IS_SCP);
1062
1063     p = NULL;
1064     len = 0;
1065
1066     while ((to_read = s_rdpkt(&p, &len)) > 0) {
1067         if (to_read > sizeof(buf)) to_read = sizeof(buf);
1068         len = s_read(buf, to_read);
1069         if (len != to_read) {
1070             closesocket(s);
1071             s = INVALID_SOCKET;
1072             return;
1073         }
1074         p = buf;
1075     }
1076
1077     assert(len == 0);
1078 }
1079
1080 /*
1081  * Receive a block of data over the SSH link. Block until
1082  * all data is available. Return nr of bytes read (0 if lost connection).
1083  * (only used by pSCP)
1084  */
1085 int ssh_scp_recv(unsigned char *buf, int len)
1086 {
1087     static int pending_input_len = 0;
1088     static unsigned char *pending_input_ptr;
1089     int to_read = len;
1090
1091     assert(IS_SCP);
1092
1093     if (pending_input_len >= to_read) {
1094         memcpy(buf, pending_input_ptr, to_read);
1095         pending_input_ptr += to_read;
1096         pending_input_len -= to_read;
1097         return len;
1098     }
1099     
1100     if (pending_input_len > 0) {
1101         memcpy(buf, pending_input_ptr, pending_input_len);
1102         buf += pending_input_len;
1103         to_read -= pending_input_len;
1104         pending_input_len = 0;
1105     }
1106
1107     if (s == INVALID_SOCKET)
1108         return 0;
1109     while (to_read > 0) {
1110         get_packet();
1111         if (s == INVALID_SOCKET)
1112             return 0;
1113         if (pktin.type == SSH_SMSG_STDOUT_DATA) {
1114             int plen = GET_32BIT(pktin.body);
1115             if (plen <= to_read) {
1116                 memcpy(buf, pktin.body + 4, plen);
1117                 buf += plen;
1118                 to_read -= plen;
1119             } else {
1120                 memcpy(buf, pktin.body + 4, to_read);
1121                 pending_input_len = plen - to_read;
1122                 pending_input_ptr = pktin.body + 4 + to_read;
1123                 to_read = 0;
1124             }
1125         } else if (pktin.type == SSH_SMSG_STDERR_DATA) {
1126             int plen = GET_32BIT(pktin.body);
1127             fwrite(pktin.body + 4, plen, 1, stderr);
1128         } else if (pktin.type == SSH_MSG_DISCONNECT) {
1129                 logevent("Received disconnect request");
1130         } else if (pktin.type == SSH_SMSG_SUCCESS ||
1131                    pktin.type == SSH_SMSG_FAILURE) {
1132                 /* ignore */
1133         } else if (pktin.type == SSH_SMSG_EXIT_STATUS) {
1134             char logbuf[100];
1135             sprintf(logbuf, "Remote exit status: %d", GET_32BIT(pktin.body));
1136             logevent(logbuf);
1137             send_packet(SSH_CMSG_EXIT_CONFIRMATION, PKT_END);
1138             logevent("Closing connection");
1139             closesocket(s);
1140             s = INVALID_SOCKET;
1141         } else {
1142             fatalbox("Strange packet received: type %d", pktin.type);
1143         }
1144     }
1145
1146     return len;
1147 }
1148
1149 /*
1150  * Send a block of data over the SSH link.
1151  * Block until all data is sent.
1152  * (only used by pSCP)
1153  */
1154 void ssh_scp_send(unsigned char *buf, int len)
1155 {
1156     assert(IS_SCP);
1157     if (s == INVALID_SOCKET)
1158         return;
1159     send_packet(SSH_CMSG_STDIN_DATA,
1160                 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
1161 }
1162
1163 /*
1164  * Send an EOF notification to the server.
1165  * (only used by pSCP)
1166  */
1167 void ssh_scp_send_eof(void)
1168 {
1169     assert(IS_SCP);
1170     if (s == INVALID_SOCKET)
1171         return;
1172     send_packet(SSH_CMSG_EOF, PKT_END);
1173 }
1174
1175 /*
1176  * Set up the connection, login on the remote host and
1177  * start execution of a command.
1178  * Returns an error message, or NULL on success.
1179  * (only used by pSCP)
1180  */
1181 char *ssh_scp_init(char *host, int port, char *cmd, char **realhost)
1182 {
1183     char buf[160], *p;
1184
1185     assert(IS_SCP);
1186
1187 #ifdef MSCRYPTOAPI
1188     if (crypto_startup() == 0)
1189         return "Microsoft high encryption pack not installed!";
1190 #endif
1191
1192     p = connect_to_host(host, port, realhost);
1193     if (p != NULL)
1194         return p;
1195
1196     random_init();
1197
1198     if (!do_ssh_init())
1199         return "Protocol initialisation error";
1200
1201     /* Exchange keys and login */
1202     do {
1203         get_packet();
1204         if (s == INVALID_SOCKET)
1205             return "Connection closed by remote host";
1206     } while (!do_ssh_login(NULL, 0, 1));
1207
1208     if (ssh_state == SSH_STATE_CLOSED) {
1209         closesocket(s);
1210         s = INVALID_SOCKET;
1211         return "Session initialisation error";
1212     }
1213
1214     /* Execute command */
1215     sprintf(buf, "Sending command: %.100s", cmd);
1216     logevent(buf);
1217     send_packet(SSH_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
1218
1219     return NULL;
1220 }
1221
1222
1223 Backend ssh_backend = {
1224     ssh_init,
1225     ssh_msg,
1226     ssh_send,
1227     ssh_size,
1228     ssh_special
1229 };
1230