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