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