net_layer.cpp 13.7 KB
Newer Older
1
/*
2
 * Copyright (C) 2014-2018 CZ.NIC
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations including
 * the two.
 */

#include <QEventLoop>
#include <QNetworkAccessManager>
#include <QNetworkCookie>
27
#include <QNetworkReply>
28
#include <QObject>
29 30 31
#include <QSslConfiguration>
#include <QTimer>

32
#include "src/datovka_shared/log/log.h"
33
#include "src/net/isds_const.h"
Martin Straka's avatar
Martin Straka committed
34 35 36 37 38 39
#include "src/net/net_layer.h"

/* 1 = POST/GET request will be printed to terminal/console. 0 = Disable
 * Enable only for debugging.
 */
#define PRINT_REQUEST_STDOUT 0
40

Martin Straka's avatar
Martin Straka committed
41 42 43 44
/* 1 = responce will be printed to terminal/console. 0 = Disable
 * Enable only for debugging.
*/
#define PRINT_RESPONSE_STDOUT 0
45

46
NetLayer::NetLayer(void)
47 48 49
{
}

Martin Straka's avatar
Martin Straka committed
50 51
bool NetLayer::createChangePwdRequest(IsdsSession::IsdsContext &ctx,
    const QString &soapEndPoint, const QByteArray &xmlDataIn,
52 53
    QByteArray &xmlDataOut)
{
54 55 56 57 58
	/* Set isds context on the base url */
	QUrl newUrl;
	newUrl.setHost(ctx.url.host());
	newUrl.setScheme(ctx.url.scheme());
	ctx.url = newUrl;
Martin Straka's avatar
Martin Straka committed
59
	ctx.url.setPath("/" + soapEndPoint, QUrl::TolerantMode);
60 61

	/* Create authorization string for header of request */
Martin Straka's avatar
Martin Straka committed
62
	QString authorization = ctx.username + ":" + ctx.password;
63 64
	if (ctx.login_method == USERNAME_PWD_HOTP ||
	    ctx.login_method == USERNAME_PWD_TOTP) {
Martin Straka's avatar
Martin Straka committed
65 66
		authorization = ctx.username + ":"
		  + ctx.password + ctx.pass_phrase;
67
	}
Martin Straka's avatar
Martin Straka committed
68 69 70 71

	/* Make target service url and create request with basic header */
	QNetworkRequest request(createRequest(ctx.url, authorization.toUtf8(),
	    xmlDataIn.length()));
72 73 74 75 76 77

	/* Set ssl context and add certificate to the request */
	if (ctx.login_method == USERNAME_PWD_CERT) {
		setCertificateToRequest(ctx, request);
	}

78
	return sendRequest(ctx, request, xmlDataIn, xmlDataOut);
79 80
}

Martin Straka's avatar
Martin Straka committed
81 82 83 84 85
bool NetLayer::createLoginRequest(IsdsSession::IsdsContext &ctx,
    const QString &soapEndPoint, const QByteArray &xmlDataIn,
    QByteArray &xmlDataOut)
{
	bool success = false;
86

Martin Straka's avatar
Martin Straka committed
87 88 89 90 91
	/* Create authorization string of header and add it to request */
	QString authorization = ctx.username + ":" + ctx.password;
	if (ctx.login_method == USERNAME_PWD_HOTP) {
		authorization = ctx.username + ":" +
		    ctx.password + ctx.pass_phrase;
92
	}
Martin Straka's avatar
Martin Straka committed
93 94 95 96 97

	/* Make target service url and create request with basic header */
	QNetworkRequest request(createRequest(
	    QUrl(ctx.url.toString().append(soapEndPoint)),
	    authorization.toUtf8(), xmlDataIn.length()));
98 99 100 101 102 103

	/* Set ssl context and add certificate to the request */
	if (ctx.login_method == USERNAME_PWD_CERT) {
		setCertificateToRequest(ctx, request);
	}

Martin Straka's avatar
Martin Straka committed
104
	success = sendRequest(ctx, request, xmlDataIn, xmlDataOut);
105

Martin Straka's avatar
Martin Straka committed
106 107 108
	if (success) {
		/* Run second phase of HOTP login if first phase is success*/
		if (ctx.login_method == USERNAME_PWD_HOTP && success) {
109 110
			success = sendSoapRequest(ctx, QString(), xmlDataIn,
			    xmlDataOut);
Martin Straka's avatar
Martin Straka committed
111 112 113 114 115 116
			if (success) {
				QString endPointUrl = ctx.url.toString();
				ctx.url = endPointUrl.remove(LOGIN_SERVICE,
				    Qt::CaseSensitive);
			}
		}
117
	}
118

Martin Straka's avatar
Martin Straka committed
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
	return success;
}

bool NetLayer::secondTotpLoginRequest(IsdsSession::IsdsContext &ctx,
    const QByteArray &xmlDataIn, QByteArray &xmlDataOut)
{
	bool success = false;

	/* Create authorization string of header and add it to request */
	QString authorization = ctx.username + ":" + ctx.password
	    + ctx.pass_phrase;

	/* Make target service url and create request with basic header */
	QNetworkRequest request(createRequest(ctx.url,
	    authorization.toUtf8(), xmlDataIn.length()));

	success = sendRequest(ctx, request, xmlDataIn, xmlDataOut);

	if (success && !ctx.pass_phrase.isEmpty()) {
138
		success = sendSoapRequest(ctx, QString(), xmlDataIn, xmlDataOut);
Martin Straka's avatar
Martin Straka committed
139 140 141 142 143
		if (success) {
			QString endPointUrl = ctx.url.toString();
			ctx.url = endPointUrl.remove(LOGIN_SERVICE,
			    Qt::CaseSensitive);
		}
144 145 146 147 148
	}

	return success;
}

Martin Straka's avatar
Martin Straka committed
149 150 151
bool NetLayer::sendSoapRequest(IsdsSession::IsdsContext &ctx,
    const QString &soapEndPoint, const QByteArray &xmlDataIn,
    QByteArray &xmlDataOut)
152
{
Martin Straka's avatar
Martin Straka committed
153 154 155 156 157 158 159 160 161 162 163 164 165 166
	QString authorization = ctx.username + ":" + ctx.password;

	/* Make target service url and create request with basic header */
	QNetworkRequest request(createRequest(
	    (!soapEndPoint.isNull()) ?
	        QUrl(ctx.url.toString().append(soapEndPoint))
	        : QUrl(ctx.url.toString()),
	    authorization.toUtf8(), xmlDataIn.length()));

	/* If any cookie is set, must be used for HOTP or TOTP only */
	if (!ctx.cookies.isEmpty()) {
		QVariant cookies;
		cookies.setValue(ctx.cookies);
		request.setHeader(QNetworkRequest::CookieHeader, cookies);
167 168 169 170 171 172 173 174
	}

	/* Set ssl context and add certificate to the request */
	if (ctx.login_method == USERNAME_PWD_CERT) {
		setCertificateToRequest(ctx, request);
	}

	/* Send request */
Martin Straka's avatar
Martin Straka committed
175
	return sendRequest(ctx, request, xmlDataIn, xmlDataOut);
176 177
}

Martin Straka's avatar
Martin Straka committed
178 179
QNetworkRequest NetLayer::createRequest(const QUrl &url,
    const QByteArray &autPhrase, int xmlDataLength)
180
{
Martin Straka's avatar
Martin Straka committed
181 182 183 184 185 186 187 188 189 190 191 192 193
	QNetworkRequest request(url);
	/* Set request header items */
	request.setRawHeader("User-Agent", QByteArray(APP_NAME));
	request.setRawHeader("Host", url.host().toUtf8());
	request.setRawHeader("Content-Type", "text/xml;charset=utf-8");
	request.setRawHeader("Accept",
	    "application/soap+xml,application/xml,text/xml");
	request.setRawHeader("Content-Length",
	    QString::number(xmlDataLength).toUtf8());
	if (!autPhrase.isNull()) {
		QByteArray authorization = autPhrase.toBase64();
		authorization.prepend("Basic ");
		request.setRawHeader("Authorization", authorization);
194
	}
Martin Straka's avatar
Martin Straka committed
195
	return request;
196 197
}

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
/*!
 * @brief Constructs a header listing.
 *
 * @param[in] reply Network reply.
 * @return Raw header listing.
 */
static
QByteArray replyHeaderListing(const QNetworkReply *reply)
{
	if (Q_UNLIKELY(reply == Q_NULLPTR)) {
		Q_ASSERT(0);
		return "\n";
	}

	QByteArray listing;

	foreach (const QNetworkReply::RawHeaderPair &pair, reply->rawHeaderPairs()) {
		listing += pair.first + ": " + pair.second + "\n";
	}

	return listing;
}

/*!
 * @brief Print reply header and its data to stdout.
 *
 * @param[in] request Reply object.
 * @param[in] data Reply data.
 */
static
void printReply(const QNetworkReply *reply, const QByteArray &data)
{
	logDebugMlLv0("\n"
	    "====================REPLY===========================\n"
	    "URL: %s\n"
	    "CODE: %d\n"
	    "ERROR: %s\n"
	    "REASON: %s\n"
	    "--------------------Headers-------------------------\n"
	    "%s" /* The listing already contains a trailing newline. */
	    "--------------------Content-------------------------\n"
	    "%s\n"
	    "====================================================\n"
	    "\n"
	    , reply->url().toString().toUtf8().constData(),
	    reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(),
	    (reply->error() == QNetworkReply::NoError) ? "" : reply->errorString().toUtf8().constData(),
	    reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString().toUtf8().constData(),
	    replyHeaderListing(reply).constData(),
	    data.constData());
}

Martin Straka's avatar
Martin Straka committed
250
bool NetLayer::getResponse(IsdsSession::IsdsContext &ctx, QNetworkReply *reply,
251 252
    QByteArray &xmlDataOut)
{
Martin Straka's avatar
Martin Straka committed
253
	bool success = false;
254 255 256 257 258

	/* Obtain HTTP status and errors */
	int statusCode = reply->attribute(
	    QNetworkRequest::HttpStatusCodeAttribute).toInt();

Martin Straka's avatar
Martin Straka committed
259
	/* Store new cookies if they are available in the response */
260 261
	QVariant variantCookies =
	    reply->header(QNetworkRequest::SetCookieHeader);
Martin Straka's avatar
Martin Straka committed
262 263 264 265 266 267 268 269 270
	if (!variantCookies.isNull()) {
		ctx.cookies = qvariant_cast<QList<QNetworkCookie>>(variantCookies);
	}

	/* Store reply data */
	xmlDataOut = reply->readAll();

#if PRINT_RESPONSE_STDOUT
	printReply(reply, xmlDataOut);
271 272
#else
	Q_UNUSED(printReply);
Martin Straka's avatar
Martin Straka committed
273
#endif
274 275 276 277 278 279 280 281

	switch (statusCode) {
	case 200: /* HTTP status 200 OK */

		/*
		 * If that it is login request and reply status is OK,
		 * set isds context as user is logged and continues.
		*/
Martin Straka's avatar
Martin Straka committed
282
		if (reply->url().toString().contains(LOGIN_SERVICE, Qt::CaseSensitive)) {
283 284 285 286 287 288 289 290 291 292
			ctx.is_logged = true;
		}
		success = true;
		break;

	case 302: /* HTTP status 302 Found */

		/*
		 * Do next step of OTP autentization process.
		 * Set received cookie into isds contex or set SMS code.
Martin Straka's avatar
Martin Straka committed
293
		 * Set new url location for redirect to isds context.
294
		 */
Martin Straka's avatar
Martin Straka committed
295
		ctx.url = QUrl::fromPercentEncoding(reply->rawHeader("Location"));
296 297 298 299 300 301
		success = true;
		break;

	case 401: /* HTTP status 401 Unauthorized */

		ctx.last_isds_msg = tr("Authorization error.");
302
		ctx.last_http_code = statusCode;
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330

		if (reply->rawHeader("WWW-Authenticate") == USERNAME_PWD_HOTP ||
		    reply->rawHeader("WWW-Authenticate") == USERNAME_PWD_TOTP ||
		    reply->rawHeader("WWW-Authenticate") == USERNAME_PWD_TOTP_SEND_SMS) {

			QByteArray resCode =
			    reply->rawHeader("X-Response-message-code");
			ctx.last_isds_msg = tr("OTP authorization error.");
			if (resCode == OTP_ERROR_NOT_LOGGED) {
				ctx.last_isds_msg = tr("Unauthorized. Wrong login data.");
			} else if (resCode == OTP_ERROR_USER_BLOCKED) {
				ctx.last_isds_msg = tr("Access has been blocked for 60 minutes.");
			} else if (resCode == OTP_PWD_EXPIR) {
				ctx.last_isds_msg = tr("Your password has expired.");
			} else if (resCode == OTP_BAD_ROLE) {
				ctx.last_isds_msg = tr("Permissions denied.");
			} else if (resCode == OTP_ERROR_SEND_QUICKLY) {
				ctx.last_isds_msg = tr("SMS code can be sent once in 30 seconds.");
			} else if (resCode == OTP_ERROR_NOT_SEND) {
				ctx.last_isds_msg = tr("SMS code couldn't be sent.");
			} else if (resCode == OTP_ERROR_NOT_ORDERED) {
				ctx.last_isds_msg = tr("Your order on premium SMS has been exhausted or canceled. SMS code cannot be sent.");
			}
		}
		break;

	case 503: /* HTTP status 503 Service Temporarily Unavailable */

Martin Straka's avatar
Martin Straka committed
331
		/* Description in Czech: Probíhá plánovaná údržba. */
332 333 334 335
		/* Omlouváme se všem uživatelům datových schránek za dočasné
		 * omezení přístupu do systému datových schránek z důvodu
		 * plánované údržby systému. Děkujeme za pochopení.
		 */
Martin Straka's avatar
Martin Straka committed
336
		ctx.last_isds_msg = tr("ISDS server is out of service. Scheduled maintenance in progress. Try again later.");
337 338 339 340
		break;

	default: /* Any error occurred */

Martin Straka's avatar
Martin Straka committed
341
		ctx.last_isds_msg = tr("Network connection failed. HTTP Status code: %1").arg(statusCode);
342 343 344 345 346 347
		break;
	}

	return success;
}

348 349 350 351 352 353 354 355
/*!
 * @brief Constructs a header listing.
 *
 * @param[in] request Network request.
 * @return Raw header listing.
 */
static
QByteArray requestHeaderListing(const QNetworkRequest &request)
356
{
357 358 359 360
	QByteArray listing;

	foreach (const QByteArray &reqName, request.rawHeaderList()) {
		listing += reqName + ": " + request.rawHeader(reqName) + "\n";
Martin Straka's avatar
Martin Straka committed
361
	}
362 363

	return listing;
364 365
}

366 367 368 369 370 371 372 373
/*!
 * @brief Print request header and its data to stdout.
 *
 * @param[in] request Request object.
 * @param[in] data Request data.
 */
static
void printRequest(const QNetworkRequest &request, const QByteArray &data)
374
{
375 376 377 378 379 380 381 382 383 384 385 386 387
	logDebugMlLv0("\n"
	    "====================REQUEST=========================\n"
	    "URL: %s\n"
	    "--------------------Headers-------------------------\n"
	    "%s" /* The listing already contains a trailing newline. */
	    "--------------------Content-------------------------\n"
	    "%s\n"
	    "====================================================\n"
	    "\n"
	    , request.url().toString().toUtf8().constData(),
	    requestHeaderListing(request).constData(),
	    data.constData()
	);
388 389
}

Martin Straka's avatar
Martin Straka committed
390 391
bool NetLayer::sendRequest(IsdsSession::IsdsContext &ctx,
    const QNetworkRequest &request, const QByteArray &xmlDataIn,
392 393
    QByteArray &xmlDataOut)
{
394
	bool success = false;
Martin Straka's avatar
Martin Straka committed
395 396
	QNetworkReply *reply = Q_NULLPTR;
	QNetworkAccessManager *nam = new QNetworkAccessManager;
397

Martin Straka's avatar
Martin Straka committed
398 399 400 401 402 403 404 405 406 407
	switch (nam->networkAccessible()) {
	case QNetworkAccessManager::UnknownAccessibility:
	case QNetworkAccessManager::NotAccessible:
		ctx.last_isds_msg = tr("Internet connection is probably not "
		    "available. Check your network or wifi settings.");
		return success;
		break;
	default:
		break;
	}
408

Martin Straka's avatar
Martin Straka committed
409 410
#if PRINT_REQUEST_STDOUT
	printRequest(request, xmlDataIn);
411 412
#else
	Q_UNUSED(printRequest);
Martin Straka's avatar
Martin Straka committed
413
#endif
414

Martin Straka's avatar
Martin Straka committed
415 416 417 418 419
	if (!xmlDataIn.isEmpty()) {
		reply = nam->post(request, xmlDataIn);
	} else {
		reply = nam->get(request);
	}
420

Martin Straka's avatar
Martin Straka committed
421 422 423 424 425 426 427 428 429 430 431 432
	/*
	 * Add timer, set timeout from context.
	 * Abort request if timer = timeout
	 */
	QTimer timer;
	timer.setSingleShot(true);
	/* this eventloop makes synchronous soap requests */
	QEventLoop eventLoop;
	QObject::connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
	QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
	timer.start(ctx.timeout);
	eventLoop.exec();
433

Martin Straka's avatar
Martin Straka committed
434 435 436 437 438
	if (timer.isActive()) {
		timer.stop();
		success = getResponse(ctx, reply, xmlDataOut);
	} else {
		// timeout expired
439 440 441 442
		QObject::disconnect(reply, SIGNAL(finished()),
		    &eventLoop, SLOT(quit()));
		ctx.last_isds_msg =
		    tr("Connection timeout expired. Check your internet connection.");
Martin Straka's avatar
Martin Straka committed
443 444
		reply->abort();
	}
445

Martin Straka's avatar
Martin Straka committed
446 447
	reply->deleteLater(); reply = Q_NULLPTR;
	nam->deleteLater(); nam = Q_NULLPTR;
448 449 450 451

	return success;
}

Martin Straka's avatar
Martin Straka committed
452
void NetLayer::setCertificateToRequest(const IsdsSession::IsdsContext &ctx,
453 454
    QNetworkRequest &request)
{
Martin Straka's avatar
Martin Straka committed
455
	QSslConfiguration sslConf(QSslConfiguration::defaultConfiguration());
456 457 458 459 460 461
	sslConf.setPeerVerifyMode(QSslSocket::VerifyNone);
	sslConf.setProtocol(QSsl::AnyProtocol);
	sslConf.setLocalCertificate(ctx.certificate);
	sslConf.setPrivateKey(ctx.key);
	request.setSslConfiguration(sslConf);
}