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