2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * Created: Sat Mar 18 22:15:47 1995 ylo
6 * Code to connect to a remote host, and to perform the client side of the
7 * login (authentication) dialog.
14 #include <openssl/bn.h>
15 #include <openssl/md5.h>
32 #include "fingerprint.h"
34 /* Session id for the current session. */
35 unsigned char session_id[16];
37 extern Options options;
40 * Connect to the given ssh server using a proxy command.
43 ssh_proxy_connect(const char *host, u_short port, uid_t original_real_uid,
44 const char *proxy_command)
53 /* Convert the port number into a string. */
54 snprintf(portstring, sizeof portstring, "%hu", port);
56 /* Build the final command string in the buffer by making the
57 appropriate substitutions to the given proxy command. */
58 buffer_init(&command);
59 for (cp = proxy_command; *cp; cp++) {
60 if (cp[0] == '%' && cp[1] == '%') {
61 buffer_append(&command, "%", 1);
65 if (cp[0] == '%' && cp[1] == 'h') {
66 buffer_append(&command, host, strlen(host));
70 if (cp[0] == '%' && cp[1] == 'p') {
71 buffer_append(&command, portstring, strlen(portstring));
75 buffer_append(&command, cp, 1);
77 buffer_append(&command, "\0", 1);
79 /* Get the final command string. */
80 command_string = buffer_ptr(&command);
82 /* Create pipes for communicating with the proxy. */
83 if (pipe(pin) < 0 || pipe(pout) < 0)
84 fatal("Could not create pipes to communicate with the proxy: %.100s",
87 debug("Executing proxy command: %.500s", command_string);
89 /* Fork and execute the proxy command. */
90 if ((pid = fork()) == 0) {
93 /* Child. Permanently give up superuser privileges. */
94 permanently_set_uid(original_real_uid);
96 /* Redirect stdin and stdout. */
99 if (dup2(pin[0], 0) < 0)
100 perror("dup2 stdin");
104 if (dup2(pout[1], 1) < 0)
105 perror("dup2 stdout");
106 /* Cannot be 1 because pin allocated two descriptors. */
109 /* Stderr is left as it is so that error messages get
110 printed on the user's terminal. */
113 argv[2] = command_string;
116 /* Execute the proxy command. Note that we gave up any
117 extra privileges above. */
118 execv("/bin/sh", argv);
124 fatal("fork failed: %.100s", strerror(errno));
126 /* Close child side of the descriptors. */
130 /* Free the command name. */
131 buffer_free(&command);
133 /* Set the connection file descriptors. */
134 packet_set_connection(pout[0], pin[1]);
140 * Creates a (possibly privileged) socket for use as the ssh connection.
143 ssh_create_socket(uid_t original_real_uid, int privileged)
148 * If we are running as root and want to connect to a privileged
149 * port, bind our own socket to a privileged port.
152 int p = IPPORT_RESERVED - 1;
154 sock = rresvport(&p);
156 fatal("rresvport: %.100s", strerror(errno));
157 debug("Allocated local port %d.", p);
159 /* Just create an ordinary socket on arbitrary port. We
160 use the user's uid to create the socket. */
161 temporarily_use_uid(original_real_uid);
162 sock = socket(AF_INET, SOCK_STREAM, 0);
164 fatal("socket: %.100s", strerror(errno));
171 * Opens a TCP/IP connection to the remote server on the given host. If
172 * port is 0, the default port will be used. If anonymous is zero,
173 * a privileged port will be allocated to make the connection.
174 * This requires super-user privileges if anonymous is false.
175 * Connection_attempts specifies the maximum number of tries (one per
176 * second). If proxy_command is non-NULL, it specifies the command (with %h
177 * and %p substituted for host and port, respectively) to use to contact
181 ssh_connect(const char *host, struct sockaddr_in * hostaddr,
182 u_short port, int connection_attempts,
183 int anonymous, uid_t original_real_uid,
184 const char *proxy_command)
186 int sock = -1, attempt, i;
190 struct linger linger;
192 debug("ssh_connect: getuid %d geteuid %d anon %d",
193 (int) getuid(), (int) geteuid(), anonymous);
195 /* Get default port if port has not been set. */
197 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
199 port = ntohs(sp->s_port);
201 port = SSH_DEFAULT_PORT;
203 /* If a proxy command is given, connect using it. */
204 if (proxy_command != NULL)
205 return ssh_proxy_connect(host, port, original_real_uid, proxy_command);
207 /* No proxy command. */
209 /* No host lookup made yet. */
212 /* Try to connect several times. On some machines, the first time
213 will sometimes fail. In general socket code appears to behave
214 quite magically on many machines. */
215 for (attempt = 0; attempt < connection_attempts; attempt++) {
217 debug("Trying again...");
219 /* Try to parse the host name as a numeric inet address. */
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) {
225 /* Valid numeric IP address */
226 debug("Connecting to %.100s port %d.",
227 inet_ntoa(hostaddr->sin_addr), port);
229 /* Create a socket. */
230 sock = ssh_create_socket(original_real_uid,
231 !anonymous && geteuid() == 0 &&
232 port < IPPORT_RESERVED);
235 * Connect to the host. We use the user's uid in the
236 * hope that it will help with the problems of
237 * tcp_wrappers showing the remote uid as root.
239 temporarily_use_uid(original_real_uid);
240 if (connect(sock, (struct sockaddr *) hostaddr, sizeof(*hostaddr))
242 /* Successful connect. */
246 debug("connect: %.100s", strerror(errno));
249 /* Destroy the failed socket. */
250 shutdown(sock, SHUT_RDWR);
253 /* Not a valid numeric inet address. */
254 /* Map host name to an address. */
256 hp = gethostbyname(host);
258 fatal("Bad host name: %.100s", host);
259 if (!hp->h_addr_list[0])
260 fatal("Host does not have an IP address: %.100s", host);
262 /* Loop through addresses for this host, and try
263 each one in sequence until the connection
265 for (i = 0; hp->h_addr_list[i]; i++) {
266 /* Set the address to connect to. */
267 hostaddr->sin_family = hp->h_addrtype;
268 memcpy(&hostaddr->sin_addr, hp->h_addr_list[i],
269 sizeof(hostaddr->sin_addr));
271 debug("Connecting to %.200s [%.100s] port %d.",
272 host, inet_ntoa(hostaddr->sin_addr), port);
274 /* Create a socket for connecting. */
275 sock = ssh_create_socket(original_real_uid,
276 !anonymous && geteuid() == 0 &&
277 port < IPPORT_RESERVED);
280 * Connect to the host. We use the user's
281 * uid in the hope that it will help with
282 * tcp_wrappers showing the remote uid as
285 temporarily_use_uid(original_real_uid);
286 if (connect(sock, (struct sockaddr *) hostaddr,
287 sizeof(*hostaddr)) >= 0) {
288 /* Successful connection. */
292 debug("connect: %.100s", strerror(errno));
296 * Close the failed socket; there appear to
297 * be some problems when reusing a socket for
298 * which connect() has already returned an
301 shutdown(sock, SHUT_RDWR);
304 if (hp->h_addr_list[i])
305 break; /* Successful connection. */
308 /* Sleep a moment before retrying. */
311 /* Return failure if we didn't get a successful connection. */
312 if (attempt >= connection_attempts)
315 debug("Connection established.");
318 * Set socket options. We would like the socket to disappear as soon
319 * as it has been closed for whatever reason.
321 /* setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
322 setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (void *) &on, sizeof(on));
325 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
327 /* Set the connection. */
328 packet_set_connection(sock, sock);
334 * Checks if the user has an authentication agent, and if so, tries to
335 * authenticate using the agent.
338 try_agent_authentication()
342 AuthenticationConnection *auth;
343 unsigned char response[16];
345 BIGNUM *e, *n, *challenge;
347 /* Get connection to the agent. */
348 auth = ssh_get_authentication_connection();
354 challenge = BN_new();
356 /* Loop through identities served by the agent. */
357 for (status = ssh_get_first_identity(auth, e, n, &comment);
359 status = ssh_get_next_identity(auth, e, n, &comment)) {
362 /* Try this identity. */
363 debug("Trying RSA authentication via agent with '%.100s'", comment);
366 /* Tell the server that we are willing to authenticate using this key. */
367 packet_start(SSH_CMSG_AUTH_RSA);
368 packet_put_bignum(n);
372 /* Wait for server's response. */
373 type = packet_read(&plen);
375 /* The server sends failure if it doesn\'t like our key or
376 does not support RSA authentication. */
377 if (type == SSH_SMSG_FAILURE) {
378 debug("Server refused our key.");
381 /* Otherwise it should have sent a challenge. */
382 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
383 packet_disconnect("Protocol error during RSA authentication: %d",
386 packet_get_bignum(challenge, &clen);
388 packet_integrity_check(plen, clen, type);
390 debug("Received RSA challenge from server.");
392 /* Ask the agent to decrypt the challenge. */
393 if (!ssh_decrypt_challenge(auth, e, n, challenge,
394 session_id, 1, response)) {
395 /* The agent failed to authenticate this identifier although it
396 advertised it supports this. Just return a wrong value. */
397 log("Authentication agent failed to decrypt challenge.");
398 memset(response, 0, sizeof(response));
400 debug("Sending response to RSA challenge.");
402 /* Send the decrypted challenge back to the server. */
403 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
404 for (i = 0; i < 16; i++)
405 packet_put_char(response[i]);
409 /* Wait for response from the server. */
410 type = packet_read(&plen);
412 /* The server returns success if it accepted the authentication. */
413 if (type == SSH_SMSG_SUCCESS) {
414 debug("RSA authentication accepted by server.");
417 BN_clear_free(challenge);
420 /* Otherwise it should return failure. */
421 if (type != SSH_SMSG_FAILURE)
422 packet_disconnect("Protocol error waiting RSA auth response: %d",
428 BN_clear_free(challenge);
430 debug("RSA authentication using agent refused.");
435 * Computes the proper response to a RSA challenge, and sends the response to
439 respond_to_rsa_challenge(BIGNUM * challenge, RSA * prv)
441 unsigned char buf[32], response[16];
445 /* Decrypt the challenge using the private key. */
446 rsa_private_decrypt(challenge, challenge, prv);
448 /* Compute the response. */
449 /* The response is MD5 of decrypted challenge plus session id. */
450 len = BN_num_bytes(challenge);
451 if (len <= 0 || len > sizeof(buf))
452 packet_disconnect("respond_to_rsa_challenge: bad challenge length %d",
455 memset(buf, 0, sizeof(buf));
456 BN_bn2bin(challenge, buf + sizeof(buf) - len);
458 MD5_Update(&md, buf, 32);
459 MD5_Update(&md, session_id, 16);
460 MD5_Final(response, &md);
462 debug("Sending response to host key RSA challenge.");
464 /* Send the response back to the server. */
465 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
466 for (i = 0; i < 16; i++)
467 packet_put_char(response[i]);
471 memset(buf, 0, sizeof(buf));
472 memset(response, 0, sizeof(response));
473 memset(&md, 0, sizeof(md));
477 * Checks if the user has authentication file, and if so, tries to authenticate
481 try_rsa_authentication(const char *authfile)
486 char *passphrase, *comment;
490 /* Try to load identification for the authentication key. */
491 public_key = RSA_new();
492 if (!load_public_key(authfile, public_key, &comment)) {
493 RSA_free(public_key);
494 /* Could not load it. Fail. */
497 debug("Trying RSA authentication with key '%.100s'", comment);
499 /* Tell the server that we are willing to authenticate using this key. */
500 packet_start(SSH_CMSG_AUTH_RSA);
501 packet_put_bignum(public_key->n);
505 /* We no longer need the public key. */
506 RSA_free(public_key);
508 /* Wait for server's response. */
509 type = packet_read(&plen);
512 * The server responds with failure if it doesn\'t like our key or
513 * doesn\'t support RSA authentication.
515 if (type == SSH_SMSG_FAILURE) {
516 debug("Server refused our key.");
520 /* Otherwise, the server should respond with a challenge. */
521 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
522 packet_disconnect("Protocol error during RSA authentication: %d", type);
524 /* Get the challenge from the packet. */
525 challenge = BN_new();
526 packet_get_bignum(challenge, &clen);
528 packet_integrity_check(plen, clen, type);
530 debug("Received RSA challenge from server.");
532 private_key = RSA_new();
534 * Load the private key. Try first with empty passphrase; if it
535 * fails, ask for a passphrase.
537 if (!load_private_key(authfile, "", private_key, NULL)) {
539 snprintf(buf, sizeof buf, "Enter passphrase for RSA key '%.100s': ",
541 if (!options.batch_mode)
542 passphrase = read_passphrase(buf, 0);
544 debug("Will not query passphrase for %.100s in batch mode.",
546 passphrase = xstrdup("");
549 /* Load the authentication file using the pasphrase. */
550 if (!load_private_key(authfile, passphrase, private_key, NULL)) {
551 memset(passphrase, 0, strlen(passphrase));
553 error("Bad passphrase.");
555 /* Send a dummy response packet to avoid protocol error. */
556 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
557 for (i = 0; i < 16; i++)
562 /* Expect the server to reject it... */
563 packet_read_expect(&plen, SSH_SMSG_FAILURE);
567 /* Destroy the passphrase. */
568 memset(passphrase, 0, strlen(passphrase));
571 /* We no longer need the comment. */
574 /* Compute and send a response to the challenge. */
575 respond_to_rsa_challenge(challenge, private_key);
577 /* Destroy the private key. */
578 RSA_free(private_key);
580 /* We no longer need the challenge. */
581 BN_clear_free(challenge);
583 /* Wait for response from the server. */
584 type = packet_read(&plen);
585 if (type == SSH_SMSG_SUCCESS) {
586 debug("RSA authentication accepted by server.");
589 if (type != SSH_SMSG_FAILURE)
590 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
591 debug("RSA authentication refused.");
596 * Tries to authenticate the user using combined rhosts or /etc/hosts.equiv
597 * authentication and RSA host authentication.
600 try_rhosts_rsa_authentication(const char *local_user, RSA * host_key)
606 debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication.");
608 /* Tell the server that we are willing to authenticate using this key. */
609 packet_start(SSH_CMSG_AUTH_RHOSTS_RSA);
610 packet_put_string(local_user, strlen(local_user));
611 packet_put_int(BN_num_bits(host_key->n));
612 packet_put_bignum(host_key->e);
613 packet_put_bignum(host_key->n);
617 /* Wait for server's response. */
618 type = packet_read(&plen);
620 /* The server responds with failure if it doesn't admit our
621 .rhosts authentication or doesn't know our host key. */
622 if (type == SSH_SMSG_FAILURE) {
623 debug("Server refused our rhosts authentication or host key.");
626 /* Otherwise, the server should respond with a challenge. */
627 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
628 packet_disconnect("Protocol error during RSA authentication: %d", type);
630 /* Get the challenge from the packet. */
631 challenge = BN_new();
632 packet_get_bignum(challenge, &clen);
634 packet_integrity_check(plen, clen, type);
636 debug("Received RSA challenge for host key from server.");
638 /* Compute a response to the challenge. */
639 respond_to_rsa_challenge(challenge, host_key);
641 /* We no longer need the challenge. */
642 BN_clear_free(challenge);
644 /* Wait for response from the server. */
645 type = packet_read(&plen);
646 if (type == SSH_SMSG_SUCCESS) {
647 debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server.");
650 if (type != SSH_SMSG_FAILURE)
651 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
652 debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused.");
658 try_kerberos_authentication()
660 KTEXT_ST auth; /* Kerberos data */
666 Key_schedule schedule;
667 u_long checksum, cksum;
669 struct sockaddr_in local, foreign;
672 /* Don't do anything if we don't have any tickets. */
673 if (stat(tkt_string(), &st) < 0)
676 strncpy(inst, (char *) krb_get_phost(get_canonical_hostname()), INST_SZ);
678 realm = (char *) krb_realmofhost(get_canonical_hostname());
680 debug("Kerberos V4: no realm for %s", get_canonical_hostname());
683 /* This can really be anything. */
684 checksum = (u_long) getpid();
686 r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
688 debug("Kerberos V4 krb_mk_req failed: %s", krb_err_txt[r]);
691 /* Get session key to decrypt the server's reply with. */
692 r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
694 debug("get_cred failed: %s", krb_err_txt[r]);
697 des_key_sched((des_cblock *) cred.session, schedule);
699 /* Send authentication info to server. */
700 packet_start(SSH_CMSG_AUTH_KERBEROS);
701 packet_put_string((char *) auth.dat, auth.length);
705 /* Zero the buffer. */
706 (void) memset(auth.dat, 0, MAX_KTXT_LEN);
709 memset(&local, 0, sizeof(local));
710 if (getsockname(packet_get_connection_in(),
711 (struct sockaddr *) & local, &r) < 0)
712 debug("getsockname failed: %s", strerror(errno));
715 memset(&foreign, 0, sizeof(foreign));
716 if (getpeername(packet_get_connection_in(),
717 (struct sockaddr *) & foreign, &r) < 0) {
718 debug("getpeername failed: %s", strerror(errno));
721 /* Get server reply. */
722 type = packet_read(&plen);
724 case SSH_SMSG_FAILURE:
725 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
726 debug("Kerberos V4 authentication failed.");
730 case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
731 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
732 debug("Kerberos V4 authentication accepted.");
734 /* Get server's response. */
735 reply = packet_get_string((unsigned int *) &auth.length);
736 memcpy(auth.dat, reply, auth.length);
739 packet_integrity_check(plen, 4 + auth.length, type);
742 * If his response isn't properly encrypted with the session
743 * key, and the decrypted checksum fails to match, he's
746 r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session,
747 &foreign, &local, &msg_data);
749 debug("Kerberos V4 krb_rd_priv failed: %s", krb_err_txt[r]);
750 packet_disconnect("Kerberos V4 challenge failed!");
752 /* Fetch the (incremented) checksum that we supplied in the request. */
753 (void) memcpy((char *) &cksum, (char *) msg_data.app_data, sizeof(cksum));
754 cksum = ntohl(cksum);
756 /* If it matches, we're golden. */
757 if (cksum == checksum + 1) {
758 debug("Kerberos V4 challenge successful.");
761 packet_disconnect("Kerberos V4 challenge failed!");
765 packet_disconnect("Protocol error on Kerberos V4 response: %d", type);
777 char pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
779 unsigned char buffer[8192];
782 /* Don't do anything if we don't have any tickets. */
783 if (stat(tkt_string(), &st) < 0)
786 creds = xmalloc(sizeof(*creds));
788 if ((r = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm)) != KSUCCESS) {
789 debug("Kerberos V4 tf_fullname failed: %s", krb_err_txt[r]);
792 if ((r = krb_get_cred("krbtgt", prealm, prealm, creds)) != GC_OK) {
793 debug("Kerberos V4 get_cred failed: %s", krb_err_txt[r]);
796 if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
797 debug("Kerberos V4 ticket expired: %s", TKT_FILE);
800 creds_to_radix(creds, buffer);
803 packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
804 packet_put_string((char *) buffer, strlen(buffer));
808 type = packet_read(&plen);
810 if (type == SSH_SMSG_FAILURE)
811 debug("Kerberos TGT for realm %s rejected.", prealm);
812 else if (type != SSH_SMSG_SUCCESS)
813 packet_disconnect("Protocol error on Kerberos TGT response: %d", type);
819 send_afs_tokens(void)
822 struct ViceIoctl parms;
823 struct ClearToken ct;
824 int i, type, len, plen;
825 char buf[2048], *p, *server_cell;
826 unsigned char buffer[8192];
828 /* Move over ktc_GetToken, here's something leaner. */
829 for (i = 0; i < 100; i++) { /* just in case */
830 parms.in = (char *) &i;
831 parms.in_size = sizeof(i);
833 parms.out_size = sizeof(buf);
834 if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0)
838 /* Get secret token. */
839 memcpy(&creds.ticket_st.length, p, sizeof(unsigned int));
840 if (creds.ticket_st.length > MAX_KTXT_LEN)
842 p += sizeof(unsigned int);
843 memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
844 p += creds.ticket_st.length;
846 /* Get clear token. */
847 memcpy(&len, p, sizeof(len));
848 if (len != sizeof(struct ClearToken))
853 p += sizeof(len); /* primary flag */
856 /* Flesh out our credentials. */
857 strlcpy(creds.service, "afs", sizeof creds.service);
858 creds.instance[0] = '\0';
859 strlcpy(creds.realm, server_cell, REALM_SZ);
860 memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
861 creds.issue_date = ct.BeginTimestamp;
862 creds.lifetime = krb_time_to_life(creds.issue_date, ct.EndTimestamp);
863 creds.kvno = ct.AuthHandle;
864 snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId);
865 creds.pinst[0] = '\0';
867 /* Encode token, ship it off. */
868 if (!creds_to_radix(&creds, buffer))
870 packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
871 packet_put_string((char *) buffer, strlen(buffer));
875 /* Roger, Roger. Clearance, Clarence. What's your vector,
877 type = packet_read(&plen);
879 if (type == SSH_SMSG_FAILURE)
880 debug("AFS token for cell %s rejected.", server_cell);
881 else if (type != SSH_SMSG_SUCCESS)
882 packet_disconnect("Protocol error on AFS token response: %d", type);
889 * Tries to authenticate with any string-based challenge/response system.
890 * Note that the client code is not tied to s/key or TIS.
893 try_skey_authentication()
895 int type, i, payload_len;
896 char *challenge, *response;
898 debug("Doing skey authentication.");
900 /* request a challenge */
901 packet_start(SSH_CMSG_AUTH_TIS);
905 type = packet_read(&payload_len);
906 if (type != SSH_SMSG_FAILURE &&
907 type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
908 packet_disconnect("Protocol error: got %d in response "
909 "to skey-auth", type);
911 if (type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
912 debug("No challenge for skey authentication.");
915 challenge = packet_get_string(&payload_len);
916 if (options.cipher == SSH_CIPHER_NONE)
917 log("WARNING: Encryption is disabled! "
918 "Reponse will be transmitted in clear text.");
919 fprintf(stderr, "%s\n", challenge);
921 for (i = 0; i < options.number_of_password_prompts; i++) {
923 error("Permission denied, please try again.");
924 response = read_passphrase("Response: ", 0);
925 packet_start(SSH_CMSG_AUTH_TIS_RESPONSE);
926 packet_put_string(response, strlen(response));
927 memset(response, 0, strlen(response));
931 type = packet_read(&payload_len);
932 if (type == SSH_SMSG_SUCCESS)
934 if (type != SSH_SMSG_FAILURE)
935 packet_disconnect("Protocol error: got %d in response "
936 "to skey-auth-reponse", type);
943 * Tries to authenticate with plain passwd authentication.
946 try_password_authentication(char *prompt)
948 int type, i, payload_len;
951 debug("Doing password authentication.");
952 if (options.cipher == SSH_CIPHER_NONE)
953 log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
954 for (i = 0; i < options.number_of_password_prompts; i++) {
956 error("Permission denied, please try again.");
957 password = read_passphrase(prompt, 0);
958 packet_start(SSH_CMSG_AUTH_PASSWORD);
959 packet_put_string(password, strlen(password));
960 memset(password, 0, strlen(password));
965 type = packet_read(&payload_len);
966 if (type == SSH_SMSG_SUCCESS)
968 if (type != SSH_SMSG_FAILURE)
969 packet_disconnect("Protocol error: got %d in response to passwd auth", type);
976 * Waits for the server identification string, and sends our own
977 * identification string.
980 ssh_exchange_identification()
982 char buf[256], remote_version[256]; /* must be same size! */
983 int remote_major, remote_minor, i;
984 int connection_in = packet_get_connection_in();
985 int connection_out = packet_get_connection_out();
987 /* Read other side\'s version identification. */
988 for (i = 0; i < sizeof(buf) - 1; i++) {
989 if (read(connection_in, &buf[i], 1) != 1)
990 fatal("ssh_exchange_identification: read: %.100s", strerror(errno));
991 if (buf[i] == '\r') {
996 if (buf[i] == '\n') {
1001 buf[sizeof(buf) - 1] = 0;
1004 * Check that the versions match. In future this might accept
1005 * several versions and set appropriate flags to handle them.
1007 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
1008 remote_version) != 3)
1009 fatal("Bad remote protocol version identification: '%.100s'", buf);
1010 debug("Remote protocol version %d.%d, remote software version %.100s",
1011 remote_major, remote_minor, remote_version);
1013 /* Check if the remote protocol version is too old. */
1014 if (remote_major == 1 && remote_minor < 3)
1015 fatal("Remote machine has too old SSH software version.");
1017 /* We speak 1.3, too. */
1018 if (remote_major == 1 && remote_minor == 3) {
1020 if (options.forward_agent && strcmp(remote_version, SSH_VERSION) != 0) {
1021 log("Agent forwarding disabled, remote version '%s' is not compatible.",
1023 options.forward_agent = 0;
1028 * Removed for now, to permit compatibility with latter versions. The
1029 * server will reject our version and disconnect if it doesn't
1032 if (remote_major != PROTOCOL_MAJOR)
1033 fatal("Protocol major versions differ: %d vs. %d",
1034 PROTOCOL_MAJOR, remote_major);
1037 /* Send our own protocol version identification. */
1038 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
1039 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
1040 if (atomicio(write, connection_out, buf, strlen(buf)) != strlen(buf))
1041 fatal("write: %.100s", strerror(errno));
1044 int ssh_cipher_default = SSH_CIPHER_3DES;
1047 read_yes_or_no(const char *prompt, int defval)
1056 f = fopen("/dev/tty", "rw");
1064 fprintf(stderr, "%s", prompt);
1065 if (fgets(buf, sizeof(buf), f) == NULL) {
1066 /* Print a newline (the prompt probably didn\'t have one). */
1067 fprintf(stderr, "\n");
1068 strlcpy(buf, "no", sizeof buf);
1070 /* Remove newline from response. */
1071 if (strchr(buf, '\n'))
1072 *strchr(buf, '\n') = 0;
1076 if (strcmp(buf, "yes") == 0)
1078 if (strcmp(buf, "no") == 0)
1090 * Starts a dialog with the server, and authenticates the current user on the
1091 * server. This does not need any extra privileges. The basic connection
1092 * to the server must already have been established before this is called.
1093 * User is the remote user; if it is NULL, the current local user name will
1094 * be used. Anonymous indicates that no rhosts authentication will be used.
1095 * If login fails, this function prints an error and never returns.
1096 * This function does not require super-user privileges.
1099 ssh_login(int host_key_valid,
1101 const char *orighost,
1102 struct sockaddr_in *hostaddr,
1103 uid_t original_real_uid)
1108 RSA *host_key, *file_key;
1111 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
1112 const char *server_user, *local_user;
1113 char *cp, *host, *ip = NULL;
1114 char hostline[1000], *hostp;
1115 unsigned char check_bytes[8];
1116 unsigned int supported_ciphers, supported_authentications, protocol_flags;
1117 HostStatus host_status;
1118 HostStatus ip_status;
1119 int host_ip_differ = 0;
1120 int local = (ntohl(hostaddr->sin_addr.s_addr) >> 24) == IN_LOOPBACKNET;
1121 int payload_len, clen, sum_len = 0;
1125 * Turn off check_host_ip for proxy connects, since
1126 * we don't have the remote ip-address
1128 if (options.proxy_command != NULL && options.check_host_ip)
1129 options.check_host_ip = 0;
1131 if (options.check_host_ip)
1132 ip = xstrdup(inet_ntoa(hostaddr->sin_addr));
1134 /* Convert the user-supplied hostname into all lowercase. */
1135 host = xstrdup(orighost);
1136 for (cp = host; *cp; cp++)
1140 /* Exchange protocol version identification strings with the server. */
1141 ssh_exchange_identification();
1143 /* Put the connection into non-blocking mode. */
1144 packet_set_nonblocking();
1146 /* Get local user name. Use it as server user if no user name was given. */
1147 pw = getpwuid(original_real_uid);
1149 fatal("User id %d not found from user database.", original_real_uid);
1150 local_user = xstrdup(pw->pw_name);
1151 server_user = options.user ? options.user : local_user;
1153 debug("Waiting for server public key.");
1155 /* Wait for a public key packet from the server. */
1156 packet_read_expect(&payload_len, SSH_SMSG_PUBLIC_KEY);
1158 /* Get check bytes from the packet. */
1159 for (i = 0; i < 8; i++)
1160 check_bytes[i] = packet_get_char();
1162 /* Get the public key. */
1163 public_key = RSA_new();
1164 bits = packet_get_int();/* bits */
1165 public_key->e = BN_new();
1166 packet_get_bignum(public_key->e, &clen);
1168 public_key->n = BN_new();
1169 packet_get_bignum(public_key->n, &clen);
1172 rbits = BN_num_bits(public_key->n);
1173 if (bits != rbits) {
1174 log("Warning: Server lies about size of server public key: "
1175 "actual size is %d bits vs. announced %d.", rbits, bits);
1176 log("Warning: This may be due to an old implementation of ssh.");
1178 /* Get the host key. */
1179 host_key = RSA_new();
1180 bits = packet_get_int();/* bits */
1181 host_key->e = BN_new();
1182 packet_get_bignum(host_key->e, &clen);
1184 host_key->n = BN_new();
1185 packet_get_bignum(host_key->n, &clen);
1188 rbits = BN_num_bits(host_key->n);
1189 if (bits != rbits) {
1190 log("Warning: Server lies about size of server host key: "
1191 "actual size is %d bits vs. announced %d.", rbits, bits);
1192 log("Warning: This may be due to an old implementation of ssh.");
1194 /* Store the host key from the known host file in here so that we
1195 can compare it with the key for the IP address. */
1196 file_key = RSA_new();
1197 file_key->n = BN_new();
1198 file_key->e = BN_new();
1200 /* Get protocol flags. */
1201 protocol_flags = packet_get_int();
1202 packet_set_protocol_flags(protocol_flags);
1204 supported_ciphers = packet_get_int();
1205 supported_authentications = packet_get_int();
1207 debug("Received server public key (%d bits) and host key (%d bits).",
1208 BN_num_bits(public_key->n), BN_num_bits(host_key->n));
1210 packet_integrity_check(payload_len,
1211 8 + 4 + sum_len + 0 + 4 + 0 + 0 + 4 + 4 + 4,
1212 SSH_SMSG_PUBLIC_KEY);
1214 compute_session_id(session_id, check_bytes, host_key->n, public_key->n);
1217 * Check if the host key is present in the user\'s list of known
1218 * hosts or in the systemwide list.
1220 host_status = check_host_in_hostfile(options.user_hostfile, host,
1221 host_key->e, host_key->n,
1222 file_key->e, file_key->n);
1223 if (host_status == HOST_NEW)
1224 host_status = check_host_in_hostfile(options.system_hostfile, host,
1225 host_key->e, host_key->n,
1226 file_key->e, file_key->n);
1228 * Force accepting of the host key for localhost and 127.0.0.1. The
1229 * problem is that if the home directory is NFS-mounted to multiple
1230 * machines, localhost will refer to a different machine in each of
1231 * them, and the user will get bogus HOST_CHANGED warnings. This
1232 * essentially disables host authentication for localhost; however,
1233 * this is probably not a real problem.
1236 debug("Forcing accepting of host key for localhost.");
1237 host_status = HOST_OK;
1240 * Also perform check for the ip address, skip the check if we are
1241 * localhost or the hostname was an ip address to begin with
1243 if (options.check_host_ip && !local && strcmp(host, ip)) {
1244 RSA *ip_key = RSA_new();
1245 ip_key->n = BN_new();
1246 ip_key->e = BN_new();
1247 ip_status = check_host_in_hostfile(options.user_hostfile, ip,
1248 host_key->e, host_key->n,
1249 ip_key->e, ip_key->n);
1251 if (ip_status == HOST_NEW)
1252 ip_status = check_host_in_hostfile(options.system_hostfile, ip,
1253 host_key->e, host_key->n,
1254 ip_key->e, ip_key->n);
1255 if (host_status == HOST_CHANGED &&
1256 (ip_status != HOST_CHANGED ||
1257 (BN_cmp(ip_key->e, file_key->e) || BN_cmp(ip_key->n, file_key->n))))
1262 ip_status = host_status;
1266 switch (host_status) {
1268 /* The host is known and the key matches. */
1269 debug("Host '%.200s' is known and matches the host key.", host);
1270 if (options.check_host_ip) {
1271 if (ip_status == HOST_NEW) {
1272 if (!add_host_to_hostfile(options.user_hostfile, ip,
1273 host_key->e, host_key->n))
1274 log("Failed to add the host key for IP address '%.30s' to the list of known hosts (%.30s).",
1275 ip, options.user_hostfile);
1277 log("Warning: Permanently added host key for IP address '%.30s' to the list of known hosts.",
1279 } else if (ip_status != HOST_OK)
1280 log("Warning: the host key for '%.200s' differs from the key for the IP address '%.30s'",
1285 /* The host is new. */
1286 if (options.strict_host_key_checking == 1) {
1287 /* User has requested strict host key checking. We will not add the host key
1288 automatically. The only alternative left is to abort. */
1289 fatal("No host key is known for %.200s and you have requested strict checking.", host);
1290 } else if (options.strict_host_key_checking == 2) {
1293 char *fp = fingerprint(host_key->e, host_key->n);
1294 snprintf(prompt, sizeof(prompt),
1295 "The authenticity of host '%.200s' can't be established.\n"
1296 "Key fingerprint is %d %s.\n"
1297 "Are you sure you want to continue connecting (yes/no)? ",
1298 host, BN_num_bits(host_key->n), fp);
1299 if (!read_yes_or_no(prompt, -1))
1300 fatal("Aborted by user!\n");
1302 if (options.check_host_ip && ip_status == HOST_NEW && strcmp(host, ip)) {
1303 snprintf(hostline, sizeof(hostline), "%s,%s", host, ip);
1308 /* If not in strict mode, add the key automatically to the local known_hosts file. */
1309 if (!add_host_to_hostfile(options.user_hostfile, hostp,
1310 host_key->e, host_key->n))
1311 log("Failed to add the host to the list of known hosts (%.500s).",
1312 options.user_hostfile);
1314 log("Warning: Permanently added '%.200s' to the list of known hosts.",
1318 if (options.check_host_ip && host_ip_differ) {
1320 if (ip_status == HOST_NEW)
1322 else if (ip_status == HOST_OK)
1323 msg = "is unchanged";
1325 msg = "has a different value";
1326 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1327 error("@ WARNING: POSSIBLE DNS SPOOFING DETECTED! @");
1328 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1329 error("The host key for %s has changed,", host);
1330 error("and the key for the according IP address %s", ip);
1331 error("%s. This could either mean that", msg);
1332 error("DNS SPOOFING is happening or the IP address for the host");
1333 error("and its host key have changed at the same time");
1335 /* The host key has changed. */
1336 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1337 error("@ WARNING: HOST IDENTIFICATION HAS CHANGED! @");
1338 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1339 error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
1340 error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
1341 error("It is also possible that the host key has just been changed.");
1342 error("Please contact your system administrator.");
1343 error("Add correct host key in %.100s to get rid of this message.",
1344 options.user_hostfile);
1347 * If strict host key checking is in use, the user will have
1348 * to edit the key manually and we can only abort.
1350 if (options.strict_host_key_checking)
1351 fatal("Host key for %.200s has changed and you have requested strict checking.", host);
1354 * If strict host key checking has not been requested, allow
1355 * the connection but without password authentication or
1358 if (options.password_authentication) {
1359 error("Password authentication is disabled to avoid trojan horses.");
1360 options.password_authentication = 0;
1362 if (options.forward_agent) {
1363 error("Agent forwarding is disabled to avoid trojan horses.");
1364 options.forward_agent = 0;
1367 * XXX Should permit the user to change to use the new id.
1368 * This could be done by converting the host key to an
1369 * identifying sentence, tell that the host identifies itself
1370 * by that sentence, and ask the user if he/she whishes to
1371 * accept the authentication.
1376 if (options.check_host_ip)
1379 /* Generate a session key. */
1383 * Generate an encryption key for the session. The key is a 256 bit
1384 * random number, interpreted as a 32-byte key, with the least
1385 * significant 8 bits being the first byte of the key.
1387 for (i = 0; i < 32; i++) {
1389 rand = arc4random();
1390 session_key[i] = rand & 0xff;
1395 * According to the protocol spec, the first byte of the session key
1396 * is the highest byte of the integer. The session key is xored with
1397 * the first 16 bytes of the session id.
1400 BN_set_word(key, 0);
1401 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
1402 BN_lshift(key, key, 8);
1404 BN_add_word(key, session_key[i] ^ session_id[i]);
1406 BN_add_word(key, session_key[i]);
1410 * Encrypt the integer using the public key and host key of the
1411 * server (key with smaller modulus first).
1413 if (BN_cmp(public_key->n, host_key->n) < 0) {
1414 /* Public key has smaller modulus. */
1415 if (BN_num_bits(host_key->n) <
1416 BN_num_bits(public_key->n) + SSH_KEY_BITS_RESERVED) {
1417 fatal("respond_to_rsa_challenge: host_key %d < public_key %d + "
1418 "SSH_KEY_BITS_RESERVED %d",
1419 BN_num_bits(host_key->n),
1420 BN_num_bits(public_key->n),
1421 SSH_KEY_BITS_RESERVED);
1423 rsa_public_encrypt(key, key, public_key);
1424 rsa_public_encrypt(key, key, host_key);
1426 /* Host key has smaller modulus (or they are equal). */
1427 if (BN_num_bits(public_key->n) <
1428 BN_num_bits(host_key->n) + SSH_KEY_BITS_RESERVED) {
1429 fatal("respond_to_rsa_challenge: public_key %d < host_key %d + "
1430 "SSH_KEY_BITS_RESERVED %d",
1431 BN_num_bits(public_key->n),
1432 BN_num_bits(host_key->n),
1433 SSH_KEY_BITS_RESERVED);
1435 rsa_public_encrypt(key, key, host_key);
1436 rsa_public_encrypt(key, key, public_key);
1439 if (options.cipher == SSH_CIPHER_NOT_SET) {
1440 if (cipher_mask() & supported_ciphers & (1 << ssh_cipher_default))
1441 options.cipher = ssh_cipher_default;
1443 debug("Cipher %s not supported, using %.100s instead.",
1444 cipher_name(ssh_cipher_default),
1445 cipher_name(SSH_FALLBACK_CIPHER));
1446 options.cipher = SSH_FALLBACK_CIPHER;
1449 /* Check that the selected cipher is supported. */
1450 if (!(supported_ciphers & (1 << options.cipher)))
1451 fatal("Selected cipher type %.100s not supported by server.",
1452 cipher_name(options.cipher));
1454 debug("Encryption type: %.100s", cipher_name(options.cipher));
1456 /* Send the encrypted session key to the server. */
1457 packet_start(SSH_CMSG_SESSION_KEY);
1458 packet_put_char(options.cipher);
1460 /* Send the check bytes back to the server. */
1461 for (i = 0; i < 8; i++)
1462 packet_put_char(check_bytes[i]);
1464 /* Send the encrypted encryption key. */
1465 packet_put_bignum(key);
1467 /* Send protocol flags. */
1468 packet_put_int(SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1470 /* Send the packet now. */
1472 packet_write_wait();
1474 /* Destroy the session key integer and the public keys since we no longer need them. */
1476 RSA_free(public_key);
1479 debug("Sent encrypted session key.");
1481 /* Set the encryption key. */
1482 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, options.cipher);
1484 /* We will no longer need the session key here. Destroy any extra copies. */
1485 memset(session_key, 0, sizeof(session_key));
1488 * Expect a success message from the server. Note that this message
1489 * will be received in encrypted form.
1491 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1493 debug("Received encrypted confirmation.");
1495 /* Send the name of the user to log in as on the server. */
1496 packet_start(SSH_CMSG_USER);
1497 packet_put_string(server_user, strlen(server_user));
1499 packet_write_wait();
1502 * The server should respond with success if no authentication is
1503 * needed (the user has no password). Otherwise the server responds
1506 type = packet_read(&payload_len);
1508 /* check whether the connection was accepted without authentication. */
1509 if (type == SSH_SMSG_SUCCESS)
1511 if (type != SSH_SMSG_FAILURE)
1512 packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER",
1516 /* Try Kerberos tgt passing if the server supports it. */
1517 if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1518 options.kerberos_tgt_passing) {
1519 if (options.cipher == SSH_CIPHER_NONE)
1520 log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1521 (void) send_kerberos_tgt();
1523 /* Try AFS token passing if the server supports it. */
1524 if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
1525 options.afs_token_passing && k_hasafs()) {
1526 if (options.cipher == SSH_CIPHER_NONE)
1527 log("WARNING: Encryption is disabled! Token will be transmitted in the clear!");
1533 if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1534 options.kerberos_authentication) {
1535 debug("Trying Kerberos authentication.");
1536 if (try_kerberos_authentication()) {
1537 /* The server should respond with success or failure. */
1538 type = packet_read(&payload_len);
1539 if (type == SSH_SMSG_SUCCESS)
1541 if (type != SSH_SMSG_FAILURE)
1542 packet_disconnect("Protocol error: got %d in response to Kerberos auth", type);
1548 * Use rhosts authentication if running in privileged socket and we
1549 * do not wish to remain anonymous.
1551 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
1552 options.rhosts_authentication) {
1553 debug("Trying rhosts authentication.");
1554 packet_start(SSH_CMSG_AUTH_RHOSTS);
1555 packet_put_string(local_user, strlen(local_user));
1557 packet_write_wait();
1559 /* The server should respond with success or failure. */
1560 type = packet_read(&payload_len);
1561 if (type == SSH_SMSG_SUCCESS)
1563 if (type != SSH_SMSG_FAILURE)
1564 packet_disconnect("Protocol error: got %d in response to rhosts auth",
1568 * Try .rhosts or /etc/hosts.equiv authentication with RSA host
1571 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
1572 options.rhosts_rsa_authentication && host_key_valid) {
1573 if (try_rhosts_rsa_authentication(local_user, own_host_key))
1576 /* Try RSA authentication if the server supports it. */
1577 if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
1578 options.rsa_authentication) {
1580 * Try RSA authentication using the authentication agent. The
1581 * agent is tried first because no passphrase is needed for
1582 * it, whereas identity files may require passphrases.
1584 if (try_agent_authentication())
1587 /* Try RSA authentication for each identity. */
1588 for (i = 0; i < options.num_identity_files; i++)
1589 if (try_rsa_authentication(options.identity_files[i]))
1592 /* Try skey authentication if the server supports it. */
1593 if ((supported_authentications & (1 << SSH_AUTH_TIS)) &&
1594 options.skey_authentication && !options.batch_mode) {
1595 if (try_skey_authentication())
1598 /* Try password authentication if the server supports it. */
1599 if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
1600 options.password_authentication && !options.batch_mode) {
1603 snprintf(prompt, sizeof(prompt), "%.30s@%.40s's password: ",
1605 if (try_password_authentication(prompt))
1608 /* All authentication methods have failed. Exit with an error message. */
1609 fatal("Permission denied.");