int test(LIBSSH2_SESSION *session)
{
    int rc;

    const char *userauth_list =
        libssh2_userauth_list(session, USERNAME, strlen(USERNAME));
    if(userauth_list == NULL) {
        print_last_session_error("libssh2_userauth_list");
        return 1;
    }

    if(strstr(userauth_list, "publickey") == NULL) {
        fprintf(stderr, "'publickey' was expected in userauth list: %s\n",
                userauth_list);
        return 1;
    }

    rc = libssh2_userauth_publickey_fromfile_ex(
        session, USERNAME, strlen(USERNAME), KEY_FILE_PUBLIC, KEY_FILE_PRIVATE,
        NULL);
    if(rc == 0) {
        fprintf(stderr, "Public-key auth succeeded with wrong key\n");
        return 1;
    }

    return 0;
}
Пример #2
0
Файл: ssh.c Проект: Posnet/ctf3
static int _git_ssh_authenticate_session(
	LIBSSH2_SESSION* session,
	const char *user,
	git_cred* cred)
{
	int rc;

	do {
		switch (cred->credtype) {
		case GIT_CREDTYPE_USERPASS_PLAINTEXT: {
			git_cred_userpass_plaintext *c = (git_cred_userpass_plaintext *)cred;
			user = c->username ? c->username : user;
			rc = libssh2_userauth_password(session, user, c->password);
			break;
		}
                case GIT_CREDTYPE_SSH_NONE: {
                    git_cred_ssh_none *c = (git_cred_ssh_none *)cred;
                    user = c->username ? c->username : user;
                    libssh2_userauth_list(session, user, strlen(user));
                    if(libssh2_userauth_authenticated(session)){
                        rc = LIBSSH2_ERROR_NONE;
                    } else {
                        rc = LIBSSH2_ERROR_AUTHENTICATION_FAILED;
                    }
                    break;
                }
		case GIT_CREDTYPE_SSH_KEY: {
			git_cred_ssh_key *c = (git_cred_ssh_key *)cred;
			user = c->username ? c->username : user;

			if (c->privatekey)
				rc = libssh2_userauth_publickey_fromfile(
					session, c->username, c->publickey,
					c->privatekey, c->passphrase);
			else
				rc = ssh_agent_auth(session, c);

			break;
		}
		case GIT_CREDTYPE_SSH_CUSTOM: {
			git_cred_ssh_custom *c = (git_cred_ssh_custom *)cred;

			user = c->username ? c->username : user;
			rc = libssh2_userauth_publickey(
				session, c->username, (const unsigned char *)c->publickey,
				c->publickey_len, c->sign_callback, &c->sign_data);
			break;
		}
		default:
			rc = LIBSSH2_ERROR_AUTHENTICATION_FAILED;
		}
	} while (LIBSSH2_ERROR_EAGAIN == rc || LIBSSH2_ERROR_TIMEOUT == rc);

	if (rc != LIBSSH2_ERROR_NONE) {
		ssh_error(session, "Failed to authenticate SSH session");
		return -1;
	}

	return 0;
}
Пример #3
0
/**
 * Recognize authenticaion types supported by remote side and filling internal 'super' structure by
 * proper enum's values.
 *
 * @param super connection data
 */
static void
sftpfs_recognize_auth_types (struct vfs_s_super *super)
{
    char *userauthlist;
    sftpfs_super_data_t *super_data;

    super_data = (sftpfs_super_data_t *) super->data;

    super_data->auth_type = NONE;

    /* check what authentication methods are available */
    userauthlist = libssh2_userauth_list (super_data->session, super->path_element->user,
                                          strlen (super->path_element->user));

    if ((strstr (userauthlist, "password") != NULL
         || strstr (userauthlist, "keyboard-interactive") != NULL)
        && (super_data->config_auth_type & PASSWORD) != 0)
        super_data->auth_type |= PASSWORD;

    if (strstr (userauthlist, "publickey") != NULL && (super_data->config_auth_type & PUBKEY) != 0)
        super_data->auth_type |= PUBKEY;

    if ((super_data->config_auth_type & AGENT) != 0)
        super_data->auth_type |= AGENT;

    g_free (userauthlist);
}
int test(LIBSSH2_SESSION *session)
{
    int rc;

    const char *userauth_list =
        libssh2_userauth_list(session, USERNAME, strlen(USERNAME));
    if(userauth_list == NULL) {
        print_last_session_error("libssh2_userauth_list");
        return 1;
    }

    if(strstr(userauth_list, "keyboard-interactive") == NULL) {
        fprintf(stderr,
                "'keyboard-interactive' was expected in userauth list: %s\n",
                userauth_list);
        return 1;
    }

    rc = libssh2_userauth_keyboard_interactive_ex(
        session, USERNAME, strlen(USERNAME), kbd_callback);
    if(rc != 0) {
        print_last_session_error("libssh2_userauth_keyboard_interactive_ex");
        return 1;
    }

    return 0;
}
Пример #5
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;
  }
}
Пример #6
0
static PyObject *
session_userauth_list(SSH2_SessionObj *self, PyObject *args)
{
	char *username;
	char *ret;
	Py_ssize_t username_len;

	if (!PyArg_ParseTuple(args, "s#:userauth_list", &username, &username_len))
		return NULL;

	if ((ret = libssh2_userauth_list(self->session, username, username_len)) == NULL)
		Py_RETURN_NONE;

	return Py_BuildValue("s", ret);
}
Пример #7
0
static int list_auth_methods(int *out, LIBSSH2_SESSION *session, const char *username)
{
	const char *list, *ptr;

	*out = 0;

	list = libssh2_userauth_list(session, username, strlen(username));

	/* either error, or the remote accepts NONE auth, which is bizarre, let's punt */
	if (list == NULL && !libssh2_userauth_authenticated(session)) {
		ssh_error(session, "Failed to retrieve list of SSH authentication methods");
		return -1;
	}

	ptr = list;
	while (ptr) {
		if (*ptr == ',')
			ptr++;

		if (!git__prefixcmp(ptr, SSH_AUTH_PUBLICKEY)) {
			*out |= GIT_CREDTYPE_SSH_KEY;
			*out |= GIT_CREDTYPE_SSH_CUSTOM;
#ifdef GIT_SSH_MEMORY_CREDENTIALS
			*out |= GIT_CREDTYPE_SSH_MEMORY;
#endif
			ptr += strlen(SSH_AUTH_PUBLICKEY);
			continue;
		}

		if (!git__prefixcmp(ptr, SSH_AUTH_PASSWORD)) {
			*out |= GIT_CREDTYPE_USERPASS_PLAINTEXT;
			ptr += strlen(SSH_AUTH_PASSWORD);
			continue;
		}

		if (!git__prefixcmp(ptr, SSH_AUTH_KEYBOARD_INTERACTIVE)) {
			*out |= GIT_CREDTYPE_SSH_INTERACTIVE;
			ptr += strlen(SSH_AUTH_KEYBOARD_INTERACTIVE);
			continue;
		}

		/* Skipt it if we don't know it */
		ptr = strchr(ptr, ',');
	}

	return 0;
}
Пример #8
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;
   }
}
Пример #9
0
int SSH2Utils::connect(const char *hostname, const char *username,
		const char *password) {
    unsigned long hostaddr;
    int rc, sock, auth_pw = 0;
    struct sockaddr_in sin;
    const char *fingerprint;
    char *userauthlist;
    LIBSSH2_SESSION *session;

    _password = password;
    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");
        m_errCode = 2;
        return -1;
    }

	/* Create a session instance */
    session = libssh2_session_init();
	if (!session) {
		m_errCode = 3;
		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_startup(session, sock))
			== LIBSSH2_ERROR_EAGAIN)
		;
	if (rc) {
		fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
		m_errCode = 4;
		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);
    printf("Fingerprint: ");
    for(int i = 0; i < 20; i++) {
        printf("%02X ", (unsigned char)fingerprint[i]);
    }
    printf("\n");

    /* check what authentication methods are available */
    userauthlist = libssh2_userauth_list(session, username, strlen(username));
    printf("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 (auth_pw & 1) {
        /* We could authenticate via password */
        if (libssh2_userauth_password(session, username, password)) {
            printf("\tAuthentication by password failed!\n");
            m_errCode = 5;
            goto shutdown;
        } else {
            printf("\tAuthentication by password succeeded.\n");
        }
    } else if (auth_pw & 2) {
        /* Or via keyboard-interactive */
        if (libssh2_userauth_keyboard_interactive(session, username,
                                                  &SSH2Utils::kbd_callback) ) {
            printf("\tAuthentication by keyboard-interactive failed!\n");
            m_errCode = 6;
            goto shutdown;
        } else {
            printf("\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)) {
            printf("\tAuthentication by public key failed!\n");
            m_errCode = 7;
            goto shutdown;
        } else {
            printf("\tAuthentication by public key succeeded.\n");
        }
    } else {
        printf("No supported authentication methods found!\n");
        m_errCode = 8;
        goto shutdown;
    }

    m_sock = sock;
    m_session = session;

    return 0;

shutdown:
	return -1;
    deconnect();
}
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;
}
Пример #11
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;
	}

}
Пример #12
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;
}
Пример #13
0
int main(int argc, char *argv[])
{
    int rc, i, auth = AUTH_NONE;
    struct sockaddr_in sin;
    socklen_t sinlen = sizeof(sin);
    const char *fingerprint;
    char *userauthlist;
    LIBSSH2_SESSION *session;
    LIBSSH2_LISTENER *listener = NULL;
    LIBSSH2_CHANNEL *channel = NULL;
    fd_set fds;
    struct timeval tv;
    ssize_t len, wr;
    char buf[16384];

#ifdef WIN32
    SOCKET sock = INVALID_SOCKET, forwardsock = INVALID_SOCKET;
    WSADATA wsadata;
    int err;

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

    if (argc > 1)
        server_ip = argv[1];
    if (argc > 2)
        username = argv[2];
    if (argc > 3)
        password = argv[3];
    if (argc > 4)
        remote_listenhost = argv[4];
    if (argc > 5)
        remote_wantport = atoi(argv[5]);
    if (argc > 6)
        local_destip = argv[6];
    if (argc > 7)
        local_destport = atoi(argv[7]);

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

    /* Connect to SSH server */
    sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
#ifdef WIN32
    if (sock == INVALID_SOCKET) {
        fprintf(stderr, "failed to open socket!\n");
        return -1;
    }
#else
    if (sock == -1) {
        perror("socket");
        return -1;
    }
#endif

    sin.sin_family = AF_INET;
    if (INADDR_NONE == (sin.sin_addr.s_addr = inet_addr(server_ip))) {
        perror("inet_addr");
        return -1;
    }
    sin.sin_port = htons(22);
    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) {
        fprintf(stderr, "Could not initialize SSH session!\n");
        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, "Error when starting up 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");

    /* 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"))
        auth |= AUTH_PASSWORD;
    if (strstr(userauthlist, "publickey"))
        auth |= AUTH_PUBLICKEY;

    /* check for options */
    if(argc > 8) {
        if ((auth & AUTH_PASSWORD) && !strcasecmp(argv[8], "-p"))
            auth = AUTH_PASSWORD;
        if ((auth & AUTH_PUBLICKEY) && !strcasecmp(argv[8], "-k"))
            auth = AUTH_PUBLICKEY;
    }

    if (auth & AUTH_PASSWORD) {
        if (libssh2_userauth_password(session, username, password)) {
            fprintf(stderr, "Authentication by password failed.\n");
            goto shutdown;
        }
    } else if (auth & AUTH_PUBLICKEY) {
        if (libssh2_userauth_publickey_fromfile(session, username, keyfile1,
                                                keyfile2, password)) {
            fprintf(stderr, "\tAuthentication by public key failed!\n");
            goto shutdown;
        }
        fprintf(stderr, "\tAuthentication by public key succeeded.\n");
    } else {
        fprintf(stderr, "No supported authentication methods found!\n");
        goto shutdown;
    }

    fprintf(stderr, "Asking server to listen on remote %s:%d\n",
        remote_listenhost, remote_wantport);

    listener = libssh2_channel_forward_listen_ex(session, remote_listenhost,
        remote_wantport, &remote_listenport, 1);
    if (!listener) {
        fprintf(stderr, "Could not start the tcpip-forward listener!\n"
                "(Note that this can be a problem at the server!"
                " Please review the server logs.)\n");
        goto shutdown;
    }

    fprintf(stderr, "Server is listening on %s:%d\n", remote_listenhost,
        remote_listenport);

    fprintf(stderr, "Waiting for remote connection\n");
    channel = libssh2_channel_forward_accept(listener);
    if (!channel) {
        fprintf(stderr, "Could not accept connection!\n"
                "(Note that this can be a problem at the server!"
                " Please review the server logs.)\n");
        goto shutdown;
    }

    fprintf(stderr,
        "Accepted remote connection. Connecting to local server %s:%d\n",
        local_destip, local_destport);
    forwardsock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
#ifdef WIN32
    if (forwardsock == INVALID_SOCKET) {
        fprintf(stderr, "failed to open forward socket!\n");
        goto shutdown;
    }
#else
    if (forwardsock == -1) {
        perror("socket");
        goto shutdown;
    }
#endif

    sin.sin_family = AF_INET;
    sin.sin_port = htons(local_destport);
    if (INADDR_NONE == (sin.sin_addr.s_addr = inet_addr(local_destip))) {
        perror("inet_addr");
        goto shutdown;
    }
    if (-1 == connect(forwardsock, (struct sockaddr *)&sin, sinlen)) {
        perror("connect");
        goto shutdown;
    }

    fprintf(stderr, "Forwarding connection from remote %s:%d to local %s:%d\n",
        remote_listenhost, remote_listenport, local_destip, local_destport);

    /* Must use non-blocking IO hereafter due to the current libssh2 API */
    libssh2_session_set_blocking(session, 0);

    while (1) {
        FD_ZERO(&fds);
        FD_SET(forwardsock, &fds);
        tv.tv_sec = 0;
        tv.tv_usec = 100000;
        rc = select(forwardsock + 1, &fds, NULL, NULL, &tv);
        if (-1 == rc) {
            perror("select");
            goto shutdown;
        }
        if (rc && FD_ISSET(forwardsock, &fds)) {
            len = recv(forwardsock, buf, sizeof(buf), 0);
            if (len < 0) {
                perror("read");
                goto shutdown;
            } else if (0 == len) {
                fprintf(stderr, "The local server at %s:%d disconnected!\n",
                    local_destip, local_destport);
                goto shutdown;
            }
            wr = 0;
            do {
                i = libssh2_channel_write(channel, buf, len);
                if (i < 0) {
                    fprintf(stderr, "libssh2_channel_write: %d\n", i);
                    goto shutdown;
                }
                wr += i;
            } while(i > 0 && wr < len);
        }
        while (1) {
            len = libssh2_channel_read(channel, buf, sizeof(buf));
            if (LIBSSH2_ERROR_EAGAIN == len)
                break;
            else if (len < 0) {
                fprintf(stderr, "libssh2_channel_read: %d", (int)len);
                goto shutdown;
            }
            wr = 0;
            while (wr < len) {
                i = send(forwardsock, buf + wr, len - wr, 0);
                if (i <= 0) {
                    perror("write");
                    goto shutdown;
                }
                wr += i;
            }
            if (libssh2_channel_eof(channel)) {
                fprintf(stderr, "The remote client at %s:%d disconnected!\n",
                    remote_listenhost, remote_listenport);
                goto shutdown;
            }
        }
    }

shutdown:
#ifdef WIN32
    closesocket(forwardsock);
#else
    close(forwardsock);
#endif
    if (channel)
        libssh2_channel_free(channel);
    if (listener)
        libssh2_channel_forward_cancel(listener);
    libssh2_session_disconnect(session, "Client disconnecting normally");
    libssh2_session_free(session);

#ifdef WIN32
    closesocket(sock);
#else
    close(sock);
#endif

    libssh2_exit();

    return 0;
}
Пример #14
0
/*
 * Curl_ssh_connect() gets called from Curl_protocol_connect() to allow us to
 * do protocol-specific actions at connect-time.
 */
CURLcode Curl_ssh_connect(struct connectdata *conn, bool *done)
{
  int i;
  struct SSHPROTO *ssh;
  const char *fingerprint;
  const char *authlist;
  char *home;
  char rsa_pub[PATH_MAX];
  char rsa[PATH_MAX];
  char tempHome[PATH_MAX];
  curl_socket_t sock;
  char *real_path;
  char *working_path;
  int working_path_len;
  bool authed = FALSE;
  CURLcode result;
  struct SessionHandle *data = conn->data;

  rsa_pub[0] = rsa[0] = '\0';

  result = ssh_init(conn);
  if (result)
    return result;

  ssh = data->reqdata.proto.ssh;

  working_path = curl_easy_unescape(data, data->reqdata.path, 0,
                                    &working_path_len);
  if (!working_path)
    return CURLE_OUT_OF_MEMORY;

#ifdef CURL_LIBSSH2_DEBUG
  if (ssh->user) {
    infof(data, "User: %s\n", ssh->user);
  }
  if (ssh->passwd) {
    infof(data, "Password: %s\n", ssh->passwd);
  }
#endif /* CURL_LIBSSH2_DEBUG */
  sock = conn->sock[FIRSTSOCKET];
  ssh->ssh_session = libssh2_session_init_ex(libssh2_malloc, libssh2_free,
                                            libssh2_realloc, ssh);
  if (ssh->ssh_session == NULL) {
    failf(data, "Failure initialising ssh session\n");
    Curl_safefree(ssh->path);
    return CURLE_FAILED_INIT;
  }
#ifdef CURL_LIBSSH2_DEBUG
  infof(data, "SSH socket: %d\n", sock);
#endif /* CURL_LIBSSH2_DEBUG */

  if (libssh2_session_startup(ssh->ssh_session, sock)) {
    failf(data, "Failure establishing ssh session\n");
    libssh2_session_free(ssh->ssh_session);
    ssh->ssh_session = NULL;
    Curl_safefree(ssh->path);
    return CURLE_FAILED_INIT;
  }

  /*
   * Before we authenticate we should check the hostkey's fingerprint against
   * our known hosts. How that is handled (reading from file, whatever) is
   * up to us. As for know not much is implemented, besides showing how to
   * get the fingerprint.
   */
  fingerprint = libssh2_hostkey_hash(ssh->ssh_session,
                                     LIBSSH2_HOSTKEY_HASH_MD5);

#ifdef CURL_LIBSSH2_DEBUG
  /* The fingerprint points to static storage (!), don't free() it. */
  infof(data, "Fingerprint: ");
  for (i = 0; i < 16; i++) {
    infof(data, "%02X ", (unsigned char) fingerprint[i]);
  }
  infof(data, "\n");
#endif /* CURL_LIBSSH2_DEBUG */

  /* TBD - methods to check the host keys need to be done */

  /*
   * Figure out authentication methods
   * NB: As soon as we have provided a username to an openssh server we must
   * never change it later. Thus, always specify the correct username here,
   * even though the libssh2 docs kind of indicate that it should be possible
   * to get a 'generic' list (not user-specific) of authentication methods,
   * presumably with a blank username. That won't work in my experience.
   * So always specify it here.
   */
  authlist = libssh2_userauth_list(ssh->ssh_session, ssh->user,
                                   strlen(ssh->user));

  /*
   * Check the supported auth types in the order I feel is most secure with the
   * requested type of authentication
   */
  if ((data->set.ssh_auth_types & CURLSSH_AUTH_PUBLICKEY) &&
      (strstr(authlist, "publickey") != NULL)) {
    /* To ponder about: should really the lib be messing about with the HOME
       environment variable etc? */
    home = curl_getenv("HOME");

    if (data->set.ssh_public_key)
      snprintf(rsa_pub, sizeof(rsa_pub), "%s", data->set.ssh_public_key);
    else if (home)
      snprintf(rsa_pub, sizeof(rsa_pub), "%s/.ssh/id_dsa.pub", home);

    if (data->set.ssh_private_key)
      snprintf(rsa, sizeof(rsa), "%s", data->set.ssh_private_key);
    else if (home)
      snprintf(rsa, sizeof(rsa), "%s/.ssh/id_dsa", home);

    curl_free(home);

    if (rsa_pub[0]) {
      /* The function below checks if the files exists, no need to stat() here.
      */
      if (libssh2_userauth_publickey_fromfile(ssh->ssh_session, ssh->user,
                                              rsa_pub, rsa, "") == 0) {
        authed = TRUE;
      }
    }
  }
  if (!authed &&
      (data->set.ssh_auth_types & CURLSSH_AUTH_PASSWORD) &&
      (strstr(authlist, "password") != NULL)) {
    if (!libssh2_userauth_password(ssh->ssh_session, ssh->user, ssh->passwd))
      authed = TRUE;
  }
  if (!authed && (data->set.ssh_auth_types & CURLSSH_AUTH_HOST) &&
      (strstr(authlist, "hostbased") != NULL)) {
  }
  if (!authed && (data->set.ssh_auth_types & CURLSSH_AUTH_KEYBOARD)
      && (strstr(authlist, "keyboard-interactive") != NULL)) {
    /* Authentication failed. Continue with keyboard-interactive now. */
    if (libssh2_userauth_keyboard_interactive_ex(ssh->ssh_session, ssh->user,
                                                 strlen(ssh->user),
                                                 &kbd_callback) == 0) {
      authed = TRUE;
    }
  }

  if (!authed) {
    failf(data, "Authentication failure\n");
    libssh2_session_free(ssh->ssh_session);
    ssh->ssh_session = NULL;
    Curl_safefree(ssh->path);
    return CURLE_FAILED_INIT;
  }

  /*
   * At this point we have an authenticated ssh session.
   */
  conn->sockfd = sock;
  conn->writesockfd = CURL_SOCKET_BAD;

  if (conn->protocol == PROT_SFTP) {
    /*
     * Start the libssh2 sftp session
     */
    ssh->sftp_session = libssh2_sftp_init(ssh->ssh_session);
    if (ssh->sftp_session == NULL) {
      failf(data, "Failure initialising sftp session\n");
      libssh2_sftp_shutdown(ssh->sftp_session);
      ssh->sftp_session = NULL;
      libssh2_session_free(ssh->ssh_session);
      ssh->ssh_session = NULL;
      return CURLE_FAILED_INIT;
    }

    /*
     * Get the "home" directory
     */
    i = libssh2_sftp_realpath(ssh->sftp_session, ".", tempHome, PATH_MAX-1);
    if (i > 0) {
      /* It seems that this string is not always NULL terminated */
      tempHome[i] = '\0';
      ssh->homedir = (char *)strdup(tempHome);
      if (!ssh->homedir) {
        libssh2_sftp_shutdown(ssh->sftp_session);
        ssh->sftp_session = NULL;
        libssh2_session_free(ssh->ssh_session);
        ssh->ssh_session = NULL;
        return CURLE_OUT_OF_MEMORY;
      }
    }
    else {
      /* Return the error type */
      i = libssh2_sftp_last_error(ssh->sftp_session);
      DEBUGF(infof(data, "error = %d\n", i));
    }
  }

  /* Check for /~/ , indicating realative to the users home directory */
  if (conn->protocol == PROT_SCP) {
    real_path = (char *)malloc(working_path_len+1);
    if (real_path == NULL) {
      Curl_safefree(working_path);
      libssh2_session_free(ssh->ssh_session);
      ssh->ssh_session = NULL;
      return CURLE_OUT_OF_MEMORY;
    }
    if (working_path[1] == '~')
      /* It is referenced to the home directory, so strip the leading '/' */
      memcpy(real_path, working_path+1, 1 + working_path_len-1);
    else
      memcpy(real_path, working_path, 1 + working_path_len);
  }
  else if (conn->protocol == PROT_SFTP) {
    if (working_path[1] == '~') {
      real_path = (char *)malloc(strlen(ssh->homedir) +
                                 working_path_len + 1);
      if (real_path == NULL) {
        libssh2_sftp_shutdown(ssh->sftp_session);
        ssh->sftp_session = NULL;
        libssh2_session_free(ssh->ssh_session);
        ssh->ssh_session = NULL;
        Curl_safefree(working_path);
        return CURLE_OUT_OF_MEMORY;
      }
      /* It is referenced to the home directory, so strip the leading '/' */
      memcpy(real_path, ssh->homedir, strlen(ssh->homedir));
      real_path[strlen(ssh->homedir)] = '/';
      real_path[strlen(ssh->homedir)+1] = '\0';
      if (working_path_len > 3) {
        memcpy(real_path+strlen(ssh->homedir)+1, working_path + 3,
               1 + working_path_len -3);
      }
    }
    else {
      real_path = (char *)malloc(working_path_len+1);
      if (real_path == NULL) {
        libssh2_session_free(ssh->ssh_session);
        ssh->ssh_session = NULL;
        Curl_safefree(working_path);
        return CURLE_OUT_OF_MEMORY;
      }
      memcpy(real_path, working_path, 1+working_path_len);
    }
  }
  else
    return CURLE_FAILED_INIT;

  Curl_safefree(working_path);
  ssh->path = real_path;

  *done = TRUE;
  return CURLE_OK;
}
Пример #15
0
netsnmp_transport *
netsnmp_ssh_transport(const struct sockaddr_in *addr, int local)
{
    netsnmp_transport *t = NULL;
    netsnmp_ssh_addr_pair *addr_pair = NULL;
    int rc = 0;
    int i, auth_pw = 0;
    const char *fingerprint;
    char *userauthlist;
    struct sockaddr_un *unaddr;
    const char *sockpath =
        netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
                              NETSNMP_DS_LIB_SSHTOSNMP_SOCKET);
    char tmpsockpath[MAXPATHLEN];

#ifdef NETSNMP_NO_LISTEN_SUPPORT
    if (local)
        return NULL;
#endif /* NETSNMP_NO_LISTEN_SUPPORT */

    if (addr == NULL || addr->sin_family != AF_INET) {
        return NULL;
    }

    t = SNMP_MALLOC_TYPEDEF(netsnmp_transport);
    if (t == NULL) {
        return NULL;
    }

    t->domain = netsnmp_snmpSSHDomain;
    t->domain_length = netsnmp_snmpSSHDomain_len;
    t->flags = NETSNMP_TRANSPORT_FLAG_STREAM | NETSNMP_TRANSPORT_FLAG_TUNNELED;

    addr_pair = SNMP_MALLOC_TYPEDEF(netsnmp_ssh_addr_pair);
    if (addr_pair == NULL) {
        netsnmp_transport_free(t);
        return NULL;
    }
    t->data = addr_pair;
    t->data_length = sizeof(netsnmp_ssh_addr_pair);

    if (local) {
#ifndef NETSNMP_NO_LISTEN_SUPPORT
#ifdef SNMPSSHDOMAIN_USE_EXTERNAL_PIPE

        /* XXX: set t->local and t->local_length */


        t->flags |= NETSNMP_TRANSPORT_FLAG_LISTEN;

        unaddr = &addr_pair->unix_socket_end;

        /* open a unix domain socket */
        /* XXX: get data from the transport def for it's location */
        unaddr->sun_family = AF_UNIX;
        if (NULL == sockpath) {
            sprintf(tmpsockpath, "%s/%s", get_persistent_directory(),
                    DEFAULT_SOCK_NAME);
            sockpath = tmpsockpath;
        }

        snprintf(unaddr->sun_path, sizeof(unaddr->sun_path), "%s", sockpath);
        snprintf(addr_pair->socket_path, sizeof(addr_pair->socket_path), "%s",
                 sockpath);

        t->sock = socket(PF_UNIX, SOCK_STREAM, 0);
        if (t->sock < 0) {
            netsnmp_transport_free(t);
            return NULL;
        }

        /* set the SO_PASSCRED option so we can receive the remote uid */
        {
            int one = 1;
            setsockopt(t->sock, SOL_SOCKET, SO_PASSCRED, (void *) &one,
                       sizeof(one));
        }

        unlink(unaddr->sun_path);
        rc = bind(t->sock, unaddr, SUN_LEN(unaddr));
        if (rc != 0) {
            DEBUGMSGTL(("netsnmp_ssh_transport",
                        "couldn't bind \"%s\", errno %d (%s)\n",
                        unaddr->sun_path, errno, strerror(errno)));
            netsnmp_ssh_close(t);
            netsnmp_transport_free(t);
            return NULL;
        }


        /* set the socket permissions */
        {
            /*
             * Apply any settings to the ownership/permissions of the
             * Sshdomain socket
             */
            int sshdomain_sock_perm =
                netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID,
                                   NETSNMP_DS_SSHDOMAIN_SOCK_PERM);
            int sshdomain_sock_user =
                netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID,
                                   NETSNMP_DS_SSHDOMAIN_SOCK_USER);
            int sshdomain_sock_group =
                netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID,
                                   NETSNMP_DS_SSHDOMAIN_SOCK_GROUP);

            DEBUGMSGTL(("ssh", "here: %s, %d, %d, %d\n",
                        unaddr->sun_path,
                        sshdomain_sock_perm, sshdomain_sock_user,
                        sshdomain_sock_group));
            if (sshdomain_sock_perm != 0) {
                DEBUGMSGTL(("ssh", "Setting socket perms to %d\n",
                            sshdomain_sock_perm));
                chmod(unaddr->sun_path, sshdomain_sock_perm);
            }

            if (sshdomain_sock_user || sshdomain_sock_group) {
                /*
                 * If either of user or group haven't been set,
                 *  then leave them unchanged.
                 */
                if (sshdomain_sock_user == 0 )
                    sshdomain_sock_user = -1;
                if (sshdomain_sock_group == 0 )
                    sshdomain_sock_group = -1;
                DEBUGMSGTL(("ssh", "Setting socket user/group to %d/%d\n",
                            sshdomain_sock_user, sshdomain_sock_group));
                chown(unaddr->sun_path,
                      sshdomain_sock_user, sshdomain_sock_group);
            }
        }

        rc = listen(t->sock, NETSNMP_STREAM_QUEUE_LEN);
        if (rc != 0) {
            DEBUGMSGTL(("netsnmp_ssh_transport",
                        "couldn't listen to \"%s\", errno %d (%s)\n",
                        unaddr->sun_path, errno, strerror(errno)));
            netsnmp_ssh_close(t);
            netsnmp_transport_free(t);
            return NULL;
        }
        

#else /* we're called directly by sshd and use stdin/out */
        /* for ssh on the server side we've been launched so bind to
           stdin/out */

        /* nothing to do */

        /* XXX: verify we're inside ssh */
        t->sock = STDIN_FILENO;
#endif /* ! SNMPSSHDOMAIN_USE_EXTERNAL_PIPE */
#else /* NETSNMP_NO_LISTEN_SUPPORT */
        netsnmp_transport_free(t);
        return NULL;
#endif /* NETSNMP_NO_LISTEN_SUPPORT */
    } else {
        char *username;
        char *keyfilepub;
        char *keyfilepriv;
        
        /* use the requested user name */
        /* XXX: default to the current user name on the system like ssh does */
        username = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
                                         NETSNMP_DS_LIB_SSH_USERNAME);
        if (!username || 0 == *username) {
            snmp_log(LOG_ERR, "You must specify a ssh username to use.  See the snmp.conf manual page\n");
            netsnmp_transport_free(t);
            return NULL;
        }

        /* use the requested public key file */
        keyfilepub = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
                                           NETSNMP_DS_LIB_SSH_PUBKEY);
        if (!keyfilepub || 0 == *keyfilepub) {
            /* XXX: default to ~/.ssh/id_rsa.pub */
            snmp_log(LOG_ERR, "You must specify a ssh public key file to use.  See the snmp.conf manual page\n");
            netsnmp_transport_free(t);
            return NULL;
        }

        /* use the requested private key file */
        keyfilepriv = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
                                            NETSNMP_DS_LIB_SSH_PRIVKEY);
        if (!keyfilepriv || 0 == *keyfilepriv) {
            /* XXX: default to keyfilepub without the .pub suffix */
            snmp_log(LOG_ERR, "You must specify a ssh private key file to use.  See the snmp.conf manual page\n");
            netsnmp_transport_free(t);
            return NULL;
        }

        /* xxx: need an ipv6 friendly one too (sigh) */

        /* XXX: not ideal when structs don't actually match size wise */
        memcpy(&(addr_pair->remote_addr), addr, sizeof(struct sockaddr_in));

        t->sock = socket(PF_INET, SOCK_STREAM, 0);
        if (t->sock < 0) {
            netsnmp_transport_free(t);
            return NULL;
        }

        t->remote_length = sizeof(*addr);
        t->remote = netsnmp_memdup(addr, sizeof(*addr));
        if (!t->remote) {
            netsnmp_ssh_close(t);
            netsnmp_transport_free(t);
            return NULL;
        }

        /*
         * This is a client-type session, so attempt to connect to the far
         * end.  We don't go non-blocking here because it's not obvious what
         * you'd then do if you tried to do snmp_sends before the connection
         * had completed.  So this can block.
         */

        rc = connect(t->sock, addr, sizeof(struct sockaddr));

        if (rc < 0) {
            netsnmp_ssh_close(t);
            netsnmp_transport_free(t);
            return NULL;
        }

        /*
         * Allow user to override the send and receive buffers. Default is
         * to use os default.  Don't worry too much about errors --
         * just plough on regardless.  
         */
        netsnmp_sock_buffer_set(t->sock, SO_SNDBUF, local, 0);
        netsnmp_sock_buffer_set(t->sock, SO_RCVBUF, local, 0);

        /* open the SSH session and channel */
        addr_pair->session = libssh2_session_init();
        if (libssh2_session_startup(addr_pair->session, t->sock)) {
          shutdown:
            snmp_log(LOG_ERR, "Failed to establish an SSH session\n");
            netsnmp_ssh_close(t);
            netsnmp_transport_free(t);
            return NULL;
        }

        /* 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(addr_pair->session, LIBSSH2_HOSTKEY_HASH_MD5);
        DEBUGMSGTL(("ssh", "Fingerprint: "));
        for(i = 0; i < 16; i++) {
            DEBUGMSG(("ssh", "%02x",
                      (unsigned char)fingerprint[i]));
        }
        DEBUGMSG(("ssh", "\n"));

        /* check what authentication methods are available */
        userauthlist =
            libssh2_userauth_list(addr_pair->session,
                                  username, strlen(username));
        DEBUGMSG(("ssh", "Authentication methods: %s\n", userauthlist));

        /* XXX: allow other types */
        /* XXX: 4 seems magic to me... */
        if (strstr(userauthlist, "publickey") != NULL) {
            auth_pw |= 4;
        }

        /* XXX: hard coded paths and users */
        if (auth_pw & 4) {
            /* public key */
            if (libssh2_userauth_publickey_fromfile(addr_pair->session,
                                                    username,
                                                    keyfilepub, keyfilepriv,
                                                    NULL)) {
                snmp_log(LOG_ERR,"Authentication by public key failed!\n");
                goto shutdown;
            } else {
                DEBUGMSG(("ssh",
                          "\tAuthentication by public key succeeded.\n"));
            }
        } else {
            snmp_log(LOG_ERR,"Authentication by public key failed!\n");
            goto shutdown;
        }

        /* we've now authenticated both sides; contining onward ... */

        /* Request a channel */
        if (!(addr_pair->channel =
              libssh2_channel_open_session(addr_pair->session))) {
            snmp_log(LOG_ERR, "Unable to open a session\n");
            goto shutdown;
        }

        /* Request a terminal with 'vanilla' terminal emulation
         * See /etc/termcap for more options
         */
        /* XXX: needed?  doubt it */
/*         if (libssh2_channel_request_pty(addr_pair->channel, "vanilla")) { */
/*             snmp_log(LOG_ERR, "Failed requesting pty\n"); */
/*             goto shutdown; */
/*         } */
        if (libssh2_channel_subsystem(addr_pair->channel, "snmp")) {
            snmp_log(LOG_ERR, "Failed to request the ssh 'snmp' subsystem\n");
            goto shutdown;
        }
    }

    DEBUGMSG(("ssh","Opened connection.\n"));
    /*
     * Message size is not limited by this transport (hence msgMaxSize
     * is equal to the maximum legal size of an SNMP message).  
     */

    t->msgMaxSize = SNMP_MAX_PACKET_LEN;
    t->f_recv     = netsnmp_ssh_recv;
    t->f_send     = netsnmp_ssh_send;
    t->f_close    = netsnmp_ssh_close;
    t->f_accept   = netsnmp_ssh_accept;
    t->f_fmtaddr  = netsnmp_ssh_fmtaddr;

    return t;
}
Пример #16
0
/* IPv6 ref: http://www.akkadia.org/drepper/userapi-ipv6.html */
int main(int argc, char** argv)
{
    int rc, sock = -1;
    struct addrinfo *ai, *r;
    struct addrinfo hints;
    char bufhost[MAXHOSTBUFSIZE];
    char bufport[MAXHOSTBUFSIZE];
    LIBSSH2_SESSION *session;

    curstatebuf = malloc(MAXSTRSIZE);
    *curstatebuf = '\0';

    /* Option defaults */
    opt_host = "127.0.0.1";
    opt_port = "ssh";
    opt_username = "******";
    if((rc = parse_options(argc, argv)) != 0)
    {
        curstate = CRITICAL;
        sprintf(curstatebuf, "Option parsing failed (%d). See stderr.", rc);
        nagios_exit();
    }

    signal(SIGALRM, timeout_handler);
    alarm(opt_timeout);

    memset(&hints, '\0', sizeof(hints));
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_ADDRCONFIG;
    dp("Connecting to %s:%s\n", opt_host, opt_port);
    int e = getaddrinfo(opt_host, opt_port, &hints, &ai);
    if (e != 0)
    {
        curstate = CRITICAL;
        sprintf(curstatebuf, "getaddrinfo: %s", gai_strerror(e));
        nagios_exit();
    }

    dp("Attempting connection to %s:%s\n", opt_host, opt_port);
    for(r = ai; r != NULL; r = r->ai_next) {
        dp("-> Trying family/socktype/proto %d/%d/%d\n",
           r->ai_family, r->ai_socktype, r->ai_protocol);
        sock = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
        if (sock != -1 && connect(sock, r->ai_addr, r->ai_addrlen) == 0)
            break;
        if (sock != -1) {
            close(sock);
            sock = -1;
        }
    }
    if (sock == -1)
    {
        freeaddrinfo(ai);
        curstate = CRITICAL;
        sprintf(curstatebuf, "No socket");
        nagios_exit();
    }

    (void) getnameinfo(r->ai_addr, r->ai_addrlen,
                       bufhost, sizeof (bufhost), bufport, sizeof(bufport),
                       NI_NUMERICHOST|NI_NUMERICSERV);
    dp("Successfully connected to %s:%s\n", bufhost, bufport);
    freeaddrinfo(ai);

    /* libssh2_init and libssh2_exit was introduced in libssh2 1.2.5 */
#if LIBSSH2_VERSION_NUM >= 0x010205
    if((rc = libssh2_init(0)) != 0)
    {
        curstate = CRITICAL;
        sprintf(curstatebuf, "libssh2 initialization failed (%d)", rc);
        nagios_exit();
    }
#endif

    session = libssh2_session_init();
    if(libssh2_session_startup(session, sock) != 0)
    {
        char *err_msg;
        libssh2_session_last_error(session, &err_msg, NULL, 0);
        curstate = CRITICAL;
        sprintf(curstatebuf, "SSH error: %s", err_msg);
        nagios_exit();
    }

    serverualist = strdup(libssh2_userauth_list(session, opt_username, strlen(opt_username)));
    dp("Server auth list: %s\n", serverualist);

    /* Run checks that were requested on the command line */
    if(opt_uablacklist != NULL && strlen(opt_uablacklist))
        uablacklistout = cslist_intersect(opt_uablacklist, serverualist);
    if(opt_uawhitelist != NULL && strlen(opt_uawhitelist))
        uawhitelistout = cslist_difference(opt_uawhitelist, serverualist);
    dp("Matching blacklist: %s\n", uablacklistout);
    dp("Matching whitelist: %s\n", uawhitelistout);

    /* Construct status string */
    curstatebufptr = curstatebuf;
    if(uablacklistout != NULL && strlen(uablacklistout))
    {
        curstate = CRITICAL;
        sprintf(curstatebufptr, "Blacklisted SSH auth methods found (%s)", uablacklistout);
        curstatebufptr = strchr(curstatebuf, '\0');
    }
    if(uawhitelistout != NULL && strlen(uawhitelistout))
    {
        if(curstatebufptr > curstatebuf)
        {
            sprintf(curstatebufptr, ", ");
            curstatebufptr = strchr(curstatebuf, '\0');
        }
        curstate = CRITICAL;
        sprintf(curstatebufptr, "Required SSH auth methods not found (%s)", uawhitelistout);
        curstatebufptr = strchr(curstatebuf, '\0');
    }

    if(uablacklistout != NULL)
        free(uablacklistout);
    if(uawhitelistout != NULL)
        free(uawhitelistout);
    free(serverualist);

    libssh2_session_disconnect(session, "ok");
    libssh2_session_free(session);
    close(sock);

#if LIBSSH2_VERSION_NUM >= 0x010205
    libssh2_exit();
#endif

    alarm(0);

    if(curstate == INIT)
    {
        curstate = OK;
        sprintf(curstatebuf, "SSH server parameters match expectations");
    }
    nagios_exit();

    return 0;
}
RET_CODE serverConnectThread::Process(void* pcThreadParam) {

    CControllerThread *singleInstance;
    singleInstance = CControllerThread::getInstance();
    
    iterServerInfoMap iterMap;
    typedef tbb::concurrent_vector<tapServerInfoMap> mapStore;
    typedef mapStore::iterator iterMapVector;
    mapStore mapStoreObj;
    int whileserverCount = 0;
    
   // CControllerThread *singleInstance;
   // singleInstance = CControllerThread::getInstance();

    unsigned long long int prevSizeroot = 0;
    unsigned long long int currentSizeroot = 0;
    unsigned long long int prevSizedolat = 0;
    unsigned long long int currentSizedolat = 0;
    vector <unsigned long long int> fileSize;
    for(int i=0;i<10;i++)
	fileSize.push_back(0);
   	
    char *hostAdress;
    const char* userName;
    const char* passWord;
    char* dbUserName;
    char* dbPassWord;
    char* dbName;
    char* dbPort;
    char* lineType;
    int globalCounter = 0;
    int count = 0;
    bool breakFlag;
    char commandBuffer[1000];
    char buffer[50];
    char c[20];
    int lProcessListIndex, lSpaceList;
    FILE *p;
   // char *lcPreferredAuthMethod[20];
    int lineCounter;
    DBConnection lDBConnectionObject;
    
    while (1) {
        count = 0;
        breakFlag = false;
        //print_micro_sec(1,stdout);
        for (int i=0;i<(singleInstance->serverObject.size()/3);i++) {
            
            lineCounter =0;
            if (IsThreadInShutdown()) {

                breakFlag = true;
                break;
            }
            tapServerInfoMap m_MapObject;
            tagServerInfo &tsi = singleInstance->serverObject[i];
            
	    //if(tsi.bIsDirty == false)
		//tsi.bIsDirty = true;
            //else
                //continue;            
            hostAdress = tsi.ipAdress;
	    cout <<"hostAdress1 ::: " << tsi.ipAdress << endl;
            userName = tsi.userName;
            passWord = tsi.password;
            dbUserName = tsi.dbUserName;
            dbPassWord = tsi.dbPassword;
            dbName = tsi.dbName;
            dbPort = tsi.dbPort;
            
            //cout <<"FilePath---" << tsi.Path[0].filePath << endl;
    //FILE *fp = fopen("LineIds.txt","w+");
            //lineType = tsi.lineType;

            globalCounter = 0;
            if (!(tsi.dbconStatus)) {
                
                if (0 == lDBConnectionObject.getQueryResult(m_MapObject, dbUserName, dbPassWord, dbName, dbPort, hostAdress, lineType)) {
                   // printf("db connection not found \n");

	          /*  for (std::map <long,std::string>::iterator iterMap = m_MapObject.begin(); iterMap != m_MapObject.end(); iterMap++)
                        {
                        fprintf(fp,"\n");
                        fprintf(fp,"%ld",(*iterMap).first);
                        }*/
                }
		for (std::map <long,std::string>::iterator iterMap = m_MapObject.begin(); iterMap != m_MapObject.end(); iterMap++)
		{		      
	 	  //cout << "userIds::" << iterMap->second << endl;
		  //cout << "first::" << iterMap->first << endl;
 		  conn->orderIds.push_back(iterMap->first);	
                }
                //std::cout<<"m_MapObject"<<m_MapObject.size()<<endl;
                mapStoreObj.push_back(m_MapObject);
                lDBConnectionObject.Close();
                tsi.dbconStatus = true;

            }
	    //memset(buffer,'\0',sizeof(buffer));
            //commandBuffer[1000] = {0};
           // buffer[50] = {0};
           // c[20] = {0};
           
            char *lpUserAuthList;
            struct sockaddr_in sin;
            int rc, sock, auth_pw = 0;
            lProcessListIndex, lSpaceList = 1;

            sprintf(buffer, "ping -c 3 %s | grep -c %s", tsi.ipAdress, "\"3 received\"");
	    g_cSystemLogger.LogMessage("(%s:%s:%d)::Ping Buffer %s", LOG_LOCATION,buffer);
            p = popen(buffer, "r");
            fgets(c, 10, p);
	    //cout << "ping Commmand buff" << buffer << endl;
	   // cout <<" C " << c << endl;
            //pclose(p);
            g_cSystemLogger.LogMessage("(%s:%s:%d)::If Ping Output %s", LOG_LOCATION,c);

            if (atoi(c) == 1) {
                tsi.serverstatus = true;
            } else {
		usleep(1000);
		p = popen(buffer,"r");
		fgets(c,10,p);
		pclose(p);
                g_cSystemLogger.LogMessage("(%s:%s:%d)::Else Ping Output %s", LOG_LOCATION,c);
		cout << "Else C" << c << endl;
		if(atoi(c) == 1)
		{
			tsi.serverstatus = true;
		}
		else
		{
			tsi.serverstatus = false;
			CcopyStructure::copyData(tsi,0,0,0);
			continue;
		}
               
            }
            
	    memset(buffer,'\0',sizeof(buffer));
            memset(c,'\0',sizeof(c));
            rc = libssh2_init(0);

            if (rc != 0) {
                g_cSystemLogger.LogMessage("(%s:%s:%d)::failure establishing ssh", LOG_LOCATION);
                return 1;
            }

            if (tsi.serverstatus == true && tsi.conectstatus == false) {

                sock = socket(AF_INET, SOCK_STREAM, 0);
                tsi.m_socketId = sock;
                sin.sin_family = AF_INET;
                sin.sin_port = htons(22);
                sin.sin_addr.s_addr = inet_addr(tsi.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, tsi.m_socketId)) {
                    return -1;
                }
                tsi.session = session;

                lpUserAuthList = libssh2_userauth_list(session, userName, strlen(userName));

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

               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);
                }
                g_cSystemLogger.LogMessage("(%s:%s(:%d)::after auth_pw 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 password succeded\n", LOG_LOCATION);
                    }
                }
                tsi.session = session;
                tsi.conectstatus = true;
            }

            tapServerInfoMap &MapObject = mapStoreObj.at(count++);

            if (strcmp(tsi.lineType, "FO") == 0) {
                
                int i=0;
                for (iterMap = MapObject.begin(); iterMap != MapObject.end(); iterMap++) {
                  
                     while (((channel = libssh2_channel_open_session(tsi.session)) == NULL) &&
                            (libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN)) {

                        waitsocket(sock, tsi.session);
                    }
                    if (channel == NULL) {
                        g_cSystemLogger.LogMessage("(%s:%s(:%d))ssh channel opening fail",LOG_LOCATION);
                        // goto shutdown;
                    }
                    sprintf(commandBuffer, "%s  %s%s%s%d%s%s%s", "/bin/netstat -n|/bin/grep -c", "\"", iterMap->second.c_str(), ":", 9602, ".*", "ESTABLISHED", "\"");

                    while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) {
                        waitsocket(sock, tsi.session);
                    }
                    int lnReturnCode;
                    lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer));
                    g_cSystemLogger.LogMessage("(%s:%s(:%d))::commandBuffer %s lnreturncode %d\n", LOG_LOCATION,commandBuffer,lnReturnCode);
                    
                    //std::cout<<"iterMap->first" <<iterMap->first <<endl;
                    if (commandBuffer[0] == '1') {
                        
                        strncpy(tsi.lineInfo[i].ipv4adresss, iterMap->second.c_str(), 16);
                        tsi.lineInfo[i].ipv4adresss[16] = '\0';
                        
                        tsi.lineInfo[i].status = TRUE;
                        tsi.lineInfo[i].userId = iterMap->first;
                    } 
                    else if (commandBuffer[0] == '0') {
                        
                        strncpy(tsi.lineInfo[i].ipv4adresss, iterMap->second.c_str(), 16);
                        tsi.lineInfo[i].ipv4adresss[16] = '\0';
                        
                        tsi.lineInfo[i].status = FALSE;
                        tsi.lineInfo[i].userId = iterMap->first;
                    }
                    //std::cout<<"tsi.lineInfo[lineCounter].userId" <<tsi.lineInfo[lineCounter].userId <<endl;
                    //std::cout<<"tsi.lineInfo[lineCounter].status" <<tsi.lineInfo[lineCounter].status <<endl;
                    if (LIBSSH2_ERROR_EAGAIN == lnReturnCode) {
                        waitsocket(sock, tsi.session);
                    }
                    i++;
                    memset(commandBuffer, 0, sizeof (commandBuffer));
                    libssh2_channel_free(channel);
                    channel = NULL;
                }
                //globalCounter = lineCounter;

            }

           /* if (strcmp(tsi.lineType, "CM") == 0) {

                int lineCounter = 0;
                for (iterMap = MapObject.begin(); iterMap != MapObject.end(); iterMap++) {
                    while (((channel = libssh2_channel_open_session(tsi.session)) == NULL) &&
                            (libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN)) {

                        waitsocket(sock, tsi.session);
                    }

                    if (channel == NULL) {
                        g_cSystemLogger.LogMessage("(%s:%s(:%d))ssh channel opening fail",LOG_LOCATION);
                        // goto shutdown;
                    }

                    sprintf(commandBuffer, "%s  %s%s%s%d%s%s%s", "/bin/netstat -n|/bin/grep -c", "\"", iterMap->second.c_str(), ":", 9601, ".*", "ESTABLISHED", "\"");

                    g_cSystemLogger.LogMessage("(%s:%s(:%d))::command for netstat %s\n", LOG_LOCATION, commandBuffer);
                    while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) {
                        waitsocket(sock, tsi.session);
                    }
                    int lnReturnCode;
                    lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer));

                    if (commandBuffer[0] == '1') {
                       
                        strncpy(tsi.lineInfo[lineCounter].ipv4adresss, iterMap->second.c_str(), 16);
                        tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0';
                        
                        tsi.lineInfo[lineCounter].status = TRUE;
                        tsi.lineInfo[lineCounter].userId = iterMap->first;
                    }  else if (commandBuffer[0] == '0') {
               
                        strncpy(tsi.lineInfo[lineCounter].ipv4adresss, iterMap->second.c_str(), 16);
                        tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0';
                        
                        tsi.lineInfo[lineCounter].status = FALSE;
                        tsi.lineInfo[lineCounter].userId = iterMap->first;
                    }
                    if (LIBSSH2_ERROR_EAGAIN == lnReturnCode) {
                        waitsocket(sock, tsi.session);
                    }
                    lineCounter++;
                    memset(commandBuffer, 0, sizeof (commandBuffer));
                    libssh2_channel_free(channel);elOrderI
                    channel = NULL;
                }
                globalCounter = lineCounter;

            }
		
 */
	  // for(int i=1;i<tsi.noOfFilePath;i++)
           // {
              //  printf("Inside Filesizecheck \n");
	   // cout <<"filePath::::" << tsi.Path[0].filePath << endl;
            if (!(strcmp(tsi.Path[0].filePath,"") == 0))
            {
                while (((channel = libssh2_channel_open_session(tsi.session)) == NULL) &&
                            (libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN)) {

                        waitsocket(sock, tsi.session);
                    }

                    if (channel == NULL) {
                        g_cSystemLogger.LogMessage("(%s:%s(:%d))ssh channel opening fail",LOG_LOCATION);
                        // goto shutdown;
                    }               
                    sprintf(commandBuffer,"%s %s %s", "du -b",tsi.Path[0].filePath,"| awk '{print $1}' ");
                    g_cSystemLogger.LogMessage("(%s:%s(:%d))::command for netstat %s\n", LOG_LOCATION, commandBuffer);
                    
                    while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) {
                        waitsocket(sock, tsi.session);
                    }
                    size_t lnReturnCode;
                    lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer));
                    
                    char buff[30];                    
                    int j=0;
		    int i=0; 		    
                    while(commandBuffer[j]!='\n')
                    {
                        buff[i]=commandBuffer[j];
                        j++;
			i++;
			lnReturnCode--;			
                    }
	            
		    lnReturnCode--;
                    currentSizeroot = (atoi(buff));		   
		    if(lnReturnCode)
		    {		   
		    i=0;
		    j++;		    		    
		    memset(buff,0,sizeof(buff));		   		   
		    while(commandBuffer[j]!='\n')
                    {
                        buff[i]=commandBuffer[j];
                        j++;
			i++;
			lnReturnCode--;
                    }
		    }
		    currentSizedolat = (atoi(buff));
                    
	    	    //cout <<"currentSizeroot" << currentSizeroot <<" "<<fileSize[0] <<endl;
		    //cout <<"currentSizedolat" << currentSizedolat <<" " <<fileSize[1] <<endl;
		    
		    if(currentSizeroot!=currentSizedolat)
	            {
			if((currentSizeroot-fileSize[0])>0 && (currentSizedolat-fileSize[1])>0)
                    	{
                        	tsi.Path[0].status=true;
                    	}
		    
                    	else
                    	{
                        	tsi.Path[0].status=false;
                    	}
			fileSize.insert(fileSize.begin()+0,currentSizeroot);
                        fileSize.insert(fileSize.begin()+1,currentSizedolat);

		    }		                        
                    
                    else
                    {
                        if((currentSizeroot-fileSize[2])>0)
                        {
                                tsi.Path[0].status=true;
                        }
                    
                        else
                        {
                                tsi.Path[0].status=false;
                        }
			fileSize.insert(fileSize.begin()+2,currentSizeroot);
                    }
                    
          		                                          
                    memset(commandBuffer, 0, sizeof (commandBuffer));
                    libssh2_channel_free(channel);
                    channel = NULL;
           // }
            }
	
	   /* std::cout<<"tsi.lineType"<<tsi.lineType<<endl;
            if (strcmp(tsi.lineType, "ColoBridge") == 0) {
	singleInstance	 g_cSystemLogger.LogMessage("(%s:%s(:%d))::Inside ColoBridge \n", LOG_LOCATION);

		memset(tsi.lineType, 0, sizeof (tsi.lineType));
		strcpy(tsi.lineType,"CM");
		std::cout<<"LineType"<<tsi.lineType<<endl;
                int lineCounter = 0;
               
                    while (((channel = libssh2_channel_open_session(tsi.session)) == NULL) &&
                            (libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN)) {

                        waitsocket(sock, tsi.session);
                    }

                    if (channel == NULL) {
                        g_cSystemLogger.LogMessage("(%s:%s(:%d))ssh channel opening fail",LOG_LOCATION);
                        // goto shutdown;
                    }

                    sprintf(commandBuffer, "%s  %s%s%s%d%s%s%s", "/bin/netstat -n|/bin/grep -c", "\"", "192.168.30.32", ":", 2004, ".*", "ESTABLISHED", "\"");

                    g_cSystemLogger.LogMessage("(%s:%s(:%d))::command for netstat %s\n", LOG_LOCATION, commandBuffer);
                    while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) {
                        waitsocket(sock, tsi.session);
                    }
                    int lnReturnCode;
                    lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer));

                    if (commandBuffer[0] == '1') { tsi.lineInfo[lineCounter].userId=2004;

                       
                        strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.32", 16);
                        tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0';
                        tsi.lineInfo[lineCounter].userId=2004;
                        tsi.lineInfo[lineCounter].status = TRUE;
                        
                    }  else if (commandBuffer[0] == '0') {
               
                        strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.32", 16);
                        tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0';
                         tsi.lineInfo[lineCounter].userId=2004;
                        tsi.lineInfo[lineCounter].status = FALSE;
                        
                    }
                    if (LIBSSH2_ERROR_EAGAIN == lnReturnCode) {
                        waitsocket(sock, tsi.session);
                    }
                    lineCounter++;
                    memset(commandBuffer, 0, sizeof (commandBuffer));
                    libssh2_channel_free(channel);
                    channel = NULL;
                    
                     while (((channel = libssh2_channel_open_session(tsi.session)) == NULL) &&
                            (libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN)) {

                        waitsocket(sock, tsi.session);
                    }

                    if (channel == NULL) {
                        g_cSystemLogger.LogMessage("(%s:%s(:%d))ssh channel opening fail",LOG_LOCATION);
                        // goto shutdown;
                    }

                    sprintf(commandBuffer, "%s  %s%s%s%d%s%s%s", "/bin/netstat -n|/bin/grep -c", "\"", "192.168.30.32", ":", 2005, ".*", "ESTABLISHED", "\"");

                    g_cSystemLogger.LogMessage("(%s:%s(:%d))::command for netstat %s\n", LOG_LOCATION, commandBuffer);
                    while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) {
                        waitsocket(sock, tsi.session);
                    }
                    lnReturnCode;
                    lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer));

                    if (commandBuffer[0] == '1') {
                       
                        strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.32", 16);
                        tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0';
                         tsi.lineInfo[lineCounter].userId=2005;
                        tsi.lineInfo[lineCounter].status = TRUE;
                        
                    }  else if (commandBuffer[0] == '0') {
               
                        strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.32", 16);
                        tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0';
                        tsi.lineInfo[lineCounter].userId=2005;
                        tsi.lineInfo[lineCounter].status = FALSE;
                        
                    }
                    if (LIBSSH2_ERROR_EAGAIN == lnReturnCode) {
                        waitsocket(sock, tsi.session);
                    }
                    lineCounter++;
                    memset(commandBuffer, 0, sizeof (commandBuffer));
                    libssh2_channel_free(channel);
                    channel = NULL;
                    singleInstance->serverObject.size()
                       while (((channel = libssh2_channel_open_session(tsi.session)) == NULL) &&
                            (libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN)) {

                        waitsocket(sock, tsi.session);
                    }

                    if (channel == NULL) {
                        g_cSystemLogger.LogMessage("(%s:%s(:%d))ssh channel opening fail",LOG_LOCATION);
                        // goto shutdown;
                    }

                    sprintf(commandBuffer, "%s  %s%s%s%d%s%s%s", "/bin/netstat -n|/bin/grep -c", "\"", "192.168.30.32", ":", 5432, ".*", "ESTABLISHED", "\"");

                    g_cSystemLogger.LogMessage("(%s:%s(:%d))::command for netstat %s\n", LOG_LOCATION, commandBuffer);
                    while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) {
                        waitsocket(sock, tsi.session);
                    }
                    lnReturnCode;
                    lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer));

                    if (commandBuffer[0] == '2') {
                       
                        strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.32", 16);
                        tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0';
                        tsi.lineInfo[lineCounter].userId=5432;
                        tsi.lineInfo[lineCounter].status = TRUE;
                        
                    }  else if (commandBuffer[0] == '0') {
               
                        strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.32", 16);
                        tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0';
                         tsi.lineInfo[lineCounter].userId=5432;
                        tsi.lineInfo[lineCounter].status = FALSE;
                        
                    }
                    if (LIBSSH2_ERROR_EAGAIN == lnReturnCode) {
                        waitsocket(sock, tsi.session);
                    }
                    lineCounter++;
                    memset(commandBuffer, 0, sizeof (commandBuffer));
                    libssh2_channel_free(channel);
                    channel = NULL;
                    
                    while (((channel = libssh2_channel_open_session(tsi.session)) == NULL) &&
                            (libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN)) {

                        waitsocket(sock, tsi.session);
                    }

                    if (channel == NULL) {
                        g_cSystemLogger.LogMessage("(%s:%s(:%d))ssh channel opening fail",LOG_LOCATION);
                        // goto shutdown;
                    }

                    sprintf(commandBuffer, "%s  %s%s%s%d%s%s%s", "/bin/netstat -n|/bin/grep -c", "\"", "192.168.30.231", ":", 2004, ".*", "ESTABLISHED", "\"");
singleInstance->serverObject.size()
                    g_cSystemLogger.LogMessage("(%s:%s(:%d))::command for netstat %s\n", LOG_LOCATION, commandBuffer);
                    while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) {
                        waitsocket(sock, tsi.session);
                    }
                    lnReturnCode;
                    lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer));

                    if (commandBuffer[0] == '1') {
                       
                        strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.231", 16);
                        tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0';
                         tsi.lineInfo[lineCounter].userId=2004;
                        tsi.lineInfo[lineCounter].status = TRUE;
                        
                    }  else if (commandBuffer[0] == '0') {
               
                        strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.231", 16);
                        tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0';
                         tsi.lineInfo[lineCounter].userId=2004;
                        tsi.lineInfo[lineCounter].status = FALSE;
                        
                    }
                    if (LIBSSH2_ERROR_EAGAIN == lnReturnCode) {
                        waitsocket(sock, tsi.session);
                    }
                    lineCounter++;
                    memset(commandBuffer, 0, sizeof (commandBuffer));
                    libssh2_channel_free(channel);
                    channel = NULL;
                    
                    while (((channel = libssh2_channel_open_session(tsi.session)) == NULL) &&
                            (libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN)) {

                        waitsocket(sock, tsi.session);
                    }

                    if (channel == NULL) {
                        g_cSystemLogger.LogMessage("(%s:%s(:%d))ssh channel opening fail",LOG_LOCATION);
                        // goto shutdown;
                    }

                    sprintf(commandBuffer, "%s  %s%s%s%d%s%s%s", "/bin/netstat -n|/bin/grep -c", "\"", "192.168.30.231", ":", 2005, ".*", "ESTABLISHED", "\"");

                    g_cSystemLogger.LogMessage("(%s:%s(:%d))::command for netstat %s\n", LOG_LOCATION, commandBuffer);
                    while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) {
                        waitsocket(sock, tsi.session);
                    }
                     lnReturnCode;
                    lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer));

                    if (commandBuffer[0] == '1') {
                       
                        strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.231", 16);
                        tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0';
                         tsi.lineInfo[lineCounter].userId=2005;
                        tsi.lineInfo[lineCounter].status = TRUE;
                        
                    }  else if (commandBuffer[0] == '0') {
               
                        strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.231", 16);
                        tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0';
                         tsi.lineInfo[lineCounter].userId=2005;
                        tsi.lineInfo[lineCounter].status = FALSE;
                        
                    }
                    if (LIBSSH2_ERROR_EAGAIN == lnReturnCode) {
                        waitsocket(sock, tsi.session);
                    }
                    lineCounter++;
                    memset(commandBuffer, 0, sizeof (commandBuffer));
                    libssh2_channel_free(channel);
                    channel = NULL;
                    
                     while (((channel = libssh2_channel_open_session(tsi.session)) == NULL) &&
                            (libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN)) {

                        waitsocket(sock, tsi.session);
                    }

                    if (channel == NULL) {
                        g_cSystemLogger.LogMessage("(%s:%s(:%d))ssh channel opening fail",LOG_LOCATION);
                        // goto shutdown;
                    }

                    sprintf(commandBuffer, "%s  %s%s%s%d%s%s%s", "/bin/netstat -n|/bin/grep -c", "\"", "192.168.30.231", ":", 5432, ".*", "ESTABLISHED", "\"");

                    g_cSystemLogger.LogMessage("(%s:%s(:%d))::command for netstat %s\n", LOG_LOCATION, commandBuffer);
                    while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) {
                        waitsocket(sock, tsi.session);
                    }
                     lnReturnCode;
                    lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer));
		    //std::cout<<"lnReturnCode"<<lnReturnCode<<endl;
                    if (commandBuffer[0] == '2') {
                       
                        strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.231", 16);
                        tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0';
                         tsi.lineInfo[lineCounter].userId=5432;
                        tsi.lineInfo[lineCounter].status = TRUE;
                        
                    }  else if (commandBuffer[0] == '0') {
               
                        strncpy(tsi.lineInfo[lineCounter].ipv4adresss, "192.168.30.231", 16);
                        tsi.lineInfo[lineCounter].ipv4adresss[16] = '\0';
                         tsi.lineInfo[lineCounter].userId=5432;
                        tsi.lineInfo[lineCounter].status = FALSE;
                        
                    }
                    if (LIBSSH2_ERROR_EAGAIN == lnReturnCode) {
                        waitsocket(sock, tsi.session);
                    }
                    lineCounter++;
                    memset(commandBuffer, 0, sizeof (commandBuffer));
                    libssh2_channel_free(channel);
                    channel = NULL;
                
                globalCounter = lineCounter;

            }*/
               
            for (lProcessListIndex = 1; lProcessListIndex < tsi.noOfProcess; lProcessListIndex++) {
                g_cSystemLogger.LogMessage("(%s:%s(:%d))::process name\n", LOG_LOCATION);
                while ((channel = libssh2_channel_open_session(tsi.session)) == NULL &&
                        libssh2_session_last_error(tsi.session, NULL, NULL, 0) == LIBSSH2_ERROR_EAGAIN) {
                    waitsocket(sock, tsi.session);
                }
                if (channel == NULL) {
                    fprintf(stderr, "failure establishing ssh");
                    //goto shutdown;
                }
                sprintf(commandBuffer, "%s %s", "pidof -s", tsi.processes[lProcessListIndex].name);
                g_cSystemLogger.LogMessage("(%s:%s(:%d)):: Pid of process command %s\n", LOG_LOCATION, commandBuffer);

                while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) {
                    waitsocket(sock, tsi.session);
                    
                }
                size_t lnReturnCode;
                lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer));
                g_cSystemLogger.LogMessage("(%s:%s(:%d))::commandBuffer %s lnreturncode %d\n", LOG_LOCATION,commandBuffer,lnReturnCode);
                if (lnReturnCode == 0) {
                    tsi.processes[lProcessListIndex].process_on_off = FALSE;

                } else {
                    tsi.processes[lProcessListIndex].process_on_off = TRUE;

                    if (lnReturnCode != LIBSSH2_ERROR_EAGAIN) {
                        g_cSystemLogger.LogMessage("(%s:%s(:%d))::libbssh2 %d\n", LOG_LOCATION, lnReturnCode);
                    }
                }
                if (LIBSSH2_ERROR_EAGAIN == lnReturnCode) {
                    waitsocket(sock, tsi.session);
                }
                g_cSystemLogger.LogMessage("(%s:%s(:%d))::tsi.processes[i].process_on_off %d \n", LOG_LOCATION, tsi.processes[lProcessListIndex].process_on_off);
                memset(commandBuffer, 0, sizeof (commandBuffer));
                if (channel) {
                    libssh2_channel_free(channel);
                    channel = NULL;
                }
            }
            char percnt[5] = "\"%\"";
            for (lSpaceList = 1; lSpaceList < tsi.noOfSpace; lSpaceList++) {

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

                if (channel == NULL) {
                    g_cSystemLogger.LogMessage("failure establishing ssh");
                }
                sprintf(commandBuffer, "%s %s  %s %s %s", "df -hk | grep", tsi.space[lSpaceList].name, "| awk '{print $(NF-1)}' | awk -F", percnt, "'{print $1}'");
                g_cSystemLogger.LogMessage("(%s:%s(:%d))::command for space%s\n", LOG_LOCATION, commandBuffer);
                while ((rc = libssh2_channel_exec(channel, commandBuffer)) == LIBSSH2_ERROR_EAGAIN) {
                    waitsocket(sock, tsi.session);

                }
                int lnReturnCode;
                lnReturnCode = libssh2_channel_read(channel, commandBuffer, sizeof (commandBuffer));

                if (lnReturnCode >= 0) {
                    if (atoi(commandBuffer) > 90) {
                        tsi.space[lSpaceList].space_full = TRUE;
                    } else {
                        tsi.space[lSpaceList].space_full = FALSE;
                    }
                }


                if (LIBSSH2_ERROR_EAGAIN == lnReturnCode) {
                    waitsocket(sock, tsi.session);
                }
                memset(commandBuffer, 0, sizeof (commandBuffer));
                if (channel) {
                    libssh2_channel_free(channel);
                    channel = NULL;
                }
            }
            CcopyStructure::copyData(tsi, tsi.noOfProcess, tsi.noOfSpace, tsi.noOfLine);

        }
       // whileserverCount++;
        //std::cout << "while count" << whileserverCount << endl;
        ///if(!(singleInstance->is_connected(singleInstance->socketId)))
		//singleInstance->makeSocketConnection();
	
        if (breakFlag) {
            break;
        }
    }
     for (int i=0;i<(singleInstance->serverObject.size()/3);i++) {
        tagServerInfo tsi;
        tsi = (singleInstance->serverObject[i]);

        libssh2_session_disconnect(tsi.session, "Shutting down,thank you");
        libssh2_session_free(tsi.session);
        close(tsi.m_socketId);
        libssh2_exit();
    }
    return 1;
}
Пример #18
0
int 
main(int argc, char *argv[])
{
	int		sock      , i, auth_pw = 0, port = 22;
	struct sockaddr_in6 sin;

	const char     *fingerprint;
	char           *userauthlist;
	LIBSSH2_SESSION *session;
	int		rc;
	LIBSSH2_SFTP   *sftp_session;
	LIBSSH2_SFTP_HANDLE *sftp_handle;
	struct hostent *server;

	if (!strcmp(argv[1], "--help"))
		usage();

	if (argc > 1) {
		inet_pton(AF_INET6,argv[1],sin.sin6_addr.s6_addr);
	}

	if (argc > 2) {
		port = atoi(argv[2]);
	}
	if (argc > 3) {
		username = argv[3];
	}
	if (argc > 4) {
		password = argv[4];
	}
	if (argc > 5) {
		sftppath = argv[5];
	}
	if (argc > 6) {
		localpath = argv[6];
	}

	sock = socket(AF_INET6, SOCK_STREAM, 0);

	server = gethostbyname2(argv[1],AF_INET6);
	if (server == NULL) {
		fprintf(stderr, "ERROR, no such host\n");
		exit(0);
	}

	memset((char *) &sin, 0, sizeof(sin));
	sin.sin6_flowinfo = 0;
	sin.sin6_family = AF_INET6;
	memmove((char *) &sin.sin6_addr.s6_addr, (char *) server->h_addr, server->h_length);
	sin.sin6_port = htons(port);

	if (connect(sock, (struct sockaddr *)(&sin),
			sizeof(struct sockaddr_in6)) != 0) {
		fprintf(stderr, "failed to connect!\n");
		return -1;
	}
	session = libssh2_session_init();
	if (!session)
		return -1;

	libssh2_session_set_blocking(session, 1);

	rc = libssh2_session_startup(session, sock);
	if (rc) {
		fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
		return -1;
	}
	fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_MD5);
	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 we got an 4. argument we set this option if supported */
	if (argc > 5) {
		if ((auth_pw & 1) && !strcasecmp(argv[5], "-p")) {
			auth_pw = 1;
		}
		if ((auth_pw & 2) && !strcasecmp(argv[5], "-i")) {
			auth_pw = 2;
		}
		if ((auth_pw & 4) && !strcasecmp(argv[5], "-k")) {
			auth_pw = 4;
		}
	}
	if (auth_pw & 1) {
		if (libssh2_userauth_password(session, username, password)) {
			return 1;
			goto shutdown;
		}
	} else if (auth_pw & 2) {
		if (libssh2_userauth_keyboard_interactive(session, username, &kbd_callback)) {
			return 1;
			goto shutdown;
		}
	} else if (auth_pw & 4) {
		if (libssh2_userauth_publickey_fromfile(session, username, keyfile1, keyfile2, password)) {
			printf("\tAuthentication by public key failed!\n");
			return 1;
			goto shutdown;
		}
	} else {
		printf("No supported authentication methods found!\n");
		return 1;
		goto shutdown;
	}

	sftp_session = libssh2_sftp_init(session);

	if (!sftp_session) {
		fprintf(stderr, "Unable to init SFTP session\n");
		return 1;
		goto shutdown;
	}
	sftp_handle =
		libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_READ, 0);

	if (!sftp_handle) {
		return 2;
		goto shutdown;
	}
	FILE           *fp = fopen(localpath, "w");
	if (fp) {
		char		mem       [1024];
		do {
			rc = libssh2_sftp_read(sftp_handle, mem, sizeof(mem));
			if (rc > 0) {
				fwrite(mem, rc, 1, fp);
			} else {
				break;
			}
		} while (1);
		fclose(fp);
	}
	libssh2_sftp_close(sftp_handle);
	libssh2_sftp_shutdown(sftp_session);

shutdown:

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

#ifdef WIN32
	closesocket(sock);
#else
	close(sock);
#endif
	return 0;
}
Пример #19
0
int main(int argc, char *argv[])
{
    unsigned long hostaddr;
    int sock, i, auth_pw = 0;
    struct sockaddr_in sin;
    const char *fingerprint;
    char *userauthlist;
    LIBSSH2_SESSION *session;
    int rc;
    LIBSSH2_SFTP *sftp_session;
    LIBSSH2_SFTP_HANDLE *sftp_handle;

#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) {
        sftppath = argv[4];
    }

    rc = libssh2_init (0);
    if (rc != 0) {
        fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);
        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 blocking */
    libssh2_session_set_blocking(session, 1);

    /* ... start it up. This will trade welcome banners, exchange keys,
     * and setup crypto, compression, and MAC layers
     */
    rc = libssh2_session_startup(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");

    /* check what authentication methods are available */
    userauthlist = libssh2_userauth_list(session, username, strlen(username));
    printf("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 > 5) {
        if ((auth_pw & 1) && !strcasecmp(argv[5], "-p")) {
            auth_pw = 1;
        }
        if ((auth_pw & 2) && !strcasecmp(argv[5], "-i")) {
            auth_pw = 2;
        }
        if ((auth_pw & 4) && !strcasecmp(argv[5], "-k")) {
            auth_pw = 4;
        }
    }

    if (auth_pw & 1) {
        /* We could authenticate via password */
        if (libssh2_userauth_password(session, username, password)) {
            fprintf(stderr, "Authentication by password failed.\n");
            goto shutdown;
        }
    } else if (auth_pw & 2) {
        /* Or via keyboard-interactive */
        if (libssh2_userauth_keyboard_interactive(session, username, &kbd_callback) ) {
            printf("\tAuthentication by keyboard-interactive failed!\n");
            goto shutdown;
        } else {
            printf("\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)) {
            printf("\tAuthentication by public key failed!\n");
            goto shutdown;
        } else {
            printf("\tAuthentication by public key succeeded.\n");
        }
    } else {
        printf("No supported authentication methods found!\n");
        goto shutdown;
    }

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

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

    fprintf(stderr, "libssh2_sftp_open()!\n");
    /* Request a file via SFTP */
    sftp_handle =
        libssh2_sftp_open(sftp_session, sftppath, LIBSSH2_FXF_READ, 0);

    if (!sftp_handle) {
        fprintf(stderr, "Unable to open file with SFTP: %ld\n",
                libssh2_sftp_last_error(sftp_session));
        goto shutdown;
    }
    fprintf(stderr, "libssh2_sftp_open() is done, now receive data!\n");
    do {
        char mem[1024];

        /* loop until we fail */
        fprintf(stderr, "libssh2_sftp_read()!\n");
        rc = libssh2_sftp_read(sftp_handle, mem, sizeof(mem));
        if (rc > 0) {
            write(1, mem, rc);
        } else {
            break;
        }
    } while (1);

    libssh2_sftp_close(sftp_handle);
    libssh2_sftp_shutdown(sftp_session);

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;
}
Пример #20
0
int Parser::initSession()
{
    QString host_ip=this->sharedHost;
    QString user_name=this->sharedUser;
    QString pass_word=this->sharedPass;

    //---------- connection --------------
    int libssh2_error = libssh2_init(0);
    if(libssh2_error)
    {
        qDebug("libssh2_init() error: %d", libssh2_error);
        return -2;
    }
    socket_=new QTcpSocket(this);
    socket_->connectToHost(host_ip, 22);
    if(!socket_->waitForConnected())
    {
        qDebug("Error connecting to host %s", host_ip.toLocal8Bit().constData());
        return -1;
    }

    session_ = libssh2_session_init();
    if(!session_)
    {
        qDebug("libssh2_session_init() failed");
        return -2;
    }

    libssh2_error = libssh2_session_startup(session_, socket_->socketDescriptor());
    if(libssh2_error)
    {
        qDebug("libssh2_session_startup() error: %d", libssh2_error);
        return -3;
    }

    {
    /* 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
     */
    }

//    qDebug("Password authentication: [%s] [%s]", user_name.toLocal8Bit().constData(), pass_word.toLocal8Bit().constData());
    libssh2_userauth_list(session_, user_name.toLocal8Bit().constData(), user_name.toLocal8Bit().length());
    if(libssh2_userauth_password(
        session_,
        user_name.toLocal8Bit().constData(),
        pass_word.toLocal8Bit().constData()
    ))
    {
        qDebug("Password authentication failed");

        socket_->disconnectFromHost();
        libssh2_session_disconnect(session_, "Client disconnecting for error");
        libssh2_session_free(session_);
        libssh2_exit();

        return -4;
    }
    return 1;
}
Пример #21
0
/**
 * Authenticates the user associated with the given session over SSH. All
 * required credentials must already be present within the user object
 * associated with the given session.
 *
 * @param session
 *     The session associated with the user to be authenticated.
 *
 * @return
 *     Zero if authentication succeeds, or non-zero if authentication has
 *     failed.
 */
static int guac_common_ssh_authenticate(guac_common_ssh_session* common_session) {

    guac_client* client = common_session->client;
    guac_common_ssh_user* user = common_session->user;
    LIBSSH2_SESSION* session = common_session->session;

    /* Get user credentials */
    char* username = user->username;
    char* password = user->password;
    guac_common_ssh_key* key = user->private_key;

    /* Get list of supported authentication methods */
    char* user_authlist = libssh2_userauth_list(session, username,
            strlen(username));
    guac_client_log(client, GUAC_LOG_DEBUG,
            "Supported authentication methods: %s", user_authlist);

    /* Authenticate with private key, if provided */
    if (key != NULL) {

        /* Check if public key auth is supported on the server */
        if (strstr(user_authlist, "publickey") == NULL) {
            guac_client_abort(client, GUAC_PROTOCOL_STATUS_CLIENT_UNAUTHORIZED,
                               "Public key authentication not supported");
            return 1;
        }

        /* Attempt public key auth */
        if (libssh2_userauth_publickey(session, username,
                    (unsigned char*) key->public_key, key->public_key_length,
                    guac_common_ssh_sign_callback, (void**) key)) {

            /* Abort on failure */
            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 1;

        }

        /* Private key authentication succeeded */
        return 0;

    }

    /* Authenticate with password */
    if (strstr(user_authlist, "password") != NULL) {
        guac_client_log(client, GUAC_LOG_DEBUG,
                "Using password authentication method");
        return libssh2_userauth_password(session, username, password);
    }

    /* Authenticate with password via keyboard-interactive auth */
    if (strstr(user_authlist, "keyboard-interactive") != NULL) {
        guac_client_log(client, GUAC_LOG_DEBUG,
                "Using keyboard-interactive authentication method");
        return libssh2_userauth_keyboard_interactive(session, username,
                &guac_common_ssh_kbd_callback);
    }

    /* No known authentication types available */
    guac_client_abort(client, GUAC_PROTOCOL_STATUS_CLIENT_BAD_TYPE,
            "No known authentication methods");
    return 1;

}
Пример #22
0
static int authenticate(BDRVSSHState *s, const char *user, Error **errp)
{
    int r, ret;
    const char *userauthlist;
    LIBSSH2_AGENT *agent = NULL;
    struct libssh2_agent_publickey *identity;
    struct libssh2_agent_publickey *prev_identity = NULL;

    userauthlist = libssh2_userauth_list(s->session, user, strlen(user));
    if (strstr(userauthlist, "publickey") == NULL) {
        ret = -EPERM;
        error_setg(errp,
                "remote server does not support \"publickey\" authentication");
        goto out;
    }

    /* Connect to ssh-agent and try each identity in turn. */
    agent = libssh2_agent_init(s->session);
    if (!agent) {
        ret = -EINVAL;
        session_error_setg(errp, s, "failed to initialize ssh-agent support");
        goto out;
    }
    if (libssh2_agent_connect(agent)) {
        ret = -ECONNREFUSED;
        session_error_setg(errp, s, "failed to connect to ssh-agent");
        goto out;
    }
    if (libssh2_agent_list_identities(agent)) {
        ret = -EINVAL;
        session_error_setg(errp, s,
                           "failed requesting identities from ssh-agent");
        goto out;
    }

    for(;;) {
        r = libssh2_agent_get_identity(agent, &identity, prev_identity);
        if (r == 1) {           /* end of list */
            break;
        }
        if (r < 0) {
            ret = -EINVAL;
            session_error_setg(errp, s,
                               "failed to obtain identity from ssh-agent");
            goto out;
        }
        r = libssh2_agent_userauth(agent, user, identity);
        if (r == 0) {
            /* Authenticated! */
            ret = 0;
            goto out;
        }
        /* Failed to authenticate with this identity, try the next one. */
        prev_identity = identity;
    }

    ret = -EPERM;
    error_setg(errp, "failed to authenticate using publickey authentication "
               "and the identities held by your ssh-agent");

 out:
    if (agent != NULL) {
        /* Note: libssh2 implementation implicitly calls
         * libssh2_agent_disconnect if necessary.
         */
        libssh2_agent_free(agent);
    }

    return ret;
}
Пример #23
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;
}
Пример #24
0
int main(int argc, char *argv[])
{
    unsigned long hostaddr;
    int sock, i, auth_pw = 0;
    struct sockaddr_in sin;
    const char *fingerprint;
    char *userauthlist;
    LIBSSH2_SESSION *session;
    LIBSSH2_CHANNEL *channel;
#ifdef WIN32
    WSADATA wsadata;

    WSAStartup(MAKEWORD(2,0), &wsadata);
#endif
    const char *pubkeyfile="etc/user.pub";
    const char *privkeyfile="etc/user";
    const char *username="******";
    const char *password="******";
    int ec = 1;

    (void)argc;
    (void)argv;

    if (getenv ("USER"))
      username = getenv ("USER");

    if (getenv ("PRIVKEY"))
      privkeyfile = getenv ("PRIVKEY");

    if (getenv ("PRIVKEY"))
      pubkeyfile = getenv ("PUBKEY");

    hostaddr = htonl(0x7F000001);

    sock = socket(AF_INET, SOCK_STREAM, 0);
#ifndef WIN32
    fcntl(sock, F_SETFL, 0);
#endif
    sin.sin_family = AF_INET;
    sin.sin_port = htons(4711);
    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_startup(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_MD5);
    printf("Fingerprint: ");
    for(i = 0; i < 16; i++) {
        printf("%02X ", (unsigned char)fingerprint[i]);
    }
    printf("\n");

    /* check what authentication methods are available */
    userauthlist = libssh2_userauth_list(session, username, strlen(username));
    printf("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 (auth_pw & 4) {
        /* Authenticate by public key */
        if (libssh2_userauth_publickey_fromfile(session, username, pubkeyfile, privkeyfile, password)) {
            printf("\tAuthentication by public key failed!\n");
            goto shutdown;
        } else {
            printf("\tAuthentication by public key succeeded.\n");
        }
    } else {
        printf("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;
    }

    ec = 0;

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

  shutdown:

    libssh2_session_disconnect(session, "Normal Shutdown");
    libssh2_session_free(session);

#ifdef WIN32
    Sleep(1000);
    closesocket(sock);
#else
    sleep(1);
    close(sock);
#endif

    return ec;
}
Пример #25
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;
}
Пример #26
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;
}
Пример #27
0
/* example ssh.run["ls /"] */
static int	ssh_run(DC_ITEM *item, AGENT_RESULT *result, const char *encoding)
{
	const char	*__function_name = "ssh_run";
	zbx_sock_t	s;
	LIBSSH2_SESSION	*session;
	LIBSSH2_CHANNEL	*channel;
	int		auth_pw = 0, rc, ret = NOTSUPPORTED,
			exitcode, bytecount = 0;
	char		buffer[MAX_BUFFER_LEN], buf[16], *userauthlist,
			*publickey = NULL, *privatekey = NULL, *ssherr;
	size_t		sz;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);

	if (FAIL == zbx_tcp_connect(&s, CONFIG_SOURCE_IP, item->interface.addr, item->interface.port, 0))
	{
		SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Cannot connect to SSH server: %s",
				zbx_tcp_strerror()));
		goto close;
	}

	/* initializes an SSH session object */
	if (NULL == (session = libssh2_session_init()))
	{
		SET_MSG_RESULT(result, zbx_strdup(NULL, "Cannot initialize SSH session"));
		goto tcp_close;
	}

	/* set blocking mode on session */
	libssh2_session_set_blocking(session, 1);

	/* Create a session instance and start it up. This will trade welcome */
	/* banners, exchange keys, and setup crypto, compression, and MAC layers */
	if (0 != libssh2_session_startup(session, s.socket))
	{
		libssh2_session_last_error(session, &ssherr, NULL, 0);
		SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Cannot establish SSH session: %s", ssherr));
		goto session_free;
	}

	/* check what authentication methods are available */
	if (NULL != (userauthlist = libssh2_userauth_list(session, item->username, strlen(item->username))))
	{
		if (NULL != strstr(userauthlist, "password"))
			auth_pw |= 1;
		if (NULL != strstr(userauthlist, "keyboard-interactive"))
			auth_pw |= 2;
		if (NULL != strstr(userauthlist, "publickey"))
			auth_pw |= 4;
	}
	else
	{
		libssh2_session_last_error(session, &ssherr, NULL, 0);
		SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Cannot obtain authentication methods: %s", ssherr));
		goto session_close;
	}

	zabbix_log(LOG_LEVEL_DEBUG, "%s() supported authentication methods:'%s'", __function_name, userauthlist);

	switch (item->authtype)
	{
		case ITEM_AUTHTYPE_PASSWORD:
			if (auth_pw & 1)
			{
				/* we could authenticate via password */
				if (0 != libssh2_userauth_password(session, item->username, item->password))
				{
					libssh2_session_last_error(session, &ssherr, NULL, 0);
					SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Password authentication failed: %s",
							ssherr));
					goto session_close;
				}
				else
					zabbix_log(LOG_LEVEL_DEBUG, "%s() password authentication succeeded",
							__function_name);
			}
			else if (auth_pw & 2)
			{
				/* or via keyboard-interactive */
				password = item->password;
				if (0 != libssh2_userauth_keyboard_interactive(session, item->username, &kbd_callback))
				{
					libssh2_session_last_error(session, &ssherr, NULL, 0);
					SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Keyboard-interactive authentication"
							" failed: %s", ssherr));
					goto session_close;
				}
				else
					zabbix_log(LOG_LEVEL_DEBUG, "%s() keyboard-interactive authentication succeeded",
							__function_name);
			}
			else
			{
				SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Unsupported authentication method."
						" Supported methods: %s", userauthlist));
				goto session_close;
			}
			break;
		case ITEM_AUTHTYPE_PUBLICKEY:
			if (auth_pw & 4)
			{
				if (NULL == CONFIG_SSH_KEY_LOCATION)
				{
					SET_MSG_RESULT(result, zbx_strdup(NULL, "Authentication by public key failed."
							" SSHKeyLocation option is not set"));
					goto session_close;
				}

				/* or by public key */
				publickey = zbx_dsprintf(publickey, "%s/%s", CONFIG_SSH_KEY_LOCATION, item->publickey);
				privatekey = zbx_dsprintf(privatekey, "%s/%s", CONFIG_SSH_KEY_LOCATION,
						item->privatekey);

				if (SUCCEED != zbx_is_regular_file(publickey))
				{
					SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Cannot access public key file %s",
							publickey));
					goto session_close;
				}

				if (SUCCEED != zbx_is_regular_file(privatekey))
				{
					SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Cannot access private key file %s",
							privatekey));
					goto session_close;
				}

				rc = libssh2_userauth_publickey_fromfile(session, item->username, publickey,
						privatekey, item->password);
				zbx_free(publickey);
				zbx_free(privatekey);

				if (0 != rc)
				{
					libssh2_session_last_error(session, &ssherr, NULL, 0);
					SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Public key authentication failed:"
							" %s", ssherr));
					goto session_close;
				}
				else
					zabbix_log(LOG_LEVEL_DEBUG, "%s() authentication by public key succeeded",
							__function_name);
			}
			else
			{
				SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Unsupported authentication method."
						" Supported methods: %s", userauthlist));
				goto session_close;
			}
			break;
	}

	/* exec non-blocking on the remove host */
	while (NULL == (channel = libssh2_channel_open_session(session)))
	{
		switch (libssh2_session_last_error(session, NULL, NULL, 0))
		{
			/* marked for non-blocking I/O but the call would block. */
			case LIBSSH2_ERROR_EAGAIN:
				waitsocket(s.socket, session);
				continue;
			default:
				SET_MSG_RESULT(result, zbx_strdup(NULL, "Cannot establish generic session channel"));
				goto session_close;
		}
	}

	dos2unix(item->params);	/* CR+LF (Windows) => LF (Unix) */
	/* request a shell on a channel and execute command */
	while (0 != (rc = libssh2_channel_exec(channel, item->params)))
	{
		switch (rc)
		{
			case LIBSSH2_ERROR_EAGAIN:
				waitsocket(s.socket, session);
				continue;
			default:
				SET_MSG_RESULT(result, zbx_strdup(NULL, "Cannot request a shell"));
				goto channel_close;
		}
	}

	for (;;)
	{
		/* loop until we block */
		do
		{
			if (0 < (rc = libssh2_channel_read(channel, buf, sizeof(buf))))
			{
				sz = (size_t)rc;
				if (sz > MAX_BUFFER_LEN - (bytecount + 1))
					sz = MAX_BUFFER_LEN - (bytecount + 1);
				if (0 == sz)
					continue;

				memcpy(buffer + bytecount, buf, sz);
				bytecount += sz;
			}
		}
		while (rc > 0);

		/* this is due to blocking that would occur otherwise so we loop on
		 * this condition
		 */
		if (LIBSSH2_ERROR_EAGAIN == rc)
			waitsocket(s.socket, session);
		else if (rc < 0)
		{
			SET_MSG_RESULT(result, zbx_strdup(NULL, "Cannot read data from SSH server"));
			goto channel_close;
		}
		else
			break;
	}

	buffer[bytecount] = '\0';
	SET_STR_RESULT(result, convert_to_utf8(buffer, bytecount, encoding));

	ret = SYSINFO_RET_OK;

channel_close:
	/* close an active data channel */
	exitcode = 127;
	while (0 != (rc = libssh2_channel_close(channel)))
	{
		switch (rc)
		{
			case LIBSSH2_ERROR_EAGAIN:
				waitsocket(s.socket, session);
				continue;
			default:
				libssh2_session_last_error(session, &ssherr, NULL, 0);
				zabbix_log(LOG_LEVEL_WARNING, "%s() cannot close generic session channel: %s",
						__function_name, ssherr);
				break;
		}
	}

	if (0 == rc)
		exitcode = libssh2_channel_get_exit_status(channel);
	zabbix_log(LOG_LEVEL_DEBUG, "%s() exitcode: %d bytecount: %d",
			__function_name, exitcode, bytecount);

	libssh2_channel_free(channel);
	channel = NULL;

session_close:
	libssh2_session_disconnect(session, "Normal Shutdown");

session_free:
	libssh2_session_free(session);

tcp_close:
	zbx_tcp_close(&s);

close:
	zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));

	return ret;
}
Пример #28
0
int main(int argc, char *argv[])
{
    int rc, i, auth = AUTH_NONE;
    struct sockaddr_in sin;
    const char *fingerprint;
    char *userauthlist;
    LIBSSH2_SESSION *session;
    LIBSSH2_CHANNEL *channel = NULL;
    char buf[1048576]; /* avoid any buffer reallocation for simplicity */
    ssize_t len;

#ifdef WIN32
    SOCKET sock = INVALID_SOCKET;
    WSADATA wsadata;
    int err;

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

    if (argc > 1)
        server_ip = argv[1];
    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;
    }

    /* Connect to SSH server */
    sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
#ifdef WIN32
    if (sock == INVALID_SOCKET) {
        fprintf(stderr, "failed to open socket!\n");
        return -1;
    }
#else
    if (sock == -1) {
        perror("socket");
        return -1;
    }
#endif

    sin.sin_family = AF_INET;
    if (INADDR_NONE == (sin.sin_addr.s_addr = inet_addr(server_ip))) {
        fprintf(stderr, "inet_addr: Invalid IP address \"%s\"\n", server_ip);
        return -1;
    }
    sin.sin_port = htons(830);
    if (connect(sock, (struct sockaddr*)(&sin),
                sizeof(struct sockaddr_in)) != 0) {
        fprintf(stderr, "Failed to connect to %s!\n", inet_ntoa(sin.sin_addr));
        return -1;
    }

    /* Create a session instance */
    session = libssh2_session_init();
    if(!session) {
        fprintf(stderr, "Could not initialize SSH session!\n");
        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, "Error when starting up 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");

    /* 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"))
        auth |= AUTH_PASSWORD;
    if (strstr(userauthlist, "publickey"))
        auth |= AUTH_PUBLICKEY;

    /* check for options */
    if(argc > 4) {
        if ((auth & AUTH_PASSWORD) && !strcasecmp(argv[4], "-p"))
            auth = AUTH_PASSWORD;
        if ((auth & AUTH_PUBLICKEY) && !strcasecmp(argv[4], "-k"))
            auth = AUTH_PUBLICKEY;
    }

    if (auth & AUTH_PASSWORD) {
        if (libssh2_userauth_password(session, username, password)) {
            fprintf(stderr, "Authentication by password failed.\n");
            goto shutdown;
        }
    } else if (auth & AUTH_PUBLICKEY) {
        if (libssh2_userauth_publickey_fromfile(session, username, keyfile1,
                                                keyfile2, password)) {
            fprintf(stderr, "Authentication by public key failed!\n");
            goto shutdown;
        }
        fprintf(stderr, "Authentication by public key succeeded.\n");
    } else {
        fprintf(stderr, "No supported authentication methods found!\n");
        goto shutdown;
    }

    /* open a channel */
    channel = libssh2_channel_open_session(session);
    if (!channel) {
        fprintf(stderr, "Could not open the channel!\n"
                "(Note that this can be a problem at the server!"
                " Please review the server logs.)\n");
        goto shutdown;
    }

    /* execute the subsystem on our channel */
    if (libssh2_channel_subsystem(channel, "netconf")) {
        fprintf(stderr, "Could not execute the \"netconf\" subsystem!\n"
                "(Note that this can be a problem at the server!"
                " Please review the server logs.)\n");
        goto shutdown;
    }

    /* NETCONF: http://tools.ietf.org/html/draft-ietf-netconf-ssh-06 */

    fprintf(stderr, "Sending NETCONF client <hello>\n");
    snprintf(buf, sizeof(buf),
      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
      "<hello>"
      "<capabilities>"
      "<capability>urn:ietf:params:xml:ns:netconf:base:1.0</capability>"
      "</capabilities>"
      "</hello>\n"
      "]]>]]>\n%n", (int *)&len);
    if (-1 == netconf_write(channel, buf, len))
        goto shutdown;

    fprintf(stderr, "Reading NETCONF server <hello>\n");
    len = netconf_read_until(channel, "</hello>", buf, sizeof(buf));
    if (-1 == len)
        goto shutdown;

    fprintf(stderr, "Got %d bytes:\n----------------------\n%s", (int)len, buf);

    fprintf(stderr, "Sending NETCONF <rpc>\n");
    snprintf(buf, sizeof(buf),
      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
      "<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
      "<get-interface-information><terse/></get-interface-information>"
      "</rpc>\n"
      "]]>]]>\n%n", (int *)&len);
    if (-1 == netconf_write(channel, buf, len))
        goto shutdown;

    fprintf(stderr, "Reading NETCONF <rpc-reply>\n");
    len = netconf_read_until(channel, "</rpc-reply>", buf, sizeof(buf));
    if (-1 == len)
        goto shutdown;

    fprintf(stderr, "Got %d bytes:\n----------------------\n%s", (int)len, buf);

shutdown:
    if (channel)
        libssh2_channel_free(channel);
    libssh2_session_disconnect(session, "Client disconnecting normally");
    libssh2_session_free(session);

#ifdef WIN32
    closesocket(sock);
#else
    close(sock);
#endif

    libssh2_exit();

    return 0;
}
Пример #29
-1
QString Parser::sshRequest(QString commandline)
{
    QString host_ip(this->sharedHost);
    QString user_name=this->sharedUser;
    QString pass_word=this->sharedPass;

    //---------- connection --------------
    int libssh2_error = libssh2_init(0);
    if(libssh2_error)
    {
        qDebug("libssh2_init() error: %d", libssh2_error);
        //return -2;
    }

    QTcpSocket socket;
    socket.connectToHost(host_ip, 22);
    if(!socket.waitForConnected())
    {
        qDebug("Error connecting to host %s", host_ip.toLocal8Bit().constData());
        //return -1;
    }

    LIBSSH2_SESSION *session = libssh2_session_init();
    if(!session)
    {
        qDebug("libssh2_session_init() failed");
        //return -2;
    }

    libssh2_error = libssh2_session_startup(session, socket.socketDescriptor());
    if(libssh2_error)
    {
        qDebug("libssh2_session_startup() error: %d", libssh2_error);
        //return -3;
    }

    {
    /* 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
     */
    const char *fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
    }

    libssh2_userauth_list(session, user_name.toLocal8Bit().constData(), user_name.toLocal8Bit().length());
    if(libssh2_userauth_password(
        session,
        user_name.toLocal8Bit().constData(),
        pass_word.toLocal8Bit().constData()
    ))
    {
        qDebug("Password authentication failed");

        socket.disconnectFromHost();
        libssh2_session_disconnect(session, "Client disconnecting for error");
        libssh2_session_free(session);
        libssh2_exit();

        //return -4;
    }

    // command channel
    //------------setup channel ----------------------
    LIBSSH2_CHANNEL *channel = NULL;
    channel = libssh2_channel_open_session(session);
    int rc;
    if ( channel == NULL )
    {
        qDebug()<<"Failed to open a new channel\n";
        socket.disconnectFromHost();
        //return -1;
    }
    libssh2_channel_set_blocking(channel, 1);
    while ((rc=libssh2_channel_exec(channel, commandline.toLocal8Bit().constData()))==LIBSSH2_ERROR_EAGAIN );
    if (rc)
    {
        //return -1;
    }

    //-------read channel-----------
    int read;
    QByteArray byte_array;
    byte_array.resize(4096);
    char* buffer=byte_array.data();
    int buffer_size=byte_array.size();

    QString myOutPut;

    while(true)
    {
        {
            read = libssh2_channel_read(channel, buffer, buffer_size);
            QByteArray debug = QByteArray(buffer, read);

            //qDebug()<<"STDOUT: "<<debug.constData();
            myOutPut = debug.constData();
            qDebug() << myOutPut;
            if(LIBSSH2_ERROR_EAGAIN == read)
            {
                qDebug("LIBSSH2_ERROR_EAGAIN");
                break;
            }
            else if(read  < 0)
            {
                qDebug(" error reading from channel");
                closeChannel(channel);
                goto next_channel;
            }

        }
        {
            read = libssh2_channel_read_stderr(channel, buffer, buffer_size);
            QByteArray debug = QByteArray(buffer, read);
            qDebug()<<"STDERR: "<<debug.constData();
            if(LIBSSH2_ERROR_EAGAIN == read)
            {
                qDebug("LIBSSH2_ERROR_EAGAIN");
                break;
            }
            else if(read  < 0)
            {
                qDebug(" error reading from channel");
                closeChannel(channel);
                goto next_channel;
            }

        }

        int i=0;

        i = libssh2_channel_eof(channel);
        if(i)
        {
            qDebug("libssh2_channel_eof %i", i);
            closeChannel(channel);
            goto next_channel;
        }
    }
next_channel:

    //------------ clean session
    socket.disconnectFromHost();

    libssh2_session_disconnect(session, "Client disconnecting normally");
    libssh2_session_free(session);
    libssh2_exit();

    return myOutPut;
}