Annotation of src/usr.bin/ssh/sshconnect.c, Revision 1.48
1.1 deraadt 1: /*
1.39 deraadt 2: * Author: Tatu Ylonen <ylo@cs.hut.fi>
3: * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4: * All rights reserved
5: * Created: Sat Mar 18 22:15:47 1995 ylo
6: * Code to connect to a remote host, and to perform the client side of the
7: * login (authentication) dialog.
8: */
1.1 deraadt 9:
10: #include "includes.h"
1.48 ! markus 11: RCSID("$Id: sshconnect.c,v 1.47 1999/12/20 08:35:36 markus Exp $");
1.1 deraadt 12:
1.3 provos 13: #include <ssl/bn.h>
1.1 deraadt 14: #include "xmalloc.h"
15: #include "rsa.h"
16: #include "ssh.h"
17: #include "packet.h"
18: #include "authfd.h"
19: #include "cipher.h"
20: #include "mpaux.h"
21: #include "uidswap.h"
1.21 markus 22: #include "compat.h"
1.27 markus 23: #include "readconf.h"
1.34 markus 24: #include "fingerprint.h"
1.1 deraadt 25:
1.24 deraadt 26: #include <ssl/md5.h>
1.10 deraadt 27:
1.1 deraadt 28: /* Session id for the current session. */
29: unsigned char session_id[16];
30:
1.43 markus 31: extern Options options;
32:
1.39 deraadt 33: /*
34: * Connect to the given ssh server using a proxy command.
35: */
1.3 provos 36: int
1.41 markus 37: ssh_proxy_connect(const char *host, u_short port, uid_t original_real_uid,
1.3 provos 38: const char *proxy_command)
1.1 deraadt 39: {
1.38 markus 40: Buffer command;
41: const char *cp;
42: char *command_string;
43: int pin[2], pout[2];
44: int pid;
45: char portstring[100];
46:
47: /* Convert the port number into a string. */
1.41 markus 48: snprintf(portstring, sizeof portstring, "%hu", port);
1.38 markus 49:
50: /* Build the final command string in the buffer by making the
51: appropriate substitutions to the given proxy command. */
52: buffer_init(&command);
53: for (cp = proxy_command; *cp; cp++) {
54: if (cp[0] == '%' && cp[1] == '%') {
55: buffer_append(&command, "%", 1);
56: cp++;
57: continue;
58: }
59: if (cp[0] == '%' && cp[1] == 'h') {
60: buffer_append(&command, host, strlen(host));
61: cp++;
62: continue;
63: }
64: if (cp[0] == '%' && cp[1] == 'p') {
65: buffer_append(&command, portstring, strlen(portstring));
66: cp++;
67: continue;
68: }
69: buffer_append(&command, cp, 1);
70: }
71: buffer_append(&command, "\0", 1);
72:
73: /* Get the final command string. */
74: command_string = buffer_ptr(&command);
75:
76: /* Create pipes for communicating with the proxy. */
77: if (pipe(pin) < 0 || pipe(pout) < 0)
78: fatal("Could not create pipes to communicate with the proxy: %.100s",
79: strerror(errno));
80:
81: debug("Executing proxy command: %.500s", command_string);
82:
83: /* Fork and execute the proxy command. */
84: if ((pid = fork()) == 0) {
85: char *argv[10];
86:
87: /* Child. Permanently give up superuser privileges. */
88: permanently_set_uid(original_real_uid);
89:
90: /* Redirect stdin and stdout. */
91: close(pin[1]);
92: if (pin[0] != 0) {
93: if (dup2(pin[0], 0) < 0)
94: perror("dup2 stdin");
95: close(pin[0]);
96: }
97: close(pout[0]);
98: if (dup2(pout[1], 1) < 0)
99: perror("dup2 stdout");
100: /* Cannot be 1 because pin allocated two descriptors. */
101: close(pout[1]);
102:
103: /* Stderr is left as it is so that error messages get
104: printed on the user's terminal. */
105: argv[0] = "/bin/sh";
106: argv[1] = "-c";
107: argv[2] = command_string;
108: argv[3] = NULL;
109:
110: /* Execute the proxy command. Note that we gave up any
111: extra privileges above. */
112: execv("/bin/sh", argv);
113: perror("/bin/sh");
114: exit(1);
115: }
116: /* Parent. */
117: if (pid < 0)
118: fatal("fork failed: %.100s", strerror(errno));
119:
120: /* Close child side of the descriptors. */
121: close(pin[0]);
122: close(pout[1]);
123:
124: /* Free the command name. */
125: buffer_free(&command);
126:
127: /* Set the connection file descriptors. */
128: packet_set_connection(pout[0], pin[1]);
1.1 deraadt 129:
1.38 markus 130: return 1;
1.1 deraadt 131: }
132:
1.39 deraadt 133: /*
134: * Creates a (possibly privileged) socket for use as the ssh connection.
135: */
1.38 markus 136: int
137: ssh_create_socket(uid_t original_real_uid, int privileged)
1.1 deraadt 138: {
1.38 markus 139: int sock;
1.1 deraadt 140:
1.40 markus 141: /*
142: * If we are running as root and want to connect to a privileged
143: * port, bind our own socket to a privileged port.
144: */
1.38 markus 145: if (privileged) {
146: int p = IPPORT_RESERVED - 1;
147:
148: sock = rresvport(&p);
149: if (sock < 0)
150: fatal("rresvport: %.100s", strerror(errno));
151: debug("Allocated local port %d.", p);
152: } else {
1.46 markus 153: /*
154: * Just create an ordinary socket on arbitrary port. We use
155: * the user's uid to create the socket.
156: */
1.38 markus 157: temporarily_use_uid(original_real_uid);
158: sock = socket(AF_INET, SOCK_STREAM, 0);
159: if (sock < 0)
160: fatal("socket: %.100s", strerror(errno));
161: restore_uid();
162: }
163: return sock;
1.1 deraadt 164: }
165:
1.39 deraadt 166: /*
167: * Opens a TCP/IP connection to the remote server on the given host. If
168: * port is 0, the default port will be used. If anonymous is zero,
169: * a privileged port will be allocated to make the connection.
170: * This requires super-user privileges if anonymous is false.
171: * Connection_attempts specifies the maximum number of tries (one per
172: * second). If proxy_command is non-NULL, it specifies the command (with %h
173: * and %p substituted for host and port, respectively) to use to contact
174: * the daemon.
175: */
1.38 markus 176: int
177: ssh_connect(const char *host, struct sockaddr_in * hostaddr,
1.41 markus 178: u_short port, int connection_attempts,
1.38 markus 179: int anonymous, uid_t original_real_uid,
180: const char *proxy_command)
1.1 deraadt 181: {
1.38 markus 182: int sock = -1, attempt, i;
183: int on = 1;
184: struct servent *sp;
185: struct hostent *hp;
186: struct linger linger;
187:
188: debug("ssh_connect: getuid %d geteuid %d anon %d",
189: (int) getuid(), (int) geteuid(), anonymous);
190:
191: /* Get default port if port has not been set. */
192: if (port == 0) {
193: sp = getservbyname(SSH_SERVICE_NAME, "tcp");
194: if (sp)
195: port = ntohs(sp->s_port);
196: else
197: port = SSH_DEFAULT_PORT;
198: }
199: /* If a proxy command is given, connect using it. */
200: if (proxy_command != NULL)
201: return ssh_proxy_connect(host, port, original_real_uid, proxy_command);
202:
203: /* No proxy command. */
204:
205: /* No host lookup made yet. */
206: hp = NULL;
207:
1.46 markus 208: /*
209: * Try to connect several times. On some machines, the first time
210: * will sometimes fail. In general socket code appears to behave
211: * quite magically on many machines.
212: */
1.38 markus 213: for (attempt = 0; attempt < connection_attempts; attempt++) {
214: if (attempt > 0)
215: debug("Trying again...");
216:
217: /* Try to parse the host name as a numeric inet address. */
218: memset(hostaddr, 0, sizeof(hostaddr));
219: hostaddr->sin_family = AF_INET;
220: hostaddr->sin_port = htons(port);
221: hostaddr->sin_addr.s_addr = inet_addr(host);
222: if ((hostaddr->sin_addr.s_addr & 0xffffffff) != 0xffffffff) {
223: /* Valid numeric IP address */
224: debug("Connecting to %.100s port %d.",
225: inet_ntoa(hostaddr->sin_addr), port);
226:
227: /* Create a socket. */
228: sock = ssh_create_socket(original_real_uid,
229: !anonymous && geteuid() == 0 &&
230: port < IPPORT_RESERVED);
231:
1.40 markus 232: /*
233: * Connect to the host. We use the user's uid in the
234: * hope that it will help with the problems of
235: * tcp_wrappers showing the remote uid as root.
236: */
1.38 markus 237: temporarily_use_uid(original_real_uid);
238: if (connect(sock, (struct sockaddr *) hostaddr, sizeof(*hostaddr))
239: >= 0) {
240: /* Successful connect. */
241: restore_uid();
242: break;
243: }
244: debug("connect: %.100s", strerror(errno));
245: restore_uid();
246:
247: /* Destroy the failed socket. */
248: shutdown(sock, SHUT_RDWR);
249: close(sock);
250: } else {
251: /* Not a valid numeric inet address. */
252: /* Map host name to an address. */
253: if (!hp)
254: hp = gethostbyname(host);
255: if (!hp)
256: fatal("Bad host name: %.100s", host);
257: if (!hp->h_addr_list[0])
258: fatal("Host does not have an IP address: %.100s", host);
259:
260: /* Loop through addresses for this host, and try
261: each one in sequence until the connection
262: succeeds. */
263: for (i = 0; hp->h_addr_list[i]; i++) {
264: /* Set the address to connect to. */
265: hostaddr->sin_family = hp->h_addrtype;
266: memcpy(&hostaddr->sin_addr, hp->h_addr_list[i],
267: sizeof(hostaddr->sin_addr));
268:
269: debug("Connecting to %.200s [%.100s] port %d.",
270: host, inet_ntoa(hostaddr->sin_addr), port);
271:
272: /* Create a socket for connecting. */
273: sock = ssh_create_socket(original_real_uid,
274: !anonymous && geteuid() == 0 &&
275: port < IPPORT_RESERVED);
276:
1.40 markus 277: /*
278: * Connect to the host. We use the user's
279: * uid in the hope that it will help with
280: * tcp_wrappers showing the remote uid as
281: * root.
282: */
1.38 markus 283: temporarily_use_uid(original_real_uid);
284: if (connect(sock, (struct sockaddr *) hostaddr,
285: sizeof(*hostaddr)) >= 0) {
286: /* Successful connection. */
287: restore_uid();
288: break;
289: }
290: debug("connect: %.100s", strerror(errno));
291: restore_uid();
292:
1.40 markus 293: /*
294: * Close the failed socket; there appear to
295: * be some problems when reusing a socket for
296: * which connect() has already returned an
297: * error.
298: */
1.38 markus 299: shutdown(sock, SHUT_RDWR);
300: close(sock);
301: }
302: if (hp->h_addr_list[i])
303: break; /* Successful connection. */
304: }
1.1 deraadt 305:
1.38 markus 306: /* Sleep a moment before retrying. */
307: sleep(1);
308: }
309: /* Return failure if we didn't get a successful connection. */
310: if (attempt >= connection_attempts)
311: return 0;
312:
313: debug("Connection established.");
314:
1.40 markus 315: /*
316: * Set socket options. We would like the socket to disappear as soon
317: * as it has been closed for whatever reason.
318: */
319: /* setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
1.38 markus 320: setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (void *) &on, sizeof(on));
321: linger.l_onoff = 1;
322: linger.l_linger = 5;
323: setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
324:
325: /* Set the connection. */
326: packet_set_connection(sock, sock);
1.1 deraadt 327:
1.38 markus 328: return 1;
1.1 deraadt 329: }
330:
1.39 deraadt 331: /*
332: * Checks if the user has an authentication agent, and if so, tries to
333: * authenticate using the agent.
334: */
1.3 provos 335: int
336: try_agent_authentication()
1.1 deraadt 337: {
1.38 markus 338: int status, type;
339: char *comment;
340: AuthenticationConnection *auth;
341: unsigned char response[16];
342: unsigned int i;
343: BIGNUM *e, *n, *challenge;
344:
345: /* Get connection to the agent. */
346: auth = ssh_get_authentication_connection();
347: if (!auth)
348: return 0;
349:
350: e = BN_new();
351: n = BN_new();
352: challenge = BN_new();
353:
354: /* Loop through identities served by the agent. */
355: for (status = ssh_get_first_identity(auth, e, n, &comment);
356: status;
357: status = ssh_get_next_identity(auth, e, n, &comment)) {
358: int plen, clen;
359:
360: /* Try this identity. */
361: debug("Trying RSA authentication via agent with '%.100s'", comment);
362: xfree(comment);
363:
364: /* Tell the server that we are willing to authenticate using this key. */
365: packet_start(SSH_CMSG_AUTH_RSA);
366: packet_put_bignum(n);
367: packet_send();
368: packet_write_wait();
369:
370: /* Wait for server's response. */
371: type = packet_read(&plen);
372:
373: /* The server sends failure if it doesn\'t like our key or
374: does not support RSA authentication. */
375: if (type == SSH_SMSG_FAILURE) {
376: debug("Server refused our key.");
377: continue;
378: }
379: /* Otherwise it should have sent a challenge. */
380: if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
381: packet_disconnect("Protocol error during RSA authentication: %d",
382: type);
383:
384: packet_get_bignum(challenge, &clen);
385:
386: packet_integrity_check(plen, clen, type);
387:
388: debug("Received RSA challenge from server.");
389:
390: /* Ask the agent to decrypt the challenge. */
391: if (!ssh_decrypt_challenge(auth, e, n, challenge,
392: session_id, 1, response)) {
393: /* The agent failed to authenticate this identifier although it
394: advertised it supports this. Just return a wrong value. */
395: log("Authentication agent failed to decrypt challenge.");
396: memset(response, 0, sizeof(response));
397: }
398: debug("Sending response to RSA challenge.");
1.1 deraadt 399:
1.38 markus 400: /* Send the decrypted challenge back to the server. */
401: packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
402: for (i = 0; i < 16; i++)
403: packet_put_char(response[i]);
404: packet_send();
405: packet_write_wait();
406:
407: /* Wait for response from the server. */
408: type = packet_read(&plen);
409:
410: /* The server returns success if it accepted the authentication. */
411: if (type == SSH_SMSG_SUCCESS) {
412: debug("RSA authentication accepted by server.");
413: BN_clear_free(e);
414: BN_clear_free(n);
415: BN_clear_free(challenge);
416: return 1;
417: }
418: /* Otherwise it should return failure. */
419: if (type != SSH_SMSG_FAILURE)
420: packet_disconnect("Protocol error waiting RSA auth response: %d",
421: type);
422: }
423:
424: BN_clear_free(e);
425: BN_clear_free(n);
426: BN_clear_free(challenge);
427:
428: debug("RSA authentication using agent refused.");
429: return 0;
1.1 deraadt 430: }
431:
1.39 deraadt 432: /*
433: * Computes the proper response to a RSA challenge, and sends the response to
434: * the server.
435: */
1.3 provos 436: void
1.38 markus 437: respond_to_rsa_challenge(BIGNUM * challenge, RSA * prv)
1.1 deraadt 438: {
1.38 markus 439: unsigned char buf[32], response[16];
440: MD5_CTX md;
441: int i, len;
442:
443: /* Decrypt the challenge using the private key. */
444: rsa_private_decrypt(challenge, challenge, prv);
445:
446: /* Compute the response. */
447: /* The response is MD5 of decrypted challenge plus session id. */
448: len = BN_num_bytes(challenge);
449: if (len <= 0 || len > sizeof(buf))
450: packet_disconnect("respond_to_rsa_challenge: bad challenge length %d",
451: len);
452:
453: memset(buf, 0, sizeof(buf));
454: BN_bn2bin(challenge, buf + sizeof(buf) - len);
455: MD5_Init(&md);
456: MD5_Update(&md, buf, 32);
457: MD5_Update(&md, session_id, 16);
458: MD5_Final(response, &md);
459:
460: debug("Sending response to host key RSA challenge.");
461:
462: /* Send the response back to the server. */
463: packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
464: for (i = 0; i < 16; i++)
465: packet_put_char(response[i]);
466: packet_send();
467: packet_write_wait();
468:
469: memset(buf, 0, sizeof(buf));
470: memset(response, 0, sizeof(response));
471: memset(&md, 0, sizeof(md));
1.1 deraadt 472: }
473:
1.39 deraadt 474: /*
475: * Checks if the user has authentication file, and if so, tries to authenticate
476: * the user using it.
477: */
1.3 provos 478: int
1.43 markus 479: try_rsa_authentication(const char *authfile)
1.1 deraadt 480: {
1.38 markus 481: BIGNUM *challenge;
482: RSA *private_key;
483: RSA *public_key;
484: char *passphrase, *comment;
485: int type, i;
486: int plen, clen;
487:
488: /* Try to load identification for the authentication key. */
489: public_key = RSA_new();
490: if (!load_public_key(authfile, public_key, &comment)) {
491: RSA_free(public_key);
1.43 markus 492: /* Could not load it. Fail. */
493: return 0;
1.38 markus 494: }
495: debug("Trying RSA authentication with key '%.100s'", comment);
496:
497: /* Tell the server that we are willing to authenticate using this key. */
498: packet_start(SSH_CMSG_AUTH_RSA);
499: packet_put_bignum(public_key->n);
500: packet_send();
501: packet_write_wait();
502:
503: /* We no longer need the public key. */
504: RSA_free(public_key);
505:
506: /* Wait for server's response. */
507: type = packet_read(&plen);
508:
1.40 markus 509: /*
510: * The server responds with failure if it doesn\'t like our key or
511: * doesn\'t support RSA authentication.
512: */
1.38 markus 513: if (type == SSH_SMSG_FAILURE) {
514: debug("Server refused our key.");
515: xfree(comment);
1.43 markus 516: return 0;
1.38 markus 517: }
518: /* Otherwise, the server should respond with a challenge. */
519: if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
520: packet_disconnect("Protocol error during RSA authentication: %d", type);
521:
522: /* Get the challenge from the packet. */
523: challenge = BN_new();
524: packet_get_bignum(challenge, &clen);
525:
526: packet_integrity_check(plen, clen, type);
527:
528: debug("Received RSA challenge from server.");
529:
530: private_key = RSA_new();
1.40 markus 531: /*
532: * Load the private key. Try first with empty passphrase; if it
533: * fails, ask for a passphrase.
534: */
1.38 markus 535: if (!load_private_key(authfile, "", private_key, NULL)) {
536: char buf[300];
537: snprintf(buf, sizeof buf, "Enter passphrase for RSA key '%.100s': ",
1.45 deraadt 538: comment);
1.38 markus 539: if (!options.batch_mode)
540: passphrase = read_passphrase(buf, 0);
541: else {
542: debug("Will not query passphrase for %.100s in batch mode.",
543: comment);
544: passphrase = xstrdup("");
545: }
546:
547: /* Load the authentication file using the pasphrase. */
548: if (!load_private_key(authfile, passphrase, private_key, NULL)) {
549: memset(passphrase, 0, strlen(passphrase));
550: xfree(passphrase);
551: error("Bad passphrase.");
552:
553: /* Send a dummy response packet to avoid protocol error. */
554: packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
555: for (i = 0; i < 16; i++)
556: packet_put_char(0);
557: packet_send();
558: packet_write_wait();
559:
560: /* Expect the server to reject it... */
561: packet_read_expect(&plen, SSH_SMSG_FAILURE);
562: xfree(comment);
563: return 0;
564: }
565: /* Destroy the passphrase. */
566: memset(passphrase, 0, strlen(passphrase));
567: xfree(passphrase);
568: }
569: /* We no longer need the comment. */
570: xfree(comment);
571:
572: /* Compute and send a response to the challenge. */
573: respond_to_rsa_challenge(challenge, private_key);
574:
575: /* Destroy the private key. */
576: RSA_free(private_key);
577:
578: /* We no longer need the challenge. */
579: BN_clear_free(challenge);
580:
581: /* Wait for response from the server. */
582: type = packet_read(&plen);
583: if (type == SSH_SMSG_SUCCESS) {
584: debug("RSA authentication accepted by server.");
585: return 1;
586: }
587: if (type != SSH_SMSG_FAILURE)
588: packet_disconnect("Protocol error waiting RSA auth response: %d", type);
589: debug("RSA authentication refused.");
590: return 0;
1.1 deraadt 591: }
592:
1.39 deraadt 593: /*
594: * Tries to authenticate the user using combined rhosts or /etc/hosts.equiv
595: * authentication and RSA host authentication.
596: */
1.3 provos 597: int
1.38 markus 598: try_rhosts_rsa_authentication(const char *local_user, RSA * host_key)
1.1 deraadt 599: {
1.38 markus 600: int type;
601: BIGNUM *challenge;
602: int plen, clen;
603:
604: debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication.");
605:
606: /* Tell the server that we are willing to authenticate using this key. */
607: packet_start(SSH_CMSG_AUTH_RHOSTS_RSA);
608: packet_put_string(local_user, strlen(local_user));
609: packet_put_int(BN_num_bits(host_key->n));
610: packet_put_bignum(host_key->e);
611: packet_put_bignum(host_key->n);
612: packet_send();
613: packet_write_wait();
614:
615: /* Wait for server's response. */
616: type = packet_read(&plen);
617:
618: /* The server responds with failure if it doesn't admit our
619: .rhosts authentication or doesn't know our host key. */
620: if (type == SSH_SMSG_FAILURE) {
621: debug("Server refused our rhosts authentication or host key.");
622: return 0;
623: }
624: /* Otherwise, the server should respond with a challenge. */
625: if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
626: packet_disconnect("Protocol error during RSA authentication: %d", type);
627:
628: /* Get the challenge from the packet. */
629: challenge = BN_new();
630: packet_get_bignum(challenge, &clen);
631:
632: packet_integrity_check(plen, clen, type);
633:
634: debug("Received RSA challenge for host key from server.");
635:
636: /* Compute a response to the challenge. */
637: respond_to_rsa_challenge(challenge, host_key);
638:
639: /* We no longer need the challenge. */
640: BN_clear_free(challenge);
641:
642: /* Wait for response from the server. */
643: type = packet_read(&plen);
644: if (type == SSH_SMSG_SUCCESS) {
645: debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server.");
646: return 1;
647: }
648: if (type != SSH_SMSG_FAILURE)
649: packet_disconnect("Protocol error waiting RSA auth response: %d", type);
650: debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused.");
651: return 0;
1.1 deraadt 652: }
653:
654: #ifdef KRB4
1.38 markus 655: int
656: try_kerberos_authentication()
1.1 deraadt 657: {
1.38 markus 658: KTEXT_ST auth; /* Kerberos data */
659: char *reply;
660: char inst[INST_SZ];
661: char *realm;
662: CREDENTIALS cred;
663: int r, type, plen;
664: Key_schedule schedule;
665: u_long checksum, cksum;
666: MSG_DAT msg_data;
667: struct sockaddr_in local, foreign;
668: struct stat st;
669:
670: /* Don't do anything if we don't have any tickets. */
671: if (stat(tkt_string(), &st) < 0)
672: return 0;
673:
674: strncpy(inst, (char *) krb_get_phost(get_canonical_hostname()), INST_SZ);
675:
676: realm = (char *) krb_realmofhost(get_canonical_hostname());
677: if (!realm) {
678: debug("Kerberos V4: no realm for %s", get_canonical_hostname());
679: return 0;
680: }
681: /* This can really be anything. */
682: checksum = (u_long) getpid();
683:
684: r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
685: if (r != KSUCCESS) {
686: debug("Kerberos V4 krb_mk_req failed: %s", krb_err_txt[r]);
687: return 0;
688: }
689: /* Get session key to decrypt the server's reply with. */
690: r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
691: if (r != KSUCCESS) {
692: debug("get_cred failed: %s", krb_err_txt[r]);
693: return 0;
694: }
695: des_key_sched((des_cblock *) cred.session, schedule);
696:
697: /* Send authentication info to server. */
698: packet_start(SSH_CMSG_AUTH_KERBEROS);
699: packet_put_string((char *) auth.dat, auth.length);
700: packet_send();
701: packet_write_wait();
702:
703: /* Zero the buffer. */
704: (void) memset(auth.dat, 0, MAX_KTXT_LEN);
705:
706: r = sizeof(local);
707: memset(&local, 0, sizeof(local));
708: if (getsockname(packet_get_connection_in(),
709: (struct sockaddr *) & local, &r) < 0)
710: debug("getsockname failed: %s", strerror(errno));
711:
712: r = sizeof(foreign);
713: memset(&foreign, 0, sizeof(foreign));
714: if (getpeername(packet_get_connection_in(),
715: (struct sockaddr *) & foreign, &r) < 0) {
716: debug("getpeername failed: %s", strerror(errno));
717: fatal_cleanup();
718: }
719: /* Get server reply. */
720: type = packet_read(&plen);
721: switch (type) {
722: case SSH_SMSG_FAILURE:
723: /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
724: debug("Kerberos V4 authentication failed.");
725: return 0;
726: break;
727:
728: case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
729: /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
730: debug("Kerberos V4 authentication accepted.");
731:
732: /* Get server's response. */
733: reply = packet_get_string((unsigned int *) &auth.length);
734: memcpy(auth.dat, reply, auth.length);
735: xfree(reply);
736:
737: packet_integrity_check(plen, 4 + auth.length, type);
738:
1.40 markus 739: /*
740: * If his response isn't properly encrypted with the session
741: * key, and the decrypted checksum fails to match, he's
742: * bogus. Bail out.
743: */
1.38 markus 744: r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session,
745: &foreign, &local, &msg_data);
746: if (r != KSUCCESS) {
747: debug("Kerberos V4 krb_rd_priv failed: %s", krb_err_txt[r]);
748: packet_disconnect("Kerberos V4 challenge failed!");
749: }
750: /* Fetch the (incremented) checksum that we supplied in the request. */
751: (void) memcpy((char *) &cksum, (char *) msg_data.app_data, sizeof(cksum));
752: cksum = ntohl(cksum);
753:
754: /* If it matches, we're golden. */
755: if (cksum == checksum + 1) {
756: debug("Kerberos V4 challenge successful.");
757: return 1;
758: } else
759: packet_disconnect("Kerberos V4 challenge failed!");
760: break;
761:
762: default:
763: packet_disconnect("Protocol error on Kerberos V4 response: %d", type);
764: }
765: return 0;
1.1 deraadt 766: }
1.38 markus 767:
1.1 deraadt 768: #endif /* KRB4 */
769:
770: #ifdef AFS
1.38 markus 771: int
772: send_kerberos_tgt()
1.1 deraadt 773: {
1.38 markus 774: CREDENTIALS *creds;
775: char pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
776: int r, type, plen;
777: unsigned char buffer[8192];
778: struct stat st;
779:
780: /* Don't do anything if we don't have any tickets. */
781: if (stat(tkt_string(), &st) < 0)
782: return 0;
783:
784: creds = xmalloc(sizeof(*creds));
785:
786: if ((r = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm)) != KSUCCESS) {
787: debug("Kerberos V4 tf_fullname failed: %s", krb_err_txt[r]);
788: return 0;
789: }
790: if ((r = krb_get_cred("krbtgt", prealm, prealm, creds)) != GC_OK) {
791: debug("Kerberos V4 get_cred failed: %s", krb_err_txt[r]);
792: return 0;
793: }
794: if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
795: debug("Kerberos V4 ticket expired: %s", TKT_FILE);
796: return 0;
797: }
798: creds_to_radix(creds, buffer);
799: xfree(creds);
800:
801: packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
802: packet_put_string((char *) buffer, strlen(buffer));
803: packet_send();
804: packet_write_wait();
805:
806: type = packet_read(&plen);
1.1 deraadt 807:
1.38 markus 808: if (type == SSH_SMSG_FAILURE)
809: debug("Kerberos TGT for realm %s rejected.", prealm);
810: else if (type != SSH_SMSG_SUCCESS)
811: packet_disconnect("Protocol error on Kerberos TGT response: %d", type);
812:
813: return 1;
1.1 deraadt 814: }
815:
1.38 markus 816: void
817: send_afs_tokens(void)
1.1 deraadt 818: {
1.38 markus 819: CREDENTIALS creds;
820: struct ViceIoctl parms;
821: struct ClearToken ct;
822: int i, type, len, plen;
823: char buf[2048], *p, *server_cell;
824: unsigned char buffer[8192];
825:
826: /* Move over ktc_GetToken, here's something leaner. */
827: for (i = 0; i < 100; i++) { /* just in case */
828: parms.in = (char *) &i;
829: parms.in_size = sizeof(i);
830: parms.out = buf;
831: parms.out_size = sizeof(buf);
832: if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0)
833: break;
834: p = buf;
835:
836: /* Get secret token. */
837: memcpy(&creds.ticket_st.length, p, sizeof(unsigned int));
838: if (creds.ticket_st.length > MAX_KTXT_LEN)
839: break;
840: p += sizeof(unsigned int);
841: memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
842: p += creds.ticket_st.length;
843:
844: /* Get clear token. */
845: memcpy(&len, p, sizeof(len));
846: if (len != sizeof(struct ClearToken))
847: break;
848: p += sizeof(len);
849: memcpy(&ct, p, len);
850: p += len;
851: p += sizeof(len); /* primary flag */
852: server_cell = p;
853:
854: /* Flesh out our credentials. */
855: strlcpy(creds.service, "afs", sizeof creds.service);
856: creds.instance[0] = '\0';
857: strlcpy(creds.realm, server_cell, REALM_SZ);
858: memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
859: creds.issue_date = ct.BeginTimestamp;
860: creds.lifetime = krb_time_to_life(creds.issue_date, ct.EndTimestamp);
861: creds.kvno = ct.AuthHandle;
862: snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId);
863: creds.pinst[0] = '\0';
864:
865: /* Encode token, ship it off. */
866: if (!creds_to_radix(&creds, buffer))
867: break;
868: packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
869: packet_put_string((char *) buffer, strlen(buffer));
870: packet_send();
871: packet_write_wait();
872:
873: /* Roger, Roger. Clearance, Clarence. What's your vector,
874: Victor? */
875: type = packet_read(&plen);
876:
877: if (type == SSH_SMSG_FAILURE)
878: debug("AFS token for cell %s rejected.", server_cell);
879: else if (type != SSH_SMSG_SUCCESS)
880: packet_disconnect("Protocol error on AFS token response: %d", type);
881: }
1.1 deraadt 882: }
1.38 markus 883:
1.1 deraadt 884: #endif /* AFS */
885:
1.39 deraadt 886: /*
1.43 markus 887: * Tries to authenticate with any string-based challenge/response system.
888: * Note that the client code is not tied to s/key or TIS.
889: */
890: int
891: try_skey_authentication()
892: {
893: int type, i, payload_len;
894: char *challenge, *response;
895:
896: debug("Doing skey authentication.");
897:
898: /* request a challenge */
899: packet_start(SSH_CMSG_AUTH_TIS);
900: packet_send();
901: packet_write_wait();
902:
903: type = packet_read(&payload_len);
904: if (type != SSH_SMSG_FAILURE &&
905: type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
906: packet_disconnect("Protocol error: got %d in response "
907: "to skey-auth", type);
908: }
909: if (type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
910: debug("No challenge for skey authentication.");
911: return 0;
912: }
913: challenge = packet_get_string(&payload_len);
914: if (options.cipher == SSH_CIPHER_NONE)
915: log("WARNING: Encryption is disabled! "
916: "Reponse will be transmitted in clear text.");
917: fprintf(stderr, "%s\n", challenge);
918: fflush(stderr);
919: for (i = 0; i < options.number_of_password_prompts; i++) {
920: if (i != 0)
921: error("Permission denied, please try again.");
922: response = read_passphrase("Response: ", 0);
923: packet_start(SSH_CMSG_AUTH_TIS_RESPONSE);
924: packet_put_string(response, strlen(response));
925: memset(response, 0, strlen(response));
926: xfree(response);
927: packet_send();
928: packet_write_wait();
929: type = packet_read(&payload_len);
930: if (type == SSH_SMSG_SUCCESS)
931: return 1;
932: if (type != SSH_SMSG_FAILURE)
933: packet_disconnect("Protocol error: got %d in response "
934: "to skey-auth-reponse", type);
935: }
936: /* failure */
937: return 0;
938: }
939:
940: /*
941: * Tries to authenticate with plain passwd authentication.
942: */
943: int
944: try_password_authentication(char *prompt)
945: {
946: int type, i, payload_len;
947: char *password;
948:
949: debug("Doing password authentication.");
950: if (options.cipher == SSH_CIPHER_NONE)
951: log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
952: for (i = 0; i < options.number_of_password_prompts; i++) {
953: if (i != 0)
954: error("Permission denied, please try again.");
955: password = read_passphrase(prompt, 0);
956: packet_start(SSH_CMSG_AUTH_PASSWORD);
957: packet_put_string(password, strlen(password));
958: memset(password, 0, strlen(password));
959: xfree(password);
960: packet_send();
961: packet_write_wait();
962:
963: type = packet_read(&payload_len);
964: if (type == SSH_SMSG_SUCCESS)
965: return 1;
966: if (type != SSH_SMSG_FAILURE)
967: packet_disconnect("Protocol error: got %d in response to passwd auth", type);
968: }
969: /* failure */
970: return 0;
971: }
972:
973: /*
1.39 deraadt 974: * Waits for the server identification string, and sends our own
975: * identification string.
976: */
1.38 markus 977: void
978: ssh_exchange_identification()
1.1 deraadt 979: {
1.38 markus 980: char buf[256], remote_version[256]; /* must be same size! */
981: int remote_major, remote_minor, i;
982: int connection_in = packet_get_connection_in();
983: int connection_out = packet_get_connection_out();
984:
985: /* Read other side\'s version identification. */
986: for (i = 0; i < sizeof(buf) - 1; i++) {
987: if (read(connection_in, &buf[i], 1) != 1)
988: fatal("ssh_exchange_identification: read: %.100s", strerror(errno));
989: if (buf[i] == '\r') {
990: buf[i] = '\n';
991: buf[i + 1] = 0;
992: break;
993: }
994: if (buf[i] == '\n') {
995: buf[i + 1] = 0;
996: break;
997: }
998: }
999: buf[sizeof(buf) - 1] = 0;
1000:
1.40 markus 1001: /*
1002: * Check that the versions match. In future this might accept
1003: * several versions and set appropriate flags to handle them.
1004: */
1.38 markus 1005: if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
1006: remote_version) != 3)
1007: fatal("Bad remote protocol version identification: '%.100s'", buf);
1008: debug("Remote protocol version %d.%d, remote software version %.100s",
1009: remote_major, remote_minor, remote_version);
1010:
1011: /* Check if the remote protocol version is too old. */
1012: if (remote_major == 1 && remote_minor < 3)
1013: fatal("Remote machine has too old SSH software version.");
1014:
1015: /* We speak 1.3, too. */
1016: if (remote_major == 1 && remote_minor == 3) {
1017: enable_compat13();
1.48 ! markus 1018: if (options.forward_agent && strcmp(remote_version, "OpenSSH-1.1") != 0) {
1.38 markus 1019: log("Agent forwarding disabled, remote version '%s' is not compatible.",
1020: remote_version);
1021: options.forward_agent = 0;
1022: }
1023: }
1.1 deraadt 1024: #if 0
1.40 markus 1025: /*
1026: * Removed for now, to permit compatibility with latter versions. The
1027: * server will reject our version and disconnect if it doesn't
1028: * support it.
1029: */
1.38 markus 1030: if (remote_major != PROTOCOL_MAJOR)
1031: fatal("Protocol major versions differ: %d vs. %d",
1032: PROTOCOL_MAJOR, remote_major);
1.1 deraadt 1033: #endif
1034:
1.38 markus 1035: /* Send our own protocol version identification. */
1036: snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
1.45 deraadt 1037: PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
1038: if (atomicio(write, connection_out, buf, strlen(buf)) != strlen(buf))
1.38 markus 1039: fatal("write: %.100s", strerror(errno));
1.1 deraadt 1040: }
1041:
1042: int ssh_cipher_default = SSH_CIPHER_3DES;
1043:
1.38 markus 1044: int
1045: read_yes_or_no(const char *prompt, int defval)
1.1 deraadt 1046: {
1.38 markus 1047: char buf[1024];
1048: FILE *f;
1049: int retval = -1;
1050:
1051: if (isatty(0))
1052: f = stdin;
1053: else
1054: f = fopen("/dev/tty", "rw");
1055:
1056: if (f == NULL)
1057: return 0;
1058:
1059: fflush(stdout);
1060:
1061: while (1) {
1062: fprintf(stderr, "%s", prompt);
1063: if (fgets(buf, sizeof(buf), f) == NULL) {
1064: /* Print a newline (the prompt probably didn\'t have one). */
1065: fprintf(stderr, "\n");
1066: strlcpy(buf, "no", sizeof buf);
1067: }
1068: /* Remove newline from response. */
1069: if (strchr(buf, '\n'))
1070: *strchr(buf, '\n') = 0;
1071:
1072: if (buf[0] == 0)
1073: retval = defval;
1074: if (strcmp(buf, "yes") == 0)
1075: retval = 1;
1076: if (strcmp(buf, "no") == 0)
1077: retval = 0;
1078:
1079: if (retval != -1) {
1080: if (f != stdin)
1081: fclose(f);
1082: return retval;
1083: }
1.1 deraadt 1084: }
1085: }
1086:
1.39 deraadt 1087: /*
1.46 markus 1088: * check whether the supplied host key is valid, return only if ok.
1.39 deraadt 1089: */
1.46 markus 1090:
1.38 markus 1091: void
1.46 markus 1092: check_host_key(char *host,
1093: struct sockaddr_in *hostaddr,
1094: RSA *host_key)
1.1 deraadt 1095: {
1.46 markus 1096: RSA *file_key;
1097: char *ip = NULL;
1.38 markus 1098: char hostline[1000], *hostp;
1099: HostStatus host_status;
1100: HostStatus ip_status;
1101: int host_ip_differ = 0;
1102: int local = (ntohl(hostaddr->sin_addr.s_addr) >> 24) == IN_LOOPBACKNET;
1.42 markus 1103:
1104: /*
1.44 markus 1105: * Turn off check_host_ip for proxy connects, since
1.42 markus 1106: * we don't have the remote ip-address
1107: */
1108: if (options.proxy_command != NULL && options.check_host_ip)
1109: options.check_host_ip = 0;
1.38 markus 1110:
1111: if (options.check_host_ip)
1112: ip = xstrdup(inet_ntoa(hostaddr->sin_addr));
1113:
1.46 markus 1114: /*
1115: * Store the host key from the known host file in here so that we can
1116: * compare it with the key for the IP address.
1117: */
1.38 markus 1118: file_key = RSA_new();
1119: file_key->n = BN_new();
1120: file_key->e = BN_new();
1121:
1.40 markus 1122: /*
1123: * Check if the host key is present in the user\'s list of known
1124: * hosts or in the systemwide list.
1125: */
1.38 markus 1126: host_status = check_host_in_hostfile(options.user_hostfile, host,
1127: host_key->e, host_key->n,
1128: file_key->e, file_key->n);
1129: if (host_status == HOST_NEW)
1130: host_status = check_host_in_hostfile(options.system_hostfile, host,
1131: host_key->e, host_key->n,
1132: file_key->e, file_key->n);
1.40 markus 1133: /*
1134: * Force accepting of the host key for localhost and 127.0.0.1. The
1135: * problem is that if the home directory is NFS-mounted to multiple
1136: * machines, localhost will refer to a different machine in each of
1137: * them, and the user will get bogus HOST_CHANGED warnings. This
1138: * essentially disables host authentication for localhost; however,
1139: * this is probably not a real problem.
1140: */
1.38 markus 1141: if (local) {
1142: debug("Forcing accepting of host key for localhost.");
1143: host_status = HOST_OK;
1144: }
1.40 markus 1145: /*
1146: * Also perform check for the ip address, skip the check if we are
1147: * localhost or the hostname was an ip address to begin with
1148: */
1.38 markus 1149: if (options.check_host_ip && !local && strcmp(host, ip)) {
1150: RSA *ip_key = RSA_new();
1151: ip_key->n = BN_new();
1152: ip_key->e = BN_new();
1153: ip_status = check_host_in_hostfile(options.user_hostfile, ip,
1154: host_key->e, host_key->n,
1155: ip_key->e, ip_key->n);
1156:
1157: if (ip_status == HOST_NEW)
1158: ip_status = check_host_in_hostfile(options.system_hostfile, ip,
1159: host_key->e, host_key->n,
1160: ip_key->e, ip_key->n);
1161: if (host_status == HOST_CHANGED &&
1162: (ip_status != HOST_CHANGED ||
1163: (BN_cmp(ip_key->e, file_key->e) || BN_cmp(ip_key->n, file_key->n))))
1164: host_ip_differ = 1;
1165:
1166: RSA_free(ip_key);
1167: } else
1168: ip_status = host_status;
1169:
1170: RSA_free(file_key);
1171:
1172: switch (host_status) {
1173: case HOST_OK:
1174: /* The host is known and the key matches. */
1175: debug("Host '%.200s' is known and matches the host key.", host);
1176: if (options.check_host_ip) {
1177: if (ip_status == HOST_NEW) {
1178: if (!add_host_to_hostfile(options.user_hostfile, ip,
1179: host_key->e, host_key->n))
1180: log("Failed to add the host key for IP address '%.30s' to the list of known hosts (%.30s).",
1181: ip, options.user_hostfile);
1182: else
1183: log("Warning: Permanently added host key for IP address '%.30s' to the list of known hosts.",
1184: ip);
1185: } else if (ip_status != HOST_OK)
1186: log("Warning: the host key for '%.200s' differs from the key for the IP address '%.30s'",
1187: host, ip);
1188: }
1189: break;
1190: case HOST_NEW:
1191: /* The host is new. */
1192: if (options.strict_host_key_checking == 1) {
1193: /* User has requested strict host key checking. We will not add the host key
1194: automatically. The only alternative left is to abort. */
1195: fatal("No host key is known for %.200s and you have requested strict checking.", host);
1196: } else if (options.strict_host_key_checking == 2) {
1197: /* The default */
1198: char prompt[1024];
1199: char *fp = fingerprint(host_key->e, host_key->n);
1200: snprintf(prompt, sizeof(prompt),
1.45 deraadt 1201: "The authenticity of host '%.200s' can't be established.\n"
1202: "Key fingerprint is %d %s.\n"
1203: "Are you sure you want to continue connecting (yes/no)? ",
1204: host, BN_num_bits(host_key->n), fp);
1.38 markus 1205: if (!read_yes_or_no(prompt, -1))
1206: fatal("Aborted by user!\n");
1207: }
1208: if (options.check_host_ip && ip_status == HOST_NEW && strcmp(host, ip)) {
1209: snprintf(hostline, sizeof(hostline), "%s,%s", host, ip);
1210: hostp = hostline;
1211: } else
1212: hostp = host;
1213:
1214: /* If not in strict mode, add the key automatically to the local known_hosts file. */
1215: if (!add_host_to_hostfile(options.user_hostfile, hostp,
1216: host_key->e, host_key->n))
1217: log("Failed to add the host to the list of known hosts (%.500s).",
1218: options.user_hostfile);
1219: else
1220: log("Warning: Permanently added '%.200s' to the list of known hosts.",
1221: hostp);
1222: break;
1223: case HOST_CHANGED:
1224: if (options.check_host_ip && host_ip_differ) {
1225: char *msg;
1226: if (ip_status == HOST_NEW)
1227: msg = "is unknown";
1228: else if (ip_status == HOST_OK)
1229: msg = "is unchanged";
1230: else
1231: msg = "has a different value";
1232: error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1233: error("@ WARNING: POSSIBLE DNS SPOOFING DETECTED! @");
1234: error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1235: error("The host key for %s has changed,", host);
1236: error("and the key for the according IP address %s", ip);
1237: error("%s. This could either mean that", msg);
1238: error("DNS SPOOFING is happening or the IP address for the host");
1239: error("and its host key have changed at the same time");
1240: }
1241: /* The host key has changed. */
1242: error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1.47 markus 1243: error("@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @");
1.38 markus 1244: error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1245: error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
1246: error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
1247: error("It is also possible that the host key has just been changed.");
1248: error("Please contact your system administrator.");
1249: error("Add correct host key in %.100s to get rid of this message.",
1250: options.user_hostfile);
1251:
1.40 markus 1252: /*
1253: * If strict host key checking is in use, the user will have
1254: * to edit the key manually and we can only abort.
1255: */
1.38 markus 1256: if (options.strict_host_key_checking)
1257: fatal("Host key for %.200s has changed and you have requested strict checking.", host);
1258:
1.40 markus 1259: /*
1260: * If strict host key checking has not been requested, allow
1261: * the connection but without password authentication or
1262: * agent forwarding.
1263: */
1.38 markus 1264: if (options.password_authentication) {
1265: error("Password authentication is disabled to avoid trojan horses.");
1266: options.password_authentication = 0;
1267: }
1268: if (options.forward_agent) {
1269: error("Agent forwarding is disabled to avoid trojan horses.");
1270: options.forward_agent = 0;
1271: }
1.40 markus 1272: /*
1273: * XXX Should permit the user to change to use the new id.
1274: * This could be done by converting the host key to an
1275: * identifying sentence, tell that the host identifies itself
1276: * by that sentence, and ask the user if he/she whishes to
1277: * accept the authentication.
1278: */
1.38 markus 1279: break;
1280: }
1281: if (options.check_host_ip)
1282: xfree(ip);
1.46 markus 1283: }
1284:
1285: /*
1286: * Starts a dialog with the server, and authenticates the current user on the
1287: * server. This does not need any extra privileges. The basic connection
1288: * to the server must already have been established before this is called.
1289: * User is the remote user; if it is NULL, the current local user name will
1290: * be used. Anonymous indicates that no rhosts authentication will be used.
1291: * If login fails, this function prints an error and never returns.
1292: * This function does not require super-user privileges.
1293: */
1294: void
1295: ssh_login(int host_key_valid,
1296: RSA *own_host_key,
1297: const char *orighost,
1298: struct sockaddr_in *hostaddr,
1299: uid_t original_real_uid)
1300: {
1301: int i, type;
1302: struct passwd *pw;
1303: BIGNUM *key;
1304: RSA *host_key;
1305: RSA *public_key;
1306: int bits, rbits;
1307: unsigned char session_key[SSH_SESSION_KEY_LENGTH];
1308: const char *server_user, *local_user;
1309: char *host, *cp;
1310: unsigned char check_bytes[8];
1311: unsigned int supported_ciphers, supported_authentications;
1312: unsigned int server_flags, client_flags;
1313: int payload_len, clen, sum_len = 0;
1314: u_int32_t rand = 0;
1315:
1316: /* Convert the user-supplied hostname into all lowercase. */
1317: host = xstrdup(orighost);
1318: for (cp = host; *cp; cp++)
1319: if (isupper(*cp))
1320: *cp = tolower(*cp);
1321:
1322: /* Exchange protocol version identification strings with the server. */
1323: ssh_exchange_identification();
1324:
1325: /* Put the connection into non-blocking mode. */
1326: packet_set_nonblocking();
1327:
1328: /* Get local user name. Use it as server user if no user name was given. */
1329: pw = getpwuid(original_real_uid);
1330: if (!pw)
1331: fatal("User id %d not found from user database.", original_real_uid);
1332: local_user = xstrdup(pw->pw_name);
1333: server_user = options.user ? options.user : local_user;
1334:
1335: debug("Waiting for server public key.");
1336:
1337: /* Wait for a public key packet from the server. */
1338: packet_read_expect(&payload_len, SSH_SMSG_PUBLIC_KEY);
1339:
1340: /* Get check bytes from the packet. */
1341: for (i = 0; i < 8; i++)
1342: check_bytes[i] = packet_get_char();
1343:
1344: /* Get the public key. */
1345: public_key = RSA_new();
1346: bits = packet_get_int();/* bits */
1347: public_key->e = BN_new();
1348: packet_get_bignum(public_key->e, &clen);
1349: sum_len += clen;
1350: public_key->n = BN_new();
1351: packet_get_bignum(public_key->n, &clen);
1352: sum_len += clen;
1353:
1354: rbits = BN_num_bits(public_key->n);
1355: if (bits != rbits) {
1356: log("Warning: Server lies about size of server public key: "
1357: "actual size is %d bits vs. announced %d.", rbits, bits);
1358: log("Warning: This may be due to an old implementation of ssh.");
1359: }
1360: /* Get the host key. */
1361: host_key = RSA_new();
1362: bits = packet_get_int();/* bits */
1363: host_key->e = BN_new();
1364: packet_get_bignum(host_key->e, &clen);
1365: sum_len += clen;
1366: host_key->n = BN_new();
1367: packet_get_bignum(host_key->n, &clen);
1368: sum_len += clen;
1369:
1370: rbits = BN_num_bits(host_key->n);
1371: if (bits != rbits) {
1372: log("Warning: Server lies about size of server host key: "
1373: "actual size is %d bits vs. announced %d.", rbits, bits);
1374: log("Warning: This may be due to an old implementation of ssh.");
1375: }
1376:
1377: /* Get protocol flags. */
1378: server_flags = packet_get_int();
1379: packet_set_protocol_flags(server_flags);
1380:
1381: supported_ciphers = packet_get_int();
1382: supported_authentications = packet_get_int();
1383:
1384: debug("Received server public key (%d bits) and host key (%d bits).",
1385: BN_num_bits(public_key->n), BN_num_bits(host_key->n));
1386:
1387: packet_integrity_check(payload_len,
1388: 8 + 4 + sum_len + 0 + 4 + 0 + 0 + 4 + 4 + 4,
1389: SSH_SMSG_PUBLIC_KEY);
1390:
1391: check_host_key(host, hostaddr, host_key);
1392:
1393: client_flags = SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN;
1394:
1395: compute_session_id(session_id, check_bytes, host_key->n, public_key->n);
1.38 markus 1396:
1397: /* Generate a session key. */
1398: arc4random_stir();
1399:
1.40 markus 1400: /*
1401: * Generate an encryption key for the session. The key is a 256 bit
1402: * random number, interpreted as a 32-byte key, with the least
1403: * significant 8 bits being the first byte of the key.
1404: */
1.38 markus 1405: for (i = 0; i < 32; i++) {
1406: if (i % 4 == 0)
1407: rand = arc4random();
1408: session_key[i] = rand & 0xff;
1409: rand >>= 8;
1410: }
1411:
1.40 markus 1412: /*
1413: * According to the protocol spec, the first byte of the session key
1414: * is the highest byte of the integer. The session key is xored with
1415: * the first 16 bytes of the session id.
1416: */
1.38 markus 1417: key = BN_new();
1418: BN_set_word(key, 0);
1419: for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
1420: BN_lshift(key, key, 8);
1421: if (i < 16)
1422: BN_add_word(key, session_key[i] ^ session_id[i]);
1423: else
1424: BN_add_word(key, session_key[i]);
1425: }
1426:
1.40 markus 1427: /*
1428: * Encrypt the integer using the public key and host key of the
1429: * server (key with smaller modulus first).
1430: */
1.38 markus 1431: if (BN_cmp(public_key->n, host_key->n) < 0) {
1432: /* Public key has smaller modulus. */
1433: if (BN_num_bits(host_key->n) <
1434: BN_num_bits(public_key->n) + SSH_KEY_BITS_RESERVED) {
1435: fatal("respond_to_rsa_challenge: host_key %d < public_key %d + "
1436: "SSH_KEY_BITS_RESERVED %d",
1437: BN_num_bits(host_key->n),
1438: BN_num_bits(public_key->n),
1439: SSH_KEY_BITS_RESERVED);
1440: }
1441: rsa_public_encrypt(key, key, public_key);
1442: rsa_public_encrypt(key, key, host_key);
1443: } else {
1444: /* Host key has smaller modulus (or they are equal). */
1445: if (BN_num_bits(public_key->n) <
1446: BN_num_bits(host_key->n) + SSH_KEY_BITS_RESERVED) {
1447: fatal("respond_to_rsa_challenge: public_key %d < host_key %d + "
1448: "SSH_KEY_BITS_RESERVED %d",
1449: BN_num_bits(public_key->n),
1450: BN_num_bits(host_key->n),
1451: SSH_KEY_BITS_RESERVED);
1452: }
1453: rsa_public_encrypt(key, key, host_key);
1454: rsa_public_encrypt(key, key, public_key);
1455: }
1456:
1457: if (options.cipher == SSH_CIPHER_NOT_SET) {
1458: if (cipher_mask() & supported_ciphers & (1 << ssh_cipher_default))
1459: options.cipher = ssh_cipher_default;
1460: else {
1461: debug("Cipher %s not supported, using %.100s instead.",
1462: cipher_name(ssh_cipher_default),
1463: cipher_name(SSH_FALLBACK_CIPHER));
1464: options.cipher = SSH_FALLBACK_CIPHER;
1465: }
1466: }
1467: /* Check that the selected cipher is supported. */
1468: if (!(supported_ciphers & (1 << options.cipher)))
1469: fatal("Selected cipher type %.100s not supported by server.",
1470: cipher_name(options.cipher));
1471:
1472: debug("Encryption type: %.100s", cipher_name(options.cipher));
1473:
1474: /* Send the encrypted session key to the server. */
1475: packet_start(SSH_CMSG_SESSION_KEY);
1476: packet_put_char(options.cipher);
1477:
1478: /* Send the check bytes back to the server. */
1479: for (i = 0; i < 8; i++)
1480: packet_put_char(check_bytes[i]);
1481:
1482: /* Send the encrypted encryption key. */
1483: packet_put_bignum(key);
1484:
1485: /* Send protocol flags. */
1.46 markus 1486: packet_put_int(client_flags);
1.38 markus 1487:
1488: /* Send the packet now. */
1489: packet_send();
1490: packet_write_wait();
1491:
1492: /* Destroy the session key integer and the public keys since we no longer need them. */
1493: BN_clear_free(key);
1494: RSA_free(public_key);
1495: RSA_free(host_key);
1496:
1497: debug("Sent encrypted session key.");
1498:
1499: /* Set the encryption key. */
1500: packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, options.cipher);
1501:
1502: /* We will no longer need the session key here. Destroy any extra copies. */
1503: memset(session_key, 0, sizeof(session_key));
1504:
1.40 markus 1505: /*
1506: * Expect a success message from the server. Note that this message
1507: * will be received in encrypted form.
1508: */
1.38 markus 1509: packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1510:
1511: debug("Received encrypted confirmation.");
1512:
1513: /* Send the name of the user to log in as on the server. */
1514: packet_start(SSH_CMSG_USER);
1515: packet_put_string(server_user, strlen(server_user));
1.16 dugsong 1516: packet_send();
1517: packet_write_wait();
1.38 markus 1518:
1.40 markus 1519: /*
1520: * The server should respond with success if no authentication is
1521: * needed (the user has no password). Otherwise the server responds
1522: * with failure.
1523: */
1.16 dugsong 1524: type = packet_read(&payload_len);
1.38 markus 1525:
1526: /* check whether the connection was accepted without authentication. */
1.16 dugsong 1527: if (type == SSH_SMSG_SUCCESS)
1.38 markus 1528: return;
1.16 dugsong 1529: if (type != SSH_SMSG_FAILURE)
1.38 markus 1530: packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER",
1531: type);
1532:
1533: #ifdef AFS
1534: /* Try Kerberos tgt passing if the server supports it. */
1535: if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1536: options.kerberos_tgt_passing) {
1537: if (options.cipher == SSH_CIPHER_NONE)
1538: log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1539: (void) send_kerberos_tgt();
1540: }
1541: /* Try AFS token passing if the server supports it. */
1542: if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
1543: options.afs_token_passing && k_hasafs()) {
1544: if (options.cipher == SSH_CIPHER_NONE)
1545: log("WARNING: Encryption is disabled! Token will be transmitted in the clear!");
1546: send_afs_tokens();
1547: }
1548: #endif /* AFS */
1549:
1550: #ifdef KRB4
1551: if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1552: options.kerberos_authentication) {
1553: debug("Trying Kerberos authentication.");
1554: if (try_kerberos_authentication()) {
1555: /* The server should respond with success or failure. */
1556: type = packet_read(&payload_len);
1557: if (type == SSH_SMSG_SUCCESS)
1558: return;
1559: if (type != SSH_SMSG_FAILURE)
1560: packet_disconnect("Protocol error: got %d in response to Kerberos auth", type);
1561: }
1562: }
1563: #endif /* KRB4 */
1564:
1.40 markus 1565: /*
1566: * Use rhosts authentication if running in privileged socket and we
1567: * do not wish to remain anonymous.
1568: */
1.38 markus 1569: if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
1570: options.rhosts_authentication) {
1571: debug("Trying rhosts authentication.");
1572: packet_start(SSH_CMSG_AUTH_RHOSTS);
1573: packet_put_string(local_user, strlen(local_user));
1574: packet_send();
1575: packet_write_wait();
1576:
1577: /* The server should respond with success or failure. */
1578: type = packet_read(&payload_len);
1579: if (type == SSH_SMSG_SUCCESS)
1580: return;
1581: if (type != SSH_SMSG_FAILURE)
1582: packet_disconnect("Protocol error: got %d in response to rhosts auth",
1583: type);
1584: }
1.40 markus 1585: /*
1586: * Try .rhosts or /etc/hosts.equiv authentication with RSA host
1587: * authentication.
1588: */
1.38 markus 1589: if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
1590: options.rhosts_rsa_authentication && host_key_valid) {
1591: if (try_rhosts_rsa_authentication(local_user, own_host_key))
1592: return;
1593: }
1594: /* Try RSA authentication if the server supports it. */
1595: if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
1596: options.rsa_authentication) {
1.40 markus 1597: /*
1598: * Try RSA authentication using the authentication agent. The
1599: * agent is tried first because no passphrase is needed for
1600: * it, whereas identity files may require passphrases.
1601: */
1.38 markus 1602: if (try_agent_authentication())
1603: return;
1604:
1605: /* Try RSA authentication for each identity. */
1606: for (i = 0; i < options.num_identity_files; i++)
1.43 markus 1607: if (try_rsa_authentication(options.identity_files[i]))
1.38 markus 1608: return;
1609: }
1610: /* Try skey authentication if the server supports it. */
1611: if ((supported_authentications & (1 << SSH_AUTH_TIS)) &&
1612: options.skey_authentication && !options.batch_mode) {
1.43 markus 1613: if (try_skey_authentication())
1614: return;
1.38 markus 1615: }
1616: /* Try password authentication if the server supports it. */
1617: if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
1618: options.password_authentication && !options.batch_mode) {
1619: char prompt[80];
1.45 deraadt 1620:
1.43 markus 1621: snprintf(prompt, sizeof(prompt), "%.30s@%.40s's password: ",
1.45 deraadt 1622: server_user, host);
1.43 markus 1623: if (try_password_authentication(prompt))
1624: return;
1.38 markus 1625: }
1626: /* All authentication methods have failed. Exit with an error message. */
1627: fatal("Permission denied.");
1628: /* NOTREACHED */
1.1 deraadt 1629: }