Example #1
1
static ssh_session create_ssh_connection(const char* hostname, const unsigned int port, const char* username,
	const char* password, const char* sshkey_path, const char* sshkey_passphrase)
{
	ssh_session sshs;

	/* Open session and set options */
	sshs = ssh_new();
	if (sshs == NULL) {
		errmsg_print("Can't create ssh session");
		return NULL;
	}

	if (!hostname)
		return NULL;

	if (ssh_options_set(sshs, SSH_OPTIONS_HOST, hostname)) {
		errmsg_print("Can't set the hostname: %s\n", hostname);
		goto failure;
	}

	if (port != 0) {
		if (ssh_options_set(sshs, SSH_OPTIONS_PORT, &port)) {
			errmsg_print("Can't set the port: %d\n", port);
			goto failure;
		}
	}

	if (!username)
		username = g_get_user_name();

	if (ssh_options_set(sshs, SSH_OPTIONS_USER, username)) {
		errmsg_print("Can't set the username: %s\n", username);
		goto failure;
	}

	verbose_print("Opening ssh connection to %s@%s:%u\n", username, hostname, port);

	/* Connect to server */
	if (ssh_connect(sshs) != SSH_OK) {
		errmsg_print("Error connecting to %s@%s:%u (%s)\n", username, hostname, port,
			ssh_get_error(sshs));
		goto failure;
	}

#ifdef HAVE_LIBSSH_USERAUTH_AGENT
	verbose_print("Connecting using ssh-agent...");
	/* Try to authenticate using ssh agent */
	if (ssh_userauth_agent(sshs, NULL) == SSH_AUTH_SUCCESS) {
		verbose_print("done\n");
		return sshs;
	}
	verbose_print("failed\n");
#endif

	/* If a public key path has been provided, try to authenticate using it */
	if (sshkey_path) {
		ssh_key pkey = ssh_key_new();
		int ret;

		verbose_print("Connecting using public key in %s...", sshkey_path);
		ret = ssh_pki_import_privkey_file(sshkey_path, sshkey_passphrase, NULL, NULL, &pkey);

		if (ret == SSH_OK) {
			if (ssh_userauth_publickey(sshs, NULL, pkey) == SSH_AUTH_SUCCESS) {
				verbose_print("done\n");
				ssh_key_free(pkey);
				return sshs;
			}
		}
		ssh_key_free(pkey);
		verbose_print("failed (%s)\n", ssh_get_error(sshs));
	}

	/* Try to authenticate using standard public key */
	verbose_print("Connecting using standard public key...");
	if (ssh_userauth_publickey_auto(sshs, NULL, NULL) == SSH_AUTH_SUCCESS) {
		verbose_print("done\n");
		return sshs;
	}
	verbose_print("failed\n");

	/* If a password has been provided and all previous attempts failed, try to use it */
	if (password) {
		verbose_print("Connecting using password...");
		if (ssh_userauth_password(sshs, username, password) == SSH_AUTH_SUCCESS) {
			verbose_print("done\n");
			return sshs;
		}
		verbose_print("failed\n");
	}

	errmsg_print("Can't find a valid authentication. Disconnecting.\n");

	/* All authentication failed. Disconnect and return */
	ssh_disconnect(sshs);

failure:
	ssh_free(sshs);
	return NULL;
}
Example #2
0
static int authenticate_password(ssh_session session, url_t* urlp)
{
  if (urlp->password)
    return ssh_userauth_password(session, NULL, urlp->password);

  if (!ftp->getpass_hook)
    return SSH_AUTH_ERROR;

  if (get_password(urlp, NULL, false))
    return SSH_AUTH_ERROR;

  return ssh_userauth_password(session, NULL, urlp->password);
}
Example #3
0
File: ssh.cpp Project: obklar/exiv2
    SSH::SSH(const std::string& host, const std::string& user, const std::string& pass, const std::string port):
        host_(host),user_(user),pass_(pass),sftp_(0) {

        std::string timeout = getEnv(envTIMEOUT);
        timeout_ = atol(timeout.c_str());
        if (timeout_ == 0) {
            throw Error(1, "Timeout Environmental Variable must be a positive integer.");
        }

        session_ = ssh_new();
        if (session_ == NULL) {
            throw Error(1, "Unable to create the the ssh session");
        }

        // try to connect
        ssh_options_set(session_, SSH_OPTIONS_HOST, host_.c_str());
        ssh_options_set(session_, SSH_OPTIONS_USER, user_.c_str());
        ssh_options_set(session_, SSH_OPTIONS_TIMEOUT, &timeout_);
        if (port != "") ssh_options_set(session_, SSH_OPTIONS_PORT_STR, port.c_str());

        if (ssh_connect(session_) != SSH_OK) {
            throw Error(1, ssh_get_error(session_));
        }
        // Authentication
        if (ssh_userauth_password(session_, NULL, pass_.c_str()) != SSH_AUTH_SUCCESS) {
            throw Error(1, ssh_get_error(session_));
        }
    }
Example #4
0
static void torture_auth_password_nonblocking(void **state) {
    struct torture_state *s = *state;
    ssh_session session = s->ssh.session;
    int rc;

    rc = ssh_options_set(session, SSH_OPTIONS_USER, TORTURE_SSH_USER_BOB);
    assert_int_equal(rc, SSH_OK);

    rc = ssh_connect(session);
    assert_int_equal(rc, SSH_OK);

    ssh_set_blocking(session,0);
    do {
      rc = ssh_userauth_none(session, NULL);
    } while (rc == SSH_AUTH_AGAIN);

    /* This request should return a SSH_REQUEST_DENIED error */
    if (rc == SSH_AUTH_ERROR) {
        assert_true(ssh_get_error_code(session) == SSH_REQUEST_DENIED);
    }

    rc = ssh_userauth_list(session, NULL);
    assert_true(rc & SSH_AUTH_METHOD_PASSWORD);

    do {
      rc = ssh_userauth_password(session, NULL, TORTURE_SSH_USER_BOB_PASSWORD);
    } while(rc==SSH_AUTH_AGAIN);

    assert_int_equal(rc, SSH_AUTH_SUCCESS);
}
Example #5
0
void
Session::connect() {
    if (this->c_session != NULL) {
        this->disconnect();
    }

    this->c_session = ssh_new();

    if (this->c_session == NULL) {
        throw std::runtime_error("Cannot start session");
    }

    ssh_options_set(this->c_session, SSH_OPTIONS_HOST, this->hostname.c_str());
    ssh_options_set(this->c_session, SSH_OPTIONS_PORT, &this->port);

    int rc = ssh_connect(this->c_session);
    if (rc != SSH_OK) {
        fprintf(stderr, "Error connecting to localhost: %s\n", ssh_get_error(this->c_session));
        throw std::runtime_error("Cannot connect to server");
    }

    if (this->password_auth) {
        rc = ssh_userauth_password(this->c_session, NULL, this->password.c_str());
        if (rc != SSH_AUTH_SUCCESS) {
            throw std::runtime_error("Cannot authenticate with server");
        }
    } else {
        rc = ssh_userauth_autopubkey(this->c_session, NULL);
        if (rc != SSH_AUTH_SUCCESS) {
            throw std::runtime_error("Cannot authenticate with server");
        }
    }
}
Example #6
0
static void torture_auth_password(void **state) {
    ssh_session session = *state;
    char *user = getenv("TORTURE_USER");
    char *password = getenv("TORTURE_PASSWORD");
    int rc;

    if (user == NULL) {
        print_message("*** Please set the environment variable TORTURE_USER"
                      " to enable this test!!\n");
        return;
    }

    if (password == NULL) {
        print_message("*** Please set the environment variable "
                      "TORTURE_PASSWORD to enable this test!!\n");
        return;
    }

    rc = ssh_options_set(session, SSH_OPTIONS_USER, user);
    assert_true(rc == SSH_OK);

    rc = ssh_connect(session);
    assert_true(rc == SSH_OK);

    rc = ssh_userauth_none(session, NULL);
    /* This request should return a SSH_REQUEST_DENIED error */
    if (rc == SSH_AUTH_ERROR) {
        assert_true(ssh_get_error_code(session) == SSH_REQUEST_DENIED);
    }
    rc = ssh_userauth_list(session, NULL);
    assert_true(rc & SSH_AUTH_METHOD_PASSWORD);

    rc = ssh_userauth_password(session, NULL, password);
    assert_true(rc == SSH_AUTH_SUCCESS);
}
Example #7
0
File: brute_ssh.c Project: hc0d3r/C
int ssh_login(const char *user, const char *passwd){
    ssh_session ssh_id;
    int ret = 0;

    printf("[*] testing => %s:%s:%s\n", target, user, passwd);

    ssh_id = ssh_new();
    ssh_options_set(ssh_id, SSH_OPTIONS_HOST, target);
    ssh_options_set(ssh_id, SSH_OPTIONS_USER, user);

    if(ssh_connect(ssh_id) != SSH_OK){
        goto end;
    }

    if(ssh_userauth_password(ssh_id, NULL, passwd) != SSH_AUTH_SUCCESS){
        goto end;
    }

    printf("\n\n\tCracked --> [%s : %s]\n\n", user, passwd);

    ret = 1;

    end:
    ssh_disconnect(ssh_id);
    ssh_free(ssh_id);

    return ret;
}
Example #8
0
int authenticate_console(ssh_session session, char* pwd){
    int rc;
    int method;
    char password[128] = {0};
    char *banner;
    // Try to authenticate
    rc = ssh_userauth_none(session, NULL);
    if (rc == SSH_AUTH_ERROR) {
        error(session);
        return rc;
    }
    method = ssh_auth_list(session);
    while (rc != SSH_AUTH_SUCCESS) {
        // Try to authenticate with public key first
        if (method & SSH_AUTH_METHOD_PUBLICKEY) {
            rc = ssh_userauth_autopubkey(session, NULL);
            if (rc == SSH_AUTH_ERROR) {
                error(session);
                return rc;
            } else if (rc == SSH_AUTH_SUCCESS) {
                break;
            }
        }
/*
        // Try to authenticate with keyboard interactive";
        if (method & SSH_AUTH_METHOD_INTERACTIVE) {
            rc = authenticate_kbdint(session, NULL);
            if (rc == SSH_AUTH_ERROR) {
                error(session);
                return rc;
            } else if (rc == SSH_AUTH_SUCCESS) {
                break;
            }
        }
        if (ssh_getpass("Password: "******"%s\n",banner);
        free(banner);
    }
    return rc;
}
Example #9
0
 void SSH::authenticate()
 {
     int rc = ssh_userauth_password(_ssh, NULL, _password.c_str());
     _logger->debug("SSH Authentication status: %d", rc);
     if (rc == SSH_AUTH_ERROR) {
         _authenticated = false;
         return;
     }
     _authenticated = true;
 }
Example #10
0
int authenticate_console(ssh_session session)
{
	int rc;
	int method;

  // Try to authenticate
	rc = ssh_userauth_none(session, NULL);
	if (rc == SSH_AUTH_ERROR) 
	{
		error(session);
		return rc;
	}

	method = ssh_userauth_list(session,NULL);
	while (rc != SSH_AUTH_SUCCESS) 
	{
    // Try to authenticate with public key first
		rc = ssh_userauth_autopubkey(session, NULL);
		if (rc == SSH_AUTH_ERROR) 
		{
			error(session);
			return rc;
		} else if (rc == SSH_AUTH_SUCCESS) 
		{
			break;
		}
		rc=authenticate_kbdint(session,pass_word);
		if (rc == SSH_AUTH_ERROR) 
		{
			error(session);
			return rc;
		} else if (rc == SSH_AUTH_SUCCESS) 
		{
			break;
		}
		rc = ssh_userauth_password(session, NULL, pass_word);
		if (rc == SSH_AUTH_ERROR) 
		{
			error(session);
			return rc;
		} else if (rc == SSH_AUTH_SUCCESS) 
		{
			break;
		} else if(rc == SSH_AUTH_DENIED)
		{
		} else if(rc == SSH_AUTH_PARTIAL)
		{
		} else if(rc == SSH_AUTH_INFO)
		{
		} else if(rc == SSH_AUTH_AGAIN)
		{
		}
	}
	return rc;
}
Example #11
0
int test()
{
    ssh_session my_ssh_session;
    int rc;

    // Open session and set options
    my_ssh_session = ssh_new();
    if (my_ssh_session == NULL)
      exit(-1);
    ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "localhost");

    // Connect to server
    rc = ssh_connect(my_ssh_session);
    if (rc != SSH_OK)
    {
      fprintf(stderr, "Error connecting to localhost: %s\n",
              ssh_get_error(my_ssh_session));
      ssh_free(my_ssh_session);
      exit(-1);
    }

    // Verify the server's identity
    // For the source code of verify_knowhost(), check previous example
//    if (verify_knownhost(my_ssh_session) < 0)
//    {
//      ssh_disconnect(my_ssh_session);
//      ssh_free(my_ssh_session);
//      exit(-1);
//    }

    // Authenticate ourselves
    QString password("whcrosedu");
    rc = ssh_userauth_password(my_ssh_session, NULL, password.toLatin1());
    if (rc != SSH_AUTH_SUCCESS)
    {
      fprintf(stderr, "Error authenticating with password: %s\n",
              ssh_get_error(my_ssh_session));
      ssh_disconnect(my_ssh_session);
      ssh_free(my_ssh_session);
      exit(-1);
    }
    qDebug()<<"evrika";

    show_remote_processes(my_ssh_session);

    ssh_disconnect(my_ssh_session);
    ssh_free(my_ssh_session);
}
Example #12
0
// libssh login version
void Connector::libsshLogin() {
// the verbosity of the ssh log

	int verbosity = SSH_LOG_PROTOCOL;
	int port = 22; // the port used (22 is default)
	
	sshSession = ssh_new() ; 

	if (sshSession == NULL){
		exit(-1);
    }

    output->append("Initializing connection with RVS cluster...") ;	

	/*Setting the options of this connection*/
	ssh_options_set(sshSession, SSH_OPTIONS_HOST, "rvs.sara.nl") ;
	ssh_options_set(sshSession, SSH_OPTIONS_USER, m_username.c_str()) ; // TODO, make the username and host flexibile
	ssh_options_set(sshSession, SSH_OPTIONS_LOG_VERBOSITY, &verbosity);
	ssh_options_set(sshSession, SSH_OPTIONS_PORT, &port);
	
    output->append("\n") ;

	/*Connecting*/
	int response = ssh_connect(sshSession);
	if (response != SSH_OK) {
        output->append("Error connecting to the RVS") ;
        output->append(ssh_get_error(sshSession)) ;
		ssh_free(sshSession);
		exit(-1);
	}

	// TODO check if the server is known!
	
	response = ssh_userauth_password(sshSession, NULL, m_passSara.c_str());
	if (response != SSH_AUTH_SUCCESS){
        output->append("ERROR: Auth. failed") ;
        output->append(ssh_get_error(sshSession)) ;
		ssh_free(sshSession);
		exit(-1);
	} else {
        output->append("Authorization succesful!") ;
	}
    output->append("\n") ;
    output->append("Waiting for VNC connection...") ;
    qApp->processEvents() ;
}
Example #13
0
int main(int argc, char *argv[])
{
	umask(0);

        con.verbosity = SSH_LOG_PROTOCOL;
        con.port = 22;
	con.user = "******";
        con.password = "******";
        con.my_ssh_session = ssh_new();
	con.mountpath = "/tmp/fuse/";
        if (con.my_ssh_session == NULL)
            perror("unable to craete a session");
        //ssh_options_set(con.my_ssh_session, SSH_OPTIONS_USER, "akanksha");
        //ssh_options_set(con.my_ssh_session, SSH_OPTIONS_HOST, "192.168.1.2");
        ssh_options_set(con.my_ssh_session, SSH_OPTIONS_HOST, "localhost");
        ssh_options_set(con.my_ssh_session, SSH_OPTIONS_LOG_VERBOSITY, &con.verbosity);
        ssh_options_set(con.my_ssh_session, SSH_OPTIONS_PORT, &con.port);
        con.rc = ssh_connect(con.my_ssh_session);
        if (con.rc != SSH_OK)
        {
             fprintf(stderr, "Error connecting to localhost: %s\n",
             ssh_get_error(con.my_ssh_session));
        } else{
             fprintf(stderr, "Connection succesful");
        }

        //con.password = getpass("Password: "******"Error authenticating with password: %s\n",
              ssh_get_error(con.my_ssh_session));
              ssh_disconnect(con.my_ssh_session);
              ssh_free(con.my_ssh_session);
        }

	
	con.sftp = create_sftp_session(); 
        int res = fuse_main(argc, argv, &xmp_oper, NULL);
        perror("Fuse main called ");
        ssh_disconnect(con.my_ssh_session);
        sftp_free(con.sftp);
	ssh_free(con.my_ssh_session);
        return res;
}
Example #14
0
bool clSSH::LoginPassword(bool throwExc)
{
    if(!m_session) { THROW_OR_FALSE("NULL SSH session"); }

    int rc;
    // interactive keyboard method failed, try another method
    rc = ssh_userauth_password(m_session, NULL, GetPassword().mb_str().data());
    if(rc == SSH_AUTH_SUCCESS) {
        return true;

    } else if(rc == SSH_AUTH_DENIED) {
        THROW_OR_FALSE("Login failed: invalid username/password");

    } else {
        THROW_OR_FALSE(wxString() << _("Authentication error: ") << ssh_get_error(m_session));
    }
    return false;
}
Example #15
0
int main()
{
    // INIT
    ssh_session sshsession = ssh_new();

    ssh_options_set(sshsession, SSH_OPTIONS_HOST, "192.168.1.117");

    if (ssh_connect(sshsession) == 0)
    {
        if (ssh_userauth_password(sshsession, "root", "password") == 0)
        {
            sftp_session sftpsession = sftp_new(sshsession);

            if (sftp_init(sftpsession) == 0)
            {
                // DIR READ
                sftp_dir dir = sftp_opendir(sftpsession, "/root/");

                sftp_attributes file;
                while((file = sftp_readdir(sftpsession, dir)))
                {

                    if (file->type == 1) // 1 == file; 2 == dir
                    {
                        // todo..
                    }
                }
                sftp_closedir(dir);

                // FILE READ
                sftp_file l_file = sftp_open(sftpsession, "/root/test.txt", O_RDONLY, 0);
                sftp_attributes attr = sftp_fstat(l_file);
                QByteArray l_ba;
                l_ba.resize(attr->size);
                sftp_read(l_file, l_ba.data(), attr->size); // Returns readed
                sftp_close(l_file);
            }
        }

        ssh_disconnect(sshsession);
    }

    return 0;
}
Example #16
0
/**
 * Authenticate in the SSH server with password
 * @param   QString password      the password to use for connect in the SSH server (password or passphrase when you use private key)
 * @return  bool                  true if it's ok, false else
 */
bool Kssh::authenticatePassword(QString password)
{
    // Try to authenticate without interactive, if fail then try with interactive
    int auth;

    auth = ssh_userauth_password(this->m_session, NULL, password.toStdString().c_str());

    if (auth == SSH_AUTH_SUCCESS) {
        return true;
    } else if (auth == SSH_AUTH_DENIED || auth == SSH_AUTH_PARTIAL) {
        // try with interactive
#ifdef DEBUG
        Klog::debug("Authentication fail with password, try with interactive");
#endif
        return this->authenticatePasswordInteractive(password);
    } else if (auth == SSH_AUTH_ERROR) {
        Klog::error(QString("Fatal error in authenticated with password : ") + QString(ssh_get_error(this->m_session)));
        return false;
    }

    return false;
}
Example #17
0
static gint
remmina_ssh_auth_password (RemminaSSH *ssh)
{
	gint ret;
	gint authlist;
	gint n;
	gint i;

	ret = SSH_AUTH_ERROR;
	if (ssh->authenticated) return 1;
	if (ssh->password == NULL) return -1;

	authlist = ssh_userauth_list (ssh->session, NULL);
	if (authlist & SSH_AUTH_METHOD_INTERACTIVE)
	{
		while ((ret = ssh_userauth_kbdint (ssh->session, NULL, NULL)) == SSH_AUTH_INFO)
		{
			n = ssh_userauth_kbdint_getnprompts (ssh->session);
			for (i = 0; i < n; i++)
			{
				ssh_userauth_kbdint_setanswer(ssh->session, i, ssh->password);
			}
		}
	}
	if (ret != SSH_AUTH_SUCCESS && authlist & SSH_AUTH_METHOD_PASSWORD)
	{
		ret = ssh_userauth_password (ssh->session, NULL, ssh->password);
	}
	if (ret != SSH_AUTH_SUCCESS)
	{
		remmina_ssh_set_error (ssh, _("SSH password authentication failed: %s"));
		return 0;
	}

	ssh->authenticated = TRUE;
	return 1;
}
Example #18
0
static int _sftp_connect(const char *uri) {
  char *scheme = NULL;
  char *user = NULL;
  char *passwd = NULL;
  char *host = NULL;
  unsigned int port = 0;
  char *path = NULL;
  unsigned char *hash = NULL;
  int hlen;
  int rc = -1;
  int state = SSH_SERVER_ERROR;
  int timeout = 10;
  int method;
  char *verbosity;

  if (_connected) {
    return 0;
  }

  rc = c_parse_uri(uri, &scheme, &user, &passwd, &host, &port, &path);
  if (rc < 0) {
    goto out;
  }

  DEBUG_SFTP(("csync_sftp - conntecting to: %s\n", host));

  /* create the session */
  _ssh_session = ssh_new();
  if (_ssh_session == NULL) {
    fprintf(stderr, "csync_sftp - error creating new connection: %s\n",
        strerror(errno));
    rc = -1;
    goto out;
  }

  rc = ssh_options_set(_ssh_session, SSH_OPTIONS_TIMEOUT, &timeout);
  if (rc < 0) {
    fprintf(stderr, "csync_sftp - error setting options: %s\n",
        strerror(errno));
    goto out;
  }

  rc = ssh_options_set(_ssh_session, SSH_OPTIONS_COMPRESSION_C_S, "none");
  if (rc < 0) {
    fprintf(stderr, "csync_sftp - error setting options: %s\n",
        strerror(errno));
    goto out;
  }

  rc = ssh_options_set(_ssh_session, SSH_OPTIONS_COMPRESSION_S_C, "none");
  if (rc < 0) {
    fprintf(stderr, "csync_sftp - error setting options: %s\n",
        strerror(errno));
    goto out;
  }

  ssh_options_set(_ssh_session, SSH_OPTIONS_HOST, host);
  if (rc < 0) {
    fprintf(stderr, "csync_sftp - error setting options: %s\n",
        strerror(errno));
    goto out;
  }

  if (port) {
    ssh_options_set(_ssh_session, SSH_OPTIONS_PORT, &port);
    if (rc < 0) {
      fprintf(stderr, "csync_sftp - error setting options: %s\n",
          strerror(errno));
      goto out;
    }
    DEBUG_SFTP(("csync_sftp - port set to: %d\n", port));
  }

  if (user && *user) {
    ssh_options_set(_ssh_session, SSH_OPTIONS_USER, user);
    if (rc < 0) {
      fprintf(stderr, "csync_sftp - error setting options: %s\n",
          strerror(errno));
      goto out;
    }
    DEBUG_SFTP(("csync_sftp - username set to: %s\n", user));
  }

  verbosity = getenv("CSYNC_SFTP_LOG_VERBOSITY");
  if (verbosity) {
    rc = ssh_options_set(_ssh_session, SSH_OPTIONS_LOG_VERBOSITY_STR, verbosity);
    if (rc < 0) {
      goto out;
    }
  }

  /* read ~/.ssh/config */
  rc = ssh_options_parse_config(_ssh_session, NULL);
  if (rc < 0) {
    goto out;
  }

  _ssh_callbacks = (ssh_callbacks) c_malloc(sizeof(struct ssh_callbacks_struct));
  if (_ssh_callbacks == NULL) {
    rc = -1;
    goto out;
  }
  ZERO_STRUCTP(_ssh_callbacks);

  _ssh_callbacks->userdata = _userdata;
  _ssh_callbacks->auth_function = _ssh_auth_callback;

  ssh_callbacks_init(_ssh_callbacks);

  ssh_set_callbacks(_ssh_session, _ssh_callbacks);

  rc = ssh_connect(_ssh_session);
  if (rc < 0) {
    fprintf(stderr, "csync_sftp - error connecting to the server: %s\n", ssh_get_error(_ssh_session));
    ssh_disconnect(_ssh_session);
    _ssh_session = NULL;
    ssh_finalize();
    goto out;
  }

  hlen = ssh_get_pubkey_hash(_ssh_session, &hash);
  if (hlen < 0) {
    fprintf(stderr, "csync_sftp - error connecting to the server: %s\n",
        ssh_get_error(_ssh_session));
    ssh_disconnect(_ssh_session);
    _ssh_session = NULL;
    ssh_finalize();
    goto out;
  }

  /* check the server public key hash */
  state = ssh_is_server_known(_ssh_session);
  switch (state) {
    case SSH_SERVER_KNOWN_OK:
      break;
    case SSH_SERVER_KNOWN_CHANGED:
      fprintf(stderr, "csync_sftp - The host key for this server was "
            "not found, but another type of key exists.\n"
            "An attacker might change the default server key to confuse your "
            "client into thinking the key does not exist.\n"
            "Please contact your system administrator.\n"
            "%s\n", ssh_get_error(_ssh_session));
      ssh_print_hexa("csync_sftp - public key hash", hash, hlen);

      ssh_disconnect(_ssh_session);
      _ssh_session = NULL;
      ssh_finalize();
      rc = -1;
      goto out;
      break;
    case SSH_SERVER_FOUND_OTHER:
      fprintf(stderr, "csync_sftp - the host key for this server was not "
          "found but an other type of key exists.\n");
      fprintf(stderr, "csync_sftp - an attacker might change the default "
          "server key to confuse your client into thinking the key does not "
          "exist\n");
      fprintf(stderr, "The host key for the server %s has changed.\n"
          "This could either mean that DNS SPOOFING is happening or the IP "
          "address for the host and its host key have changed at the same time.\n"
          "The fingerprint for the key sent by the remote host is:\n", host);
          ssh_print_hexa("", hash, hlen);
          fprintf(stderr, "Please contact your system administrator.\n"
          "%s\n", ssh_get_error(_ssh_session));

      ssh_disconnect(_ssh_session);
      _ssh_session = NULL;
      ssh_finalize();
      rc = -1;
      goto out;
      break;
    case SSH_SERVER_NOT_KNOWN:
      if (_authcb) {
        char *hexa;
        char *prompt;
        char buf[4] = {0};

        hexa = ssh_get_hexa(hash, hlen);
        if (hexa == NULL) {
          ssh_disconnect(_ssh_session);
          _ssh_session = NULL;
          ssh_finalize();
          rc = -1;
          goto out;
        }

        if (asprintf(&prompt,
              "The authenticity of host '%s' can't be established.\n"
              "RSA key fingerprint is %s.\n"
              "Are you sure you want to continue connecting (yes/no)?",
              host, hexa) < 0 ) {
          free(hexa);
          ssh_disconnect(_ssh_session);
          _ssh_session = NULL;
          ssh_finalize();
          rc = -1;
          goto out;
        }

        free(hexa);

        if ((*_authcb)(prompt, buf, sizeof(buf), 1, 0, _userdata) < 0) {
          free(prompt);
          ssh_disconnect(_ssh_session);
          _ssh_session = NULL;
          ssh_finalize();
          rc = -1;
          goto out;
        }

        free(prompt);

        if (strncasecmp(buf, "yes", 3) != 0) {
          ssh_disconnect(_ssh_session);
          _ssh_session = NULL;
          ssh_finalize();
          rc = -1;
          goto out;
        }

        if (ssh_write_knownhost(_ssh_session) < 0) {
          ssh_disconnect(_ssh_session);
          _ssh_session = NULL;
          ssh_finalize();
          rc = -1;
          goto out;
        }
      } else {
        fprintf(stderr,"csync_sftp - the server is unknown. Connect manually to "
            "the host to retrieve the public key hash, then try again.\n");
      }
      ssh_disconnect(_ssh_session);
      _ssh_session = NULL;
      ssh_finalize();
      rc = -1;
      goto out;
      break;
    case SSH_SERVER_ERROR:
      fprintf(stderr, "%s\n", ssh_get_error(_ssh_session));

      ssh_disconnect(_ssh_session);
      _ssh_session = NULL;
      ssh_finalize();
      rc = -1;
      goto out;
      break;
    default:
      break;
  }

  /* Try to authenticate */
  rc = ssh_userauth_none(_ssh_session, NULL);
  if (rc == SSH_AUTH_ERROR) {
      ssh_disconnect(_ssh_session);
      _ssh_session = NULL;
      ssh_finalize();
      rc = -1;
      goto out;
  }

#if 0
  /* authenticate with the server */
  if (passwd && *passwd) {
    DEBUG_SFTP(("csync_sftp - authenticating with user/password\n"));
    /*
     * This is tunneled cleartext password authentication and possibly needs
     * to be allowed by the ssh server. Set 'PasswordAuthentication yes'
     */
    auth = ssh_userauth_password(_ssh_session, user, passwd);
  } else {
    DEBUG_SFTP(("csync_sftp - authenticating with pubkey\n"));
    auth = ssh_userauth_autopubkey(_ssh_session, NULL);
  }

  if (auth == SSH_AUTH_ERROR) {
    fprintf(stderr, "csync_sftp - authenticating with pubkey: %s\n",
        ssh_get_error(_ssh_session));
    ssh_disconnect(_ssh_session);
    _ssh_session = NULL;
    ssh_finalize();
    rc = -1;
    goto out;
  }

  if (auth != SSH_AUTH_SUCCESS) {
    if (_authcb != NULL) {
      auth = auth_kbdint(_ssh_session);
      if (auth == SSH_AUTH_ERROR) {
        fprintf(stderr,"csync_sftp - authentication failed: %s\n",
            ssh_get_error(_ssh_session));
        ssh_disconnect(_ssh_session);
        _ssh_session = NULL;
        ssh_finalize();
        rc = -1;
        goto out;
      }
    } else {
      ssh_disconnect(_ssh_session);
      _ssh_session = NULL;
      ssh_finalize();
      rc = -1;
      goto out;
    }
  }


#endif
  method = ssh_auth_list(_ssh_session);

  while (rc != SSH_AUTH_SUCCESS) {
    /* Try to authenticate with public key first */
    if (method & SSH_AUTH_METHOD_PUBLICKEY) {
      rc = ssh_userauth_autopubkey(_ssh_session, NULL);
      if (rc == SSH_AUTH_ERROR) {
        ssh_disconnect(_ssh_session);
        _ssh_session = NULL;
        ssh_finalize();
        rc = -1;
        goto out;
      } else if (rc == SSH_AUTH_SUCCESS) {
        break;
      }
    }

    /* Try to authenticate with keyboard interactive */
    if (method & SSH_AUTH_METHOD_INTERACTIVE) {
      rc = auth_kbdint(_ssh_session, user, passwd);
      if (rc == SSH_AUTH_ERROR) {
        ssh_disconnect(_ssh_session);
        _ssh_session = NULL;
        ssh_finalize();
        rc = -1;
        goto out;
      } else if (rc == SSH_AUTH_SUCCESS) {
        break;
      }
    }

    /* Try to authenticate with password */
    if ((method & SSH_AUTH_METHOD_PASSWORD) && passwd && *passwd) {
      rc = ssh_userauth_password(_ssh_session, user, passwd);
      if (rc == SSH_AUTH_ERROR) {
        ssh_disconnect(_ssh_session);
        _ssh_session = NULL;
        ssh_finalize();
        rc = -1;
        goto out;
      } else if (rc == SSH_AUTH_SUCCESS) {
        break;
      }
    }
  }

  DEBUG_SFTP(("csync_sftp - creating sftp channel...\n"));
  /* start the sftp session */
  _sftp_session = sftp_new(_ssh_session);
  if (_sftp_session == NULL) {
    fprintf(stderr, "csync_sftp - sftp error initialising channel: %s\n", ssh_get_error(_ssh_session));
    rc = -1;
    goto out;
  }

  rc = sftp_init(_sftp_session);
  if (rc < 0) {
    fprintf(stderr, "csync_sftp - error initialising sftp: %s\n", ssh_get_error(_ssh_session));
    goto out;
  }

  DEBUG_SFTP(("csync_sftp - connection established...\n"));
  _connected = 1;
  rc = 0;
out:
  SAFE_FREE(scheme);
  SAFE_FREE(user);
  SAFE_FREE(passwd);
  SAFE_FREE(host);
  SAFE_FREE(path);
  SAFE_FREE(hash);

  return rc;
}
Example #19
0
int main(int argc, char **argv) {

    // check for args num
    if (argc < 3) exit(-1);

    // assign first arg to host var
    char host[20];
    strcpy(host, argv[1]);

    // assign second arg to port var
    int port = atoi(argv[2]);

// set verbosity if need
//    int verbosity = SSH_LOG_FUNCTIONS;
//    int verbosity = SSH_LOG_PROTOCOL;
    int connection;

    ssh_session session;
    session = ssh_new();

    if (session == NULL) exit(-1);

    ssh_options_set(session, SSH_OPTIONS_HOST, host);
//    ssh_options_set(session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity);
    ssh_options_set(session, SSH_OPTIONS_PORT, &port);
    ssh_options_set(session, SSH_OPTIONS_USER, "gluck");

    printf("Connecting to host %s and port %d\n", host, port);
    connection = ssh_connect(session);

    if (connection != SSH_OK) {
        printf("Error connecting to %s: %s\n", host, ssh_get_error(session));
        exit -1;
    } else {
        printf("Connected.\n");
    }

    if (verify_knownhost(session) < 0) {
        ssh_disconnect(session);
        ssh_free(session);
        exit(-1);
    }

    int rc;
    char *password;

    password = getpass("Password: "******"Error authenticating with password: %s\n",
            ssh_get_error(session));
        ssh_disconnect(session);
        ssh_free(session);
        exit(-1);
    }

    if (show_remote_processes(session) != SSH_OK) {
        printf("Error executing request\n");
        ssh_get_error(session);
        ssh_disconnect(session);
        ssh_free(session);
        exit(-1);
    } else {
        printf("\nRequest completed successfully!\n");
    }

    ssh_disconnect(session);
    ssh_free(session);
}
Example #20
0
static const gchar *
cockpit_ssh_authenticate (CockpitSshData *data)
{
  gss_cred_id_t gsscreds = GSS_C_NO_CREDENTIAL;
  const gchar *password = NULL;
  const gchar *problem;
  gboolean tried = FALSE;
  gchar *description;
  int methods;
  int rc;

  problem = "not-authorized";

  rc = ssh_userauth_none (data->session, NULL);
  if (rc == SSH_AUTH_ERROR)
    {
      if (g_atomic_int_get (data->connecting))
        g_message ("%s: server authentication handshake failed: %s",
                   data->logname, ssh_get_error (data->session));
      problem = "internal-error";
      goto out;
    }

  if (rc == SSH_AUTH_SUCCESS)
    {
      problem = NULL;
      goto out;
    }

  methods = ssh_userauth_list (data->session, NULL);
  if (methods & SSH_AUTH_METHOD_PASSWORD)
    {
      password = cockpit_creds_get_password (data->creds);
      if (password)
        {
          tried = TRUE;
          rc = ssh_userauth_password (data->session, NULL, password);
          switch (rc)
            {
            case SSH_AUTH_SUCCESS:
              g_debug ("%s: password auth succeeded", data->logname);
              problem = NULL;
              goto out;
            case SSH_AUTH_DENIED:
              g_debug ("%s: password auth failed", data->logname);
              break;
            case SSH_AUTH_PARTIAL:
              g_message ("%s: password auth worked, but server wants more authentication",
                         data->logname);
              break;
            default:
              if (g_atomic_int_get (data->connecting))
                g_message ("%s: couldn't authenticate: %s", data->logname,
                           ssh_get_error (data->session));
              problem = "internal-error";
              goto out;
            }
        }
    }

  if (methods & SSH_AUTH_METHOD_GSSAPI_MIC)
    {
      tried = TRUE;

      gsscreds = cockpit_creds_push_thread_default_gssapi (data->creds);
      if (gsscreds != GSS_C_NO_CREDENTIAL)
        {
#ifdef HAVE_SSH_GSSAPI_SET_CREDS
          ssh_gssapi_set_creds (data->session, gsscreds);
#else
          g_warning ("unable to forward delegated gssapi kerberos credentials because the "
                     "version of libssh on this system does not support it.");
#endif

          rc = ssh_userauth_gssapi (data->session);

#ifdef HAVE_SSH_GSSAPI_SET_CREDS
          ssh_gssapi_set_creds (data->session, NULL);
#endif

          switch (rc)
            {
            case SSH_AUTH_SUCCESS:
              g_debug("%s: gssapi auth succeeded", data->logname);
              problem = NULL;
              goto out;
            case SSH_AUTH_DENIED:
              g_debug ("%s: gssapi auth failed", data->logname);
              break;
            case SSH_AUTH_PARTIAL:
              g_message ("%s: gssapi auth worked, but server wants more authentication",
                         data->logname);
              break;
            default:
              if (g_atomic_int_get (data->connecting))
                g_message ("%s: couldn't authenticate: %s", data->logname,
                           ssh_get_error (data->session));
              problem = "internal-error";
              goto out;
            }
        }
    }

  if (!tried)
    {
      description = auth_method_description (methods);
      g_message ("%s: server offered unsupported authentication methods: %s",
                 data->logname, description);
      g_free (description);
      problem = "not-authorized";
    }
  else if (!password && gsscreds == GSS_C_NO_CREDENTIAL)
    {
      problem = "no-forwarding";
    }
  else
    {
      problem = "not-authorized";
    }

out:
  cockpit_creds_pop_thread_default_gssapi (data->creds, gsscreds);
  return problem;
}
Example #21
0
int main(int argc, char **argv)
{
    int verbose = SSH_LOG_PROTOCOL;
    int port = 22;
    int rc = 0;
    char *username = "******";
    char *passwd = "2113";
    ssh_session my_ssh_session = ssh_new();

    if (my_ssh_session == NULL)
        exit(-1);

    ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "localhost");
    ssh_options_set(my_ssh_session, SSH_OPTIONS_LOG_VERBOSITY, &verbose);
    ssh_options_set(my_ssh_session, SSH_OPTIONS_PORT, &port);
  
    rc = ssh_connect(my_ssh_session);
    printf("conn: ok=?%d, %d, %s\n", rc==SSH_OK, rc, ssh_get_error(my_ssh_session));

    rc = ssh_userauth_password(my_ssh_session, username, passwd);
    printf("conn: ok=?%d, %d, %s\n", rc==SSH_OK, rc, ssh_get_error(my_ssh_session));

    ssh_channel channel;

    channel = ssh_channel_new(my_ssh_session);
    if (channel == NULL) {

    }

    rc = ssh_channel_open_session(channel);
    printf("conn: ok=?%d, %d, %s\n", rc==SSH_OK, rc, ssh_get_error(my_ssh_session));
    
    rc = ssh_channel_request_exec(channel, "ls -lh");
    printf("conn: ok=?%d, %d, %s\n", rc==SSH_OK, rc, ssh_get_error(my_ssh_session));

    char buffer[100];
    unsigned int nbytes;


    nbytes = ssh_channel_read(channel, buffer, sizeof(buffer)-1, 0);
    buffer[nbytes] = '\0';
    printf("ssh out byte: %d, %s\n", nbytes, buffer);

    while (nbytes > 0) {
        nbytes = ssh_channel_read(channel, buffer, sizeof(buffer)-1, 0);
        buffer[nbytes] = '\0';
        printf("ssh out byte: %d, %s\n", nbytes, buffer);
    }

    nbytes = ssh_channel_read(channel, buffer, sizeof(buffer)-1, 1);
    buffer[nbytes] = '\0';
    printf("ssh err byte: %d, %s\n", nbytes, buffer);

    while (nbytes > 0) {
        nbytes = ssh_channel_read(channel, buffer, sizeof(buffer)-1, 1);
        buffer[nbytes] = '\0';
        printf("ssh err byte: %d, %s\n", nbytes, buffer);
    } 

    ssh_channel_send_eof(channel);
    ssh_channel_close(channel);
    ssh_channel_free(channel);

    ssh_disconnect(my_ssh_session);

    ssh_free(my_ssh_session);

    return 0;
}
Example #22
0
int start_ssh(int s, char *ip, int port, unsigned char options, char *miscptr, FILE * fp) {
  char *empty = "";
  char *login, *pass, keep_login[300];
  int auth_state = 0, rc = 0, i = 0;

  if (strlen(login = hydra_get_next_login()) == 0)
    login = empty;
  if (strlen(pass = hydra_get_next_password()) == 0)
    pass = empty;

  if (new_session) {
    if (session) {
      ssh_disconnect(session);
      ssh_finalize();
      ssh_free(session);
    }

    session = ssh_new();
    ssh_options_set(session, SSH_OPTIONS_PORT, &port);
    ssh_options_set(session, SSH_OPTIONS_HOST, hydra_address2string(ip));
    ssh_options_set(session, SSH_OPTIONS_USER, login);
    ssh_options_set(session, SSH_OPTIONS_COMPRESSION_C_S, "none");
    ssh_options_set(session, SSH_OPTIONS_COMPRESSION_S_C, "none");
    if (ssh_connect(session) != 0) {
      //if the connection was drop, trying to reconnect
      if (verbose)
        hydra_report(stderr, "Error: could not connect to target port %d\n", port);
      return 1;
    }

    if ((rc = ssh_userauth_none(session, NULL)) == SSH_AUTH_ERROR) {
      return 3;
    } else if (rc == SSH_AUTH_SUCCESS) {
      hydra_report_found_host(port, ip, "ssh", fp);
      hydra_completed_pair_found();
      if (memcmp(hydra_get_next_pair(), &HYDRA_EXIT, sizeof(HYDRA_EXIT)) == 0)
        return 2;
      else
        return 1;
    }
  } else
    new_session = 1;

  auth_state = ssh_auth_list(session);
  if ((auth_state & SSH_AUTH_METHOD_PASSWORD) > 0) {
    auth_state = ssh_userauth_password(session, NULL, pass);
  } else if ((auth_state & SSH_AUTH_METHOD_INTERACTIVE) > 0) {
    auth_state = ssh_userauth_kbdint(session, NULL, NULL);
    while (auth_state == SSH_AUTH_INFO) {
      rc = ssh_userauth_kbdint_getnprompts(session);
      for (i = 0; i < rc; i++)
        ssh_userauth_kbdint_setanswer(session, i, pass);
      auth_state = ssh_userauth_kbdint(session, NULL, NULL);
    }
  } else {
    return 4;
  }

  if (auth_state == SSH_AUTH_ERROR) {
    new_session = 1;
    return 1;
  }

  if (auth_state == SSH_AUTH_SUCCESS || auth_state == SSH_AUTH_PARTIAL) {
    hydra_report_found_host(port, ip, "ssh", fp);
    hydra_completed_pair_found();
    if (memcmp(hydra_get_next_pair(), &HYDRA_EXIT, sizeof(HYDRA_EXIT)) == 0)
      return 2;
    return 1;
  } else {
    strncpy(keep_login, login, sizeof(keep_login) - 1);
    keep_login[sizeof(keep_login) - 1] = '\0';
    hydra_completed_pair();
    if (memcmp(hydra_get_next_pair(), &HYDRA_EXIT, sizeof(HYDRA_EXIT)) == 0)
      return 2;
    login = hydra_get_next_login();
    if (strcmp(login, keep_login) == 0)
      new_session = 0;
    return 1;
  }

  /* not reached */
  return 1;
}
Example #23
0
bool
SSHClient::sshConnect(int /* fd */, std::string &hostname)
{
//     GNASH_REPORT_FUNCTION;
    char *password;
    char *banner;
    char *hexa;

    // We always need a hostname to connect to
    if (ssh_options_set(_session, SSH_OPTIONS_HOST, hostname.c_str()) < 0) {
	log_error(_("Couldn't set hostname option"));
	return false;
    }

    // We always need a user name for the connection
    if (_user.empty()) {
	if (ssh_options_set(_session, SSH_OPTIONS_USER, _user.c_str()) < 0) {
	    log_error(_("Couldn't set user name option"));
	    return false;
	}
    }
    
    // Start a new session
    _session = ssh_new();
    if(ssh_connect(_session)){
        log_error(_("Connection failed : %s\n"), ssh_get_error(_session));
	sshShutdown();
        return false;
    }

    _state = ssh_is_server_known(_session);

    unsigned char *hash = 0;
    int hlen = ssh_get_pubkey_hash(_session, &hash);
    if (hlen < 0) {
	sshShutdown();
	return false;
    }
    switch(_state){
      case SSH_SERVER_KNOWN_OK:	// ok
	  log_debug(_("SSH Server is currently known: %d"), _state);
	  break; 
      case SSH_SERVER_KNOWN_CHANGED:
	  log_error(_("Host key for server changed : server's one is now: "));
	  ssh_print_hexa(_("Public key hash"), hash, hlen);
	  free(hash);
	  log_error(_("For security reason, connection will be stopped"));
	  sshShutdown();
	  return false;;
      case SSH_SERVER_FOUND_OTHER:
	  log_error(_("The host key for this server was not found but an other type of key exists."));
	  log_error(_("An attacker might change the default server key to confuse your client"
		    " into thinking the key does not exist"
		      "We advise you to rerun the client with -d or -r for more safety."));
	  sshShutdown();
	  return false;;
      case SSH_SERVER_NOT_KNOWN:
	  hexa = ssh_get_hexa(hash, hlen);
	  free(hash);
	  // FIXME: for now, accecpt all new keys, and update the 
	  // $HOME/.ssh/know_hosts file.
#if 0
	  log_error(_("The server is unknown. Do you trust the host key ? (yes,no)"));
	  log_error(_("Public key hash: %s"), hexa);
	  free(hexa);
	  fgets(buf, sizeof(buf), stdin);
	  if(strncasecmp(buf, "yes", 3) != 0){
	      sshShutdown();
	      return false;
	  }
	  log_error(_("This new key will be written on disk for further usage. do you agree? (yes,no) "));
	  fgets(buf, sizeof(buf), stdin);
	  if(strncasecmp(buf, "yes", 3)==0){
	      if(ssh_write_knownhost(_session))
		  log_error(ssh_get_error(_session));
	  }
#else
	  if(ssh_write_knownhost(_session)) {
	      log_error(ssh_get_error(_session));
	  }
#endif  
	  break;
      case SSH_SERVER_ERROR:
	  free(hash);
	  log_error(ssh_get_error(_session));
	  sshShutdown();
	  return false;
    }
    
    free(hash);
    
    ssh_userauth_none(_session, NULL);
    
    int auth = ssh_auth_list(_session);

//    log_debug("auth: 0x%04x", auth);
    log_debug(_("supported auth methods: "));
    if (auth & SSH_AUTH_METHOD_PUBLICKEY) {
	log_debug(_("\tpublickey"));
    }
    if (auth & SSH_AUTH_METHOD_INTERACTIVE) {
	log_debug(_("\tkeyboard-interactive"));
    }

    /* no ? you should :) */
    auth=ssh_userauth_autopubkey(_session, NULL);
    if(auth == SSH_AUTH_ERROR){
        log_debug(_("Authenticating with pubkey: %s"), ssh_get_error(_session));
	ssh_finalize();
        return false;
    }
    banner = ssh_get_issue_banner(_session);
    if(banner){
        log_debug(banner);
        free(banner);
    }
    if(auth != SSH_AUTH_SUCCESS){
        auth = authKbdint(_session);
        if(auth == SSH_AUTH_ERROR){
            log_error(_("authenticating with keyb-interactive: %s"),
		      ssh_get_error(_session));
	    ssh_finalize();
            return false;
        }
    }
    if(auth != SSH_AUTH_SUCCESS){
        password = getpass("Password: "******"Authentication failed: %s"), ssh_get_error(_session));
            ssh_disconnect(_session);
                ssh_finalize();
            return false;
        }
        memset(password, 0, strlen(password));
    }
    ssh_log(_session, SSH_LOG_FUNCTIONS, "Authentication success");

#if 0
    if(strstr(argv[0],"sftp")){
        sftp = 1;
        ssh_log(_session, SSH_LOG_FUNCTIONS, "Doing sftp instead");
    }
    if(!sftp){
        if(!cmds[0])
            shell(_session);
        else
            batch_shell(_session);
    }
    else
        do_sftp(_session);
    if(!sftp && !cmds[0])
        do_cleanup(0);
#endif
    
    return true;
}
int FSSftp::CheckSession( int* err, FSCInfo* info )
{
	if ( sshSession ) { return 0; }

	try
	{
		sshSession = ssh_new();

		if ( !sshSession ) { throw int( SSH_INTERROR_X3 ); }

		if ( ssh_options_set( sshSession, SSH_OPTIONS_HOST, unicode_to_utf8( _operParam.server.Data() ).ptr() ) )
		{
			throw int( SSH_INTERROR_X3 );
		}

		int port = _operParam.port;

		if ( ssh_options_set( sshSession, SSH_OPTIONS_PORT, &port ) )
		{
			throw int( SSH_INTERROR_X3 );
		}


		FSString userName = "";

		if ( _operParam.user.Data()[0] )
		{
			userName = _operParam.user.Data();
		}
		else
		{
			char* ret = getenv( "LOGNAME" );

			if ( ret )
			{
				userName = FSString( sys_charset_id, ret );
				_operParam.user = userName.GetUnicode();

				MutexLock infoLock( &infoMutex );
				_infoParam.user = userName.GetUnicode();
			}
		};

		if ( ssh_options_set( sshSession, SSH_OPTIONS_USER, ( char* )userName.Get( _operParam.charset ) ) ) //есть сомнения, что надо все таки в utf8
		{
			throw int( SSH_INTERROR_X3 );
		}

		if ( ssh_connect( sshSession ) != SSH_OK )
		{
			throw int( SSH_INTERROR_CONNECT );
		}


		int method = ssh_userauth_list( sshSession, 0 );

		int ret;


		static unicode_t userSymbol = '@';

		if ( method & SSH_AUTH_METHOD_PASSWORD )
		{
			FSPromptData data;
			data.visible = false;
			data.prompt = utf8_to_unicode( "Password:"******"SFTP_" ).ptr(),
			        carray_cat<unicode_t>( userName.GetUnicode(), &userSymbol, _operParam.server.Data() ).ptr(),
			        &data, 1 ) ) { throw int( SSH_INTERROR_STOPPED ); }

			ret = ssh_userauth_password( sshSession,
			                             ( char* )FSString( _operParam.user.Data() ).Get( _operParam.charset ),
			                             ( char* )FSString( data.prompt.Data() ).Get( _operParam.charset ) );
		}

		if ( ret != SSH_AUTH_SUCCESS &&
		     ( method & SSH_AUTH_METHOD_INTERACTIVE ) != 0 )
		{
			while ( true )
			{
				ret = ssh_userauth_kbdint( sshSession, 0, 0 );

				if ( ret != SSH_AUTH_INFO ) { break; }

				const char* instruction = ssh_userauth_kbdint_getinstruction( sshSession );

				if ( !instruction ) { instruction = ""; }

				int n = ssh_userauth_kbdint_getnprompts( sshSession );

				if ( n <= 0 ) { continue; }

				std::vector<FSPromptData> pData( n );
				int i;

				for ( i = 0; i < n; i++ )
				{
					char echo;
					const char* prompt = ssh_userauth_kbdint_getprompt( sshSession, i, &echo );

					if ( !prompt ) { break; }

					pData[i].visible = echo != 0;
					pData[i].prompt = utf8_to_unicode( prompt ).ptr();
				}

				if ( !info ) { throw int( SSH_INTERROR_AUTH ); }

				if ( !info->Prompt(
				        utf8_to_unicode( "SFTP" ).ptr(),
				        carray_cat<unicode_t>( userName.GetUnicode(), &userSymbol, _operParam.server.Data() ).ptr(),
				        pData.ptr(), n ) ) { throw int( SSH_INTERROR_STOPPED ); }

				for ( i = 0; i < n; i++ )
				{
					if ( ssh_userauth_kbdint_setanswer( sshSession, i, ( char* )FSString( pData[i].prompt.Data() ).Get( _operParam.charset ) ) < 0 )
					{
						throw int( SSH_INTERROR_AUTH );
					}
				}
			}
		}

		if ( ret != SSH_AUTH_SUCCESS )
		{
			if ( ret == SSH_AUTH_PARTIAL )
			{
				throw int( SSH_INTERROR_UNSUPPORTED_AUTH );
			}
			else
			{
				throw int( SSH_INTERROR_AUTH );
			}
		}

		sftpSession = sftp_new( sshSession );

		if ( !sftpSession ) { throw int( SSH_INTERROR_FATAL ); }

		if ( sftp_init( sftpSession ) != SSH_OK ) { throw int( SSH_INTERROR_FATAL ); }

	}
	catch ( int e )
	{
		if ( err ) { *err = e; }

		if ( sftpSession ) { sftp_free( sftpSession ); }

		if ( sshSession ) { ssh_free( sshSession ); }

		sshSession = 0;
		sftpSession = 0;
		return ( e == SSH_INTERROR_STOPPED ) ? -2 : -1;
	}

	return 0;
}
Example #25
0
int SSH_Socket::authenticate_console()
{
    int rc;
    int method;
    char *banner;

    // Try to authenticate
    rc = ssh_userauth_none(session, nullptr);
    switch(rc)
    {
        case SSH_AUTH_ERROR:   //some error happened during authentication
            std::cout << "ssh_userauth_none SSH_AUTH_ERROR!" << std::endl;
            error();
            return rc;
        case SSH_AUTH_DENIED:  //no key matched
            std::cout << "ssh_userauth_none SSH_AUTH_DENIED!" << std::endl;
            break;
        case SSH_AUTH_SUCCESS: //you are now authenticated
            std::cout << "ssh_userauth_none SSH_AUTH_SUCCESS!" << std::endl;
            break;
        case SSH_AUTH_PARTIAL:
            //some key matched but you still have
            //to provide an other mean of authentication (like a password).
            std::cout << "ssh_userauth_none SSH_AUTH_PARTIAL!" << std::endl;
            break;
    }

    int failureCounter = 0;

    // Get a list of excepted Auth Sessions server wants.
    method = ssh_auth_list(session);
    while(rc != SSH_AUTH_SUCCESS && failureCounter < 20)
    {
/*
    Retrieve the public key with ssh_import_pubkey_file().
    Offer the public key to the SSH server using ssh_userauth_try_publickey().
     * If the return value is SSH_AUTH_SUCCESS, the SSH server accepts
     * to authenticate using the public key and you can go to the next step.
    Retrieve the private key, using the ssh_pki_import_privkey_file() function.
     * If a pass phrase is needed, either the pass phrase specified
     * as argument or a callback will be used.
    Authenticate using ssh_userauth_publickey() with your private key.
    Do not forget cleaning up memory using ssh_key_free().
*/
        // The function ssh_userauth_autopubkey() does this using the
        // available keys in "~/.ssh/" or ssh-agent. The return values are the following:
        // ** Public Key Needs more testing.
        if(method & SSH_AUTH_METHOD_PUBLICKEY)
        {
            rc = ssh_userauth_autopubkey(session, nullptr);
            switch(rc)
            {
                case SSH_AUTH_ERROR:   //some serious error happened during authentication
                    std::cout << "SSH_AUTH_METHOD_PUBLICKEY - SSH_AUTH_ERROR!" << std::endl;
                    error();
                    return rc;
                case SSH_AUTH_DENIED:  //no key matched
                    std::cout << "SSH_AUTH_METHOD_PUBLICKEY - SSH_AUTH_DENIED!" << std::endl;
                    ++failureCounter;
                    break;
                case SSH_AUTH_SUCCESS: //you are now authenticated
                    std::cout << "SSH_AUTH_METHOD_PUBLICKEY - SSH_AUTH_SUCCESS!" << std::endl;
                    break;
                case SSH_AUTH_PARTIAL:
                    // some key matched but you still have
                    // to provide an other mean of authentication (like a password).
                    std::cout << "SSH_AUTH_METHOD_PUBLICKEY - SSH_AUTH_PARTIAL!" << std::endl;
                    ++failureCounter;
                    break;
                default:
                    break;
            }
/*
            // Validate with specific public key file
            rc = ssh_userauth_try_publickey(session, NULL, "pubkey.pub");
            switch (rc)
            {
                case SSH_AUTH_ERROR:   //some serious error happened during authentication
                    printf("\r\n try_publickey - SSH_AUTH_ERROR! \r\n");
                    error(session);
                    return rc;
                case SSH_AUTH_DENIED:  //no key matched
                    printf("\r\n try_publickey - SSH_AUTH_DENIED! \r\n");
                    break;
                case SSH_AUTH_SUCCESS: //you are now authenticated
                    printf("\r\n try_publickey - SSH_AUTH_SUCCESS! \r\n");
                    break;
                case SSH_AUTH_PARTIAL: //some key matched but you still have to
                                       //provide an other mean of authentication (like a password).
                    printf("\r\n try_publickey - SSH_AUTH_PARTIAL! \r\n");
                    break;
                default:
                    break;
            }
             */
        }

        // Try to authenticate with keyboard interactive";
        if(method & SSH_AUTH_METHOD_INTERACTIVE)
        {
            //rc = authenticate_kbdint(session, NULL);
            switch(rc)
            {
                case SSH_AUTH_ERROR:   //some serious error happened during authentication
                    std::cout << "SSH_AUTH_METHOD_INTERACTIVE - SSH_AUTH_ERROR!" << std::endl;
                    error();
                    return rc;
                case SSH_AUTH_DENIED:  //no key matched
                    std::cout << "SSH_AUTH_METHOD_INTERACTIVE - SSH_AUTH_DENIED!" << std::endl;
                    ++failureCounter;
                    break;
                case SSH_AUTH_SUCCESS: //you are now authenticated
                    std::cout << "SSH_AUTH_METHOD_INTERACTIVE - SSH_AUTH_SUCCESS!" << std::endl;
                    break;
                case SSH_AUTH_PARTIAL: //some key matched but you still have to
                                       //provide an other mean of authentication (like a password).
                    std::cout << "SSH_AUTH_METHOD_INTERACTIVE - SSH_AUTH_PARTIAL!" << std::endl;
                    ++failureCounter;
                    break;
                default:
                    break;
            }
        }
        /*
        if (ssh_getpass("Password: "******"")
            {
                rc = ssh_userauth_password(session, nullptr, password.c_str());
                switch(rc)
                {
                    case SSH_AUTH_ERROR:   //some serious error happened during authentication
                        std::cout << "SSH_AUTH_METHOD_PASSWORD - SSH_AUTH_ERROR!" << std::endl;
                        error();
                        return rc;
                    case SSH_AUTH_DENIED:  //no key matched
                        std::cout << "SSH_AUTH_METHOD_PASSWORD - SSH_AUTH_DENIED!" << std::endl;
                        ++failureCounter;
                        break;
                    case SSH_AUTH_SUCCESS: //you are now authenticated
                        std::cout << "SSH_AUTH_METHOD_PASSWORD - SSH_AUTH_SUCCESS!" << std::endl;
                        break;
                    case SSH_AUTH_PARTIAL: //some key matched but you still have to
                                           // provide an other mean of authentication (like a password).
                        std::cout << "SSH_AUTH_METHOD_PASSWORD - SSH_AUTH_PARTIAL!" << std::endl;
                        ++failureCounter;
                        break;
                    default:
                        break;
                }
            }
        }
    }
    banner = ssh_get_issue_banner(session);
    if(banner)
    {
        std::cout << banner << std::endl;
        ssh_string_free_char(banner);
    }

    std::cout << " *** SSH Authenticate Completed." << std::endl;
    return rc;
}
Example #26
0
int main(int argc, char **argv){
    SSH_SESSION *session;
    SSH_OPTIONS *options;
    int auth=0;
    char *password;
    char *banner;
    int state;
    char buf[10];
    unsigned char hash[MD5_DIGEST_LEN];

    options=ssh_options_new();
    if(ssh_options_getopt(options,&argc, argv))
        usage();
    opts(argc,argv);
    signal(SIGTERM,do_exit);
    if(user)
        ssh_options_set_username(options,user);
    ssh_options_set_host(options,host);
    session=ssh_new();
    ssh_set_options(session,options);
    if(ssh_connect(session)){
        fprintf(stderr,"Connection failed : %s\n",ssh_get_error(session));
        ssh_disconnect(session);
	ssh_finalize();
        return 1;
    }
    state=ssh_is_server_known(session);
    switch(state){
        case SSH_SERVER_KNOWN_OK:
            break; /* ok */
        case SSH_SERVER_KNOWN_CHANGED:
            fprintf(stderr,"Host key for server changed : server's one is now :\n");
            ssh_get_pubkey_hash(session,hash);
            ssh_print_hexa("Public key hash",hash,MD5_DIGEST_LEN);
            fprintf(stderr,"For security reason, connection will be stopped\n");
            ssh_disconnect(session);
	    ssh_finalize();
            exit(-1);
        case SSH_SERVER_FOUND_OTHER:
            fprintf(stderr,"The host key for this server was not found but an other type of key exists.\n");
            fprintf(stderr,"An attacker might change the default server key to confuse your client"
                "into thinking the key does not exist\n"
                "We advise you to rerun the client with -d or -r for more safety.\n");
                ssh_disconnect(session);
		ssh_finalize();
                exit(-1);
        case SSH_SERVER_NOT_KNOWN:
            fprintf(stderr,"The server is unknown. Do you trust the host key ?\n");
            ssh_get_pubkey_hash(session,hash);
            ssh_print_hexa("Public key hash",hash,MD5_DIGEST_LEN);
            fgets(buf,sizeof(buf),stdin);
            if(strncasecmp(buf,"yes",3)!=0){
                ssh_disconnect(session);
                exit(-1);
            }
            fprintf(stderr,"This new key will be written on disk for further usage. do you agree ?\n");
            fgets(buf,sizeof(buf),stdin);
            if(strncasecmp(buf,"yes",3)==0){
                if(ssh_write_knownhost(session))
                    fprintf(stderr,"error %s\n",ssh_get_error(session));
            }
            
            break;
        case SSH_SERVER_ERROR:
            fprintf(stderr,"%s",ssh_get_error(session));
            ssh_disconnect(session);
	    ssh_finalize();
            exit(-1);
    }

    /* no ? you should :) */
    auth=ssh_userauth_autopubkey(session);
    if(auth==SSH_AUTH_ERROR){
        fprintf(stderr,"Authenticating with pubkey: %s\n",ssh_get_error(session));
	ssh_finalize();
        return -1;
    }
    banner=ssh_get_issue_banner(session);
    if(banner){
        printf("%s\n",banner);
        free(banner);
    }
    if(auth!=SSH_AUTH_SUCCESS){
        auth=auth_kbdint(session);
        if(auth==SSH_AUTH_ERROR){
            fprintf(stderr,"authenticating with keyb-interactive: %s\n",
                    ssh_get_error(session));
	    ssh_finalize();
            return -1;
        }
    }
    if(auth!=SSH_AUTH_SUCCESS){
        password=getpass("Password : "******"Authentication failed: %s\n",ssh_get_error(session));
            ssh_disconnect(session);
	    ssh_finalize();
            return -1;
        }
        memset(password,0,strlen(password));
    }
    ssh_say(1,"Authentication success\n");
    printf("%s\n",argv[0]);
    if(strstr(argv[0],"sftp")){
        sftp=1;
        ssh_say(1,"doing sftp instead\n");
    }
    if(!sftp){
        if(!cmds[0])
            shell(session);
        else
            batch_shell(session);
    }
    else
        do_sftp(session);    
    if(!sftp && !cmds[0])
        do_cleanup();
    ssh_disconnect(session);
    ssh_finalize();

    return 0;
}
Example #27
0
int SSHConnection::login(const std::string &username, const std::string &password)
{
    return ssh_userauth_password(session.get(), username.c_str(), password.c_str());
}
Example #28
0
/**
    Authenticating the user by using password

    @param session is current ssh password
    @param username should be null
    @param password is login password
    @return integer of the status
*/
int SSHSession::authenticateUser(ssh_session session, const char *username, const char *password) {
  return ssh_userauth_password(session, username, password);
}