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