[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: ssh_userauth_none crashes


HI,

Attached files for SSH,
Could be hempful if you could check

From: Yang Yubo [mailto:yang@xxxxxxxxxxxx]
Sent: Friday, October 16, 2015 6:43 PM
To: libssh@xxxxxxxxxx
Subject: Re: ssh_userauth_none crashes

Hi Sruthi,

I use libssh in one of my application, didn’t ever encounter such ssh_userauth_none crash error.

It looks like some mySshSession was released or point to another memory address.

I think it would be better if you could paste full example code that can reproduce the issue.

Best

Yang

On Oct 16, 2015, at 18:59, Sruthi Mohan (RBEI/EIA1) <Sruthi.Mohan@xxxxxxxxxxxx<mailto:Sruthi.Mohan@xxxxxxxxxxxx>> wrote:

Dear sir,
I am using libssh 0.7
I have followed the following steps,
ssh_connect(mySshSession);=succesful

Known host verification ==successful

ssh_userauth_none(mySshSession, NULL);

ssh_userauth_none crashes with the error
Heap block at 27415180 modified at 27415240 past requested size of b8.

Any help would be appreciated



Best regards

Sruthi Mohan
RBEI/EIA1

Tel. +91(80)6783-7826

/***************************************************************************************************
/**\file myipconnect.cpp
*
* \brief Implementation of the MyIpConnect class
*/
/***************************************************************************************************
* (c) Copyright by BOSCH REXROTH AG, all rights reserved *
****************************************************************************************************
*
* PROJECT: Spiderworks
*
* FILE VERSION INFORMATION:
* Revision: 1
* Date: 2015-june-16 17:00:00 IST
* Author: som5kor
*
* REVISION HISTORY:
*
* 1. som5kor : Implementaion of IpConnect
* 2.
*
***************************************************************************************************/
/**** include files ********************************************************************************
 * List of include files needed in this module. */

#include "myipconnect.h"
QLoggingCategory network_category("s3.database");


/**************************************************************************************************
 * FUNCTION: MYIpConnect
 */
/**\brief Constructor for MYIpConnect Class
 * This is a default constructor , Initializes the private variables
 */
/*************************************************************************************************/

MYIpConnect::MYIpConnect()
{
    port = 155;
    access = O_WRONLY | O_CREAT | O_TRUNC;
    PublickeyFile="DDM_login/ddm_key.pub";
    PrivateKeyFile="DDM_login/rsa_key";
    Passphrase = "N(wdZt3-f=k<=U4";
    ConfigDestFile="/usr/local/S3/upload/myspider.zip";
    ConfigSourceFile="DDM_Login/spider3config.zip";
    DirectoryLocation="/usr/local/S3/upload";
    User="s3ddm";
    source=NULL;

    if (CreateSSHSession()!=DDM_OK)
        exit(1);
}

/**************************************************************************************************
 * FUNCTION: CreateSFTPSession
 */
/**\brief CreateSFTPSession -Creates an SFTP session
 * \return DDM_Result -returns the success/failure of the operation
 */
/*************************************************************************************************/

DDM_Result MYIpConnect::CreateSFTPSession()
{try{
        mySftpSession = sftp_new(mySshSession);
        if (mySftpSession==NULL)
        {
            throw;
        }
        rc =sftp_init(mySftpSession);
    }
    catch(std::exception &e)
    {
        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO).critical(network_category)<< "SFTP error : " + QString::fromStdString(e.what());
    }
    catch(...)
    {
        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO).critical(network_category)<< Error_Map[E_SFTP];
        return DDM_ERR;
    }
    return DDM_OK;
}
/**************************************************************************************************
 * FUNCTION: GetDirectoryInfo
 */
/**\brief CreateSFTPSession-prints the constens of the directory to the console.
 * \return void
 */
/*************************************************************************************************/

void MYIpConnect::GetDirectoryInfo()
{int err_code;
    QString err_desc;
    try{
        dir = sftp_opendir(mySftpSession, DirectoryLocation.toStdString().c_str());
        if (!dir)
        {
            err_code=SSH_ERROR;
            err_desc="Error directory not opened: ";


        }
        qDebug() << "Name Size Perms Owner\tGroup";
        while ((attributes = sftp_readdir(mySftpSession, dir)) != NULL)
        {
            qDebug() << attributes->name << (long long unsigned int) attributes->size << attributes->permissions << attributes->owner << attributes->uid << attributes->group << attributes->gid;

            sftp_attributes_free(attributes);
        }
        if (!sftp_dir_eof(dir))
        {

            sftp_closedir(dir);
            err_code=SSH_ERROR;
            err_desc="Error can't list directory: ";
            throw;
        }
        rc = sftp_closedir(dir);
        if (rc != SSH_OK)
        {
            err_desc="Error can't close directory: ";
            throw;
            exit(rc);
        }
    }
    catch(std::exception &e)
    {
        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO).critical(network_category)<<  QString::fromStdString(e.what());
    }
    catch(...)
    {
        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO).critical(network_category)<<err_desc+ssh_get_error(mySshSession);
        exit(err_code);
    }
}




/**************************************************************************************************
 * FUNCTION: FreeSFTPsession
 */
/**\brief FreeSFTPsession-Frees the contents of SFTP session.
 * \return void
 */
/*************************************************************************************************/

void MYIpConnect::FreeSFTPsession()
{ if (mySftpSession!=NULL)
        sftp_free(mySftpSession);
}





/**************************************************************************************************
 * FUNCTION: TransferConfigFile
 */
/**\brief TransferConfigFile-Transfer the config file to a given location in the device
 * \return DDM_Result:success or failure of the operation
 */
/*************************************************************************************************/

DDM_Result MYIpConnect::TransferConfigFile()
{  try{
        char data[MAX_XFER_BUF_SIZE]={0};
        int nwritten;

        file = sftp_open(mySftpSession, ConfigDestFile.toStdString().c_str(),access,S_IRWXU);
        if (file == NULL)
        {
            throw("Cannot open file for writing");// <<ssh_get_error(mySshSession);

        }
        source = fopen(ConfigSourceFile.toStdString().c_str(), "rb");
        if(!source){
            throw("Error Opening the file for reading");//<<ssh_get_error(mySshSession);
            return DDM_ERR;
        }
        sftp_file_set_nonblocking(file) 	;
        while ((nwritten = fread(data, 1, MAX_XFER_BUF_SIZE, source))>0) {
            if(sftp_write(file,data,nwritten)!=nwritten){
                qDebug()<<"Error writing to file "<<ssh_get_error(mySshSession);
                return DDM_ERR;
            }
        }
    }
    catch(std::exception &e)
    {
        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO).critical(network_category)<<  QString::fromStdString(e.what());
    }
    catch(QString err_desc)
    {
        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO).critical(network_category)<< err_desc;
        return DDM_ERR;
    }

    return DDM_OK;
}





/**************************************************************************************************
 * FUNCTION: CreateSSHSession
 */
/**\brief CreateSSHSession-Creates an SSh session
 * \return DDM_Result:success or failure of the operation
 */
/*************************************************************************************************/
DDM_Result MYIpConnect::CreateSSHSession()
{
    try{
        mySshSession = ssh_new();
        if (mySshSession == NULL)
        {
            throw;
        }
    }
    catch(std::exception &e)
    {
        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO).critical(network_category)<<  QString::fromStdString(e.what());
    }
    catch(...)
    {
        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO).critical(network_category)<<Error_Map[E_SSH];
        return DDM_ERR;
    }
    return DDM_OK;
}




/**************************************************************************************************
 * FUNCTION: ConnectToIP
 */
/**\brief ConnectToIP-Connects to give IP address
 * \param IPAddress QString -IPAddress to be connected to
 * \return DDM_Result:success or failure of the operation
 */
/*************************************************************************************************/
DDM_Result MYIpConnect::ConnectToIP(QString IPAddress)
{
    try{
        qDebug()<<"IPCONNEct called"<<IPAddress;
        ssh_options_set(mySshSession, SSH_OPTIONS_HOST, IPAddress.toStdString().c_str());
        ssh_options_set(mySshSession, SSH_OPTIONS_PORT, &port);
        ssh_options_set(mySshSession, SSH_OPTIONS_USER, User.toStdString().c_str());

        rc = ssh_connect(mySshSession);
        if (rc!=SSH_OK)
        {
            throw("Could not connect to IP :"+IPAddress+ssh_get_error(mySshSession));

        }
        if (VerifyKnownHosts()==DDM_ERR)
            throw("Verification unsuccessful");
        if(AuthenticatePublicPrivateKey()==DDM_ERR)
            throw("Authentification unsuccesful");
    }
    catch(std::exception &e)
    {
        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO).critical(network_category)<<  QString::fromStdString(e.what());
    }
    catch(QString err_desc)
    {
        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO).critical(network_category)<<Error_Map[E_SSH_AUTH];
        return DDM_ERR;
    }
    return DDM_OK;
}




/**************************************************************************************************
 * FUNCTION: VerifyKnownHosts
 */
/**\brief VerifyKnownHosts-Cheks if the validity of the server. if the client is not previously
 * added, adds it to known host
 * \return DDM_Result:success or failure of the operation
 */
/*************************************************************************************************/
DDM_Result MYIpConnect::VerifyKnownHosts()
{
    int state, hlen;
    unsigned char *hash = NULL;
    char *hexa;
    state = ssh_is_server_known(mySshSession);
    hlen = ssh_get_pubkey_hash(mySshSession, &hash);
    if (hlen < 0)
        return DDM_ERR;
    switch (state)
    {
    case SSH_SERVER_KNOWN_OK:
        break; /* ok */
    case SSH_SERVER_KNOWN_CHANGED:
        qDebug() << "Host key for server changed: it is now:";
        ssh_print_hexa("Public key hash", hash, hlen);
        qDebug() << "For security reasons, connection will be stopped.";
        free(hash);
        return DDM_ERR;
    case SSH_SERVER_FOUND_OTHER:
        qDebug() << "The host key for this server was not found but an other type of key exists.";
        qDebug() << "An attacker might change the default server key to confuse your client into thinking the key does not exist.";
        free(hash);
        return DDM_ERR;
    case SSH_SERVER_FILE_NOT_FOUND:
        qDebug() << "Could not find known host file.";
        qDebug() << "If you accept the host key here, the file will be automatically created.";
        /* fallback to SSH_SERVER_NOT_KNOWN behavior */
        return DDM_ERR;
    case SSH_SERVER_NOT_KNOWN:
        hexa = ssh_get_hexa(hash, hlen);
        qDebug() << "The server is unknown.Writing to known hosts";
        qDebug() << "Public key hash: " << hexa;
        if (ssh_write_knownhost(mySshSession) < 0)
        {
            qDebug() << "Error " << strerror(errno);
            free(hash);
            return DDM_ERR ;
        }
        break;
    case SSH_SERVER_ERROR:
        qDebug() << "Error " << ssh_get_error(mySshSession);
        free(hash);
        return DDM_ERR;
    }
    free(hash);
    return DDM_OK;
}
/**************************************************************************************************
 * FUNCTION: AuthenticatePublicPrivateKey
 */
/**\brief VerifyKnownHosts-Cheks if the validity of the server. if the client is not previously
 * added, adds it to known host
 * \return DDM_Result:success or failure of the operation
 */
/*************************************************************************************************/
DDM_Result MYIpConnect::AuthenticatePublicPrivateKey()
{
    QString err_desc;
    try{
        qDebug()<<"connected to host";
        ssh_userauth_none(mySshSession, NULL);
        if (ssh_pki_import_pubkey_file(PublickeyFile.toStdString().c_str(), &pubkey) != SSH_OK) {
            throw("Failed to import the key");

        }
        if(ssh_userauth_try_publickey(mySshSession,User.toStdString().c_str(),pubkey)==SSH_ERROR)
            return DDM_ERR;

        if (ssh_pki_import_privkey_file(PrivateKeyFile.toStdString().c_str(), Passphrase.toStdString().c_str(), NULL, NULL, &privkey) !=SSH_OK)
        {
            ssh_key_free(pubkey);
            err_desc="Failed to import Private key from file"+PrivateKeyFile;
            throw;

        }
        rc = ssh_userauth_publickey(mySshSession, NULL, privkey);

        if (rc == SSH_AUTH_ERROR) {
            err_desc="Authentication failure Error";
            throw;
        }
        if (rc == SSH_OK) {
            qDebug()<<"Authentication Succesful";
        }
    }
    catch(std::exception &e)
    {
        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO).critical(network_category)<<  QString::fromStdString(e.what());
    }
    catch(...)
    {
        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO).critical(network_category)<<Error_Map[E_SSH_AUTH]+","+err_desc+ssh_get_error(mySshSession);
        return DDM_ERR;
    }
    return DDM_OK;

}
/**************************************************************************************************
 * FUNCTION: DeleteAuthentication
 */
/**\brief DeleteAuthentication-Deletes the ssh session and the public private key created
 *
 * \Return void:
 */
/*************************************************************************************************/

void MYIpConnect::DeleteAuthentication()
{
    if (mySshSession !=NULL)
    {
        ssh_disconnect(mySshSession);
        ssh_free(mySshSession);
        ssh_key_free(pubkey);
        ssh_key_free(privkey);
    }
}


/**************************************************************************************************
 * FUNCTION: Destructor
 */
/**\brief Deletes the oblect and  variables created in heap
 *
 * \Return void:
 */
/*************************************************************************************************/

MYIpConnect::~MYIpConnect()
{    DeleteAuthentication();
     FreeSFTPsession();
}


/***************************************************************************************************
* *
* FILENAME: */
/**\file myipconnect.h
*
* \file myipconnect.h
* \brief Ip connection and file transfer handling class used in spider works
*
*/
/***************************************************************************************************
* (c) Copyright by BOSCH REXROTH AG, all rights reserved *
****************************************************************************************************
*
* PROJECT: SPIDERWORKS
*
* FILE VERSION INFORMATION:
* Revision: 1
* Date: 2015-June-16 12:00:00 IST
* Author: som5kor
*
* REVISION HISTORY:
*
* 1.som5kor:Supports SFTP of config file and connect to the device
*
***************************************************************************************************/

#ifndef MYIPCONNECT_H
#define MYIPCONNECT_H

/**** include files ********************************************************************************
 * List of include files needed in this module. */

#include <QApplication>
#include<libssh/libssh.h>
#include<libssh/sftp.h>
#include <QDebug>
#include<QFile>
#include <direct.h>
#include <iostream>
#include <fcntl.h>
#include <sys/stat.h>
#include <fstream>
#include <datatypes.h>
#include <QString>
#include <QtCore>
#include <QObject>
#include<networkinterface.h>


/*
 * Buffersize for file transfer
 */
#define MAX_XFER_BUF_SIZE 16384
using namespace std;


/***************************************************************************************************
 * Class used for Connecting to the device.Authentication is done using public private key checking
 * uses libssh 0.7 dynamically linked library.
 * Transfers files using SFTP.

***************************************************************************************************/
class MYIpConnect: public QObject ,public NetworkInterface
{
public:
    MYIpConnect();
    ~MYIpConnect();
    void sftp_cmmd();
    /*Initialize SSH session*/
    DDM_Result CreateSSHSession();
    /*Tries Connecting to a given IP address*/
    DDM_Result ConnectToIP(QString IPAddress);
    DDM_Result VerifyKnownHosts();
    DDM_Result AuthenticatePublicPrivateKey();
    DDM_Result CreateSFTPSession();
    void DeleteAuthentication();
    void GetDirectoryInfo();
    DDM_Result TransferConfigFile();
    void FreeSFTPsession();
private:

    QString PublickeyFile;
    QString PrivateKeyFile;
    QString Passphrase;
    QString ConfigSourceFile;
    QString ConfigDestFile;
    QString User; //Device user
    QString DirectoryLocation;
    FILE *source;
    int access; //file access
    ssh_session mySshSession;
    int rc ;
    int port; //port for communicating with device
    ssh_key  pubkey;
    ssh_key privkey;
    sftp_dir dir; //destination directory where file has to be copied
    sftp_attributes attributes;
    sftp_session mySftpSession;
    sftp_file file;


};

#endif // MYIPCONNECT_H
#ifndef DATATYPES_H
#define DATATYPES_H
#include <stdio.h>

enum DDM_Result { DDM_OK=0,
                    DDM_ERR};


#endif // DATATYPES_H


Follow-Ups:
Re: ssh_userauth_none crashesYang Yubo <yang@xxxxxxxxxxxx>
References:
ssh_userauth_none crashes"Sruthi Mohan (RBEI/EIA1)" <Sruthi.Mohan@xxxxxxxxxxxx>
Re: ssh_userauth_none crashesYang Yubo <yang@xxxxxxxxxxxx>
Archive administrator: postmaster@lists.cynapses.org