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