Peter Schellenbach's patch: re-implement the PuTTY cryptographic
[u/mdw/putty] / scpssh.c
1 /*
2 * scpssh.c - SSH implementation for PuTTY Secure Copy
3 * Joris van Rantwijk, Aug 1999.
4 * Based on PuTTY ssh.c by Simon Tatham.
5 */
6
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <winsock.h>
11
12 #include "putty.h"
13 #include "ssh.h"
14 #include "scp.h"
15
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_EXEC_CMD 13
22 #define SSH_SMSG_SUCCESS 14
23 #define SSH_SMSG_FAILURE 15
24 #define SSH_CMSG_STDIN_DATA 16
25 #define SSH_SMSG_STDOUT_DATA 17
26 #define SSH_SMSG_STDERR_DATA 18
27 #define SSH_CMSG_EOF 19
28 #define SSH_SMSG_EXIT_STATUS 20
29 #define SSH_CMSG_EXIT_CONFIRMATION 33
30 #define SSH_MSG_IGNORE 32
31 #define SSH_MSG_DEBUG 36
32
33 #define GET_32BIT(cp) \
34 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
35 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
36 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
37 ((unsigned long)(unsigned char)(cp)[3]))
38
39 #define PUT_32BIT(cp, value) { \
40 (cp)[0] = (unsigned char)((value) >> 24); \
41 (cp)[1] = (unsigned char)((value) >> 16); \
42 (cp)[2] = (unsigned char)((value) >> 8); \
43 (cp)[3] = (unsigned char)(value); }
44
45 static SOCKET s = INVALID_SOCKET;
46
47 static unsigned char session_key[32];
48 static struct ssh_cipher *cipher = NULL;
49
50 static char *savedhost;
51
52 struct Packet {
53 long length;
54 int type;
55 unsigned long crc;
56 unsigned char *data;
57 unsigned char *body;
58 long maxlen;
59 };
60
61 static struct Packet pktin = { 0, 0, 0, NULL, 0 };
62 static struct Packet pktout = { 0, 0, 0, NULL, 0 };
63
64
65 static void s_write (char *buf, int len) {
66 while (len > 0) {
67 int i = send (s, buf, len, 0);
68 noise_ultralight(i);
69 if (i <= 0)
70 fatalbox("Lost connection while sending");
71 len -= i, buf += i;
72 }
73 }
74
75 static int s_read (char *buf, int len) {
76 int ret = 0;
77 while (len > 0) {
78 int i = recv (s, buf, len, 0);
79 noise_ultralight(i);
80 if (i > 0)
81 len -= i, buf += i, ret += i;
82 else
83 return i;
84 }
85 return ret;
86 }
87
88 /*
89 * Read and decrypt one incoming SSH packet.
90 */
91 static void get_packet(void)
92 {
93 unsigned char buf[4];
94 int ret;
95 int len, pad, biglen;
96
97 next_packet:
98
99 pktin.type = 0;
100 pktin.length = 0;
101
102 ret = s_read(buf, 4);
103 if (ret != 4) {
104 closesocket(s);
105 s = INVALID_SOCKET;
106 return;
107 }
108
109 len = GET_32BIT(buf);
110
111 #ifdef FWHACK
112 if (len == 0x52656d6f) {
113 len = 0x300;
114 }
115 #endif
116
117 pad = 8 - (len % 8);
118 biglen = len + pad;
119 len -= 5; /* type and CRC */
120
121 pktin.length = len;
122 if (pktin.maxlen < biglen) {
123 pktin.maxlen = biglen;
124 #ifdef MSCRYPTOAPI
125 /* allocate enough buffer space for extra block
126 * for MS CryptEncrypt() */
127 pktin.data = (pktin.data == NULL) ?
128 smalloc(biglen+8) : srealloc(pktin.data, biglen+8);
129 #else
130 pktin.data = (pktin.data == NULL) ?
131 smalloc(biglen) : srealloc(pktin.data, biglen);
132 #endif
133 }
134
135 ret = s_read(pktin.data, biglen);
136 if (ret != biglen) {
137 closesocket(s);
138 s = INVALID_SOCKET;
139 return;
140 }
141
142 if (cipher)
143 cipher->decrypt(pktin.data, biglen);
144
145 pktin.type = pktin.data[pad];
146 pktin.body = pktin.data + pad + 1;
147
148 if (pktin.type == SSH_MSG_DEBUG) {
149 if (verbose) {
150 int len = GET_32BIT(pktin.body);
151 fprintf(stderr, "Remote: ");
152 fwrite(pktin.body + 4, len, 1, stderr);
153 fprintf(stderr, "\n");
154 }
155 goto next_packet;
156 }
157 if (pktin.type == SSH_MSG_IGNORE) {
158 goto next_packet;
159 }
160 }
161
162 static void s_wrpkt_start(int type, int len) {
163 int pad, biglen;
164
165 len += 5; /* type and CRC */
166 pad = 8 - (len%8);
167 biglen = len + pad;
168
169 pktout.length = len-5;
170 if (pktout.maxlen < biglen) {
171 pktout.maxlen = biglen;
172 #ifdef MSCRYPTOAPI
173 /* Allocate enough buffer space for extra block
174 * for MS CryptEncrypt() */
175 pktout.data = (pktout.data == NULL ? malloc(biglen+8) :
176 realloc(pktout.data, biglen+8));
177 #else
178 pktout.data = (pktout.data == NULL ? malloc(biglen+4) :
179 realloc(pktout.data, biglen+4));
180 #endif
181 if (!pktout.data)
182 fatalbox("Out of memory");
183 }
184
185 pktout.type = type;
186 pktout.body = pktout.data+4+pad+1;
187 }
188
189 static void s_wrpkt(void) {
190 int pad, len, biglen, i;
191 unsigned long crc;
192
193 len = pktout.length + 5; /* type and CRC */
194 pad = 8 - (len%8);
195 biglen = len + pad;
196
197 pktout.body[-1] = pktout.type;
198 for (i=0; i<pad; i++)
199 pktout.data[i+4] = random_byte();
200 crc = crc32(pktout.data+4, biglen-4);
201 PUT_32BIT(pktout.data+biglen, crc);
202 PUT_32BIT(pktout.data, len);
203
204 if (cipher)
205 cipher->encrypt(pktout.data+4, biglen);
206
207 s_write(pktout.data, biglen+4);
208 }
209
210 static int do_ssh_init(void) {
211 char c;
212 char version[10];
213 char vstring[40];
214 int i;
215
216 #ifdef FWHACK
217 i = 0;
218 while (s_read(&c, 1) == 1) {
219 if (c == 'S' && i < 2) i++;
220 else if (c == 'S' && i == 2) i = 2;
221 else if (c == 'H' && i == 2) break;
222 else i = 0;
223 }
224 #else
225 if (s_read(&c,1) != 1 || c != 'S') return 0;
226 if (s_read(&c,1) != 1 || c != 'S') return 0;
227 if (s_read(&c,1) != 1 || c != 'H') return 0;
228 #endif
229 if (s_read(&c,1) != 1 || c != '-') return 0;
230 i = 0;
231 while (1) {
232 if (s_read(&c,1) != 1)
233 return 0;
234 if (i >= 0) {
235 if (c == '-') {
236 version[i] = '\0';
237 i = -1;
238 } else if (i < sizeof(version)-1)
239 version[i++] = c;
240 }
241 else if (c == '\n')
242 break;
243 }
244
245 sprintf(vstring, "SSH-%s-7.7.7\n",
246 (strcmp(version, "1.5") <= 0 ? version : "1.5"));
247 s_write(vstring, strlen(vstring));
248 return 1;
249 }
250
251
252 /*
253 * Login on the server and request execution of the command.
254 */
255 static void ssh_login(char *username, char *cmd)
256 {
257 int i, j, len;
258 unsigned char session_id[16];
259 unsigned char *rsabuf, *keystr1, *keystr2;
260 unsigned char cookie[8];
261 struct RSAKey servkey, hostkey;
262 struct MD5Context md5c;
263 unsigned long supported_ciphers_mask;
264 int cipher_type;
265
266 extern struct ssh_cipher ssh_3des;
267 extern struct ssh_cipher ssh_blowfish;
268
269 get_packet();
270
271 if (pktin.type != SSH_SMSG_PUBLIC_KEY)
272 fatalbox("Public key packet not received");
273
274 memcpy(cookie, pktin.body, 8);
275
276 MD5Init(&md5c);
277
278 i = makekey(pktin.body+8, &servkey, &keystr1);
279 j = makekey(pktin.body+8+i, &hostkey, &keystr2);
280
281 supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
282
283 MD5Update(&md5c, keystr2, hostkey.bytes);
284 MD5Update(&md5c, keystr1, servkey.bytes);
285 MD5Update(&md5c, pktin.body, 8);
286
287 MD5Final(session_id, &md5c);
288
289 for (i=0; i<32; i++)
290 session_key[i] = random_byte();
291
292 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
293
294 rsabuf = malloc(len);
295 if (!rsabuf)
296 fatalbox("Out of memory");
297
298 /*
299 * Verify the host key.
300 */
301 {
302 /*
303 * First format the key into a string.
304 */
305 int len = rsastr_len(&hostkey);
306 char *keystr = malloc(len);
307 if (!keystr)
308 fatalbox("Out of memory");
309 rsastr_fmt(keystr, &hostkey);
310 verify_ssh_host_key(savedhost, keystr);
311 free(keystr);
312 }
313
314 for (i=0; i<32; i++) {
315 rsabuf[i] = session_key[i];
316 if (i < 16)
317 rsabuf[i] ^= session_id[i];
318 }
319
320 if (hostkey.bytes > servkey.bytes) {
321 rsaencrypt(rsabuf, 32, &servkey);
322 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
323 } else {
324 rsaencrypt(rsabuf, 32, &hostkey);
325 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
326 }
327
328 cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
329 SSH_CIPHER_3DES;
330 if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
331 fprintf(stderr, "Selected cipher not supported, falling back to 3DES\n");
332 cipher_type = SSH_CIPHER_3DES;
333 }
334
335 s_wrpkt_start(SSH_CMSG_SESSION_KEY, len+15);
336 pktout.body[0] = cipher_type;
337 memcpy(pktout.body+1, cookie, 8);
338 pktout.body[9] = (len*8) >> 8;
339 pktout.body[10] = (len*8) & 0xFF;
340 memcpy(pktout.body+11, rsabuf, len);
341 pktout.body[len+11] = pktout.body[len+12] = 0; /* protocol flags */
342 pktout.body[len+13] = pktout.body[len+14] = 0;
343 s_wrpkt();
344
345 free(rsabuf);
346
347 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish :
348 &ssh_3des;
349 cipher->sesskey(session_key);
350
351 get_packet();
352
353 if (pktin.type != SSH_SMSG_SUCCESS)
354 fatalbox("Encryption not successfully enabled");
355
356 if (verbose)
357 fprintf(stderr, "Logging in as \"%s\".\n", username);
358 s_wrpkt_start(SSH_CMSG_USER, 4+strlen(username));
359 pktout.body[0] = pktout.body[1] = pktout.body[2] = 0;
360 pktout.body[3] = strlen(username);
361 memcpy(pktout.body+4, username, strlen(username));
362 s_wrpkt();
363
364 get_packet();
365
366 while (pktin.type == SSH_SMSG_FAILURE) {
367 char password[100];
368 char prompt[200];
369 sprintf(prompt, "%s@%s's password: ", username, savedhost);
370 ssh_get_password(prompt, password, 100);
371 s_wrpkt_start(SSH_CMSG_AUTH_PASSWORD, 4+strlen(password));
372 pktout.body[0] = pktout.body[1] = pktout.body[2] = 0;
373 pktout.body[3] = strlen(password);
374 memcpy(pktout.body+4, password, strlen(password));
375 s_wrpkt();
376 memset(password, 0, strlen(password));
377 get_packet();
378 if (pktin.type == SSH_SMSG_FAILURE) {
379 fprintf(stderr, "Access denied\n");
380 } else if (pktin.type != SSH_SMSG_SUCCESS) {
381 fatalbox("Strange packet received, type %d", pktin.type);
382 }
383 }
384
385 /* Execute command */
386 if (verbose)
387 fprintf(stderr, "Sending command: %s\n", cmd);
388 i = strlen(cmd);
389 s_wrpkt_start(SSH_CMSG_EXEC_CMD, 4+i);
390 PUT_32BIT(pktout.body, i);
391 memcpy(pktout.body+4, cmd, i);
392 s_wrpkt();
393 }
394
395
396 /*
397 * Receive a block of data over the SSH link. Block until
398 * all data is available. Return nr of bytes read (0 if lost connection).
399 */
400 int ssh_recv(unsigned char *buf, int len)
401 {
402 static int pending_input_len = 0;
403 static unsigned char *pending_input_ptr;
404 int to_read = len;
405
406 if (pending_input_len >= to_read) {
407 memcpy(buf, pending_input_ptr, to_read);
408 pending_input_ptr += to_read;
409 pending_input_len -= to_read;
410 return len;
411 }
412
413 if (pending_input_len > 0) {
414 memcpy(buf, pending_input_ptr, pending_input_len);
415 buf += pending_input_len;
416 to_read -= pending_input_len;
417 pending_input_len = 0;
418 }
419
420 if (s == INVALID_SOCKET)
421 return 0;
422 while (to_read > 0) {
423 get_packet();
424 if (s == INVALID_SOCKET)
425 return 0;
426 if (pktin.type == SSH_SMSG_STDOUT_DATA) {
427 int plen = GET_32BIT(pktin.body);
428 if (plen <= to_read) {
429 memcpy(buf, pktin.body + 4, plen);
430 buf += plen;
431 to_read -= plen;
432 } else {
433 memcpy(buf, pktin.body + 4, to_read);
434 pending_input_len = plen - to_read;
435 pending_input_ptr = pktin.body + 4 + to_read;
436 to_read = 0;
437 }
438 } else if (pktin.type == SSH_SMSG_STDERR_DATA) {
439 int plen = GET_32BIT(pktin.body);
440 fwrite(pktin.body + 4, plen, 1, stderr);
441 } else if (pktin.type == SSH_MSG_DISCONNECT) {
442 } else if (pktin.type == SSH_SMSG_SUCCESS ||
443 pktin.type == SSH_SMSG_FAILURE) {
444 } else if (pktin.type == SSH_SMSG_EXIT_STATUS) {
445 if (verbose)
446 fprintf(stderr, "Remote exit status %d\n",
447 GET_32BIT(pktin.body));
448 s_wrpkt_start(SSH_CMSG_EXIT_CONFIRMATION, 0);
449 s_wrpkt();
450 if (verbose)
451 fprintf(stderr, "Closing connection\n");
452 closesocket(s);
453 s = INVALID_SOCKET;
454 }
455 }
456
457 return len;
458 }
459
460
461 /*
462 * Send a block of data over the SSH link.
463 * Block until all data is sent.
464 */
465 void ssh_send(unsigned char *buf, int len)
466 {
467 if (s == INVALID_SOCKET)
468 return;
469 s_wrpkt_start(SSH_CMSG_STDIN_DATA, 4 + len);
470 PUT_32BIT(pktout.body, len);
471 memcpy(pktout.body + 4, buf, len);
472 s_wrpkt();
473 }
474
475
476 /*
477 * Send an EOF notification to the server.
478 */
479 void ssh_send_eof(void)
480 {
481 if (s == INVALID_SOCKET)
482 return;
483 s_wrpkt_start(SSH_CMSG_EOF, 0);
484 s_wrpkt();
485 }
486
487
488 /*
489 * Set up the connection, login on the remote host and
490 * start execution of a command.
491 *
492 * Returns an error message, or NULL on success.
493 *
494 * Also places the canonical host name into `realhost'.
495 */
496 char *ssh_init(char *host, int port, char *cmd, char **realhost) {
497 SOCKADDR_IN addr;
498 struct hostent *h;
499 unsigned long a;
500 #ifdef FWHACK
501 char *FWhost;
502 int FWport;
503 #endif
504
505 #ifdef MSCRYPTOAPI
506 if(crypto_startup() == 0)
507 return "Microsoft high encryption pack not installed!";
508 #endif
509
510 savedhost = malloc(1+strlen(host));
511 if (!savedhost)
512 fatalbox("Out of memory");
513 strcpy(savedhost, host);
514
515 #ifdef FWHACK
516 FWhost = host;
517 FWport = port;
518 host = FWSTR;
519 port = 23;
520 #endif
521
522 /*
523 * Try to find host.
524 */
525 if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
526 if ( (h = gethostbyname(host)) == NULL)
527 switch (WSAGetLastError()) {
528 case WSAENETDOWN: return "Network is down";
529 case WSAHOST_NOT_FOUND: case WSANO_DATA:
530 return "Host does not exist";
531 case WSATRY_AGAIN: return "Host not found";
532 default: return "gethostbyname: unknown error";
533 }
534 memcpy (&a, h->h_addr, sizeof(a));
535 *realhost = h->h_name;
536 } else
537 *realhost = host;
538 #ifdef FWHACK
539 *realhost = FWhost;
540 #endif
541 a = ntohl(a);
542
543 if (port < 0)
544 port = 22; /* default ssh port */
545
546 /*
547 * Open socket.
548 */
549 s = socket(AF_INET, SOCK_STREAM, 0);
550 if (s == INVALID_SOCKET)
551 switch (WSAGetLastError()) {
552 case WSAENETDOWN: return "Network is down";
553 case WSAEAFNOSUPPORT: return "TCP/IP support not present";
554 default: return "socket(): unknown error";
555 }
556
557 /*
558 * Bind to local address.
559 */
560 addr.sin_family = AF_INET;
561 addr.sin_addr.s_addr = htonl(INADDR_ANY);
562 addr.sin_port = htons(0);
563 if (bind (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
564 switch (WSAGetLastError()) {
565 case WSAENETDOWN: return "Network is down";
566 default: return "bind(): unknown error";
567 }
568
569 /*
570 * Connect to remote address.
571 */
572 addr.sin_addr.s_addr = htonl(a);
573 addr.sin_port = htons((short)port);
574 if (connect (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
575 switch (WSAGetLastError()) {
576 case WSAENETDOWN: return "Network is down";
577 case WSAECONNREFUSED: return "Connection refused";
578 case WSAENETUNREACH: return "Network is unreachable";
579 case WSAEHOSTUNREACH: return "No route to host";
580 default: return "connect(): unknown error";
581 }
582
583 #ifdef FWHACK
584 send(s, "connect ", 8, 0);
585 send(s, FWhost, strlen(FWhost), 0);
586 {
587 char buf[20];
588 sprintf(buf, " %d\n", FWport);
589 send (s, buf, strlen(buf), 0);
590 }
591 #endif
592
593 random_init();
594
595 if (!do_ssh_init())
596 return "Protocol initialisation error";
597
598 ssh_login(cfg.username, cmd);
599
600 return NULL;
601 }
602
603 /* end */