Annotation of src/usr.bin/ssh/sshconnect.c, Revision 1.55
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.55 ! markus 11: RCSID("$OpenBSD: sshconnect.c,v 1.54 2000/02/05 10:13:11 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;
635: Key_schedule schedule;
636: u_long checksum, cksum;
637: MSG_DAT msg_data;
638: struct sockaddr_in local, foreign;
639: struct stat st;
640:
641: /* Don't do anything if we don't have any tickets. */
642: if (stat(tkt_string(), &st) < 0)
643: return 0;
644:
645: strncpy(inst, (char *) krb_get_phost(get_canonical_hostname()), INST_SZ);
646:
647: realm = (char *) krb_realmofhost(get_canonical_hostname());
648: if (!realm) {
649: debug("Kerberos V4: no realm for %s", get_canonical_hostname());
650: return 0;
651: }
652: /* This can really be anything. */
653: checksum = (u_long) getpid();
654:
655: r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
656: if (r != KSUCCESS) {
657: debug("Kerberos V4 krb_mk_req failed: %s", krb_err_txt[r]);
658: return 0;
659: }
660: /* Get session key to decrypt the server's reply with. */
661: r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
662: if (r != KSUCCESS) {
663: debug("get_cred failed: %s", krb_err_txt[r]);
664: return 0;
665: }
666: des_key_sched((des_cblock *) cred.session, schedule);
667:
668: /* Send authentication info to server. */
669: packet_start(SSH_CMSG_AUTH_KERBEROS);
670: packet_put_string((char *) auth.dat, auth.length);
671: packet_send();
672: packet_write_wait();
673:
674: /* Zero the buffer. */
675: (void) memset(auth.dat, 0, MAX_KTXT_LEN);
676:
677: r = sizeof(local);
678: memset(&local, 0, sizeof(local));
679: if (getsockname(packet_get_connection_in(),
680: (struct sockaddr *) & local, &r) < 0)
681: debug("getsockname failed: %s", strerror(errno));
682:
683: r = sizeof(foreign);
684: memset(&foreign, 0, sizeof(foreign));
685: if (getpeername(packet_get_connection_in(),
686: (struct sockaddr *) & foreign, &r) < 0) {
687: debug("getpeername failed: %s", strerror(errno));
688: fatal_cleanup();
689: }
690: /* Get server reply. */
691: type = packet_read(&plen);
692: switch (type) {
693: case SSH_SMSG_FAILURE:
694: /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
695: debug("Kerberos V4 authentication failed.");
696: return 0;
697: break;
698:
699: case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
700: /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
701: debug("Kerberos V4 authentication accepted.");
702:
703: /* Get server's response. */
704: reply = packet_get_string((unsigned int *) &auth.length);
705: memcpy(auth.dat, reply, auth.length);
706: xfree(reply);
707:
708: packet_integrity_check(plen, 4 + auth.length, type);
709:
1.40 markus 710: /*
711: * If his response isn't properly encrypted with the session
712: * key, and the decrypted checksum fails to match, he's
713: * bogus. Bail out.
714: */
1.38 markus 715: r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session,
716: &foreign, &local, &msg_data);
717: if (r != KSUCCESS) {
718: debug("Kerberos V4 krb_rd_priv failed: %s", krb_err_txt[r]);
719: packet_disconnect("Kerberos V4 challenge failed!");
720: }
721: /* Fetch the (incremented) checksum that we supplied in the request. */
722: (void) memcpy((char *) &cksum, (char *) msg_data.app_data, sizeof(cksum));
723: cksum = ntohl(cksum);
724:
725: /* If it matches, we're golden. */
726: if (cksum == checksum + 1) {
727: debug("Kerberos V4 challenge successful.");
728: return 1;
729: } else
730: packet_disconnect("Kerberos V4 challenge failed!");
731: break;
732:
733: default:
734: packet_disconnect("Protocol error on Kerberos V4 response: %d", type);
735: }
736: return 0;
1.1 deraadt 737: }
1.38 markus 738:
1.1 deraadt 739: #endif /* KRB4 */
740:
741: #ifdef AFS
1.38 markus 742: int
743: send_kerberos_tgt()
1.1 deraadt 744: {
1.38 markus 745: CREDENTIALS *creds;
746: char pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
747: int r, type, plen;
748: unsigned char buffer[8192];
749: struct stat st;
750:
751: /* Don't do anything if we don't have any tickets. */
752: if (stat(tkt_string(), &st) < 0)
753: return 0;
754:
755: creds = xmalloc(sizeof(*creds));
756:
757: if ((r = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm)) != KSUCCESS) {
758: debug("Kerberos V4 tf_fullname failed: %s", krb_err_txt[r]);
759: return 0;
760: }
761: if ((r = krb_get_cred("krbtgt", prealm, prealm, creds)) != GC_OK) {
762: debug("Kerberos V4 get_cred failed: %s", krb_err_txt[r]);
763: return 0;
764: }
765: if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
766: debug("Kerberos V4 ticket expired: %s", TKT_FILE);
767: return 0;
768: }
769: creds_to_radix(creds, buffer);
770: xfree(creds);
771:
772: packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
773: packet_put_string((char *) buffer, strlen(buffer));
774: packet_send();
775: packet_write_wait();
776:
777: type = packet_read(&plen);
1.1 deraadt 778:
1.38 markus 779: if (type == SSH_SMSG_FAILURE)
780: debug("Kerberos TGT for realm %s rejected.", prealm);
781: else if (type != SSH_SMSG_SUCCESS)
782: packet_disconnect("Protocol error on Kerberos TGT response: %d", type);
783:
784: return 1;
1.1 deraadt 785: }
786:
1.38 markus 787: void
788: send_afs_tokens(void)
1.1 deraadt 789: {
1.38 markus 790: CREDENTIALS creds;
791: struct ViceIoctl parms;
792: struct ClearToken ct;
793: int i, type, len, plen;
794: char buf[2048], *p, *server_cell;
795: unsigned char buffer[8192];
796:
797: /* Move over ktc_GetToken, here's something leaner. */
798: for (i = 0; i < 100; i++) { /* just in case */
799: parms.in = (char *) &i;
800: parms.in_size = sizeof(i);
801: parms.out = buf;
802: parms.out_size = sizeof(buf);
803: if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0)
804: break;
805: p = buf;
806:
807: /* Get secret token. */
808: memcpy(&creds.ticket_st.length, p, sizeof(unsigned int));
809: if (creds.ticket_st.length > MAX_KTXT_LEN)
810: break;
811: p += sizeof(unsigned int);
812: memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
813: p += creds.ticket_st.length;
814:
815: /* Get clear token. */
816: memcpy(&len, p, sizeof(len));
817: if (len != sizeof(struct ClearToken))
818: break;
819: p += sizeof(len);
820: memcpy(&ct, p, len);
821: p += len;
822: p += sizeof(len); /* primary flag */
823: server_cell = p;
824:
825: /* Flesh out our credentials. */
826: strlcpy(creds.service, "afs", sizeof creds.service);
827: creds.instance[0] = '\0';
828: strlcpy(creds.realm, server_cell, REALM_SZ);
829: memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
830: creds.issue_date = ct.BeginTimestamp;
831: creds.lifetime = krb_time_to_life(creds.issue_date, ct.EndTimestamp);
832: creds.kvno = ct.AuthHandle;
833: snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId);
834: creds.pinst[0] = '\0';
835:
836: /* Encode token, ship it off. */
837: if (!creds_to_radix(&creds, buffer))
838: break;
839: packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
840: packet_put_string((char *) buffer, strlen(buffer));
841: packet_send();
842: packet_write_wait();
843:
844: /* Roger, Roger. Clearance, Clarence. What's your vector,
845: Victor? */
846: type = packet_read(&plen);
847:
848: if (type == SSH_SMSG_FAILURE)
849: debug("AFS token for cell %s rejected.", server_cell);
850: else if (type != SSH_SMSG_SUCCESS)
851: packet_disconnect("Protocol error on AFS token response: %d", type);
852: }
1.1 deraadt 853: }
1.38 markus 854:
1.1 deraadt 855: #endif /* AFS */
856:
1.39 deraadt 857: /*
1.43 markus 858: * Tries to authenticate with any string-based challenge/response system.
859: * Note that the client code is not tied to s/key or TIS.
860: */
861: int
862: try_skey_authentication()
863: {
864: int type, i, payload_len;
865: char *challenge, *response;
866:
867: debug("Doing skey authentication.");
868:
869: /* request a challenge */
870: packet_start(SSH_CMSG_AUTH_TIS);
871: packet_send();
872: packet_write_wait();
873:
874: type = packet_read(&payload_len);
875: if (type != SSH_SMSG_FAILURE &&
876: type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
877: packet_disconnect("Protocol error: got %d in response "
878: "to skey-auth", type);
879: }
880: if (type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
881: debug("No challenge for skey authentication.");
882: return 0;
883: }
884: challenge = packet_get_string(&payload_len);
885: if (options.cipher == SSH_CIPHER_NONE)
886: log("WARNING: Encryption is disabled! "
887: "Reponse will be transmitted in clear text.");
888: fprintf(stderr, "%s\n", challenge);
1.54 markus 889: xfree(challenge);
1.43 markus 890: fflush(stderr);
891: for (i = 0; i < options.number_of_password_prompts; i++) {
892: if (i != 0)
893: error("Permission denied, please try again.");
894: response = read_passphrase("Response: ", 0);
895: packet_start(SSH_CMSG_AUTH_TIS_RESPONSE);
896: packet_put_string(response, strlen(response));
897: memset(response, 0, strlen(response));
898: xfree(response);
899: packet_send();
900: packet_write_wait();
901: type = packet_read(&payload_len);
902: if (type == SSH_SMSG_SUCCESS)
903: return 1;
904: if (type != SSH_SMSG_FAILURE)
905: packet_disconnect("Protocol error: got %d in response "
906: "to skey-auth-reponse", type);
907: }
908: /* failure */
909: return 0;
910: }
911:
912: /*
913: * Tries to authenticate with plain passwd authentication.
914: */
915: int
916: try_password_authentication(char *prompt)
917: {
918: int type, i, payload_len;
919: char *password;
920:
921: debug("Doing password authentication.");
922: if (options.cipher == SSH_CIPHER_NONE)
923: log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
924: for (i = 0; i < options.number_of_password_prompts; i++) {
925: if (i != 0)
926: error("Permission denied, please try again.");
927: password = read_passphrase(prompt, 0);
928: packet_start(SSH_CMSG_AUTH_PASSWORD);
929: packet_put_string(password, strlen(password));
930: memset(password, 0, strlen(password));
931: xfree(password);
932: packet_send();
933: packet_write_wait();
934:
935: type = packet_read(&payload_len);
936: if (type == SSH_SMSG_SUCCESS)
937: return 1;
938: if (type != SSH_SMSG_FAILURE)
939: packet_disconnect("Protocol error: got %d in response to passwd auth", type);
940: }
941: /* failure */
942: return 0;
943: }
944:
945: /*
1.39 deraadt 946: * Waits for the server identification string, and sends our own
947: * identification string.
948: */
1.38 markus 949: void
950: ssh_exchange_identification()
1.1 deraadt 951: {
1.38 markus 952: char buf[256], remote_version[256]; /* must be same size! */
953: int remote_major, remote_minor, i;
954: int connection_in = packet_get_connection_in();
955: int connection_out = packet_get_connection_out();
956:
957: /* Read other side\'s version identification. */
958: for (i = 0; i < sizeof(buf) - 1; i++) {
959: if (read(connection_in, &buf[i], 1) != 1)
960: fatal("ssh_exchange_identification: read: %.100s", strerror(errno));
961: if (buf[i] == '\r') {
962: buf[i] = '\n';
963: buf[i + 1] = 0;
964: break;
965: }
966: if (buf[i] == '\n') {
967: buf[i + 1] = 0;
968: break;
969: }
970: }
971: buf[sizeof(buf) - 1] = 0;
972:
1.40 markus 973: /*
974: * Check that the versions match. In future this might accept
975: * several versions and set appropriate flags to handle them.
976: */
1.38 markus 977: if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
978: remote_version) != 3)
979: fatal("Bad remote protocol version identification: '%.100s'", buf);
980: debug("Remote protocol version %d.%d, remote software version %.100s",
981: remote_major, remote_minor, remote_version);
982:
983: /* Check if the remote protocol version is too old. */
984: if (remote_major == 1 && remote_minor < 3)
985: fatal("Remote machine has too old SSH software version.");
986:
987: /* We speak 1.3, too. */
988: if (remote_major == 1 && remote_minor == 3) {
989: enable_compat13();
1.53 markus 990: if (options.forward_agent) {
991: log("Agent forwarding disabled for protocol 1.3");
1.38 markus 992: options.forward_agent = 0;
993: }
994: }
1.1 deraadt 995: #if 0
1.40 markus 996: /*
997: * Removed for now, to permit compatibility with latter versions. The
998: * server will reject our version and disconnect if it doesn't
999: * support it.
1000: */
1.38 markus 1001: if (remote_major != PROTOCOL_MAJOR)
1002: fatal("Protocol major versions differ: %d vs. %d",
1003: PROTOCOL_MAJOR, remote_major);
1.1 deraadt 1004: #endif
1005:
1.38 markus 1006: /* Send our own protocol version identification. */
1007: snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
1.45 deraadt 1008: PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
1009: if (atomicio(write, connection_out, buf, strlen(buf)) != strlen(buf))
1.38 markus 1010: fatal("write: %.100s", strerror(errno));
1.1 deraadt 1011: }
1012:
1013: int ssh_cipher_default = SSH_CIPHER_3DES;
1014:
1.38 markus 1015: int
1016: read_yes_or_no(const char *prompt, int defval)
1.1 deraadt 1017: {
1.38 markus 1018: char buf[1024];
1019: FILE *f;
1020: int retval = -1;
1021:
1022: if (isatty(0))
1023: f = stdin;
1024: else
1025: f = fopen("/dev/tty", "rw");
1026:
1027: if (f == NULL)
1028: return 0;
1029:
1030: fflush(stdout);
1031:
1032: while (1) {
1033: fprintf(stderr, "%s", prompt);
1034: if (fgets(buf, sizeof(buf), f) == NULL) {
1035: /* Print a newline (the prompt probably didn\'t have one). */
1036: fprintf(stderr, "\n");
1037: strlcpy(buf, "no", sizeof buf);
1038: }
1039: /* Remove newline from response. */
1040: if (strchr(buf, '\n'))
1041: *strchr(buf, '\n') = 0;
1042:
1043: if (buf[0] == 0)
1044: retval = defval;
1045: if (strcmp(buf, "yes") == 0)
1046: retval = 1;
1047: if (strcmp(buf, "no") == 0)
1048: retval = 0;
1049:
1050: if (retval != -1) {
1051: if (f != stdin)
1052: fclose(f);
1053: return retval;
1054: }
1.1 deraadt 1055: }
1056: }
1057:
1.39 deraadt 1058: /*
1.46 markus 1059: * check whether the supplied host key is valid, return only if ok.
1.39 deraadt 1060: */
1.46 markus 1061:
1.38 markus 1062: void
1.49 markus 1063: check_host_key(char *host, struct sockaddr *hostaddr, RSA *host_key)
1.1 deraadt 1064: {
1.46 markus 1065: RSA *file_key;
1066: char *ip = NULL;
1.38 markus 1067: char hostline[1000], *hostp;
1068: HostStatus host_status;
1069: HostStatus ip_status;
1.49 markus 1070: int local = 0, host_ip_differ = 0;
1071: char ntop[NI_MAXHOST];
1072:
1073: /*
1074: * Force accepting of the host key for loopback/localhost. The
1075: * problem is that if the home directory is NFS-mounted to multiple
1076: * machines, localhost will refer to a different machine in each of
1077: * them, and the user will get bogus HOST_CHANGED warnings. This
1078: * essentially disables host authentication for localhost; however,
1079: * this is probably not a real problem.
1080: */
1081: switch (hostaddr->sa_family) {
1082: case AF_INET:
1083: local = (ntohl(((struct sockaddr_in *)hostaddr)->sin_addr.s_addr) >> 24) == IN_LOOPBACKNET;
1084: break;
1085: case AF_INET6:
1086: local = IN6_IS_ADDR_LOOPBACK(&(((struct sockaddr_in6 *)hostaddr)->sin6_addr));
1087: break;
1088: default:
1089: local = 0;
1090: break;
1091: }
1092: if (local) {
1093: debug("Forcing accepting of host key for loopback/localhost.");
1094: return;
1095: }
1.42 markus 1096:
1097: /*
1.44 markus 1098: * Turn off check_host_ip for proxy connects, since
1.42 markus 1099: * we don't have the remote ip-address
1100: */
1101: if (options.proxy_command != NULL && options.check_host_ip)
1102: options.check_host_ip = 0;
1.38 markus 1103:
1.49 markus 1104: if (options.check_host_ip) {
1105: if (getnameinfo(hostaddr, hostaddr->sa_len, ntop, sizeof(ntop),
1106: NULL, 0, NI_NUMERICHOST) != 0)
1107: fatal("check_host_key: getnameinfo failed");
1108: ip = xstrdup(ntop);
1109: }
1.38 markus 1110:
1.46 markus 1111: /*
1112: * Store the host key from the known host file in here so that we can
1113: * compare it with the key for the IP address.
1114: */
1.38 markus 1115: file_key = RSA_new();
1116: file_key->n = BN_new();
1117: file_key->e = BN_new();
1118:
1.40 markus 1119: /*
1120: * Check if the host key is present in the user\'s list of known
1121: * hosts or in the systemwide list.
1122: */
1.38 markus 1123: host_status = check_host_in_hostfile(options.user_hostfile, host,
1124: host_key->e, host_key->n,
1125: file_key->e, file_key->n);
1126: if (host_status == HOST_NEW)
1127: host_status = check_host_in_hostfile(options.system_hostfile, host,
1128: host_key->e, host_key->n,
1129: file_key->e, file_key->n);
1.40 markus 1130: /*
1131: * Also perform check for the ip address, skip the check if we are
1132: * localhost or the hostname was an ip address to begin with
1133: */
1.38 markus 1134: if (options.check_host_ip && !local && strcmp(host, ip)) {
1135: RSA *ip_key = RSA_new();
1136: ip_key->n = BN_new();
1137: ip_key->e = BN_new();
1138: ip_status = check_host_in_hostfile(options.user_hostfile, ip,
1139: host_key->e, host_key->n,
1140: ip_key->e, ip_key->n);
1141:
1142: if (ip_status == HOST_NEW)
1143: ip_status = check_host_in_hostfile(options.system_hostfile, ip,
1144: host_key->e, host_key->n,
1145: ip_key->e, ip_key->n);
1146: if (host_status == HOST_CHANGED &&
1147: (ip_status != HOST_CHANGED ||
1148: (BN_cmp(ip_key->e, file_key->e) || BN_cmp(ip_key->n, file_key->n))))
1149: host_ip_differ = 1;
1150:
1151: RSA_free(ip_key);
1152: } else
1153: ip_status = host_status;
1154:
1155: RSA_free(file_key);
1156:
1157: switch (host_status) {
1158: case HOST_OK:
1159: /* The host is known and the key matches. */
1160: debug("Host '%.200s' is known and matches the host key.", host);
1161: if (options.check_host_ip) {
1162: if (ip_status == HOST_NEW) {
1163: if (!add_host_to_hostfile(options.user_hostfile, ip,
1164: host_key->e, host_key->n))
1165: log("Failed to add the host key for IP address '%.30s' to the list of known hosts (%.30s).",
1166: ip, options.user_hostfile);
1167: else
1168: log("Warning: Permanently added host key for IP address '%.30s' to the list of known hosts.",
1169: ip);
1170: } else if (ip_status != HOST_OK)
1171: log("Warning: the host key for '%.200s' differs from the key for the IP address '%.30s'",
1172: host, ip);
1173: }
1174: break;
1175: case HOST_NEW:
1176: /* The host is new. */
1177: if (options.strict_host_key_checking == 1) {
1178: /* User has requested strict host key checking. We will not add the host key
1179: automatically. The only alternative left is to abort. */
1180: fatal("No host key is known for %.200s and you have requested strict checking.", host);
1181: } else if (options.strict_host_key_checking == 2) {
1182: /* The default */
1183: char prompt[1024];
1184: char *fp = fingerprint(host_key->e, host_key->n);
1185: snprintf(prompt, sizeof(prompt),
1.45 deraadt 1186: "The authenticity of host '%.200s' can't be established.\n"
1187: "Key fingerprint is %d %s.\n"
1188: "Are you sure you want to continue connecting (yes/no)? ",
1189: host, BN_num_bits(host_key->n), fp);
1.38 markus 1190: if (!read_yes_or_no(prompt, -1))
1191: fatal("Aborted by user!\n");
1192: }
1193: if (options.check_host_ip && ip_status == HOST_NEW && strcmp(host, ip)) {
1194: snprintf(hostline, sizeof(hostline), "%s,%s", host, ip);
1195: hostp = hostline;
1196: } else
1197: hostp = host;
1198:
1199: /* If not in strict mode, add the key automatically to the local known_hosts file. */
1200: if (!add_host_to_hostfile(options.user_hostfile, hostp,
1201: host_key->e, host_key->n))
1202: log("Failed to add the host to the list of known hosts (%.500s).",
1203: options.user_hostfile);
1204: else
1205: log("Warning: Permanently added '%.200s' to the list of known hosts.",
1206: hostp);
1207: break;
1208: case HOST_CHANGED:
1209: if (options.check_host_ip && host_ip_differ) {
1210: char *msg;
1211: if (ip_status == HOST_NEW)
1212: msg = "is unknown";
1213: else if (ip_status == HOST_OK)
1214: msg = "is unchanged";
1215: else
1216: msg = "has a different value";
1217: error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1218: error("@ WARNING: POSSIBLE DNS SPOOFING DETECTED! @");
1219: error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1220: error("The host key for %s has changed,", host);
1221: error("and the key for the according IP address %s", ip);
1222: error("%s. This could either mean that", msg);
1223: error("DNS SPOOFING is happening or the IP address for the host");
1224: error("and its host key have changed at the same time");
1225: }
1226: /* The host key has changed. */
1227: error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1.47 markus 1228: error("@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @");
1.38 markus 1229: error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1230: error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
1231: error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
1232: error("It is also possible that the host key has just been changed.");
1233: error("Please contact your system administrator.");
1234: error("Add correct host key in %.100s to get rid of this message.",
1235: options.user_hostfile);
1236:
1.40 markus 1237: /*
1238: * If strict host key checking is in use, the user will have
1239: * to edit the key manually and we can only abort.
1240: */
1.38 markus 1241: if (options.strict_host_key_checking)
1242: fatal("Host key for %.200s has changed and you have requested strict checking.", host);
1243:
1.40 markus 1244: /*
1245: * If strict host key checking has not been requested, allow
1246: * the connection but without password authentication or
1247: * agent forwarding.
1248: */
1.38 markus 1249: if (options.password_authentication) {
1250: error("Password authentication is disabled to avoid trojan horses.");
1251: options.password_authentication = 0;
1252: }
1253: if (options.forward_agent) {
1254: error("Agent forwarding is disabled to avoid trojan horses.");
1255: options.forward_agent = 0;
1256: }
1.40 markus 1257: /*
1258: * XXX Should permit the user to change to use the new id.
1259: * This could be done by converting the host key to an
1260: * identifying sentence, tell that the host identifies itself
1261: * by that sentence, and ask the user if he/she whishes to
1262: * accept the authentication.
1263: */
1.38 markus 1264: break;
1265: }
1266: if (options.check_host_ip)
1267: xfree(ip);
1.46 markus 1268: }
1269:
1270: /*
1.51 markus 1271: * SSH1 key exchange
1.46 markus 1272: */
1273: void
1.51 markus 1274: ssh_kex(char *host, struct sockaddr *hostaddr)
1.46 markus 1275: {
1.51 markus 1276: int i;
1.46 markus 1277: BIGNUM *key;
1278: RSA *host_key;
1279: RSA *public_key;
1280: int bits, rbits;
1281: unsigned char session_key[SSH_SESSION_KEY_LENGTH];
1.51 markus 1282: unsigned char cookie[8];
1283: unsigned int supported_ciphers;
1.46 markus 1284: unsigned int server_flags, client_flags;
1285: int payload_len, clen, sum_len = 0;
1286: u_int32_t rand = 0;
1287:
1288: debug("Waiting for server public key.");
1289:
1290: /* Wait for a public key packet from the server. */
1291: packet_read_expect(&payload_len, SSH_SMSG_PUBLIC_KEY);
1292:
1.51 markus 1293: /* Get cookie from the packet. */
1.46 markus 1294: for (i = 0; i < 8; i++)
1.51 markus 1295: cookie[i] = packet_get_char();
1.46 markus 1296:
1297: /* Get the public key. */
1298: public_key = RSA_new();
1299: bits = packet_get_int();/* bits */
1300: public_key->e = BN_new();
1301: packet_get_bignum(public_key->e, &clen);
1302: sum_len += clen;
1303: public_key->n = BN_new();
1304: packet_get_bignum(public_key->n, &clen);
1305: sum_len += clen;
1306:
1307: rbits = BN_num_bits(public_key->n);
1308: if (bits != rbits) {
1309: log("Warning: Server lies about size of server public key: "
1310: "actual size is %d bits vs. announced %d.", rbits, bits);
1311: log("Warning: This may be due to an old implementation of ssh.");
1312: }
1313: /* Get the host key. */
1314: host_key = RSA_new();
1315: bits = packet_get_int();/* bits */
1316: host_key->e = BN_new();
1317: packet_get_bignum(host_key->e, &clen);
1318: sum_len += clen;
1319: host_key->n = BN_new();
1320: packet_get_bignum(host_key->n, &clen);
1321: sum_len += clen;
1322:
1323: rbits = BN_num_bits(host_key->n);
1324: if (bits != rbits) {
1325: log("Warning: Server lies about size of server host key: "
1326: "actual size is %d bits vs. announced %d.", rbits, bits);
1327: log("Warning: This may be due to an old implementation of ssh.");
1328: }
1329:
1330: /* Get protocol flags. */
1331: server_flags = packet_get_int();
1332: packet_set_protocol_flags(server_flags);
1333:
1334: supported_ciphers = packet_get_int();
1335: supported_authentications = packet_get_int();
1336:
1337: debug("Received server public key (%d bits) and host key (%d bits).",
1338: BN_num_bits(public_key->n), BN_num_bits(host_key->n));
1339:
1340: packet_integrity_check(payload_len,
1341: 8 + 4 + sum_len + 0 + 4 + 0 + 0 + 4 + 4 + 4,
1342: SSH_SMSG_PUBLIC_KEY);
1343:
1344: check_host_key(host, hostaddr, host_key);
1345:
1346: client_flags = SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN;
1347:
1.51 markus 1348: compute_session_id(session_id, cookie, host_key->n, public_key->n);
1.38 markus 1349:
1350: /* Generate a session key. */
1351: arc4random_stir();
1352:
1.40 markus 1353: /*
1354: * Generate an encryption key for the session. The key is a 256 bit
1355: * random number, interpreted as a 32-byte key, with the least
1356: * significant 8 bits being the first byte of the key.
1357: */
1.38 markus 1358: for (i = 0; i < 32; i++) {
1359: if (i % 4 == 0)
1360: rand = arc4random();
1361: session_key[i] = rand & 0xff;
1362: rand >>= 8;
1363: }
1364:
1.40 markus 1365: /*
1366: * According to the protocol spec, the first byte of the session key
1367: * is the highest byte of the integer. The session key is xored with
1368: * the first 16 bytes of the session id.
1369: */
1.38 markus 1370: key = BN_new();
1371: BN_set_word(key, 0);
1372: for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
1373: BN_lshift(key, key, 8);
1374: if (i < 16)
1375: BN_add_word(key, session_key[i] ^ session_id[i]);
1376: else
1377: BN_add_word(key, session_key[i]);
1378: }
1379:
1.40 markus 1380: /*
1381: * Encrypt the integer using the public key and host key of the
1382: * server (key with smaller modulus first).
1383: */
1.38 markus 1384: if (BN_cmp(public_key->n, host_key->n) < 0) {
1385: /* Public key has smaller modulus. */
1386: if (BN_num_bits(host_key->n) <
1387: BN_num_bits(public_key->n) + SSH_KEY_BITS_RESERVED) {
1388: fatal("respond_to_rsa_challenge: host_key %d < public_key %d + "
1389: "SSH_KEY_BITS_RESERVED %d",
1390: BN_num_bits(host_key->n),
1391: BN_num_bits(public_key->n),
1392: SSH_KEY_BITS_RESERVED);
1393: }
1394: rsa_public_encrypt(key, key, public_key);
1395: rsa_public_encrypt(key, key, host_key);
1396: } else {
1397: /* Host key has smaller modulus (or they are equal). */
1398: if (BN_num_bits(public_key->n) <
1399: BN_num_bits(host_key->n) + SSH_KEY_BITS_RESERVED) {
1400: fatal("respond_to_rsa_challenge: public_key %d < host_key %d + "
1401: "SSH_KEY_BITS_RESERVED %d",
1402: BN_num_bits(public_key->n),
1403: BN_num_bits(host_key->n),
1404: SSH_KEY_BITS_RESERVED);
1405: }
1406: rsa_public_encrypt(key, key, host_key);
1407: rsa_public_encrypt(key, key, public_key);
1408: }
1409:
1.52 markus 1410: /* Destroy the public keys since we no longer need them. */
1411: RSA_free(public_key);
1412: RSA_free(host_key);
1413:
1.38 markus 1414: if (options.cipher == SSH_CIPHER_NOT_SET) {
1415: if (cipher_mask() & supported_ciphers & (1 << ssh_cipher_default))
1416: options.cipher = ssh_cipher_default;
1417: else {
1418: debug("Cipher %s not supported, using %.100s instead.",
1419: cipher_name(ssh_cipher_default),
1420: cipher_name(SSH_FALLBACK_CIPHER));
1421: options.cipher = SSH_FALLBACK_CIPHER;
1422: }
1423: }
1424: /* Check that the selected cipher is supported. */
1425: if (!(supported_ciphers & (1 << options.cipher)))
1426: fatal("Selected cipher type %.100s not supported by server.",
1427: cipher_name(options.cipher));
1428:
1429: debug("Encryption type: %.100s", cipher_name(options.cipher));
1430:
1431: /* Send the encrypted session key to the server. */
1432: packet_start(SSH_CMSG_SESSION_KEY);
1433: packet_put_char(options.cipher);
1434:
1.51 markus 1435: /* Send the cookie back to the server. */
1.38 markus 1436: for (i = 0; i < 8; i++)
1.51 markus 1437: packet_put_char(cookie[i]);
1.38 markus 1438:
1.52 markus 1439: /* Send and destroy the encrypted encryption key integer. */
1.38 markus 1440: packet_put_bignum(key);
1.52 markus 1441: BN_clear_free(key);
1.38 markus 1442:
1443: /* Send protocol flags. */
1.46 markus 1444: packet_put_int(client_flags);
1.38 markus 1445:
1446: /* Send the packet now. */
1447: packet_send();
1448: packet_write_wait();
1449:
1450: debug("Sent encrypted session key.");
1451:
1452: /* Set the encryption key. */
1453: packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, options.cipher);
1454:
1455: /* We will no longer need the session key here. Destroy any extra copies. */
1456: memset(session_key, 0, sizeof(session_key));
1457:
1.40 markus 1458: /*
1459: * Expect a success message from the server. Note that this message
1460: * will be received in encrypted form.
1461: */
1.38 markus 1462: packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1463:
1464: debug("Received encrypted confirmation.");
1.51 markus 1465: }
1466:
1467: /*
1468: * Authenticate user
1469: */
1470: void
1471: ssh_userauth(int host_key_valid, RSA *own_host_key,
1472: uid_t original_real_uid, char *host)
1473: {
1474: int i, type;
1475: int payload_len;
1476: struct passwd *pw;
1477: const char *server_user, *local_user;
1478:
1479: /* Get local user name. Use it as server user if no user name was given. */
1480: pw = getpwuid(original_real_uid);
1481: if (!pw)
1482: fatal("User id %d not found from user database.", original_real_uid);
1483: local_user = xstrdup(pw->pw_name);
1484: server_user = options.user ? options.user : local_user;
1.38 markus 1485:
1486: /* Send the name of the user to log in as on the server. */
1487: packet_start(SSH_CMSG_USER);
1488: packet_put_string(server_user, strlen(server_user));
1.16 dugsong 1489: packet_send();
1490: packet_write_wait();
1.38 markus 1491:
1.40 markus 1492: /*
1493: * The server should respond with success if no authentication is
1494: * needed (the user has no password). Otherwise the server responds
1495: * with failure.
1496: */
1.16 dugsong 1497: type = packet_read(&payload_len);
1.38 markus 1498:
1499: /* check whether the connection was accepted without authentication. */
1.16 dugsong 1500: if (type == SSH_SMSG_SUCCESS)
1.38 markus 1501: return;
1.16 dugsong 1502: if (type != SSH_SMSG_FAILURE)
1.38 markus 1503: packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER",
1504: type);
1505:
1506: #ifdef AFS
1507: /* Try Kerberos tgt passing if the server supports it. */
1508: if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1509: options.kerberos_tgt_passing) {
1510: if (options.cipher == SSH_CIPHER_NONE)
1511: log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1512: (void) send_kerberos_tgt();
1513: }
1514: /* Try AFS token passing if the server supports it. */
1515: if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
1516: options.afs_token_passing && k_hasafs()) {
1517: if (options.cipher == SSH_CIPHER_NONE)
1518: log("WARNING: Encryption is disabled! Token will be transmitted in the clear!");
1519: send_afs_tokens();
1520: }
1521: #endif /* AFS */
1522:
1523: #ifdef KRB4
1524: if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1525: options.kerberos_authentication) {
1526: debug("Trying Kerberos authentication.");
1527: if (try_kerberos_authentication()) {
1528: /* The server should respond with success or failure. */
1529: type = packet_read(&payload_len);
1530: if (type == SSH_SMSG_SUCCESS)
1531: return;
1532: if (type != SSH_SMSG_FAILURE)
1533: packet_disconnect("Protocol error: got %d in response to Kerberos auth", type);
1534: }
1535: }
1536: #endif /* KRB4 */
1537:
1.40 markus 1538: /*
1539: * Use rhosts authentication if running in privileged socket and we
1540: * do not wish to remain anonymous.
1541: */
1.38 markus 1542: if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
1543: options.rhosts_authentication) {
1544: debug("Trying rhosts authentication.");
1545: packet_start(SSH_CMSG_AUTH_RHOSTS);
1546: packet_put_string(local_user, strlen(local_user));
1547: packet_send();
1548: packet_write_wait();
1549:
1550: /* The server should respond with success or failure. */
1551: type = packet_read(&payload_len);
1552: if (type == SSH_SMSG_SUCCESS)
1553: return;
1554: if (type != SSH_SMSG_FAILURE)
1555: packet_disconnect("Protocol error: got %d in response to rhosts auth",
1556: type);
1557: }
1.40 markus 1558: /*
1559: * Try .rhosts or /etc/hosts.equiv authentication with RSA host
1560: * authentication.
1561: */
1.38 markus 1562: if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
1563: options.rhosts_rsa_authentication && host_key_valid) {
1564: if (try_rhosts_rsa_authentication(local_user, own_host_key))
1565: return;
1566: }
1567: /* Try RSA authentication if the server supports it. */
1568: if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
1569: options.rsa_authentication) {
1.40 markus 1570: /*
1571: * Try RSA authentication using the authentication agent. The
1572: * agent is tried first because no passphrase is needed for
1573: * it, whereas identity files may require passphrases.
1574: */
1.38 markus 1575: if (try_agent_authentication())
1576: return;
1577:
1578: /* Try RSA authentication for each identity. */
1579: for (i = 0; i < options.num_identity_files; i++)
1.43 markus 1580: if (try_rsa_authentication(options.identity_files[i]))
1.38 markus 1581: return;
1582: }
1583: /* Try skey authentication if the server supports it. */
1584: if ((supported_authentications & (1 << SSH_AUTH_TIS)) &&
1585: options.skey_authentication && !options.batch_mode) {
1.43 markus 1586: if (try_skey_authentication())
1587: return;
1.38 markus 1588: }
1589: /* Try password authentication if the server supports it. */
1590: if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
1591: options.password_authentication && !options.batch_mode) {
1592: char prompt[80];
1.45 deraadt 1593:
1.43 markus 1594: snprintf(prompt, sizeof(prompt), "%.30s@%.40s's password: ",
1.45 deraadt 1595: server_user, host);
1.43 markus 1596: if (try_password_authentication(prompt))
1597: return;
1.38 markus 1598: }
1599: /* All authentication methods have failed. Exit with an error message. */
1600: fatal("Permission denied.");
1601: /* NOTREACHED */
1.51 markus 1602: }
1603:
1604: /*
1605: * Starts a dialog with the server, and authenticates the current user on the
1606: * server. This does not need any extra privileges. The basic connection
1607: * to the server must already have been established before this is called.
1608: * If login fails, this function prints an error and never returns.
1609: * This function does not require super-user privileges.
1610: */
1611: void
1612: ssh_login(int host_key_valid, RSA *own_host_key, const char *orighost,
1613: struct sockaddr *hostaddr, uid_t original_real_uid)
1614: {
1615: char *host, *cp;
1616:
1617: /* Convert the user-supplied hostname into all lowercase. */
1618: host = xstrdup(orighost);
1619: for (cp = host; *cp; cp++)
1620: if (isupper(*cp))
1621: *cp = tolower(*cp);
1622:
1623: /* Exchange protocol version identification strings with the server. */
1624: ssh_exchange_identification();
1625:
1626: /* Put the connection into non-blocking mode. */
1627: packet_set_nonblocking();
1628:
1629: supported_authentications = 0;
1630: /* key exchange */
1631: ssh_kex(host, hostaddr);
1632: if (supported_authentications == 0)
1633: fatal("supported_authentications == 0.");
1634: /* authenticate user */
1635: ssh_userauth(host_key_valid, own_host_key, original_real_uid, host);
1.1 deraadt 1636: }