16 #define SSH_MSG_DISCONNECT 1
17 #define SSH_SMSG_PUBLIC_KEY 2
18 #define SSH_CMSG_SESSION_KEY 3
19 #define SSH_CMSG_USER 4
20 #define SSH_CMSG_AUTH_PASSWORD 9
21 #define SSH_CMSG_REQUEST_PTY 10
22 #define SSH_CMSG_EXEC_SHELL 12
23 #define SSH_CMSG_STDIN_DATA 16
24 #define SSH_SMSG_STDOUT_DATA 17
25 #define SSH_SMSG_STDERR_DATA 18
26 #define SSH_SMSG_SUCCESS 14
27 #define SSH_SMSG_FAILURE 15
28 #define SSH_SMSG_EXITSTATUS 20
29 #define SSH_MSG_IGNORE 32
30 #define SSH_CMSG_EXIT_CONFIRMATION 33
31 #define SSH_MSG_DEBUG 36
32 #define SSH_CMSG_AUTH_TIS 39
33 #define SSH_SMSG_AUTH_TIS_CHALLENGE 40
34 #define SSH_CMSG_AUTH_TIS_RESPONSE 41
36 #define SSH_AUTH_TIS 5
38 /* Coroutine mechanics for the sillier bits of the code */
39 #define crBegin1 static int crLine = 0;
40 #define crBegin2 switch(crLine) { case 0:;
41 #define crBegin crBegin1; crBegin2;
42 #define crFinish(z) } crLine = 0; return (z)
43 #define crFinishV } crLine = 0; return
46 crLine=__LINE__; return (z); case __LINE__:;\
50 crLine=__LINE__; return; case __LINE__:;\
52 #define crStop(z) do{ crLine = 0; return (z); }while(0)
53 #define crStopV do{ crLine = 0; return; }while(0)
62 static SOCKET s = INVALID_SOCKET;
64 static unsigned char session_key[32];
65 static struct ssh_cipher *cipher = NULL;
67 static char *savedhost;
70 SSH_STATE_BEFORE_SIZE,
74 } ssh_state = SSH_STATE_BEFORE_SIZE;
76 static int size_needed = FALSE;
78 static void s_write (char *buf, int len) {
80 int i = send (s, buf, len, 0);
86 static int s_read (char *buf, int len) {
89 int i = recv (s, buf, len, 0);
91 len -= i, buf += i, ret += i;
98 static void c_write (char *buf, int len) {
100 int new_head = (inbuf_head + 1) & INBUF_MASK;
101 if (new_head != inbuf_reap) {
102 inbuf[inbuf_head] = *buf++;
103 inbuf_head = new_head;
106 if( inbuf_head == inbuf_reap ) len++; else break;
120 static struct Packet pktin = { 0, 0, 0, NULL, 0 };
121 static struct Packet pktout = { 0, 0, 0, NULL, 0 };
123 static void ssh_protocol(unsigned char *in, int inlen, int ispkt);
124 static void ssh_size(void);
126 static void ssh_gotdata(unsigned char *data, int datalen) {
127 static long len, biglen, to_read;
128 static unsigned char *p;
133 for (i = len = 0; i < 4; i++) {
136 len = (len << 8) + *data;
141 if (len == 0x52656d6f) { /* "Remo"te server has closed ... */
142 len = 0x300; /* big enough to carry to end */
150 len -= 5; /* type and CRC */
153 if (pktin.maxlen < biglen) {
154 pktin.maxlen = biglen;
155 pktin.data = (pktin.data == NULL ? malloc(biglen) :
156 realloc(pktin.data, biglen));
158 fatalbox("Out of memory");
161 p = pktin.data, to_read = biglen;
162 while (to_read > 0) {
169 memcpy(p, data, chunk);
177 cipher->decrypt(pktin.data, biglen);
179 pktin.type = pktin.data[pad];
180 pktin.body = pktin.data+pad+1;
182 if (pktin.type == SSH_MSG_DEBUG) {
184 } else if (pktin.type == SSH_MSG_IGNORE) {
187 ssh_protocol(NULL, 0, 1);
192 static void s_wrpkt_start(int type, int len) {
195 len += 5; /* type and CRC */
199 pktout.length = len-5;
200 if (pktout.maxlen < biglen) {
201 pktout.maxlen = biglen;
202 pktout.data = (pktout.data == NULL ? malloc(biglen+4) :
203 realloc(pktout.data, biglen+4));
205 fatalbox("Out of memory");
209 pktout.body = pktout.data+4+pad+1;
212 static void s_wrpkt(void) {
213 int pad, len, biglen, i;
216 len = pktout.length + 5; /* type and CRC */
220 pktout.body[-1] = pktout.type;
221 for (i=0; i<pad; i++)
222 pktout.data[i+4] = random_byte();
223 crc = crc32(pktout.data+4, biglen-4);
225 pktout.data[biglen+0] = (unsigned char) ((crc >> 24) & 0xFF);
226 pktout.data[biglen+1] = (unsigned char) ((crc >> 16) & 0xFF);
227 pktout.data[biglen+2] = (unsigned char) ((crc >> 8) & 0xFF);
228 pktout.data[biglen+3] = (unsigned char) (crc & 0xFF);
230 pktout.data[0] = (len >> 24) & 0xFF;
231 pktout.data[1] = (len >> 16) & 0xFF;
232 pktout.data[2] = (len >> 8) & 0xFF;
233 pktout.data[3] = len & 0xFF;
236 cipher->encrypt(pktout.data+4, biglen);
238 s_write(pktout.data, biglen+4);
241 static int ssh_versioncmp(char *a, char *b) {
243 unsigned long av, bv;
245 av = strtoul(a, &ae, 10);
246 bv = strtoul(b, &be, 10);
247 if (av != bv) return (av < bv ? -1 : +1);
248 if (*ae == '.') ae++;
249 if (*be == '.') be++;
250 av = strtoul(ae, &ae, 10);
251 bv = strtoul(be, &be, 10);
252 if (av != bv) return (av < bv ? -1 : +1);
256 static int do_ssh_init(void) {
260 char vlog[sizeof(vstring)+20];
265 while (s_read(&c, 1) == 1) {
266 if (c == 'S' && i < 2) i++;
267 else if (c == 'S' && i == 2) i = 2;
268 else if (c == 'H' && i == 2) break;
272 if (s_read(&c,1) != 1 || c != 'S') return 0;
273 if (s_read(&c,1) != 1 || c != 'S') return 0;
274 if (s_read(&c,1) != 1 || c != 'H') return 0;
276 strcpy(vstring, "SSH-");
278 if (s_read(&c,1) != 1 || c != '-') return 0;
281 if (s_read(&c,1) != 1)
283 if (vsp < vstring+sizeof(vstring)-1)
289 } else if (i < sizeof(version)-1)
297 sprintf(vlog, "Server version: %s", vstring);
298 vlog[strcspn(vlog, "\r\n")] = '\0';
301 sprintf(vstring, "SSH-%s-PuTTY\n",
302 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
303 sprintf(vlog, "We claim version: %s", vstring);
304 vlog[strcspn(vlog, "\r\n")] = '\0';
306 s_write(vstring, strlen(vstring));
310 static void ssh_protocol(unsigned char *in, int inlen, int ispkt) {
312 unsigned char session_id[16];
313 unsigned char *rsabuf, *keystr1, *keystr2;
314 unsigned char cookie[8];
315 struct RSAKey servkey, hostkey;
316 struct MD5Context md5c;
317 static unsigned long supported_ciphers_mask, supported_auths_mask;
320 extern struct ssh_cipher ssh_3des;
321 extern struct ssh_cipher ssh_des;
322 extern struct ssh_cipher ssh_blowfish;
331 if (pktin.type != SSH_SMSG_PUBLIC_KEY)
332 fatalbox("Public key packet not received");
334 logevent("Received public keys");
336 memcpy(cookie, pktin.body, 8);
338 i = makekey(pktin.body+8, &servkey, &keystr1);
340 j = makekey(pktin.body+8+i, &hostkey, &keystr2);
343 * Hash the host key and print the hash in the log box. Just as
344 * a last resort in case the registry's host key checking is
345 * compromised, we'll allow the user some ability to verify
349 MD5Update(&md5c, keystr2, hostkey.bytes);
350 MD5Final(session_id, &md5c);
354 logevent("Host key MD5 is:");
356 for (i = 0; i < 16; i++)
357 sprintf(logmsg+strlen(logmsg), "%02x", session_id[i]);
361 supported_ciphers_mask = ((pktin.body[12+i+j] << 24) |
362 (pktin.body[13+i+j] << 16) |
363 (pktin.body[14+i+j] << 8) |
364 (pktin.body[15+i+j]));
366 supported_auths_mask = ((pktin.body[16+i+j] << 24) |
367 (pktin.body[17+i+j] << 16) |
368 (pktin.body[18+i+j] << 8) |
369 (pktin.body[19+i+j]));
373 MD5Update(&md5c, keystr2, hostkey.bytes);
374 MD5Update(&md5c, keystr1, servkey.bytes);
375 MD5Update(&md5c, pktin.body, 8);
377 MD5Final(session_id, &md5c);
380 session_key[i] = random_byte();
382 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
384 rsabuf = malloc(len);
386 fatalbox("Out of memory");
389 * Verify the host key.
393 * First format the key into a string.
395 int len = rsastr_len(&hostkey);
396 char *keystr = malloc(len);
398 fatalbox("Out of memory");
399 rsastr_fmt(keystr, &hostkey);
400 verify_ssh_host_key(savedhost, keystr);
404 for (i=0; i<32; i++) {
405 rsabuf[i] = session_key[i];
407 rsabuf[i] ^= session_id[i];
410 if (hostkey.bytes > servkey.bytes) {
411 rsaencrypt(rsabuf, 32, &servkey);
412 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
414 rsaencrypt(rsabuf, 32, &hostkey);
415 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
418 logevent("Encrypted session key");
420 cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
421 cfg.cipher == CIPHER_DES ? SSH_CIPHER_DES :
423 if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
424 c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
425 cipher_type = SSH_CIPHER_3DES;
427 switch (cipher_type) {
428 case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
429 case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
430 case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
433 s_wrpkt_start(SSH_CMSG_SESSION_KEY, len+15);
434 pktout.body[0] = cipher_type;
435 memcpy(pktout.body+1, cookie, 8);
436 pktout.body[9] = (len*8) >> 8;
437 pktout.body[10] = (len*8) & 0xFF;
438 memcpy(pktout.body+11, rsabuf, len);
439 pktout.body[len+11] = pktout.body[len+12] = 0; /* protocol flags */
440 pktout.body[len+13] = pktout.body[len+14] = 0;
442 logevent("Trying to enable encryption...");
446 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish :
447 cipher_type == SSH_CIPHER_DES ? &ssh_des :
449 cipher->sesskey(session_key);
451 do { crReturnV; } while (!ispkt);
453 if (pktin.type != SSH_SMSG_SUCCESS)
454 fatalbox("Encryption not successfully enabled");
456 logevent("Successfully started encryption");
460 static char username[100];
463 if (!*cfg.username) {
464 c_write("login as: ", 10);
466 do { crReturnV; } while (ispkt);
467 while (inlen--) switch (c = *in++) {
489 if (c >= ' ' && c <= '~' && pos < 40) {
497 username[strcspn(username, "\n\r")] = '\0';
500 strncpy(username, cfg.username, 99);
502 sprintf(stuff, "Sent username \"%s\".\r\n", username);
503 c_write(stuff, strlen(stuff));
505 s_wrpkt_start(SSH_CMSG_USER, 4+strlen(username));
507 char userlog[20+sizeof(username)];
508 sprintf(userlog, "Sent username \"%s\"", username);
511 pktout.body[0] = pktout.body[1] = pktout.body[2] = 0;
512 pktout.body[3] = strlen(username);
513 memcpy(pktout.body+4, username, strlen(username));
517 do { crReturnV; } while (!ispkt);
519 while (pktin.type == SSH_SMSG_FAILURE) {
520 static char password[100];
523 static int pwpkt_type;
526 * Show password prompt, having first obtained it via a TIS
527 * exchange if we're doing TIS authentication.
529 pwpkt_type = SSH_CMSG_AUTH_PASSWORD;
530 if (pktin.type == SSH_SMSG_FAILURE &&
532 (supported_auths_mask & (1<<SSH_AUTH_TIS))) {
533 pwpkt_type = SSH_CMSG_AUTH_TIS_RESPONSE;
534 logevent("Requested TIS authentication");
535 s_wrpkt_start(SSH_CMSG_AUTH_TIS, 0);
537 do { crReturnV; } while (!ispkt);
538 if (pktin.type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
539 logevent("TIS authentication declined");
540 c_write("TIS authentication refused.\r\n", 29);
542 int challengelen = ((pktin.body[0] << 24) |
543 (pktin.body[1] << 16) |
544 (pktin.body[2] << 8) |
546 logevent("Received TIS challenge");
547 c_write(pktin.body+4, challengelen);
550 if (pwpkt_type == SSH_CMSG_AUTH_PASSWORD)
551 c_write("password: ", 10);
555 do { crReturnV; } while (ispkt);
556 while (inlen--) switch (c = *in++) {
573 if (c >= ' ' && c <= '~' && pos < 40)
579 s_wrpkt_start(pwpkt_type, 4+strlen(password));
580 pktout.body[0] = pktout.body[1] = pktout.body[2] = 0;
581 pktout.body[3] = strlen(password);
582 memcpy(pktout.body+4, password, strlen(password));
584 logevent("Sent password");
585 memset(password, 0, strlen(password));
586 do { crReturnV; } while (!ispkt);
587 if (pktin.type == 15) {
588 c_write("Access denied\r\n", 15);
589 logevent("Authentication refused");
590 } else if (pktin.type != 14) {
591 fatalbox("Strange packet received, type %d", pktin.type);
595 logevent("Authentication successful");
598 i = strlen(cfg.termtype);
599 s_wrpkt_start(SSH_CMSG_REQUEST_PTY, i+5*4+1);
600 pktout.body[0] = (i >> 24) & 0xFF;
601 pktout.body[1] = (i >> 16) & 0xFF;
602 pktout.body[2] = (i >> 8) & 0xFF;
603 pktout.body[3] = i & 0xFF;
604 memcpy(pktout.body+4, cfg.termtype, i);
606 pktout.body[i++] = (rows >> 24) & 0xFF;
607 pktout.body[i++] = (rows >> 16) & 0xFF;
608 pktout.body[i++] = (rows >> 8) & 0xFF;
609 pktout.body[i++] = rows & 0xFF;
610 pktout.body[i++] = (cols >> 24) & 0xFF;
611 pktout.body[i++] = (cols >> 16) & 0xFF;
612 pktout.body[i++] = (cols >> 8) & 0xFF;
613 pktout.body[i++] = cols & 0xFF;
614 memset(pktout.body+i, 0, 9); /* 0 pixwidth, 0 pixheight, 0.b endofopt */
616 ssh_state = SSH_STATE_INTERMED;
617 do { crReturnV; } while (!ispkt);
618 if (pktin.type != SSH_SMSG_SUCCESS && pktin.type != SSH_SMSG_FAILURE) {
619 fatalbox("Protocol confusion");
620 } else if (pktin.type == SSH_SMSG_FAILURE) {
621 c_write("Server refused to allocate pty\r\n", 32);
623 logevent("Allocated pty");
626 s_wrpkt_start(SSH_CMSG_EXEC_SHELL, 0);
628 logevent("Started session");
630 ssh_state = SSH_STATE_SESSION;
637 if (pktin.type == SSH_SMSG_STDOUT_DATA ||
638 pktin.type == SSH_SMSG_STDERR_DATA) {
640 for (i = 0; i < 4; i++)
641 len = (len << 8) + pktin.body[i];
642 c_write(pktin.body+4, len);
643 } else if (pktin.type == SSH_MSG_DISCONNECT) {
644 ssh_state = SSH_STATE_CLOSED;
645 logevent("Received disconnect request");
646 } else if (pktin.type == SSH_SMSG_SUCCESS) {
647 /* may be from EXEC_SHELL on some servers */
648 } else if (pktin.type == SSH_SMSG_FAILURE) {
649 /* may be from EXEC_SHELL on some servers
650 * if no pty is available or in other odd cases. Ignore */
651 } else if (pktin.type == SSH_SMSG_EXITSTATUS) {
652 s_wrpkt_start(SSH_CMSG_EXIT_CONFIRMATION, 0);
655 fatalbox("Strange packet received: type %d", pktin.type);
658 s_wrpkt_start(SSH_CMSG_STDIN_DATA, 4+inlen);
659 pktout.body[0] = (inlen >> 24) & 0xFF;
660 pktout.body[1] = (inlen >> 16) & 0xFF;
661 pktout.body[2] = (inlen >> 8) & 0xFF;
662 pktout.body[3] = inlen & 0xFF;
663 memcpy(pktout.body+4, in, inlen);
672 * Called to set up the connection. Will arrange for WM_NETEVENT
673 * messages to be passed to the specified window, whose window
674 * procedure should then call telnet_msg().
676 * Returns an error message, or NULL on success.
678 * Also places the canonical host name into `realhost'.
680 static char *ssh_init (HWND hwnd, char *host, int port, char **realhost) {
689 savedhost = malloc(1+strlen(host));
691 fatalbox("Out of memory");
692 strcpy(savedhost, host);
704 if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
705 if ( (h = gethostbyname(host)) == NULL)
706 switch (WSAGetLastError()) {
707 case WSAENETDOWN: return "Network is down";
708 case WSAHOST_NOT_FOUND: case WSANO_DATA:
709 return "Host does not exist";
710 case WSATRY_AGAIN: return "Host not found";
711 default: return "gethostbyname: unknown error";
713 memcpy (&a, h->h_addr, sizeof(a));
714 *realhost = h->h_name;
723 port = 22; /* default ssh port */
728 s = socket(AF_INET, SOCK_STREAM, 0);
729 if (s == INVALID_SOCKET)
730 switch (WSAGetLastError()) {
731 case WSAENETDOWN: return "Network is down";
732 case WSAEAFNOSUPPORT: return "TCP/IP support not present";
733 default: return "socket(): unknown error";
737 * Bind to local address.
739 addr.sin_family = AF_INET;
740 addr.sin_addr.s_addr = htonl(INADDR_ANY);
741 addr.sin_port = htons(0);
742 if (bind (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
743 switch (WSAGetLastError()) {
744 case WSAENETDOWN: return "Network is down";
745 default: return "bind(): unknown error";
749 * Connect to remote address.
751 addr.sin_addr.s_addr = htonl(a);
752 addr.sin_port = htons((short)port);
753 if (connect (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
754 switch (WSAGetLastError()) {
755 case WSAENETDOWN: return "Network is down";
756 case WSAECONNREFUSED: return "Connection refused";
757 case WSAENETUNREACH: return "Network is unreachable";
758 case WSAEHOSTUNREACH: return "No route to host";
759 default: return "connect(): unknown error";
763 send(s, "connect ", 8, 0);
764 send(s, FWhost, strlen(FWhost), 0);
767 sprintf(buf, " %d\n", FWport);
768 send (s, buf, strlen(buf), 0);
773 return "Protocol initialisation error";
775 if (WSAAsyncSelect (s, hwnd, WM_NETEVENT, FD_READ | FD_CLOSE) == SOCKET_ERROR)
776 switch (WSAGetLastError()) {
777 case WSAENETDOWN: return "Network is down";
778 default: return "WSAAsyncSelect(): unknown error";
785 * Process a WM_NETEVENT message. Will return 0 if the connection
786 * has closed, or <0 for a socket error.
788 static int ssh_msg (WPARAM wParam, LPARAM lParam) {
793 * Because reading less than the whole of the available pending
794 * data can generate an FD_READ event, we need to allow for the
795 * possibility that FD_READ may arrive with FD_CLOSE already in
796 * the queue; so it's possible that we can get here even with s
797 * invalid. If so, we return 1 and don't worry about it.
799 if (s == INVALID_SOCKET)
802 if (WSAGETSELECTERROR(lParam) != 0)
803 return -WSAGETSELECTERROR(lParam);
805 switch (WSAGETSELECTEVENT(lParam)) {
808 ret = recv(s, buf, sizeof(buf), 0);
809 if (ret < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
811 if (ret < 0) /* any _other_ error */
812 return -10000-WSAGetLastError();
817 ssh_gotdata (buf, ret);
820 return 1; /* shouldn't happen, but WTF */
824 * Called to send data down the Telnet connection.
826 static void ssh_send (char *buf, int len) {
827 if (s == INVALID_SOCKET)
830 ssh_protocol(buf, len, 0);
834 * Called to set the size of the window from Telnet's POV.
836 static void ssh_size(void) {
838 case SSH_STATE_BEFORE_SIZE:
839 case SSH_STATE_CLOSED:
840 break; /* do nothing */
841 case SSH_STATE_INTERMED:
842 size_needed = TRUE; /* buffer for later */
844 case SSH_STATE_SESSION:
846 s_wrpkt_start(11, 16);
847 pktout.body[0] = (rows >> 24) & 0xFF;
848 pktout.body[1] = (rows >> 16) & 0xFF;
849 pktout.body[2] = (rows >> 8) & 0xFF;
850 pktout.body[3] = rows & 0xFF;
851 pktout.body[4] = (cols >> 24) & 0xFF;
852 pktout.body[5] = (cols >> 16) & 0xFF;
853 pktout.body[6] = (cols >> 8) & 0xFF;
854 pktout.body[7] = cols & 0xFF;
855 memset(pktout.body+8, 0, 8);
862 * (Send Telnet special codes)
864 static void ssh_special (Telnet_Special code) {
868 Backend ssh_backend = {