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