Annotation of src/usr.bin/ssh/sshconnect.c, Revision 1.12
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.12 ! provos 18: RCSID("$Id: sshconnect.c,v 1.11 1999/10/03 19:22:39 deraadt 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();
889:
890: /* Read other side\'s version identification. */
891: for (i = 0; i < sizeof(buf) - 1; i++)
892: {
893: if (read(connection_in, &buf[i], 1) != 1)
894: fatal("read: %.100s", strerror(errno));
895: if (buf[i] == '\r')
896: {
897: buf[i] = '\n';
898: buf[i + 1] = 0;
899: break;
900: }
901: if (buf[i] == '\n')
902: {
903: buf[i + 1] = 0;
904: break;
905: }
906: }
907: buf[sizeof(buf) - 1] = 0;
908:
909: /* Check that the versions match. In future this might accept several
910: versions and set appropriate flags to handle them. */
911: if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
912: remote_version) != 3)
913: fatal("Bad remote protocol version identification: '%.100s'", buf);
914: debug("Remote protocol version %d.%d, remote software version %.100s",
915: remote_major, remote_minor, remote_version);
916: #if 0
917: /* Removed for now, to permit compatibility with latter versions. The server
918: will reject our version and disconnect if it doesn't support it. */
919: if (remote_major != PROTOCOL_MAJOR)
920: fatal("Protocol major versions differ: %d vs. %d",
921: PROTOCOL_MAJOR, remote_major);
922: #endif
923:
924: /* Check if the remote protocol version is too old. */
925: if (remote_major == 1 && remote_minor == 0)
926: fatal("Remote machine has too old SSH software version.");
927:
928: /* Send our own protocol version identification. */
1.6 deraadt 929: snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
1.1 deraadt 930: PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
931: if (write(connection_out, buf, strlen(buf)) != strlen(buf))
932: fatal("write: %.100s", strerror(errno));
933: }
934:
935: int ssh_cipher_default = SSH_CIPHER_3DES;
936:
937: int read_yes_or_no(const char *prompt, int defval)
938: {
939: char buf[1024];
940: FILE *f;
941: int retval = -1;
942:
943: if (isatty(0))
944: f = stdin;
945: else
946: f = fopen("/dev/tty", "rw");
947:
948: if (f == NULL)
949: return 0;
950:
951: fflush(stdout);
952:
953: while (1)
954: {
955: fprintf(stderr, "%s", prompt);
956: if (fgets(buf, sizeof(buf), f) == NULL)
957: {
958: /* Print a newline (the prompt probably didn\'t have one). */
959: fprintf(stderr, "\n");
1.6 deraadt 960: strlcpy(buf, "no", sizeof buf);
1.1 deraadt 961: }
962: /* Remove newline from response. */
963: if (strchr(buf, '\n'))
964: *strchr(buf, '\n') = 0;
965:
966: if (buf[0] == 0)
967: retval = defval;
968: if (strcmp(buf, "yes") == 0)
969: retval = 1;
970: if (strcmp(buf, "no") == 0)
971: retval = 0;
972:
973: if (retval != -1)
974: {
975: if (f != stdin)
976: fclose(f);
977: return retval;
978: }
979: }
980: }
981:
982: /* Starts a dialog with the server, and authenticates the current user on the
983: server. This does not need any extra privileges. The basic connection
984: to the server must already have been established before this is called.
985: User is the remote user; if it is NULL, the current local user name will
986: be used. Anonymous indicates that no rhosts authentication will be used.
987: If login fails, this function prints an error and never returns.
988: This function does not require super-user privileges. */
989:
1.3 provos 990: void ssh_login(int host_key_valid,
991: RSA *own_host_key,
1.1 deraadt 992: const char *orighost,
1.12 ! provos 993: struct sockaddr_in *hostaddr,
1.1 deraadt 994: Options *options, uid_t original_real_uid)
995: {
996: int i, type;
997: char *password;
998: struct passwd *pw;
1.3 provos 999: BIGNUM *key;
1.12 ! provos 1000: RSA *host_key, *file_key;
1.3 provos 1001: RSA *public_key;
1.1 deraadt 1002: unsigned char session_key[SSH_SESSION_KEY_LENGTH];
1003: const char *server_user, *local_user;
1004: char *cp, *host;
1005: unsigned char check_bytes[8];
1006: unsigned int supported_ciphers, supported_authentications, protocol_flags;
1007: HostStatus host_status;
1.12 ! provos 1008: HostStatus ip_status;
1.1 deraadt 1009: int payload_len, clen, sum_len = 0;
1.5 dugsong 1010: u_int32_t rand = 0;
1.1 deraadt 1011:
1012: /* Convert the user-supplied hostname into all lowercase. */
1013: host = xstrdup(orighost);
1014: for (cp = host; *cp; cp++)
1015: if (isupper(*cp))
1016: *cp = tolower(*cp);
1017:
1018: /* Exchange protocol version identification strings with the server. */
1019: ssh_exchange_identification();
1020:
1021: /* Put the connection into non-blocking mode. */
1022: packet_set_nonblocking();
1023:
1024: /* Get local user name. Use it as server user if no user name
1025: was given. */
1026: pw = getpwuid(original_real_uid);
1027: if (!pw)
1028: fatal("User id %d not found from user database.", original_real_uid);
1029: local_user = xstrdup(pw->pw_name);
1030: server_user = options->user ? options->user : local_user;
1031:
1032: debug("Waiting for server public key.");
1033:
1034: /* Wait for a public key packet from the server. */
1035: packet_read_expect(&payload_len, SSH_SMSG_PUBLIC_KEY);
1036:
1037: /* Get check bytes from the packet. */
1038: for (i = 0; i < 8; i++)
1039: check_bytes[i] = packet_get_char();
1040:
1041: /* Get the public key. */
1.3 provos 1042: public_key = RSA_new();
1043: packet_get_int(); /* bits */
1044: public_key->e = BN_new();
1045: packet_get_bignum(public_key->e, &clen);
1.1 deraadt 1046: sum_len += clen;
1.3 provos 1047: public_key->n = BN_new();
1048: packet_get_bignum(public_key->n, &clen);
1.1 deraadt 1049: sum_len += clen;
1050:
1051: /* Get the host key. */
1.3 provos 1052: host_key = RSA_new();
1053: packet_get_int(); /* bits */
1054: host_key->e = BN_new();
1055: packet_get_bignum(host_key->e, &clen);
1.1 deraadt 1056: sum_len += clen;
1.3 provos 1057: host_key->n = BN_new();
1058: packet_get_bignum(host_key->n, &clen);
1.1 deraadt 1059: sum_len += clen;
1060:
1.12 ! provos 1061: if (options->check_host_ip && strcmp(host, inet_ntoa(hostaddr->sin_addr))) {
! 1062: /* Store the host key from the known host file in here
! 1063: * so that we can compare it with the key for the IP
! 1064: * address. */
! 1065: file_key = RSA_new();
! 1066: file_key->n = BN_new();
! 1067: file_key->e = BN_new();
! 1068: }
! 1069:
1.1 deraadt 1070: /* Get protocol flags. */
1071: protocol_flags = packet_get_int();
1072: packet_set_protocol_flags(protocol_flags);
1073:
1074: /* Get supported cipher types. */
1075: supported_ciphers = packet_get_int();
1076:
1077: /* Get supported authentication types. */
1078: supported_authentications = packet_get_int();
1079:
1080: debug("Received server public key (%d bits) and host key (%d bits).",
1.3 provos 1081: BN_num_bits(public_key->n), BN_num_bits(host_key->n));
1.1 deraadt 1082:
1083: packet_integrity_check(payload_len,
1084: 8 + 4 + sum_len + 0 + 4 + 0 + 0 + 4 + 4 + 4,
1085: SSH_SMSG_PUBLIC_KEY);
1086:
1087: /* Compute the session id. */
1.3 provos 1088: compute_session_id(session_id, check_bytes,
1089: BN_num_bits(host_key->n), host_key->n,
1090: BN_num_bits(public_key->n), public_key->n);
1.1 deraadt 1091:
1092: /* Check if the host key is present in the user\'s list of known hosts
1093: or in the systemwide list. */
1094: host_status = check_host_in_hostfile(options->user_hostfile,
1.3 provos 1095: host, BN_num_bits(host_key->n),
1.12 ! provos 1096: host_key->e, host_key->n,
! 1097: file_key->e, file_key->n);
1.1 deraadt 1098: if (host_status == HOST_NEW)
1099: host_status = check_host_in_hostfile(options->system_hostfile, host,
1.3 provos 1100: BN_num_bits(host_key->n),
1.12 ! provos 1101: host_key->e, host_key->n,
! 1102: file_key->e, file_key->n);
1.1 deraadt 1103: /* Force accepting of the host key for localhost and 127.0.0.1.
1104: The problem is that if the home directory is NFS-mounted to multiple
1105: machines, localhost will refer to a different machine in each of them,
1106: and the user will get bogus HOST_CHANGED warnings. This essentially
1107: disables host authentication for localhost; however, this is probably
1108: not a real problem. */
1109: if (strcmp(host, "localhost") == 0 ||
1110: strcmp(host, "127.0.0.1") == 0)
1111: {
1112: debug("Forcing accepting of host key for localhost.");
1113: host_status = HOST_OK;
1114: }
1115:
1.12 ! provos 1116: /* Also perform check for the ip address */
! 1117: if (options->check_host_ip && strcmp(host, inet_ntoa(hostaddr->sin_addr))) {
! 1118: RSA *ip_key = RSA_new();
! 1119: ip_key->n = BN_new();
! 1120: ip_key->e = BN_new();
! 1121: ip_status = check_host_in_hostfile(options->user_hostfile,
! 1122: inet_ntoa(hostaddr->sin_addr),
! 1123: BN_num_bits(host_key->n),
! 1124: host_key->e, host_key->n,
! 1125: ip_key->e, ip_key->n);
! 1126:
! 1127: if (ip_status == HOST_NEW)
! 1128: ip_status = check_host_in_hostfile(options->system_hostfile,
! 1129: inet_ntoa(hostaddr->sin_addr),
! 1130: BN_num_bits(host_key->n),
! 1131: host_key->e, host_key->n,
! 1132: ip_key->e, ip_key->n);
! 1133: if (ip_status == HOST_CHANGED && host_status == HOST_CHANGED &&
! 1134: (BN_cmp(ip_key->e, file_key->e) || BN_cmp(ip_key->n, file_key->n)))
! 1135: ip_status = HOST_DIFFER;
! 1136:
! 1137: RSA_free(ip_key);
! 1138: RSA_free(file_key);
! 1139: } else
! 1140: ip_status = host_status;
! 1141:
! 1142: switch (host_status) {
! 1143: case HOST_OK:
! 1144: /* The host is known and the key matches. */
! 1145: debug("Host '%.200s' is known and matches the host key.", host);
! 1146: if (options->check_host_ip) {
! 1147: if (ip_status == HOST_NEW) {
! 1148: if (!add_host_to_hostfile(options->user_hostfile,
! 1149: inet_ntoa(hostaddr->sin_addr),
! 1150: BN_num_bits(host_key->n),
! 1151: host_key->e, host_key->n))
! 1152: log("Failed to add the host ip to the list of known hosts (%.30s).",
! 1153: options->user_hostfile);
! 1154: else
! 1155: log("Warning: Permanently added host ip '%.30s' to the list of known hosts.", inet_ntoa(hostaddr->sin_addr));
! 1156: } else if (ip_status != HOST_OK)
! 1157: log("Warning: the host key differ from the key of the ip address '%.30s' differs", inet_ntoa(hostaddr->sin_addr));
! 1158: }
! 1159:
! 1160: break;
! 1161: case HOST_NEW:
1.1 deraadt 1162: {
1.12 ! provos 1163: char hostline[1000], *hostp = hostline;
1.1 deraadt 1164: /* The host is new. */
1.12 ! provos 1165: if (options->strict_host_key_checking == 1) {
! 1166: /* User has requested strict host key checking. We will not
! 1167: add the host key automatically. The only alternative left
! 1168: is to abort. */
! 1169: fatal("No host key is known for %.200s and you have requested strict checking.", host);
! 1170: } else if (options->strict_host_key_checking == 2) { /* The default */
! 1171: char prompt[1024];
! 1172: snprintf(prompt, sizeof(prompt),
! 1173: "The authenticity of host '%.200s' can't be established.\n"
! 1174: "Are you sure you want to continue connecting (yes/no)? ",
! 1175: host);
! 1176: if (!read_yes_or_no(prompt, -1))
! 1177: fatal("Aborted by user!\n");
! 1178: }
! 1179:
! 1180: if (options->check_host_ip && ip_status == HOST_NEW &&
! 1181: strcmp(host, inet_ntoa(hostaddr->sin_addr)))
! 1182: snprintf(hostline, sizeof(hostline), "%s,%s",
! 1183: host, inet_ntoa(hostaddr->sin_addr));
! 1184: else
! 1185: hostp = host;
! 1186:
1.1 deraadt 1187: /* If not in strict mode, add the key automatically to the local
1188: known_hosts file. */
1.12 ! provos 1189: if (!add_host_to_hostfile(options->user_hostfile, hostp,
1.3 provos 1190: BN_num_bits(host_key->n),
1191: host_key->e, host_key->n))
1.1 deraadt 1192: log("Failed to add the host to the list of known hosts (%.500s).",
1193: options->user_hostfile);
1194: else
1.12 ! provos 1195: log("Warning: Permanently added '%.200s' to the list of known hosts.",
! 1196: hostp);
1.1 deraadt 1197: break;
1198: }
1.12 ! provos 1199: case HOST_CHANGED:
! 1200: if (options->check_host_ip) {
! 1201: if (ip_status != HOST_CHANGED) {
! 1202: error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
! 1203: error("@ WARNING: POSSIBLE DNS SPOOFNG DETECTED! @");
! 1204: error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
! 1205: error("The host key for %s has changed,", host);
! 1206: error("but the key for the according IP address %s has",
! 1207: inet_ntoa(hostaddr->sin_addr));
! 1208: error("a different status. This could either mean that DNS");
! 1209: error("SPOOFING is happening or the IP address for the host");
! 1210: error("and its host key have changed at the same time");
! 1211: }
! 1212: }
! 1213:
! 1214: /* The host key has changed. */
! 1215: error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
! 1216: error("@ WARNING: HOST IDENTIFICATION HAS CHANGED! @");
! 1217: error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
! 1218: error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
! 1219: error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
! 1220: error("It is also possible that the host key has just been changed.");
! 1221: error("Please contact your system administrator.");
! 1222: error("Add correct host key in %.100s to get rid of this message.",
! 1223: options->user_hostfile);
! 1224:
! 1225: /* If strict host key checking is in use, the user will have to edit
! 1226: the key manually and we can only abort. */
! 1227: if (options->strict_host_key_checking)
! 1228: fatal("Host key for %.200s has changed and you have requested strict checking.", host);
! 1229:
! 1230: /* If strict host key checking has not been requested, allow the
! 1231: connection but without password authentication. */
! 1232: error("Password authentication is disabled to avoid trojan horses.");
! 1233: options->password_authentication = 0;
! 1234: /* XXX Should permit the user to change to use the new id. This could
! 1235: be done by converting the host key to an identifying sentence, tell
! 1236: that the host identifies itself by that sentence, and ask the user
! 1237: if he/she whishes to accept the authentication. */
! 1238: break;
! 1239: }
! 1240:
1.1 deraadt 1241: /* Generate a session key. */
1.3 provos 1242: arc4random_stir();
1.1 deraadt 1243:
1244: /* Generate an encryption key for the session. The key is a 256 bit
1245: random number, interpreted as a 32-byte key, with the least significant
1246: 8 bits being the first byte of the key. */
1.3 provos 1247: for (i = 0; i < 32; i++) {
1248: if (i % 4 == 0)
1249: rand = arc4random();
1250: session_key[i] = rand & 0xff;
1251: rand >>= 8;
1252: }
1.1 deraadt 1253:
1254: /* According to the protocol spec, the first byte of the session key is
1255: the highest byte of the integer. The session key is xored with the
1256: first 16 bytes of the session id. */
1.3 provos 1257: key = BN_new();
1258: BN_set_word(key, 0);
1.1 deraadt 1259: for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++)
1260: {
1.3 provos 1261: BN_lshift(key, key, 8);
1.1 deraadt 1262: if (i < 16)
1.3 provos 1263: BN_add_word(key, session_key[i] ^ session_id[i]);
1.1 deraadt 1264: else
1.3 provos 1265: BN_add_word(key, session_key[i]);
1.1 deraadt 1266: }
1267:
1268: /* Encrypt the integer using the public key and host key of the server
1269: (key with smaller modulus first). */
1.3 provos 1270: if (BN_cmp(public_key->n, host_key->n) < 0)
1.1 deraadt 1271: {
1272: /* Public key has smaller modulus. */
1.3 provos 1273: assert(BN_num_bits(host_key->n) >=
1274: BN_num_bits(public_key->n) + SSH_KEY_BITS_RESERVED);
1.1 deraadt 1275:
1.3 provos 1276: rsa_public_encrypt(key, key, public_key);
1277: rsa_public_encrypt(key, key, host_key);
1.1 deraadt 1278: }
1279: else
1280: {
1281: /* Host key has smaller modulus (or they are equal). */
1.3 provos 1282: assert(BN_num_bits(public_key->n) >=
1283: BN_num_bits(host_key->n) + SSH_KEY_BITS_RESERVED);
1.1 deraadt 1284:
1.3 provos 1285: rsa_public_encrypt(key, key, host_key);
1286: rsa_public_encrypt(key, key, public_key);
1.1 deraadt 1287: }
1288:
1.3 provos 1289: if (options->cipher == SSH_CIPHER_NOT_SET) {
1.1 deraadt 1290: if (cipher_mask() & supported_ciphers & (1 << ssh_cipher_default))
1291: options->cipher = ssh_cipher_default;
1.3 provos 1292: else {
1293: debug("Cipher %d not supported, using %.100s instead.",
1294: cipher_name(ssh_cipher_default),
1295: cipher_name(SSH_FALLBACK_CIPHER));
1296: options->cipher = SSH_FALLBACK_CIPHER;
1297: }
1298: }
1.1 deraadt 1299:
1300: /* Check that the selected cipher is supported. */
1301: if (!(supported_ciphers & (1 << options->cipher)))
1302: fatal("Selected cipher type %.100s not supported by server.",
1303: cipher_name(options->cipher));
1304:
1305: debug("Encryption type: %.100s", cipher_name(options->cipher));
1306:
1307: /* Send the encrypted session key to the server. */
1308: packet_start(SSH_CMSG_SESSION_KEY);
1309: packet_put_char(options->cipher);
1310:
1311: /* Send the check bytes back to the server. */
1312: for (i = 0; i < 8; i++)
1313: packet_put_char(check_bytes[i]);
1314:
1315: /* Send the encrypted encryption key. */
1.3 provos 1316: packet_put_bignum(key);
1.1 deraadt 1317:
1318: /* Send protocol flags. */
1319: packet_put_int(SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1320:
1321: /* Send the packet now. */
1322: packet_send();
1323: packet_write_wait();
1324:
1325: /* Destroy the session key integer and the public keys since we no longer
1326: need them. */
1.3 provos 1327: BN_clear_free(key);
1328: RSA_free(public_key);
1329: RSA_free(host_key);
1.1 deraadt 1330:
1331: debug("Sent encrypted session key.");
1332:
1333: /* Set the encryption key. */
1334: packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH,
1335: options->cipher, 1);
1336:
1337: /* We will no longer need the session key here. Destroy any extra copies. */
1338: memset(session_key, 0, sizeof(session_key));
1339:
1340: /* Expect a success message from the server. Note that this message will
1341: be received in encrypted form. */
1342: packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1343:
1344: debug("Received encrypted confirmation.");
1345:
1346: /* Send the name of the user to log in as on the server. */
1347: packet_start(SSH_CMSG_USER);
1348: packet_put_string(server_user, strlen(server_user));
1349: packet_send();
1350: packet_write_wait();
1351:
1352: /* The server should respond with success if no authentication is needed
1353: (the user has no password). Otherwise the server responds with
1354: failure. */
1355: type = packet_read(&payload_len);
1356: if (type == SSH_SMSG_SUCCESS)
1357: return; /* Connection was accepted without authentication. */
1358: if (type != SSH_SMSG_FAILURE)
1359: packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER",
1360: type);
1361:
1.5 dugsong 1362: #ifdef AFS
1.1 deraadt 1363: /* Try Kerberos tgt passing if the server supports it. */
1364: if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1.5 dugsong 1365: options->kerberos_tgt_passing)
1366: {
1367: if (options->cipher == SSH_CIPHER_NONE)
1368: log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1369: (void)send_kerberos_tgt();
1370: }
1371:
1.1 deraadt 1372: /* Try AFS token passing if the server supports it. */
1373: if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
1374: options->afs_token_passing && k_hasafs()) {
1375: if (options->cipher == SSH_CIPHER_NONE)
1376: log("WARNING: Encryption is disabled! Token will be transmitted in the clear!");
1377: send_afs_tokens();
1378: }
1379: #endif /* AFS */
1380:
1.5 dugsong 1381: #ifdef KRB4
1.1 deraadt 1382: if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1383: options->kerberos_authentication)
1384: {
1.5 dugsong 1385: debug("Trying Kerberos authentication.");
1.1 deraadt 1386: if (try_kerberos_authentication()) {
1387: /* The server should respond with success or failure. */
1388: type = packet_read(&payload_len);
1389: if (type == SSH_SMSG_SUCCESS)
1390: return; /* Successful connection. */
1391: if (type != SSH_SMSG_FAILURE)
1392: packet_disconnect("Protocol error: got %d in response to Kerberos auth", type);
1393: }
1394: }
1395: #endif /* KRB4 */
1396:
1397: /* Use rhosts authentication if running in privileged socket and we do not
1398: wish to remain anonymous. */
1399: if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
1400: options->rhosts_authentication)
1401: {
1402: debug("Trying rhosts authentication.");
1403: packet_start(SSH_CMSG_AUTH_RHOSTS);
1404: packet_put_string(local_user, strlen(local_user));
1405: packet_send();
1406: packet_write_wait();
1407:
1408: /* The server should respond with success or failure. */
1409: type = packet_read(&payload_len);
1410: if (type == SSH_SMSG_SUCCESS)
1411: return; /* Successful connection. */
1412: if (type != SSH_SMSG_FAILURE)
1413: packet_disconnect("Protocol error: got %d in response to rhosts auth",
1414: type);
1415: }
1416:
1417: /* Try .rhosts or /etc/hosts.equiv authentication with RSA host
1418: authentication. */
1419: if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
1420: options->rhosts_rsa_authentication && host_key_valid)
1421: {
1422: if (try_rhosts_rsa_authentication(local_user, own_host_key))
1423: return; /* Successful authentication. */
1424: }
1425:
1426: /* Try RSA authentication if the server supports it. */
1427: if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
1428: options->rsa_authentication)
1429: {
1430: /* Try RSA authentication using the authentication agent. The agent
1431: is tried first because no passphrase is needed for it, whereas
1432: identity files may require passphrases. */
1433: if (try_agent_authentication())
1434: return; /* Successful connection. */
1435:
1436: /* Try RSA authentication for each identity. */
1437: for (i = 0; i < options->num_identity_files; i++)
1438: if (try_rsa_authentication(pw, options->identity_files[i],
1439: !options->batch_mode))
1440: return; /* Successful connection. */
1441: }
1442:
1443: /* Try password authentication if the server supports it. */
1444: if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
1445: options->password_authentication && !options->batch_mode)
1446: {
1.4 provos 1447: char prompt[80];
1448: snprintf(prompt, sizeof(prompt), "%.30s@%.30s's password: ",
1449: server_user, host);
1.1 deraadt 1450: debug("Doing password authentication.");
1451: if (options->cipher == SSH_CIPHER_NONE)
1452: log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
1.4 provos 1453: password = read_passphrase(prompt, 0);
1.1 deraadt 1454: packet_start(SSH_CMSG_AUTH_PASSWORD);
1455: packet_put_string(password, strlen(password));
1456: memset(password, 0, strlen(password));
1457: xfree(password);
1458: packet_send();
1459: packet_write_wait();
1460:
1461: type = packet_read(&payload_len);
1462: if (type == SSH_SMSG_SUCCESS)
1463: return; /* Successful connection. */
1464: if (type != SSH_SMSG_FAILURE)
1465: packet_disconnect("Protocol error: got %d in response to passwd auth",
1466: type);
1467: }
1468:
1469: /* All authentication methods have failed. Exit with an error message. */
1470: fatal("Permission denied.");
1471: /*NOTREACHED*/
1472: }