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.
11 RCSID("$OpenBSD: sshconnect.c,v 1.58 2000/03/23 22:15:33 markus Exp $");
14 #include <openssl/rsa.h>
15 #include <openssl/dsa.h>
16 #include <openssl/md5.h>
17 #include <openssl/bn.h>
39 /* Session id for the current session. */
40 unsigned char session_id[16];
42 /* authentications supported by server */
43 unsigned int supported_authentications;
45 extern Options options;
46 extern char *__progname;
49 * Connect to the given ssh server using a proxy command.
52 ssh_proxy_connect(const char *host, u_short port, uid_t original_real_uid,
53 const char *proxy_command)
60 char strport[NI_MAXSERV];
62 /* Convert the port number into a string. */
63 snprintf(strport, sizeof strport, "%hu", port);
65 /* Build the final command string in the buffer by making the
66 appropriate substitutions to the given proxy command. */
67 buffer_init(&command);
68 for (cp = proxy_command; *cp; cp++) {
69 if (cp[0] == '%' && cp[1] == '%') {
70 buffer_append(&command, "%", 1);
74 if (cp[0] == '%' && cp[1] == 'h') {
75 buffer_append(&command, host, strlen(host));
79 if (cp[0] == '%' && cp[1] == 'p') {
80 buffer_append(&command, strport, strlen(strport));
84 buffer_append(&command, cp, 1);
86 buffer_append(&command, "\0", 1);
88 /* Get the final command string. */
89 command_string = buffer_ptr(&command);
91 /* Create pipes for communicating with the proxy. */
92 if (pipe(pin) < 0 || pipe(pout) < 0)
93 fatal("Could not create pipes to communicate with the proxy: %.100s",
96 debug("Executing proxy command: %.500s", command_string);
98 /* Fork and execute the proxy command. */
99 if ((pid = fork()) == 0) {
102 /* Child. Permanently give up superuser privileges. */
103 permanently_set_uid(original_real_uid);
105 /* Redirect stdin and stdout. */
108 if (dup2(pin[0], 0) < 0)
109 perror("dup2 stdin");
113 if (dup2(pout[1], 1) < 0)
114 perror("dup2 stdout");
115 /* Cannot be 1 because pin allocated two descriptors. */
118 /* Stderr is left as it is so that error messages get
119 printed on the user's terminal. */
122 argv[2] = command_string;
125 /* Execute the proxy command. Note that we gave up any
126 extra privileges above. */
127 execv("/bin/sh", argv);
133 fatal("fork failed: %.100s", strerror(errno));
135 /* Close child side of the descriptors. */
139 /* Free the command name. */
140 buffer_free(&command);
142 /* Set the connection file descriptors. */
143 packet_set_connection(pout[0], pin[1]);
149 * Creates a (possibly privileged) socket for use as the ssh connection.
152 ssh_create_socket(uid_t original_real_uid, int privileged, int family)
157 * If we are running as root and want to connect to a privileged
158 * port, bind our own socket to a privileged port.
161 int p = IPPORT_RESERVED - 1;
162 sock = rresvport_af(&p, family);
164 error("rresvport: af=%d %.100s", family, strerror(errno));
166 debug("Allocated local port %d.", p);
169 * Just create an ordinary socket on arbitrary port. We use
170 * the user's uid to create the socket.
172 temporarily_use_uid(original_real_uid);
173 sock = socket(family, SOCK_STREAM, 0);
175 error("socket: %.100s", strerror(errno));
182 * Opens a TCP/IP connection to the remote server on the given host.
183 * The address of the remote host will be returned in hostaddr.
184 * If port is 0, the default port will be used. If anonymous is zero,
185 * a privileged port will be allocated to make the connection.
186 * This requires super-user privileges if anonymous is false.
187 * Connection_attempts specifies the maximum number of tries (one per
188 * second). If proxy_command is non-NULL, it specifies the command (with %h
189 * and %p substituted for host and port, respectively) to use to contact
193 ssh_connect(const char *host, struct sockaddr_storage * hostaddr,
194 u_short port, int connection_attempts,
195 int anonymous, uid_t original_real_uid,
196 const char *proxy_command)
198 int sock = -1, attempt;
200 struct addrinfo hints, *ai, *aitop;
201 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
203 struct linger linger;
205 debug("ssh_connect: getuid %d geteuid %d anon %d",
206 (int) getuid(), (int) geteuid(), anonymous);
208 /* Get default port if port has not been set. */
210 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
212 port = ntohs(sp->s_port);
214 port = SSH_DEFAULT_PORT;
216 /* If a proxy command is given, connect using it. */
217 if (proxy_command != NULL)
218 return ssh_proxy_connect(host, port, original_real_uid, proxy_command);
220 /* No proxy command. */
222 memset(&hints, 0, sizeof(hints));
223 hints.ai_family = IPv4or6;
224 hints.ai_socktype = SOCK_STREAM;
225 snprintf(strport, sizeof strport, "%d", port);
226 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
227 fatal("%s: %.100s: %s", __progname, host,
228 gai_strerror(gaierr));
231 * Try to connect several times. On some machines, the first time
232 * will sometimes fail. In general socket code appears to behave
233 * quite magically on many machines.
235 for (attempt = 0; attempt < connection_attempts; attempt++) {
237 debug("Trying again...");
239 /* Loop through addresses for this host, and try each one in
240 sequence until the connection succeeds. */
241 for (ai = aitop; ai; ai = ai->ai_next) {
242 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
244 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
245 ntop, sizeof(ntop), strport, sizeof(strport),
246 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
247 error("ssh_connect: getnameinfo failed");
250 debug("Connecting to %.200s [%.100s] port %s.",
251 host, ntop, strport);
253 /* Create a socket for connecting. */
254 sock = ssh_create_socket(original_real_uid,
255 !anonymous && geteuid() == 0 && port < IPPORT_RESERVED,
260 /* Connect to the host. We use the user's uid in the
261 * hope that it will help with tcp_wrappers showing
262 * the remote uid as root.
264 temporarily_use_uid(original_real_uid);
265 if (connect(sock, ai->ai_addr, ai->ai_addrlen) >= 0) {
266 /* Successful connection. */
267 memcpy(hostaddr, ai->ai_addr, sizeof(*(ai->ai_addr)));
271 debug("connect: %.100s", strerror(errno));
274 * Close the failed socket; there appear to
275 * be some problems when reusing a socket for
276 * which connect() has already returned an
279 shutdown(sock, SHUT_RDWR);
284 break; /* Successful connection. */
286 /* Sleep a moment before retrying. */
292 /* Return failure if we didn't get a successful connection. */
293 if (attempt >= connection_attempts)
296 debug("Connection established.");
299 * Set socket options. We would like the socket to disappear as soon
300 * as it has been closed for whatever reason.
302 /* setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
305 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
307 /* Set the connection. */
308 packet_set_connection(sock, sock);
314 * Checks if the user has an authentication agent, and if so, tries to
315 * authenticate using the agent.
318 try_agent_authentication()
322 AuthenticationConnection *auth;
323 unsigned char response[16];
325 BIGNUM *e, *n, *challenge;
327 /* Get connection to the agent. */
328 auth = ssh_get_authentication_connection();
334 challenge = BN_new();
336 /* Loop through identities served by the agent. */
337 for (status = ssh_get_first_identity(auth, e, n, &comment);
339 status = ssh_get_next_identity(auth, e, n, &comment)) {
342 /* Try this identity. */
343 debug("Trying RSA authentication via agent with '%.100s'", comment);
346 /* Tell the server that we are willing to authenticate using this key. */
347 packet_start(SSH_CMSG_AUTH_RSA);
348 packet_put_bignum(n);
352 /* Wait for server's response. */
353 type = packet_read(&plen);
355 /* The server sends failure if it doesn\'t like our key or
356 does not support RSA authentication. */
357 if (type == SSH_SMSG_FAILURE) {
358 debug("Server refused our key.");
361 /* Otherwise it should have sent a challenge. */
362 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
363 packet_disconnect("Protocol error during RSA authentication: %d",
366 packet_get_bignum(challenge, &clen);
368 packet_integrity_check(plen, clen, type);
370 debug("Received RSA challenge from server.");
372 /* Ask the agent to decrypt the challenge. */
373 if (!ssh_decrypt_challenge(auth, e, n, challenge,
374 session_id, 1, response)) {
375 /* The agent failed to authenticate this identifier although it
376 advertised it supports this. Just return a wrong value. */
377 log("Authentication agent failed to decrypt challenge.");
378 memset(response, 0, sizeof(response));
380 debug("Sending response to RSA challenge.");
382 /* Send the decrypted challenge back to the server. */
383 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
384 for (i = 0; i < 16; i++)
385 packet_put_char(response[i]);
389 /* Wait for response from the server. */
390 type = packet_read(&plen);
392 /* The server returns success if it accepted the authentication. */
393 if (type == SSH_SMSG_SUCCESS) {
394 debug("RSA authentication accepted by server.");
397 BN_clear_free(challenge);
400 /* Otherwise it should return failure. */
401 if (type != SSH_SMSG_FAILURE)
402 packet_disconnect("Protocol error waiting RSA auth response: %d",
408 BN_clear_free(challenge);
410 debug("RSA authentication using agent refused.");
415 * Computes the proper response to a RSA challenge, and sends the response to
419 respond_to_rsa_challenge(BIGNUM * challenge, RSA * prv)
421 unsigned char buf[32], response[16];
425 /* Decrypt the challenge using the private key. */
426 rsa_private_decrypt(challenge, challenge, prv);
428 /* Compute the response. */
429 /* The response is MD5 of decrypted challenge plus session id. */
430 len = BN_num_bytes(challenge);
431 if (len <= 0 || len > sizeof(buf))
432 packet_disconnect("respond_to_rsa_challenge: bad challenge length %d",
435 memset(buf, 0, sizeof(buf));
436 BN_bn2bin(challenge, buf + sizeof(buf) - len);
438 MD5_Update(&md, buf, 32);
439 MD5_Update(&md, session_id, 16);
440 MD5_Final(response, &md);
442 debug("Sending response to host key RSA challenge.");
444 /* Send the response back to the server. */
445 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
446 for (i = 0; i < 16; i++)
447 packet_put_char(response[i]);
451 memset(buf, 0, sizeof(buf));
452 memset(response, 0, sizeof(response));
453 memset(&md, 0, sizeof(md));
457 * Checks if the user has authentication file, and if so, tries to authenticate
461 try_rsa_authentication(const char *authfile)
466 char *passphrase, *comment;
470 /* Try to load identification for the authentication key. */
471 public_key = RSA_new();
472 if (!load_public_key(authfile, public_key, &comment)) {
473 RSA_free(public_key);
474 /* Could not load it. Fail. */
477 debug("Trying RSA authentication with key '%.100s'", comment);
479 /* Tell the server that we are willing to authenticate using this key. */
480 packet_start(SSH_CMSG_AUTH_RSA);
481 packet_put_bignum(public_key->n);
485 /* We no longer need the public key. */
486 RSA_free(public_key);
488 /* Wait for server's response. */
489 type = packet_read(&plen);
492 * The server responds with failure if it doesn\'t like our key or
493 * doesn\'t support RSA authentication.
495 if (type == SSH_SMSG_FAILURE) {
496 debug("Server refused our key.");
500 /* Otherwise, the server should respond with a challenge. */
501 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
502 packet_disconnect("Protocol error during RSA authentication: %d", type);
504 /* Get the challenge from the packet. */
505 challenge = BN_new();
506 packet_get_bignum(challenge, &clen);
508 packet_integrity_check(plen, clen, type);
510 debug("Received RSA challenge from server.");
512 private_key = RSA_new();
514 * Load the private key. Try first with empty passphrase; if it
515 * fails, ask for a passphrase.
517 if (!load_private_key(authfile, "", private_key, NULL)) {
519 snprintf(buf, sizeof buf, "Enter passphrase for RSA key '%.100s': ",
521 if (!options.batch_mode)
522 passphrase = read_passphrase(buf, 0);
524 debug("Will not query passphrase for %.100s in batch mode.",
526 passphrase = xstrdup("");
529 /* Load the authentication file using the pasphrase. */
530 if (!load_private_key(authfile, passphrase, private_key, NULL)) {
531 memset(passphrase, 0, strlen(passphrase));
533 error("Bad passphrase.");
535 /* Send a dummy response packet to avoid protocol error. */
536 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
537 for (i = 0; i < 16; i++)
542 /* Expect the server to reject it... */
543 packet_read_expect(&plen, SSH_SMSG_FAILURE);
547 /* Destroy the passphrase. */
548 memset(passphrase, 0, strlen(passphrase));
551 /* We no longer need the comment. */
554 /* Compute and send a response to the challenge. */
555 respond_to_rsa_challenge(challenge, private_key);
557 /* Destroy the private key. */
558 RSA_free(private_key);
560 /* We no longer need the challenge. */
561 BN_clear_free(challenge);
563 /* Wait for response from the server. */
564 type = packet_read(&plen);
565 if (type == SSH_SMSG_SUCCESS) {
566 debug("RSA authentication accepted by server.");
569 if (type != SSH_SMSG_FAILURE)
570 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
571 debug("RSA authentication refused.");
576 * Tries to authenticate the user using combined rhosts or /etc/hosts.equiv
577 * authentication and RSA host authentication.
580 try_rhosts_rsa_authentication(const char *local_user, RSA * host_key)
586 debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication.");
588 /* Tell the server that we are willing to authenticate using this key. */
589 packet_start(SSH_CMSG_AUTH_RHOSTS_RSA);
590 packet_put_string(local_user, strlen(local_user));
591 packet_put_int(BN_num_bits(host_key->n));
592 packet_put_bignum(host_key->e);
593 packet_put_bignum(host_key->n);
597 /* Wait for server's response. */
598 type = packet_read(&plen);
600 /* The server responds with failure if it doesn't admit our
601 .rhosts authentication or doesn't know our host key. */
602 if (type == SSH_SMSG_FAILURE) {
603 debug("Server refused our rhosts authentication or host key.");
606 /* Otherwise, the server should respond with a challenge. */
607 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
608 packet_disconnect("Protocol error during RSA authentication: %d", type);
610 /* Get the challenge from the packet. */
611 challenge = BN_new();
612 packet_get_bignum(challenge, &clen);
614 packet_integrity_check(plen, clen, type);
616 debug("Received RSA challenge for host key from server.");
618 /* Compute a response to the challenge. */
619 respond_to_rsa_challenge(challenge, host_key);
621 /* We no longer need the challenge. */
622 BN_clear_free(challenge);
624 /* Wait for response from the server. */
625 type = packet_read(&plen);
626 if (type == SSH_SMSG_SUCCESS) {
627 debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server.");
630 if (type != SSH_SMSG_FAILURE)
631 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
632 debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused.");
638 try_kerberos_authentication()
640 KTEXT_ST auth; /* Kerberos data */
647 Key_schedule schedule;
648 u_long checksum, cksum;
650 struct sockaddr_in local, foreign;
653 /* Don't do anything if we don't have any tickets. */
654 if (stat(tkt_string(), &st) < 0)
657 strncpy(inst, (char *) krb_get_phost(get_canonical_hostname()), INST_SZ);
659 realm = (char *) krb_realmofhost(get_canonical_hostname());
661 debug("Kerberos V4: no realm for %s", get_canonical_hostname());
664 /* This can really be anything. */
665 checksum = (u_long) getpid();
667 r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
669 debug("Kerberos V4 krb_mk_req failed: %s", krb_err_txt[r]);
672 /* Get session key to decrypt the server's reply with. */
673 r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
675 debug("get_cred failed: %s", krb_err_txt[r]);
678 des_key_sched((des_cblock *) cred.session, schedule);
680 /* Send authentication info to server. */
681 packet_start(SSH_CMSG_AUTH_KERBEROS);
682 packet_put_string((char *) auth.dat, auth.length);
686 /* Zero the buffer. */
687 (void) memset(auth.dat, 0, MAX_KTXT_LEN);
689 slen = sizeof(local);
690 memset(&local, 0, sizeof(local));
691 if (getsockname(packet_get_connection_in(),
692 (struct sockaddr *) & local, &slen) < 0)
693 debug("getsockname failed: %s", strerror(errno));
695 slen = sizeof(foreign);
696 memset(&foreign, 0, sizeof(foreign));
697 if (getpeername(packet_get_connection_in(),
698 (struct sockaddr *) & foreign, &slen) < 0) {
699 debug("getpeername failed: %s", strerror(errno));
702 /* Get server reply. */
703 type = packet_read(&plen);
705 case SSH_SMSG_FAILURE:
706 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
707 debug("Kerberos V4 authentication failed.");
711 case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
712 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
713 debug("Kerberos V4 authentication accepted.");
715 /* Get server's response. */
716 reply = packet_get_string((unsigned int *) &auth.length);
717 memcpy(auth.dat, reply, auth.length);
720 packet_integrity_check(plen, 4 + auth.length, type);
723 * If his response isn't properly encrypted with the session
724 * key, and the decrypted checksum fails to match, he's
727 r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session,
728 &foreign, &local, &msg_data);
730 debug("Kerberos V4 krb_rd_priv failed: %s", krb_err_txt[r]);
731 packet_disconnect("Kerberos V4 challenge failed!");
733 /* Fetch the (incremented) checksum that we supplied in the request. */
734 (void) memcpy((char *) &cksum, (char *) msg_data.app_data, sizeof(cksum));
735 cksum = ntohl(cksum);
737 /* If it matches, we're golden. */
738 if (cksum == checksum + 1) {
739 debug("Kerberos V4 challenge successful.");
742 packet_disconnect("Kerberos V4 challenge failed!");
746 packet_disconnect("Protocol error on Kerberos V4 response: %d", type);
758 char pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
763 /* Don't do anything if we don't have any tickets. */
764 if (stat(tkt_string(), &st) < 0)
767 creds = xmalloc(sizeof(*creds));
769 if ((r = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm)) != KSUCCESS) {
770 debug("Kerberos V4 tf_fullname failed: %s", krb_err_txt[r]);
773 if ((r = krb_get_cred("krbtgt", prealm, prealm, creds)) != GC_OK) {
774 debug("Kerberos V4 get_cred failed: %s", krb_err_txt[r]);
777 if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
778 debug("Kerberos V4 ticket expired: %s", TKT_FILE);
781 creds_to_radix(creds, (unsigned char *)buffer);
784 packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
785 packet_put_string(buffer, strlen(buffer));
789 type = packet_read(&plen);
791 if (type == SSH_SMSG_FAILURE)
792 debug("Kerberos TGT for realm %s rejected.", prealm);
793 else if (type != SSH_SMSG_SUCCESS)
794 packet_disconnect("Protocol error on Kerberos TGT response: %d", type);
800 send_afs_tokens(void)
803 struct ViceIoctl parms;
804 struct ClearToken ct;
805 int i, type, len, plen;
806 char buf[2048], *p, *server_cell;
809 /* Move over ktc_GetToken, here's something leaner. */
810 for (i = 0; i < 100; i++) { /* just in case */
811 parms.in = (char *) &i;
812 parms.in_size = sizeof(i);
814 parms.out_size = sizeof(buf);
815 if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0)
819 /* Get secret token. */
820 memcpy(&creds.ticket_st.length, p, sizeof(unsigned int));
821 if (creds.ticket_st.length > MAX_KTXT_LEN)
823 p += sizeof(unsigned int);
824 memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
825 p += creds.ticket_st.length;
827 /* Get clear token. */
828 memcpy(&len, p, sizeof(len));
829 if (len != sizeof(struct ClearToken))
834 p += sizeof(len); /* primary flag */
837 /* Flesh out our credentials. */
838 strlcpy(creds.service, "afs", sizeof creds.service);
839 creds.instance[0] = '\0';
840 strlcpy(creds.realm, server_cell, REALM_SZ);
841 memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
842 creds.issue_date = ct.BeginTimestamp;
843 creds.lifetime = krb_time_to_life(creds.issue_date, ct.EndTimestamp);
844 creds.kvno = ct.AuthHandle;
845 snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId);
846 creds.pinst[0] = '\0';
848 /* Encode token, ship it off. */
849 if (!creds_to_radix(&creds, (unsigned char*) buffer))
851 packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
852 packet_put_string(buffer, strlen(buffer));
856 /* Roger, Roger. Clearance, Clarence. What's your vector,
858 type = packet_read(&plen);
860 if (type == SSH_SMSG_FAILURE)
861 debug("AFS token for cell %s rejected.", server_cell);
862 else if (type != SSH_SMSG_SUCCESS)
863 packet_disconnect("Protocol error on AFS token response: %d", type);
870 * Tries to authenticate with any string-based challenge/response system.
871 * Note that the client code is not tied to s/key or TIS.
874 try_skey_authentication()
879 char *challenge, *response;
881 debug("Doing skey authentication.");
883 /* request a challenge */
884 packet_start(SSH_CMSG_AUTH_TIS);
888 type = packet_read(&payload_len);
889 if (type != SSH_SMSG_FAILURE &&
890 type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
891 packet_disconnect("Protocol error: got %d in response "
892 "to skey-auth", type);
894 if (type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
895 debug("No challenge for skey authentication.");
898 challenge = packet_get_string(&clen);
899 packet_integrity_check(payload_len, (4 + clen), type);
900 if (options.cipher == SSH_CIPHER_NONE)
901 log("WARNING: Encryption is disabled! "
902 "Reponse will be transmitted in clear text.");
903 fprintf(stderr, "%s\n", challenge);
906 for (i = 0; i < options.number_of_password_prompts; i++) {
908 error("Permission denied, please try again.");
909 response = read_passphrase("Response: ", 0);
910 packet_start(SSH_CMSG_AUTH_TIS_RESPONSE);
911 packet_put_string(response, strlen(response));
912 memset(response, 0, strlen(response));
916 type = packet_read(&payload_len);
917 if (type == SSH_SMSG_SUCCESS)
919 if (type != SSH_SMSG_FAILURE)
920 packet_disconnect("Protocol error: got %d in response "
921 "to skey-auth-reponse", type);
928 * Tries to authenticate with plain passwd authentication.
931 try_password_authentication(char *prompt)
933 int type, i, payload_len;
936 debug("Doing password authentication.");
937 if (options.cipher == SSH_CIPHER_NONE)
938 log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
939 for (i = 0; i < options.number_of_password_prompts; i++) {
941 error("Permission denied, please try again.");
942 password = read_passphrase(prompt, 0);
943 packet_start(SSH_CMSG_AUTH_PASSWORD);
944 packet_put_string(password, strlen(password));
945 memset(password, 0, strlen(password));
950 type = packet_read(&payload_len);
951 if (type == SSH_SMSG_SUCCESS)
953 if (type != SSH_SMSG_FAILURE)
954 packet_disconnect("Protocol error: got %d in response to passwd auth", type);
961 * Waits for the server identification string, and sends our own
962 * identification string.
965 ssh_exchange_identification()
967 char buf[256], remote_version[256]; /* must be same size! */
968 int remote_major, remote_minor, i;
969 int connection_in = packet_get_connection_in();
970 int connection_out = packet_get_connection_out();
972 /* Read other side\'s version identification. */
973 for (i = 0; i < sizeof(buf) - 1; i++) {
974 int len = read(connection_in, &buf[i], 1);
976 fatal("ssh_exchange_identification: read: %.100s", strerror(errno));
978 fatal("ssh_exchange_identification: Connection closed by remote host");
979 if (buf[i] == '\r') {
984 if (buf[i] == '\n') {
989 buf[sizeof(buf) - 1] = 0;
992 * Check that the versions match. In future this might accept
993 * several versions and set appropriate flags to handle them.
995 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
996 remote_version) != 3)
997 fatal("Bad remote protocol version identification: '%.100s'", buf);
998 debug("Remote protocol version %d.%d, remote software version %.100s",
999 remote_major, remote_minor, remote_version);
1001 /* Check if the remote protocol version is too old. */
1002 if (remote_major == 1 && remote_minor < 3)
1003 fatal("Remote machine has too old SSH software version.");
1005 /* We speak 1.3, too. */
1006 if (remote_major == 1 && remote_minor == 3) {
1008 if (options.forward_agent) {
1009 log("Agent forwarding disabled for protocol 1.3");
1010 options.forward_agent = 0;
1015 * Removed for now, to permit compatibility with latter versions. The
1016 * server will reject our version and disconnect if it doesn't
1019 if (remote_major != PROTOCOL_MAJOR)
1020 fatal("Protocol major versions differ: %d vs. %d",
1021 PROTOCOL_MAJOR, remote_major);
1024 /* Send our own protocol version identification. */
1025 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
1026 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
1027 if (atomicio(write, connection_out, buf, strlen(buf)) != strlen(buf))
1028 fatal("write: %.100s", strerror(errno));
1031 int ssh_cipher_default = SSH_CIPHER_3DES;
1034 read_yes_or_no(const char *prompt, int defval)
1043 f = fopen("/dev/tty", "rw");
1051 fprintf(stderr, "%s", prompt);
1052 if (fgets(buf, sizeof(buf), f) == NULL) {
1053 /* Print a newline (the prompt probably didn\'t have one). */
1054 fprintf(stderr, "\n");
1055 strlcpy(buf, "no", sizeof buf);
1057 /* Remove newline from response. */
1058 if (strchr(buf, '\n'))
1059 *strchr(buf, '\n') = 0;
1063 if (strcmp(buf, "yes") == 0)
1065 if (strcmp(buf, "no") == 0)
1077 * check whether the supplied host key is valid, return only if ok.
1081 check_host_key(char *host, struct sockaddr *hostaddr, Key *host_key)
1085 char hostline[1000], *hostp;
1086 HostStatus host_status;
1087 HostStatus ip_status;
1088 int local = 0, host_ip_differ = 0;
1090 char ntop[NI_MAXHOST];
1093 * Force accepting of the host key for loopback/localhost. The
1094 * problem is that if the home directory is NFS-mounted to multiple
1095 * machines, localhost will refer to a different machine in each of
1096 * them, and the user will get bogus HOST_CHANGED warnings. This
1097 * essentially disables host authentication for localhost; however,
1098 * this is probably not a real problem.
1100 switch (hostaddr->sa_family) {
1102 local = (ntohl(((struct sockaddr_in *)hostaddr)->sin_addr.s_addr) >> 24) == IN_LOOPBACKNET;
1103 salen = sizeof(struct sockaddr_in);
1106 local = IN6_IS_ADDR_LOOPBACK(&(((struct sockaddr_in6 *)hostaddr)->sin6_addr));
1107 salen = sizeof(struct sockaddr_in6);
1111 salen = sizeof(struct sockaddr_storage);
1115 debug("Forcing accepting of host key for loopback/localhost.");
1120 * Turn off check_host_ip for proxy connects, since
1121 * we don't have the remote ip-address
1123 if (options.proxy_command != NULL && options.check_host_ip)
1124 options.check_host_ip = 0;
1126 if (options.check_host_ip) {
1127 if (getnameinfo(hostaddr, salen, ntop, sizeof(ntop),
1128 NULL, 0, NI_NUMERICHOST) != 0)
1129 fatal("check_host_key: getnameinfo failed");
1134 * Store the host key from the known host file in here so that we can
1135 * compare it with the key for the IP address.
1137 file_key = key_new(host_key->type);
1140 * Check if the host key is present in the user\'s list of known
1141 * hosts or in the systemwide list.
1143 host_status = check_host_in_hostfile(options.user_hostfile, host, host_key, file_key);
1144 if (host_status == HOST_NEW)
1145 host_status = check_host_in_hostfile(options.system_hostfile, host, host_key, file_key);
1147 * Also perform check for the ip address, skip the check if we are
1148 * localhost or the hostname was an ip address to begin with
1150 if (options.check_host_ip && !local && strcmp(host, ip)) {
1151 Key *ip_key = key_new(host_key->type);
1152 ip_status = check_host_in_hostfile(options.user_hostfile, ip, host_key, ip_key);
1154 if (ip_status == HOST_NEW)
1155 ip_status = check_host_in_hostfile(options.system_hostfile, ip, host_key, ip_key);
1156 if (host_status == HOST_CHANGED &&
1157 (ip_status != HOST_CHANGED || !key_equal(ip_key, file_key)))
1162 ip_status = host_status;
1166 switch (host_status) {
1168 /* The host is known and the key matches. */
1169 debug("Host '%.200s' is known and matches the host key.", host);
1170 if (options.check_host_ip) {
1171 if (ip_status == HOST_NEW) {
1172 if (!add_host_to_hostfile(options.user_hostfile, ip, host_key))
1173 log("Failed to add the host key for IP address '%.30s' to the list of known hosts (%.30s).",
1174 ip, options.user_hostfile);
1176 log("Warning: Permanently added host key for IP address '%.30s' to the list of known hosts.",
1178 } else if (ip_status != HOST_OK)
1179 log("Warning: the host key for '%.200s' differs from the key for the IP address '%.30s'",
1184 /* The host is new. */
1185 if (options.strict_host_key_checking == 1) {
1186 /* User has requested strict host key checking. We will not add the host key
1187 automatically. The only alternative left is to abort. */
1188 fatal("No host key is known for %.200s and you have requested strict checking.", host);
1189 } else if (options.strict_host_key_checking == 2) {
1192 char *fp = key_fingerprint(host_key);
1193 snprintf(prompt, sizeof(prompt),
1194 "The authenticity of host '%.200s' can't be established.\n"
1195 "Key fingerprint is %s.\n"
1196 "Are you sure you want to continue connecting (yes/no)? ",
1198 if (!read_yes_or_no(prompt, -1))
1199 fatal("Aborted by user!\n");
1201 if (options.check_host_ip && ip_status == HOST_NEW && strcmp(host, ip)) {
1202 snprintf(hostline, sizeof(hostline), "%s,%s", host, ip);
1207 /* If not in strict mode, add the key automatically to the local known_hosts file. */
1208 if (!add_host_to_hostfile(options.user_hostfile, hostp, host_key))
1209 log("Failed to add the host to the list of known hosts (%.500s).",
1210 options.user_hostfile);
1212 log("Warning: Permanently added '%.200s' to the list of known hosts.",
1216 if (options.check_host_ip && host_ip_differ) {
1218 if (ip_status == HOST_NEW)
1220 else if (ip_status == HOST_OK)
1221 msg = "is unchanged";
1223 msg = "has a different value";
1224 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1225 error("@ WARNING: POSSIBLE DNS SPOOFING DETECTED! @");
1226 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1227 error("The host key for %s has changed,", host);
1228 error("and the key for the according IP address %s", ip);
1229 error("%s. This could either mean that", msg);
1230 error("DNS SPOOFING is happening or the IP address for the host");
1231 error("and its host key have changed at the same time");
1233 /* The host key has changed. */
1234 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1235 error("@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @");
1236 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1237 error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
1238 error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
1239 error("It is also possible that the host key has just been changed.");
1240 error("Please contact your system administrator.");
1241 error("Add correct host key in %.100s to get rid of this message.",
1242 options.user_hostfile);
1245 * If strict host key checking is in use, the user will have
1246 * to edit the key manually and we can only abort.
1248 if (options.strict_host_key_checking)
1249 fatal("Host key for %.200s has changed and you have requested strict checking.", host);
1252 * If strict host key checking has not been requested, allow
1253 * the connection but without password authentication or
1256 if (options.password_authentication) {
1257 error("Password authentication is disabled to avoid trojan horses.");
1258 options.password_authentication = 0;
1260 if (options.forward_agent) {
1261 error("Agent forwarding is disabled to avoid trojan horses.");
1262 options.forward_agent = 0;
1265 * XXX Should permit the user to change to use the new id.
1266 * This could be done by converting the host key to an
1267 * identifying sentence, tell that the host identifies itself
1268 * by that sentence, and ask the user if he/she whishes to
1269 * accept the authentication.
1273 if (options.check_host_ip)
1277 check_rsa_host_key(char *host, struct sockaddr *hostaddr, RSA *host_key)
1282 check_host_key(host, hostaddr, &k);
1289 ssh_kex(char *host, struct sockaddr *hostaddr)
1296 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
1297 unsigned char cookie[8];
1298 unsigned int supported_ciphers;
1299 unsigned int server_flags, client_flags;
1300 int payload_len, clen, sum_len = 0;
1303 debug("Waiting for server public key.");
1305 /* Wait for a public key packet from the server. */
1306 packet_read_expect(&payload_len, SSH_SMSG_PUBLIC_KEY);
1308 /* Get cookie from the packet. */
1309 for (i = 0; i < 8; i++)
1310 cookie[i] = packet_get_char();
1312 /* Get the public key. */
1313 public_key = RSA_new();
1314 bits = packet_get_int();/* bits */
1315 public_key->e = BN_new();
1316 packet_get_bignum(public_key->e, &clen);
1318 public_key->n = BN_new();
1319 packet_get_bignum(public_key->n, &clen);
1322 rbits = BN_num_bits(public_key->n);
1323 if (bits != rbits) {
1324 log("Warning: Server lies about size of server public key: "
1325 "actual size is %d bits vs. announced %d.", rbits, bits);
1326 log("Warning: This may be due to an old implementation of ssh.");
1328 /* Get the host key. */
1329 host_key = RSA_new();
1330 bits = packet_get_int();/* bits */
1331 host_key->e = BN_new();
1332 packet_get_bignum(host_key->e, &clen);
1334 host_key->n = BN_new();
1335 packet_get_bignum(host_key->n, &clen);
1338 rbits = BN_num_bits(host_key->n);
1339 if (bits != rbits) {
1340 log("Warning: Server lies about size of server host key: "
1341 "actual size is %d bits vs. announced %d.", rbits, bits);
1342 log("Warning: This may be due to an old implementation of ssh.");
1345 /* Get protocol flags. */
1346 server_flags = packet_get_int();
1347 packet_set_protocol_flags(server_flags);
1349 supported_ciphers = packet_get_int();
1350 supported_authentications = packet_get_int();
1352 debug("Received server public key (%d bits) and host key (%d bits).",
1353 BN_num_bits(public_key->n), BN_num_bits(host_key->n));
1355 packet_integrity_check(payload_len,
1356 8 + 4 + sum_len + 0 + 4 + 0 + 0 + 4 + 4 + 4,
1357 SSH_SMSG_PUBLIC_KEY);
1359 check_rsa_host_key(host, hostaddr, host_key);
1361 client_flags = SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN;
1363 compute_session_id(session_id, cookie, host_key->n, public_key->n);
1365 /* Generate a session key. */
1369 * Generate an encryption key for the session. The key is a 256 bit
1370 * random number, interpreted as a 32-byte key, with the least
1371 * significant 8 bits being the first byte of the key.
1373 for (i = 0; i < 32; i++) {
1375 rand = arc4random();
1376 session_key[i] = rand & 0xff;
1381 * According to the protocol spec, the first byte of the session key
1382 * is the highest byte of the integer. The session key is xored with
1383 * the first 16 bytes of the session id.
1386 BN_set_word(key, 0);
1387 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
1388 BN_lshift(key, key, 8);
1390 BN_add_word(key, session_key[i] ^ session_id[i]);
1392 BN_add_word(key, session_key[i]);
1396 * Encrypt the integer using the public key and host key of the
1397 * server (key with smaller modulus first).
1399 if (BN_cmp(public_key->n, host_key->n) < 0) {
1400 /* Public key has smaller modulus. */
1401 if (BN_num_bits(host_key->n) <
1402 BN_num_bits(public_key->n) + SSH_KEY_BITS_RESERVED) {
1403 fatal("respond_to_rsa_challenge: host_key %d < public_key %d + "
1404 "SSH_KEY_BITS_RESERVED %d",
1405 BN_num_bits(host_key->n),
1406 BN_num_bits(public_key->n),
1407 SSH_KEY_BITS_RESERVED);
1409 rsa_public_encrypt(key, key, public_key);
1410 rsa_public_encrypt(key, key, host_key);
1412 /* Host key has smaller modulus (or they are equal). */
1413 if (BN_num_bits(public_key->n) <
1414 BN_num_bits(host_key->n) + SSH_KEY_BITS_RESERVED) {
1415 fatal("respond_to_rsa_challenge: public_key %d < host_key %d + "
1416 "SSH_KEY_BITS_RESERVED %d",
1417 BN_num_bits(public_key->n),
1418 BN_num_bits(host_key->n),
1419 SSH_KEY_BITS_RESERVED);
1421 rsa_public_encrypt(key, key, host_key);
1422 rsa_public_encrypt(key, key, public_key);
1425 /* Destroy the public keys since we no longer need them. */
1426 RSA_free(public_key);
1429 if (options.cipher == SSH_CIPHER_NOT_SET) {
1430 if (cipher_mask() & supported_ciphers & (1 << ssh_cipher_default))
1431 options.cipher = ssh_cipher_default;
1433 debug("Cipher %s not supported, using %.100s instead.",
1434 cipher_name(ssh_cipher_default),
1435 cipher_name(SSH_FALLBACK_CIPHER));
1436 options.cipher = SSH_FALLBACK_CIPHER;
1439 /* Check that the selected cipher is supported. */
1440 if (!(supported_ciphers & (1 << options.cipher)))
1441 fatal("Selected cipher type %.100s not supported by server.",
1442 cipher_name(options.cipher));
1444 debug("Encryption type: %.100s", cipher_name(options.cipher));
1446 /* Send the encrypted session key to the server. */
1447 packet_start(SSH_CMSG_SESSION_KEY);
1448 packet_put_char(options.cipher);
1450 /* Send the cookie back to the server. */
1451 for (i = 0; i < 8; i++)
1452 packet_put_char(cookie[i]);
1454 /* Send and destroy the encrypted encryption key integer. */
1455 packet_put_bignum(key);
1458 /* Send protocol flags. */
1459 packet_put_int(client_flags);
1461 /* Send the packet now. */
1463 packet_write_wait();
1465 debug("Sent encrypted session key.");
1467 /* Set the encryption key. */
1468 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, options.cipher);
1470 /* We will no longer need the session key here. Destroy any extra copies. */
1471 memset(session_key, 0, sizeof(session_key));
1474 * Expect a success message from the server. Note that this message
1475 * will be received in encrypted form.
1477 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1479 debug("Received encrypted confirmation.");
1486 ssh_userauth(int host_key_valid, RSA *own_host_key,
1487 uid_t original_real_uid, char *host)
1492 const char *server_user, *local_user;
1494 /* Get local user name. Use it as server user if no user name was given. */
1495 pw = getpwuid(original_real_uid);
1497 fatal("User id %d not found from user database.", original_real_uid);
1498 local_user = xstrdup(pw->pw_name);
1499 server_user = options.user ? options.user : local_user;
1501 /* Send the name of the user to log in as on the server. */
1502 packet_start(SSH_CMSG_USER);
1503 packet_put_string(server_user, strlen(server_user));
1505 packet_write_wait();
1508 * The server should respond with success if no authentication is
1509 * needed (the user has no password). Otherwise the server responds
1512 type = packet_read(&payload_len);
1514 /* check whether the connection was accepted without authentication. */
1515 if (type == SSH_SMSG_SUCCESS)
1517 if (type != SSH_SMSG_FAILURE)
1518 packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER",
1522 /* Try Kerberos tgt passing if the server supports it. */
1523 if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1524 options.kerberos_tgt_passing) {
1525 if (options.cipher == SSH_CIPHER_NONE)
1526 log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1527 (void) send_kerberos_tgt();
1529 /* Try AFS token passing if the server supports it. */
1530 if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
1531 options.afs_token_passing && k_hasafs()) {
1532 if (options.cipher == SSH_CIPHER_NONE)
1533 log("WARNING: Encryption is disabled! Token will be transmitted in the clear!");
1539 if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1540 options.kerberos_authentication) {
1541 debug("Trying Kerberos authentication.");
1542 if (try_kerberos_authentication()) {
1543 /* The server should respond with success or failure. */
1544 type = packet_read(&payload_len);
1545 if (type == SSH_SMSG_SUCCESS)
1547 if (type != SSH_SMSG_FAILURE)
1548 packet_disconnect("Protocol error: got %d in response to Kerberos auth", type);
1554 * Use rhosts authentication if running in privileged socket and we
1555 * do not wish to remain anonymous.
1557 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
1558 options.rhosts_authentication) {
1559 debug("Trying rhosts authentication.");
1560 packet_start(SSH_CMSG_AUTH_RHOSTS);
1561 packet_put_string(local_user, strlen(local_user));
1563 packet_write_wait();
1565 /* The server should respond with success or failure. */
1566 type = packet_read(&payload_len);
1567 if (type == SSH_SMSG_SUCCESS)
1569 if (type != SSH_SMSG_FAILURE)
1570 packet_disconnect("Protocol error: got %d in response to rhosts auth",
1574 * Try .rhosts or /etc/hosts.equiv authentication with RSA host
1577 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
1578 options.rhosts_rsa_authentication && host_key_valid) {
1579 if (try_rhosts_rsa_authentication(local_user, own_host_key))
1582 /* Try RSA authentication if the server supports it. */
1583 if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
1584 options.rsa_authentication) {
1586 * Try RSA authentication using the authentication agent. The
1587 * agent is tried first because no passphrase is needed for
1588 * it, whereas identity files may require passphrases.
1590 if (try_agent_authentication())
1593 /* Try RSA authentication for each identity. */
1594 for (i = 0; i < options.num_identity_files; i++)
1595 if (try_rsa_authentication(options.identity_files[i]))
1598 /* Try skey authentication if the server supports it. */
1599 if ((supported_authentications & (1 << SSH_AUTH_TIS)) &&
1600 options.skey_authentication && !options.batch_mode) {
1601 if (try_skey_authentication())
1604 /* Try password authentication if the server supports it. */
1605 if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
1606 options.password_authentication && !options.batch_mode) {
1609 snprintf(prompt, sizeof(prompt), "%.30s@%.40s's password: ",
1611 if (try_password_authentication(prompt))
1614 /* All authentication methods have failed. Exit with an error message. */
1615 fatal("Permission denied.");
1619 * Starts a dialog with the server, and authenticates the current user on the
1620 * server. This does not need any extra privileges. The basic connection
1621 * to the server must already have been established before this is called.
1622 * If login fails, this function prints an error and never returns.
1623 * This function does not require super-user privileges.
1626 ssh_login(int host_key_valid, RSA *own_host_key, const char *orighost,
1627 struct sockaddr *hostaddr, uid_t original_real_uid)
1631 /* Convert the user-supplied hostname into all lowercase. */
1632 host = xstrdup(orighost);
1633 for (cp = host; *cp; cp++)
1637 /* Exchange protocol version identification strings with the server. */
1638 ssh_exchange_identification();
1640 /* Put the connection into non-blocking mode. */
1641 packet_set_nonblocking();
1643 supported_authentications = 0;
1645 ssh_kex(host, hostaddr);
1646 if (supported_authentications == 0)
1647 fatal("supported_authentications == 0.");
1649 /* authenticate user */
1650 ssh_userauth(host_key_valid, own_host_key, original_real_uid, host);