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