fixed creation of hidden service and saving of private key/hostname

This commit is contained in:
csoler 2017-12-26 17:21:57 +01:00
parent 659367ca96
commit 1a9a9ca208
9 changed files with 194 additions and 83 deletions

View File

@ -127,11 +127,11 @@ void HiddenService::servicePublished()
loadPrivateKey();
if (m_hostname.isEmpty()) {
qDebug() << "Failed to read hidden service hostname";
std::cerr << "Failed to read hidden service hostname" << std::endl;
return;
}
qDebug() << "Hidden service published successfully";
std::cerr << "Hidden service published successfully" << std::endl;
setStatus(Online);
}

View File

@ -52,6 +52,21 @@
Tor::TorControl *torControl = 0;
class nullstream: public std::ostream {};
static std::ostream& torctrldebug()
{
static nullstream null ;
if(true)
return std::cerr << time(NULL) << ":TOR CONTROL: " ;
else
return null ;
}
#define torCtrlDebug torctrldebug
using namespace Tor;
namespace Tor {
@ -223,7 +238,7 @@ void TorControl::connect(const QHostAddress &address, quint16 port)
{
if (status() > Connecting)
{
qDebug() << "Ignoring TorControl::connect due to existing connection";
torCtrlDebug() << "Ignoring TorControl::connect due to existing connection" << std::endl;
return;
}
@ -262,7 +277,7 @@ void TorControlPrivate::authenticateReply()
return;
}
qDebug() << "torctrl: Authentication successful";
torCtrlDebug() << "torctrl: Authentication successful" << std::endl;
setStatus(TorControl::Connected);
setTorStatus(TorControl::TorUnknown);
@ -280,11 +295,12 @@ void TorControlPrivate::authenticateReply()
q->saveConfiguration();
}
void TorControlPrivate::socketConnected()
{
Q_ASSERT(status == TorControl::Connecting);
qDebug() << "torctrl: Connected socket; querying information";
torCtrlDebug() << "torctrl: Connected socket; querying information" << std::endl;
setStatus(TorControl::Authenticating);
ProtocolInfoCommand *command = new ProtocolInfoCommand(q);
@ -327,14 +343,14 @@ void TorControlPrivate::protocolInfoReply()
if (methods.testFlag(ProtocolInfoCommand::AuthNull))
{
qDebug() << "torctrl: Using null authentication";
torCtrlDebug() << "torctrl: Using null authentication" << std::endl;
data = auth->build();
}
else if (methods.testFlag(ProtocolInfoCommand::AuthCookie) && !info->cookieFile().isEmpty())
{
QString cookieFile = info->cookieFile();
QString cookieError;
qDebug() << "torctrl: Using cookie authentication with file" << cookieFile;
torCtrlDebug() << "torctrl: Using cookie authentication with file" << cookieFile.toStdString() << std::endl;
QFile file(cookieFile);
if (file.open(QIODevice::ReadOnly))
@ -359,7 +375,7 @@ void TorControlPrivate::protocolInfoReply()
* but it has happened. */
if (methods.testFlag(ProtocolInfoCommand::AuthHashedPassword) && !authPassword.isEmpty())
{
qDebug() << "torctrl: Unable to read authentication cookie file:" << cookieError;
torCtrlDebug() << "torctrl: Unable to read authentication cookie file:" << cookieError.toStdString() << std::endl;
goto usePasswordAuth;
}
@ -371,7 +387,7 @@ void TorControlPrivate::protocolInfoReply()
else if (methods.testFlag(ProtocolInfoCommand::AuthHashedPassword) && !authPassword.isEmpty())
{
usePasswordAuth:
qDebug() << "torctrl: Using hashed password authentication";
torCtrlDebug() << "torctrl: Using hashed password authentication" << std::endl;
data = auth->build(authPassword);
}
else
@ -404,7 +420,7 @@ void TorControlPrivate::getTorInfo()
quint16 port = (quint16)settings.read("socksPort").toInt();
if (!forceAddress.isNull() && port) {
qDebug() << "torctrl: Using manually specified SOCKS connection settings";
torCtrlDebug() << "torctrl: Using manually specified SOCKS connection settings";
socksAddress = forceAddress;
socksPort = port;
emit q->connectivityChanged();
@ -442,12 +458,12 @@ void TorControlPrivate::getTorInfoReply()
* listener yet. To handle that situation, we'll try to read the socks address again when TorReady state
* is reached. */
if (!socksAddress.isNull()) {
qDebug().nospace() << "torctrl: SOCKS address is " << socksAddress.toString() << ":" << socksPort;
torCtrlDebug() << "torctrl: SOCKS address is " << socksAddress.toString().toStdString() << ":" << socksPort << std::endl;
emit q->connectivityChanged();
}
if (command->get(QByteArray("status/circuit-established")).toInt() == 1) {
qDebug() << "torctrl: Tor indicates that circuits have been established; state is TorReady";
torCtrlDebug() << "torctrl: Tor indicates that circuits have been established; state is TorReady" << std::endl;
setTorStatus(TorControl::TorReady);
} else {
setTorStatus(TorControl::TorOffline);
@ -468,14 +484,20 @@ void TorControl::addHiddenService(HiddenService *service)
void TorControlPrivate::publishServices()
{
torCtrlDebug() << "Publish Services... " ;
Q_ASSERT(q->isConnected());
if (services.isEmpty())
{
std::cerr << "No service regstered!" << std::endl;
return;
}
std::cerr << std::endl;
SettingsObject settings(QStringLiteral("tor"));
if (settings.read("neverPublishServices").toBool())
{
qDebug() << "torctrl: Skipping service publication because neverPublishService is enabled";
torCtrlDebug() << "torctrl: Skipping service publication because neverPublishService is enabled" << std::endl;
/* Call servicePublished under the assumption that they're published externally. */
for (QList<HiddenService*>::Iterator it = services.begin(); it != services.end(); ++it)
@ -487,15 +509,15 @@ void TorControlPrivate::publishServices()
if (q->torVersionAsNewAs(QStringLiteral("0.2.7"))) {
foreach (HiddenService *service, services) {
if (service->hostname().isEmpty())
qDebug() << "torctrl: Creating a new hidden service";
torCtrlDebug() << "torctrl: Creating a new hidden service" << std::endl;
else
qDebug() << "torctrl: Publishing hidden service" << service->hostname();
torCtrlDebug() << "torctrl: Publishing hidden service: " << service->hostname().toStdString() << std::endl;
AddOnionCommand *onionCommand = new AddOnionCommand(service);
QObject::connect(onionCommand, &AddOnionCommand::succeeded, service, &HiddenService::servicePublished);
socket->sendCommand(onionCommand, onionCommand->build());
}
} else {
qDebug() << "torctrl: Using legacy SETCONF hidden service configuration for tor" << torVersion;
torCtrlDebug() << "torctrl: Using legacy SETCONF hidden service configuration for tor" << torVersion.toStdString() << std::endl;
SetConfCommand *command = new SetConfCommand;
QList<QPair<QByteArray,QByteArray> > torConfig;
@ -510,7 +532,7 @@ void TorControlPrivate::publishServices()
continue;
}
qDebug() << "torctrl: Configuring hidden service at" << service->dataPath();
torCtrlDebug() << "torctrl: Configuring hidden service at" << service->dataPath().toStdString() << std::endl;
QDir dir(service->dataPath());
torConfig.append(qMakePair(QByteArray("HiddenServiceDir"), dir.absolutePath().toLocal8Bit()));
@ -565,7 +587,7 @@ void TorControlPrivate::statusEvent(int code, const QByteArray &data)
if (tokens.size() < 3)
return;
qDebug() << "torctrl: status event:" << data.trimmed();
torCtrlDebug() << "torctrl: status event:" << QString(data.trimmed()).toStdString() << std::endl;
if (tokens[2] == "CIRCUIT_ESTABLISHED") {
setTorStatus(TorControl::TorReady);
@ -591,7 +613,8 @@ void TorControlPrivate::updateBootstrap(const QList<QByteArray> &data)
bootstrapStatus[key.toLower()] = value;
}
qDebug() << bootstrapStatus;
//torCtrlDebug() << bootstrapStatus << std::endl;
emit q->bootstrapStatusChanged();
}
@ -694,7 +717,7 @@ private slots:
return;
}
qDebug() << "torctrl: Wrote torrc file";
torCtrlDebug() << "torctrl: Wrote torrc file" << std::endl;
finishWithSuccess();
}

View File

@ -33,6 +33,8 @@
#ifndef TORCONTROL_H
#define TORCONTROL_H
#include <iostream>
#include <QObject>
#include <QHostAddress>
#include "PendingOperation.h"

View File

@ -30,6 +30,8 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include "TorControlSocket.h"
#include "TorControlCommand.h"
#include <QDebug>
@ -55,7 +57,7 @@ void TorControlSocket::sendCommand(TorControlCommand *command, const QByteArray
commandQueue.append(command);
write(data);
qDebug() << "torctrl: Sent" << data.trimmed();
std::cerr << "torctrl: Sent: \"" << QString(data.trimmed()).toStdString() << "\"" << std::endl;
}
void TorControlSocket::registerEvent(const QByteArray &event, TorControlCommand *command)

View File

@ -16,8 +16,6 @@ TorControlDialog::TorControlDialog(Tor::TorManager *tm,QWidget *parent)
{
setupUi(this) ;
QObject::connect(tm,SIGNAL(errorChanged()),this,SLOT(showLog())) ;
QObject::connect(tm->control(),SIGNAL(statusChanged(int,int)),this,SLOT(statusChanged())) ;
QObject::connect(tm->control(),SIGNAL(connected()),this,SLOT(statusChanged()));
QObject::connect(tm->control(),SIGNAL(disconnected()),this,SLOT(statusChanged()));
@ -28,8 +26,14 @@ TorControlDialog::TorControlDialog(Tor::TorManager *tm,QWidget *parent)
mIncomingServer = new QTcpServer(this) ;
mHiddenService = NULL ;
mHiddenServiceStatus = HIDDEN_SERVICE_STATUS_UNKNOWN;
connect(mIncomingServer, SIGNAL(QTcpServer::newConnection()), this, SLOT(onIncomingConnection()));
QTimer *timer = new QTimer ;
QObject::connect(timer,SIGNAL(timeout()),this,SLOT(showLog())) ;
timer->start(500) ;
}
void TorControlDialog::onIncomingConnection()
@ -103,14 +107,16 @@ void TorControlDialog::showLog()
s += *it + "\n" ;
torLog_TB->setText(s) ;
QCoreApplication::processEvents() ;
// QCoreApplication::processEvents() ;
// std::cerr << s.toStdString() << std::endl;
}
TorControlDialog::TorStatus TorControlDialog::checkForTor()
{
switch(mTorManager->control()->status())
{
case Tor::TorControl::Connected: usleep(2*1000*1000);return TOR_STATUS_OK ;
case Tor::TorControl::Connected: usleep(1*1000*1000);return TOR_STATUS_OK ;
case Tor::TorControl::Error: return TOR_STATUS_FAIL ;
default:
@ -120,32 +126,60 @@ TorControlDialog::TorStatus TorControlDialog::checkForTor()
TorControlDialog::HiddenServiceStatus TorControlDialog::checkForHiddenService()
{
std::cerr << "Checking for hidden services:" << std::endl;
std::cerr << "Checking for hidden services:" ;
switch(mHiddenServiceStatus)
{
default:
case HIDDEN_SERVICE_STATUS_UNKNOWN: {
std::cerr << " trying to setup. " ;
if(!mTorManager->setupHiddenService())
{
mHiddenServiceStatus = HIDDEN_SERVICE_STATUS_FAIL ;
std::cerr << "Failed." << std::endl;
return mHiddenServiceStatus ;
}
std::cerr << "Done." << std::endl;
mHiddenServiceStatus = HIDDEN_SERVICE_STATUS_REQUESTED ;
break ;
return mHiddenServiceStatus ;
}
case HIDDEN_SERVICE_STATUS_REQUESTED: {
QList<Tor::HiddenService*> hidden_services = mTorManager->control()->hiddenServices();
if(mHiddenService == NULL)
mHiddenService = *(hidden_services.begin()) ;
}
case HIDDEN_SERVICE_STATUS_OK : break;
if(hidden_services.empty())
{
std::cerr << "Not ready yet." << std::endl;
return mHiddenServiceStatus ;
}
else
{
if(mHiddenService == NULL)
mHiddenService = *(hidden_services.begin()) ;
default: break ;
}
Tor::HiddenService::Status hss = mHiddenService->status();
return mHiddenServiceStatus ;
std::cerr << "New service acquired. Status is " << hss ;
if(hss == Tor::HiddenService::Online)
{
mHiddenServiceStatus = HIDDEN_SERVICE_STATUS_OK ;
std::cerr << ": published and running!" << std::endl;
return mHiddenServiceStatus ;
}
else
{
std::cerr << ": not ready yet." << std::endl;
return mHiddenServiceStatus ;
}
}
}
case HIDDEN_SERVICE_STATUS_OK :
std::cerr << "New service acquired." << std::endl;
return mHiddenServiceStatus ;
}
}

View File

@ -147,6 +147,13 @@ bool TorManager::setupHiddenService()
QString keyData ;//= m_settings->read("serviceKey").toString();
QString legacyDir = d->hiddenServiceDir;
std::cerr << "TorManager: setting up hidden service." << std::endl;
if(legacyDir.isNull())
{
std::cerr << "legacy dir not set! Cannot proceed." << std::endl;
return false ;
}
// if (!keyData.isEmpty())
// {
// CryptoKey key;
@ -160,9 +167,11 @@ bool TorManager::setupHiddenService()
// }
// else
std::cerr << "Using legacy dir: " << legacyDir.toStdString() << std::endl;
if (!legacyDir.isEmpty() && QFile::exists(legacyDir + QLatin1String("/private_key")))
{
qDebug() << "Attempting to load key from legacy filesystem format in" << legacyDir;
std::cerr << "Attempting to load key from legacy filesystem format in " << legacyDir.toStdString() << std::endl;
CryptoKey key;
if (!key.loadFromFile(legacyDir + QLatin1String("/private_key"), CryptoKey::PrivateKey))
@ -170,11 +179,12 @@ bool TorManager::setupHiddenService()
qWarning() << "Cannot load legacy format key from" << legacyDir << "for conversion";
return false;
}
else
{
keyData = QString::fromLatin1(key.encodedPrivateKey(CryptoKey::DER).toBase64());
d->hiddenService = new Tor::HiddenService(key, legacyDir, this);
}
keyData = QString::fromLatin1(key.encodedPrivateKey(CryptoKey::DER).toBase64());
d->hiddenService = new Tor::HiddenService(key, legacyDir, this);
std::cerr << "Got key from legacy dir: " << std::endl;
std::cerr << keyData.toStdString() << std::endl;
}
// else if (!m_settings->read("initializing").toBool())
// {
@ -185,11 +195,13 @@ bool TorManager::setupHiddenService()
{
d->hiddenService = new Tor::HiddenService(legacyDir, this);
connect(d->hiddenService, SIGNAL(Tor::HiddenService::privateKeyChanged), this, SLOT(hiddenServicePrivateKeyChanged())) ;
std::cerr << "Creating new hidden service." << std::endl;
connect(d->hiddenService, SIGNAL(privateKeyChanged()), this, SLOT(hiddenServicePrivateKeyChanged())) ;
}
Q_ASSERT(d->hiddenService);
connect(d->hiddenService, SIGNAL(statusChanged(int,int)), SLOT(onStatusChanged(int,int)));
connect(d->hiddenService, SIGNAL(statusChanged(int,int)), this, SLOT(hiddenServiceStatusChanged(int,int)));
// Generally, these are not used, and we bind to localhost and port 0
// for an automatic (and portable) selection.
@ -198,20 +210,29 @@ bool TorManager::setupHiddenService()
quint16 port = 7934;//(quint16)m_settings->read("localListenPort").toInt();
std::cerr << "Testing host address: " << address.toString().toStdString() << ":" << port ;
if (!QTcpServer().listen(address, port))
{
// XXX error case
qWarning() << "Failed to open incoming socket on port :" << port;
std::cerr << " Failed to open incoming socket" << std::endl;
return false;
}
std::cerr << " OK - Adding hidden service to TorControl." << std::endl;
//d->hiddenService->addTarget(9878, mIncomingServer->serverAddress(), mIncomingServer->serverPort());
d->hiddenService->addTarget(9878, QHostAddress::LocalHost,7934);
torControl->addHiddenService(d->hiddenService);
control()->addHiddenService(d->hiddenService);
return true ;
}
void hiddenServiceStatusChanged(int old_status,int new_status)
{
std::cerr << "Hidden service status changed from " << old_status << " to " << new_status << std::endl;
}
void TorManager::hiddenServicePrivateKeyChanged()
{
QString key = QString::fromLatin1(d->hiddenService->privateKey().encodedPrivateKey(CryptoKey::DER).toBase64());
@ -220,8 +241,25 @@ void TorManager::hiddenServicePrivateKeyChanged()
outfile.open( QIODevice::WriteOnly | QIODevice::Text );
QTextStream s(&outfile);
s << key ;
s << "-----BEGIN RSA PRIVATE KEY-----" << endl;
for(uint32_t i=0;i<key.length();i+=64)
s << key.mid(i,64) << endl ;
s << "-----END RSA PRIVATE KEY-----" << endl;
outfile.close();
std::cerr << "Hidden service private key changed!" << std::endl;
std::cerr << key.toStdString() << std::endl;
QFile outfile2(d->hiddenServiceDir + QLatin1String("/hostname")) ;
outfile2.open( QIODevice::WriteOnly | QIODevice::Text );
QTextStream t(&outfile2);
t << d->hiddenService->hostname() << endl;
outfile2.close();
}
bool TorManager::configurationNeeded() const
@ -329,7 +367,8 @@ void TorManager::start()
void TorManagerPrivate::processStateChanged(int state)
{
qDebug() << Q_FUNC_INFO << state << TorProcess::Ready << process->controlPassword() << process->controlHost() << process->controlPort();
std::cerr << Q_FUNC_INFO << "state: " << state << " passwd=\"" << QString(process->controlPassword()).toStdString() << "\" " << process->controlHost().toString().toStdString()
<< ":" << process->controlPort() << std::endl;
if (state == TorProcess::Ready) {
control->setAuthPassword(process->controlPassword());
control->connect(process->controlHost(), process->controlPort());
@ -338,13 +377,13 @@ void TorManagerPrivate::processStateChanged(int state)
void TorManagerPrivate::processErrorChanged(const QString &errorMessage)
{
qDebug() << "tor error:" << errorMessage;
std::cerr << "tor error:" << errorMessage.toStdString() << std::endl;
setError(errorMessage);
}
void TorManagerPrivate::processLogMessage(const QString &message)
{
qDebug() << "tor:" << message;
std::cerr << "tor:" << message.toStdString() << std::endl;
if (logMessages.size() >= 50)
logMessages.takeFirst();
logMessages.append(message);

View File

@ -104,7 +104,7 @@ void TorSocket::reconnect()
m_connectTimer.stop();
if (!m_host.isEmpty() && m_port) {
qDebug() << "Attempting reconnection of socket to" << m_host << m_port;
std::cerr << "Attempting reconnection of socket to" << m_host.toStdString() << ":" << m_port << std::endl;
connectToHost(m_host, m_port);
}
}
@ -150,6 +150,6 @@ void TorSocket::onFailed()
if (reconnectEnabled() && !m_connectTimer.isActive()) {
m_connectAttempts++;
m_connectTimer.start(reconnectInterval() * 1000);
qDebug() << "Reconnecting socket to" << m_host << m_port << "in" << m_connectTimer.interval() / 1000 << "seconds";
std::cerr << "Reconnecting socket to" << m_host.toStdString() << ":" << m_port << "in" << m_connectTimer.interval() / 1000 << "seconds" << std::endl;
}
}

View File

@ -45,6 +45,7 @@
#include "idle/idle.h"
#include "lang/languagesupport.h"
#include "util/RsGxsUpdateBroadcast.h"
#include "util/rsdir.h"
#ifdef RETROTOR
#include "TorControl/TorManager.h"
@ -281,35 +282,35 @@ feenableexcept(FE_INVALID | FE_DIVBYZERO);
/* Setup The GUI Stuff */
Rshare rshare(args, argc, argv, QString::fromUtf8(RsAccounts::ConfigDirectory().c_str()));
#ifdef RETROTOR
// First check that we can start the Tor engine, if not, quit.
/* Tor control manager */
Tor::TorManager *torManager = Tor::TorManager::instance();
torManager->setDataDirectory(Rshare::dataDirectory() + QString("/tor/"));
torManager->start();
// We do not need to show this dialog. If too much of a pain, we may hide it and only show when it reports an error.
{
TorControlDialog tcd(torManager) ;
tcd.show();
while(tcd.checkForTor() == TorControlDialog::TOR_STATUS_UNKNOWN) // runs until some status is reached: either tor works, or it fails.
{
QCoreApplication::processEvents();
usleep(1000) ;
}
tcd.hide();
if(tcd.checkForTor() != TorControlDialog::TOR_STATUS_OK)
{
QMessageBox::critical(NULL,QObject::tr("Tor not found!"),QObject::tr("Tor wasn't found on your system. Please install it and re-start Retroshare.")) ;
return 1 ;
}
}
#endif
// #ifdef RETROTOR
// // First check that we can start the Tor engine, if not, quit.
//
// /* Tor control manager */
// Tor::TorManager *torManager = Tor::TorManager::instance();
// torManager->setDataDirectory(Rshare::dataDirectory() + QString("/tor/"));
// torManager->start();
//
// // We do not need to show this dialog. If too much of a pain, we may hide it and only show when it reports an error.
// TorControlDialog tcd(torManager) ;
//
// {
// tcd.show();
//
// while(tcd.checkForTor() == TorControlDialog::TOR_STATUS_UNKNOWN) // runs until some status is reached: either tor works, or it fails.
// {
// QCoreApplication::processEvents();
// usleep(1000) ;
// }
//
// tcd.hide();
//
// if(tcd.checkForTor() != TorControlDialog::TOR_STATUS_OK)
// {
// QMessageBox::critical(NULL,QObject::tr("Tor not found!"),QObject::tr("Tor wasn't found on your system. Please install it and re-start Retroshare.")) ;
// return 1 ;
// }
// }
// #endif
/* Start RetroShare */
QSplashScreen splashScreen(QPixmap(":/images/logo/logo_splash.png")/* , Qt::WindowStaysOnTopHint*/);
@ -378,16 +379,25 @@ feenableexcept(FE_INVALID | FE_DIVBYZERO);
#ifdef RETROTOR
// Now that we know the Tor service running, and we know the SSL id, we can make sure it provides a viable hidden service
{
torManager->setDataDirectory(Rshare::dataDirectory() + QString("/hidden_service/")); // re-set it, because now it's changed to the specific location that is run
QString tor_hidden_service_dir = QString::fromStdString(RsAccounts::AccountDirectory()) + QString("/hidden_service/") ;
Tor::TorManager *torManager = Tor::TorManager::instance();
torManager->setDataDirectory(Rshare::dataDirectory() + QString("/tor/"));
torManager->setHiddenServiceDirectory(tor_hidden_service_dir); // re-set it, because now it's changed to the specific location that is run
RsDirUtil::checkCreateDirectory(std::string(tor_hidden_service_dir.toUtf8())) ;
torManager->setupHiddenService();
torManager->start();
{
TorControlDialog tcd(torManager) ;
tcd.show();
while(tcd.checkForHiddenService() == TorControlDialog::HIDDEN_SERVICE_STATUS_UNKNOWN) // runs until some status is reached: either tor works, or it fails.
while(tcd.checkForHiddenService() != 1+TorControlDialog::HIDDEN_SERVICE_STATUS_OK) // runs until some status is reached: either tor works, or it fails.
{
QCoreApplication::processEvents();
usleep(1000) ;
usleep(0.2*1000*1000) ;
}
tcd.hide();

View File

@ -4,6 +4,7 @@ TEMPLATE = app
QT += network xml
CONFIG += qt gui uic qrc resources idle bitdht
CONFIG += link_prl
CONFIG += console
TARGET = retroshare
DEFINES += TARGET=\\\"$${TARGET}\\\"