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