2 * scpssh.c - SSH implementation for PuTTY Secure Copy
3 * Joris van Rantwijk, Aug 1999.
4 * Based on PuTTY ssh.c by Simon Tatham.
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
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]))
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); }
45 static SOCKET s = INVALID_SOCKET;
47 static unsigned char session_key[32];
48 static struct ssh_cipher *cipher = NULL;
50 static char *savedhost;
61 static struct Packet pktin = { 0, 0, 0, NULL, 0 };
62 static struct Packet pktout = { 0, 0, 0, NULL, 0 };
65 static void s_write (char *buf, int len) {
67 int i = send (s, buf, len, 0);
70 fatalbox("Lost connection while sending");
75 static int s_read (char *buf, int len) {
78 int i = recv (s, buf, len, 0);
81 len -= i, buf += i, ret += i;
89 * Read and decrypt one incoming SSH packet.
91 static void get_packet()
102 ret = s_read(buf, 4);
109 len = GET_32BIT(buf);
112 if (len == 0x52656d6f) {
119 len -= 5; /* type and CRC */
122 if (pktin.maxlen < biglen) {
123 pktin.maxlen = biglen;
124 pktin.data = (pktin.data == NULL) ?
125 smalloc(biglen) : srealloc(pktin.data, biglen);
128 ret = s_read(pktin.data, biglen);
136 cipher->decrypt(pktin.data, biglen);
138 pktin.type = pktin.data[pad];
139 pktin.body = pktin.data + pad + 1;
141 if (pktin.type == SSH_MSG_DEBUG) {
143 int len = GET_32BIT(pktin.body);
144 fprintf(stderr, "Remote: ");
145 fwrite(pktin.body + 4, len, 1, stderr);
146 fprintf(stderr, "\n");
150 if (pktin.type == SSH_MSG_IGNORE) {
155 static void s_wrpkt_start(int type, int len) {
158 len += 5; /* type and CRC */
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));
168 fatalbox("Out of memory");
172 pktout.body = pktout.data+4+pad+1;
175 static void s_wrpkt(void) {
176 int pad, len, biglen, i;
179 len = pktout.length + 5; /* type and CRC */
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);
191 cipher->encrypt(pktout.data+4, biglen);
193 s_write(pktout.data, biglen+4);
196 static int do_ssh_init(void) {
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;
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;
215 if (s_read(&c,1) != 1 || c != '-') return 0;
218 if (s_read(&c,1) != 1)
224 } else if (i < sizeof(version)-1)
231 sprintf(vstring, "SSH-%s-7.7.7\n",
232 (strcmp(version, "1.5") <= 0 ? version : "1.5"));
233 s_write(vstring, strlen(vstring));
239 * Login on the server and request execution of the command.
241 static void ssh_login(char *username, char *cmd)
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;
252 extern struct ssh_cipher ssh_3des;
253 extern struct ssh_cipher ssh_blowfish;
257 if (pktin.type != SSH_SMSG_PUBLIC_KEY)
258 fatalbox("Public key packet not received");
260 memcpy(cookie, pktin.body, 8);
264 i = makekey(pktin.body+8, &servkey, &keystr1);
265 j = makekey(pktin.body+8+i, &hostkey, &keystr2);
267 supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
269 MD5Update(&md5c, keystr2, hostkey.bytes);
270 MD5Update(&md5c, keystr1, servkey.bytes);
271 MD5Update(&md5c, pktin.body, 8);
273 MD5Final(session_id, &md5c);
276 session_key[i] = random_byte();
278 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
280 rsabuf = malloc(len);
282 fatalbox("Out of memory");
284 verify_ssh_host_key(savedhost, &hostkey);
286 for (i=0; i<32; i++) {
287 rsabuf[i] = session_key[i];
289 rsabuf[i] ^= session_id[i];
292 if (hostkey.bytes > servkey.bytes) {
293 rsaencrypt(rsabuf, 32, &servkey);
294 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
296 rsaencrypt(rsabuf, 32, &hostkey);
297 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
300 cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
302 if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
303 fprintf(stderr, "Selected cipher not supported, falling back to 3DES\n");
304 cipher_type = SSH_CIPHER_3DES;
307 s_wrpkt_start(SSH_CMSG_SESSION_KEY, len+15);
308 pktout.body[0] = cipher_type;
309 memcpy(pktout.body+1, cookie, 8);
310 pktout.body[9] = (len*8) >> 8;
311 pktout.body[10] = (len*8) & 0xFF;
312 memcpy(pktout.body+11, rsabuf, len);
313 pktout.body[len+11] = pktout.body[len+12] = 0; /* protocol flags */
314 pktout.body[len+13] = pktout.body[len+14] = 0;
319 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish :
321 cipher->sesskey(session_key);
325 if (pktin.type != SSH_SMSG_SUCCESS)
326 fatalbox("Encryption not successfully enabled");
329 fprintf(stderr, "Logging in as \"%s\".\n", username);
330 s_wrpkt_start(SSH_CMSG_USER, 4+strlen(username));
331 pktout.body[0] = pktout.body[1] = pktout.body[2] = 0;
332 pktout.body[3] = strlen(username);
333 memcpy(pktout.body+4, username, strlen(username));
338 while (pktin.type == SSH_SMSG_FAILURE) {
341 sprintf(prompt, "%s@%s's password: ", username, savedhost);
342 ssh_get_password(prompt, password, 100);
343 s_wrpkt_start(SSH_CMSG_AUTH_PASSWORD, 4+strlen(password));
344 pktout.body[0] = pktout.body[1] = pktout.body[2] = 0;
345 pktout.body[3] = strlen(password);
346 memcpy(pktout.body+4, password, strlen(password));
348 memset(password, 0, strlen(password));
350 if (pktin.type == SSH_SMSG_FAILURE) {
351 fprintf(stderr, "Access denied\n");
352 } else if (pktin.type != SSH_SMSG_SUCCESS) {
353 fatalbox("Strange packet received, type %d", pktin.type);
357 /* Execute command */
359 fprintf(stderr, "Sending command: %s\n", cmd);
361 s_wrpkt_start(SSH_CMSG_EXEC_CMD, 4+i);
362 PUT_32BIT(pktout.body, i);
363 memcpy(pktout.body+4, cmd, i);
369 * Receive a block of data over the SSH link. Block until
370 * all data is available. Return nr of bytes read (0 if lost connection).
372 int ssh_recv(unsigned char *buf, int len)
374 static int pending_input_len = 0;
375 static unsigned char *pending_input_ptr;
378 if (pending_input_len >= to_read) {
379 memcpy(buf, pending_input_ptr, to_read);
380 pending_input_ptr += to_read;
381 pending_input_len -= to_read;
385 if (pending_input_len > 0) {
386 memcpy(buf, pending_input_ptr, pending_input_len);
387 buf += pending_input_len;
388 to_read -= pending_input_len;
389 pending_input_len = 0;
392 if (s == INVALID_SOCKET)
394 while (to_read > 0) {
396 if (s == INVALID_SOCKET)
398 if (pktin.type == SSH_SMSG_STDOUT_DATA) {
399 int plen = GET_32BIT(pktin.body);
400 if (plen <= to_read) {
401 memcpy(buf, pktin.body + 4, plen);
405 memcpy(buf, pktin.body + 4, to_read);
406 pending_input_len = plen - to_read;
407 pending_input_ptr = pktin.body + 4 + to_read;
410 } else if (pktin.type == SSH_SMSG_STDERR_DATA) {
411 int plen = GET_32BIT(pktin.body);
412 fwrite(pktin.body + 4, plen, 1, stderr);
413 } else if (pktin.type == SSH_MSG_DISCONNECT) {
414 } else if (pktin.type == SSH_SMSG_SUCCESS ||
415 pktin.type == SSH_SMSG_FAILURE) {
416 } else if (pktin.type == SSH_SMSG_EXIT_STATUS) {
418 fprintf(stderr, "Remote exit status %d\n",
419 GET_32BIT(pktin.body));
420 s_wrpkt_start(SSH_CMSG_EXIT_CONFIRMATION, 0);
423 fprintf(stderr, "Closing connection\n");
434 * Send a block of data over the SSH link.
435 * Block until all data is sent.
437 void ssh_send(unsigned char *buf, int len)
439 if (s == INVALID_SOCKET)
441 s_wrpkt_start(SSH_CMSG_STDIN_DATA, 4 + len);
442 PUT_32BIT(pktout.body, len);
443 memcpy(pktout.body + 4, buf, len);
449 * Send an EOF notification to the server.
451 void ssh_send_eof(void)
453 if (s == INVALID_SOCKET)
455 s_wrpkt_start(SSH_CMSG_EOF, 0);
461 * Set up the connection, login on the remote host and
462 * start execution of a command.
464 * Returns an error message, or NULL on success.
466 * Also places the canonical host name into `realhost'.
468 char *ssh_init(char *host, int port, char *cmd, char **realhost) {
477 savedhost = malloc(1+strlen(host));
479 fatalbox("Out of memory");
480 strcpy(savedhost, host);
492 if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
493 if ( (h = gethostbyname(host)) == NULL)
494 switch (WSAGetLastError()) {
495 case WSAENETDOWN: return "Network is down";
496 case WSAHOST_NOT_FOUND: case WSANO_DATA:
497 return "Host does not exist";
498 case WSATRY_AGAIN: return "Host not found";
499 default: return "gethostbyname: unknown error";
501 memcpy (&a, h->h_addr, sizeof(a));
502 *realhost = h->h_name;
511 port = 22; /* default ssh port */
516 s = socket(AF_INET, SOCK_STREAM, 0);
517 if (s == INVALID_SOCKET)
518 switch (WSAGetLastError()) {
519 case WSAENETDOWN: return "Network is down";
520 case WSAEAFNOSUPPORT: return "TCP/IP support not present";
521 default: return "socket(): unknown error";
525 * Bind to local address.
527 addr.sin_family = AF_INET;
528 addr.sin_addr.s_addr = htonl(INADDR_ANY);
529 addr.sin_port = htons(0);
530 if (bind (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
531 switch (WSAGetLastError()) {
532 case WSAENETDOWN: return "Network is down";
533 default: return "bind(): unknown error";
537 * Connect to remote address.
539 addr.sin_addr.s_addr = htonl(a);
540 addr.sin_port = htons((short)port);
541 if (connect (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
542 switch (WSAGetLastError()) {
543 case WSAENETDOWN: return "Network is down";
544 case WSAECONNREFUSED: return "Connection refused";
545 case WSAENETUNREACH: return "Network is unreachable";
546 case WSAEHOSTUNREACH: return "No route to host";
547 default: return "connect(): unknown error";
551 send(s, "connect ", 8, 0);
552 send(s, FWhost, strlen(FWhost), 0);
555 sprintf(buf, " %d\n", FWport);
556 send (s, buf, strlen(buf), 0);
563 return "Protocol initialisation error";
565 ssh_login(cfg.username, cmd);