module-auth.cc 46.6 KB
Newer Older
jehan's avatar
jehan committed
1
/*
2 3
 Flexisip, a flexible SIP proxy server with media capabilities.
 Copyright (C) 2010-2015  Belledonne Communications SARL, All rights reserved.
4

5 6 7 8
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as
 published by the Free Software Foundation, either version 3 of the
 License, or (at your option) any later version.
9

10 11 12 13
 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 Affero General Public License for more details.
14

15 16 17
 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
jehan's avatar
jehan committed
18

19
#include "module.hh"
jehan's avatar
jehan committed
20 21
#include "agent.hh"
#include <string>
22
#include <ctime>
jehan's avatar
jehan committed
23 24
#include <map>
#include <list>
25
#include <vector>
jehan's avatar
jehan committed
26 27 28
#include "sofia-sip/auth_module.h"
#include "sofia-sip/sip_status.h"
#include "sofia-sip/msg_addr.h"
jehan's avatar
jehan committed
29 30
#include "sofia-sip/auth_plugin.h"
#include "sofia-sip/su_tagarg.h"
31
#include "sofia-sip/sip_extra.h"
32
#include <sofia-sip/nua.h>
33
#include "bctoolbox/crypto.h"
jehan's avatar
jehan committed
34

35
#include "authdb.hh"
36
#include <assert.h>
jehan's avatar
jehan committed
37

38 39
#include <regex.h>

40
using namespace std;
41
class Authentication;
jehan's avatar
jehan committed
42

43
struct auth_plugin_t {
44 45 46 47 48
	su_root_t *mRoot;
	auth_scheme_t *mBase;
	auth_splugin_t *mlist;
	auth_splugin_t **mTail;
	Authentication *mModule;
jehan's avatar
jehan committed
49 50
};
/**
Mickaël Turnel's avatar
Mickaël Turnel committed
51 52
* to compute auth_mod size with plugin
*/
53
struct auth_mod_size {
54 55
	auth_mod_t mod[1];
	auth_plugin_t plug[1];
56
};
57

58
void flexisipSha256(char* input, size_t size, uint8_t* a1buf, char* out){
59
	size_t di;
Mickaël Turnel's avatar
Mickaël Turnel committed
60
	bctbx_sha256((const unsigned char*)input, strlen(input),size, a1buf);
61 62
	for (di = 0; di < size; ++di)
		sprintf(out + di * 2, "%02x", a1buf[di]);
Mickaël Turnel's avatar
Mickaël Turnel committed
63
	out[64]='\0';
64 65 66
}

void auth_digest_a1_for_algorithm(auth_response_t *ar,char const *secret,char* ha1) {
67 68 69
	char input[100];
	uint8_t a1buf[32];

Mickaël Turnel's avatar
Mickaël Turnel committed
70
	snprintf(input,sizeof(input),"%s:%s:%s",ar->ar_username,ar->ar_realm,secret);
71 72
	flexisipSha256(input, 32, a1buf, ha1);
	LOGD("auth_digest_ha1() has A1 = SHA256(%s:%s:%s) = %s\n",
Mickaël Turnel's avatar
Mickaël Turnel committed
73
		ar->ar_username,ar->ar_realm, "*******", ha1);
74 75 76
}

void auth_digest_a1sess_for_algorithm(auth_response_t *ar,char* ha1) {
77 78
	char input[100];
	uint8_t a1buf[32];
Mickaël Turnel's avatar
Mickaël Turnel committed
79
	char* ha1_ref=ha1;
80

Mickaël Turnel's avatar
Mickaël Turnel committed
81
	snprintf(input,sizeof(input),"%s:%s:%s",ha1,ar->ar_nonce,ar->ar_cnonce);
82 83
	flexisipSha256(input, 32, a1buf, ha1);
	LOGD("auth_sessionkey has A1' = SHA256(%s:%s:%s) = %s\n",
Mickaël Turnel's avatar
Mickaël Turnel committed
84
		ha1_ref, ar->ar_nonce, ar->ar_cnonce, ha1);
85 86 87
}

void auth_digest_response_for_algorithm(auth_response_t *ar,
Mickaël Turnel's avatar
Mickaël Turnel committed
88 89
										char const *method_name,
										void const *data, isize_t dlen, char* response, const char* ha1){
90 91
	char  input[200];
	uint8_t a1buf[32];
Mickaël Turnel's avatar
Mickaël Turnel committed
92
	char ha2[65],Hentity[65];
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
	if (ar->ar_auth_int)
		ar->ar_qop = "auth-int";
	else if (ar->ar_auth)
		ar->ar_qop = "auth";
	else
		ar->ar_qop = NULL;

	/* Calculate Hentity */
	if (ar->ar_auth_int) {
		if (data && dlen) {
			snprintf(input, sizeof(input), "%s", reinterpret_cast<const char *>(data));
			flexisipSha256(input, 32, a1buf, Hentity);
		} else {
			strcpy(Hentity, "d7580069de562f5c7fd932cc986472669122da91a0f72f30ef1b20ad6e4f61a3");
		}
	}

	/* Calculate A2 */
	if (ar->ar_auth_int) {
		snprintf(input, sizeof(input), "%s:%s:%s", method_name, ar->ar_uri, Hentity);
	} else
		snprintf(input, sizeof(input), "%s:%s", method_name, ar->ar_uri);
	flexisipSha256(input, 32, a1buf, ha2);
	LOGD("A2 = SHA256(%s:%s%s%s)\n", method_name, ar->ar_uri,
	     ar->ar_auth_int ? ":" : "", ar->ar_auth_int ? Hentity : "");

	/* Calculate response */
	snprintf(input, sizeof(input), "%s:%s:%s:%s:%s:%s", ha1, ar->ar_nonce, ar->ar_nc, ar->ar_cnonce, ar->ar_qop, ha2);
	flexisipSha256(input, 32, a1buf, response);
	LOGD("auth_response: %s = SHA256(%s:%s%s%s%s%s%s%s:%s) (qop=%s)\n",
	     response, ha1, ar->ar_nonce,
	     ar->ar_auth ||  ar->ar_auth_int ? ":" : "",
	     ar->ar_auth ||  ar->ar_auth_int ? ar->ar_nc : "",
	     ar->ar_auth ||  ar->ar_auth_int ? ":" : "",
	     ar->ar_auth ||  ar->ar_auth_int ? ar->ar_cnonce : "",
	     ar->ar_auth ||  ar->ar_auth_int ? ":" : "",
	     ar->ar_auth ||  ar->ar_auth_int ? ar->ar_qop : "",
	     ha2,
	     ar->ar_qop ? ar->ar_qop : "NONE");
132
}
133

134
class NonceStore {
135 136 137 138 139 140 141 142 143 144
	struct NonceCount {
		NonceCount(int c, time_t ex) : nc(c), expires(ex) {
		}
		int nc;
		time_t expires;
	};
	map<string, NonceCount> mNc;
	mutex mMutex;
	int mNonceExpires;

145
public:
146 147
	NonceStore() : mNonceExpires(3600) {}

148 149 150
	void setNonceExpires(int value) {
		mNonceExpires = value;
	}
151

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
	int getNc(const string &nonce) {
		unique_lock<mutex> lck(mMutex);
		auto it = mNc.find(nonce);
		if (it != mNc.end())
			return (*it).second.nc;
		return -1;
	}

	void insert(msg_header_t *response) {
		const char *nonce = msg_header_find_param((msg_common_t const *)response, "nonce");
		string snonce(nonce);
		snonce = snonce.substr(1, snonce.length() - 2);
		LOGD("New nonce %s", snonce.c_str());
		insert(snonce);
	}
167

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
	void insert(const string &nonce) {
		unique_lock<mutex> lck(mMutex);
		time_t expiration = getCurrentTime() + mNonceExpires;
		auto it = mNc.find(nonce);
		if (it != mNc.end()) {
			LOGE("Replacing nonce count for %s", nonce.c_str());
			it->second.nc = 0;
			it->second.expires = expiration;
		} else {
			mNc.insert(make_pair(nonce, NonceCount(0, expiration)));
		}
	}

	void updateNc(const string &nonce, int newnc) {
		unique_lock<mutex> lck(mMutex);
		auto it = mNc.find(nonce);
		if (it != mNc.end()) {
			LOGD("Updating nonce %s with nc=%d", nonce.c_str(), newnc);
			(*it).second.nc = newnc;
		} else {
			LOGE("Couldn't update nonce %s: not found", nonce.c_str());
		}
	}

	void erase(const string &nonce) {
		unique_lock<mutex> lck(mMutex);
		LOGD("Erasing nonce %s", nonce.c_str());
		mNc.erase(nonce);
	}

	void cleanExpired() {
		unique_lock<mutex> lck(mMutex);
		int count = 0;
		time_t now = getCurrentTime();
		size_t size = 0;
		for (auto it = mNc.begin(); it != mNc.end();) {
			if (now > it->second.expires) {
				LOGD("Cleaning expired nonce %s", it->first.c_str());
				auto eraseIt = it;
				++it;
				mNc.erase(eraseIt);
				++count;
			} else
				++it;
			size++;
		}
		if (count)
			LOGD("Cleaned %d expired nonces, %zd remaining", count, size);
	}
217
};
218

jehan's avatar
jehan committed
219
class Authentication : public Module {
220
private:
221 222 223 224 225 226 227 228 229
	class AuthenticationListener : public AuthDbListener {
		friend class Authentication;
		Authentication *mModule;
		shared_ptr<RequestSipEvent> mEv;
		auth_mod_t *mAm;
		auth_status_t *mAs;
		auth_challenger_t const *mAch;
		bool mPasswordFound;
		AuthDbResult mResult;
230
		string mPassword;
231 232 233 234

	public:
		bool mImmediateRetrievePass;
		bool mNo403;
Mickaël Turnel's avatar
Mickaël Turnel committed
235
		list<string> mAlgoUsed;
236
		auth_response_t mAr;
237
		AuthenticationListener(Authentication *, shared_ptr<RequestSipEvent>);
238 239
		virtual ~AuthenticationListener() {
		}
240

241 242 243 244
		void setData(auth_mod_t *am, auth_status_t *as, auth_challenger_t const *ach);
		void checkPassword(const char *password);
		int checkPasswordMd5(const char *password);
		int checkPasswordForAlgorithm(const char *password);
245
		void onResult(AuthDbResult result, const string &passwd);
246
		void onResult(AuthDbResult result, const vector<passwd_algo_t> &passwd);
247 248
		void onError();
		void finish(); /*the listener is destroyed when calling this, careful*/
249 250
		void finishForAlgorithm();
		void finishVerifyAlgos(const vector<passwd_algo_t> &pass);
251
	
252 253 254 255 256 257 258 259 260 261 262 263 264
		su_root_t *getRoot() {
			return getAgent()->getRoot();
		}
		Agent *getAgent() {
			return mModule->getAgent();
		}
		Authentication *getModule() {
			return mModule;
		}
	private:
		void processResponse();
		static void main_thread_async_response_cb(su_root_magic_t *rm, su_msg_r msg, void *u);
	};
265

266
private:
267 268 269 270 271
	static ModuleInfo<Authentication> sInfo;
	map<string, auth_mod_t *> mAuthModules;
	list<string> mDomains;
	list<BinaryIp> mTrustedHosts;
	list<string> mTrustedClientCertificates;
272
	list<string> mAlgorithms;
273

274
	regex_t mRequiredSubject;
275 276 277 278 279 280 281 282 283
	auth_challenger_t mRegistrarChallenger;
	auth_challenger_t mProxyChallenger;
	auth_scheme_t *mOdbcAuthScheme;
	shared_ptr<BooleanExpression> mNo403Expr;
	AuthenticationListener *mCurrentAuthOp;
	bool mImmediateRetrievePassword;
	bool mNewAuthOn407;
	bool mTestAccountsEnabled;
	bool mDisableQOPAuth;
284
	bool mRequiredSubjectCheckSet;
285
	bool mRejectWrongClientCertificates;
286
	bool mTrustDomainCertificates;
287

288

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
	static int authPluginInit(auth_mod_t *am, auth_scheme_t *base, su_root_t *root, tag_type_t tag, tag_value_t value,
	                          ...) {
		auth_plugin_t *ap = AUTH_PLUGIN(am);
		int retval = -1;
		ta_list ta;
		ta_start(ta, tag, value);

		if (auth_init_default(am, base, root, ta_tags(ta)) != -1) {
			ap->mRoot = root;
			ap->mBase = base;
			ap->mTail = &ap->mlist;
			retval = 0;
		} else {
			LOGE("cannot init odbc plugin");
		}
		auth_readdb_if_needed(am);
		ta_end(ta);
		return retval;
	}
	bool empty(const char *value) {
		return value == NULL || value[0] == '\0';
	}

	void static flexisip_auth_method_digest(auth_mod_t *am, auth_status_t *as, msg_auth_t *au,
Mickaël Turnel's avatar
Mickaël Turnel committed
313
											auth_challenger_t const *ach);
314
	void static flexisip_auth_check_digest(auth_mod_t *am, auth_status_t *as, auth_response_t *ar,
Mickaël Turnel's avatar
Mickaël Turnel committed
315
										auth_challenger_t const *ach);
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
	const char *findIncomingSubjectInTrusted(shared_ptr<RequestSipEvent> &ev, const char *fromDomain) {
		if (mTrustedClientCertificates.empty())
			return NULL;
		list<string> toCheck;
		for (auto it = mTrustedClientCertificates.cbegin(); it != mTrustedClientCertificates.cend(); ++it) {
			if (it->find("@") != string::npos)
				toCheck.push_back(*it);
			else
				toCheck.push_back(*it + "@" + string(fromDomain));
		}
		const char *res = ev->findIncomingSubject(toCheck);
		return res;
	}

	void loadTrustedHosts(const ConfigStringList &trustedHosts) {
		list<string> hosts = trustedHosts.read();
		transform(hosts.begin(), hosts.end(), back_inserter(mTrustedHosts), [](string host) {
			return BinaryIp(host.c_str());
		});

		const GenericStruct *clusterSection = GenericManager::get()->getRoot()->get<GenericStruct>("cluster");
		bool clusterEnabled = clusterSection->get<ConfigBoolean>("enabled")->read();
		if (clusterEnabled) {
			list<string> clusterNodes = clusterSection->get<ConfigStringList>("nodes")->read();
			for (list<string>::const_iterator node = clusterNodes.cbegin(); node != clusterNodes.cend(); node++) {
				BinaryIp nodeIp((*node).c_str());

				if (find(mTrustedHosts.cbegin(), mTrustedHosts.cend(), nodeIp) == mTrustedHosts.cend()) {
					mTrustedHosts.push_back(nodeIp);
				}
			}
		}
348

349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
		const GenericStruct *presenceSection = GenericManager::get()->getRoot()->get<GenericStruct>("module::Presence");
		bool presenceServer = presenceSection->get<ConfigBoolean>("enabled")->read();
		if (presenceServer) {
			SofiaAutoHome home;
			string presenceServer = presenceSection->get<ConfigString>("presence-server")->read();
			sip_contact_t *contact = sip_contact_make(home.home(), presenceServer.c_str());
			url_t *url = contact ? contact->m_url : NULL;
			if (url && url->url_host) {
				BinaryIp host(url->url_host);

				if (find(mTrustedHosts.cbegin(), mTrustedHosts.cend(), host) == mTrustedHosts.cend()) {
					SLOGI << "Adding presence server '" << url->url_host << "' to trusted hosts";
					mTrustedHosts.push_back(host);
				}
			} else {
				SLOGW << "Could not parse presence server URL '" << presenceServer << "', cannot be added to trusted hosts!";
			}
		}
	}
368

369
public:
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
	StatCounter64 *mCountAsyncRetrieve;
	StatCounter64 *mCountSyncRetrieve;
	StatCounter64 *mCountPassFound;
	StatCounter64 *mCountPassNotFound;
	NonceStore mNonceStore;

	Authentication(Agent *ag) : Module(ag), mCountAsyncRetrieve(NULL), mCountSyncRetrieve(NULL) {
		mNewAuthOn407 = false;
		mProxyChallenger.ach_status = 407; /*SIP_407_PROXY_AUTH_REQUIRED*/
		mProxyChallenger.ach_phrase = sip_407_Proxy_auth_required;
		mProxyChallenger.ach_header = sip_proxy_authenticate_class;
		mProxyChallenger.ach_info = sip_proxy_authentication_info_class;

		mRegistrarChallenger.ach_status = 401; /*SIP_401_UNAUTHORIZED*/
		mRegistrarChallenger.ach_phrase = sip_401_Unauthorized;
		mRegistrarChallenger.ach_header = sip_www_authenticate_class;
		mRegistrarChallenger.ach_info = sip_authentication_info_class;

		auth_scheme *lOdbcAuthScheme = new auth_scheme();
		lOdbcAuthScheme->asch_method = "odbc";
		lOdbcAuthScheme->asch_size = sizeof(struct auth_mod_size);
		lOdbcAuthScheme->asch_init = authPluginInit;
		lOdbcAuthScheme->asch_check = flexisip_auth_method_digest;
		lOdbcAuthScheme->asch_challenge = auth_challenge_digest;
		lOdbcAuthScheme->asch_cancel = auth_cancel_default;
		lOdbcAuthScheme->asch_destroy = auth_destroy_default;
		mOdbcAuthScheme = lOdbcAuthScheme;
		if (auth_mod_register_plugin(mOdbcAuthScheme)) {
			LOGE("Cannot register auth plugin");
		}
		mCurrentAuthOp = NULL;
401
		mRequiredSubjectCheckSet = false;
402
	}
403

404 405 406 407 408
	~Authentication() {
		for (auto it = mAuthModules.begin(); it != mAuthModules.end(); ++it) {
			auth_mod_destroy(it->second);
		}
		mAuthModules.clear();
409 410 411
		if (mRequiredSubjectCheckSet){
			regfree(&mRequiredSubject);
		}
412 413
		delete mOdbcAuthScheme;
	}
414

415 416
	virtual void onDeclare(GenericStruct *mc) {
		ConfigItemDescriptor items[] = {
417
			{StringList, "auth-domains", "List of whitespace separated domain names to challenge. Others are denied.",
Mickaël Turnel's avatar
Mickaël Turnel committed
418
				"localhost"},
419

420
			{StringList, "trusted-hosts", "List of whitespace separated IP which will not be challenged.", ""},
421

422
			{String, "db-implementation", "Database backend implementation for digest authentication [odbc,soci,file].", "file"},
423

424 425 426 427 428 429
			{String, "datasource",
				"Odbc connection string to use for connecting to database. "
				"ex1: DSN=myodbc3; where 'myodbc3' is the datasource name. "
				"ex2: DRIVER={MySQL};SERVER=host;DATABASE=db;USER=user;PASSWORD=pass;OPTION=3; for a DSN-less connection. "
				"ex3: /etc/flexisip/passwd; for a file containing user credentials in clear-text, md5 or sha256. "
				"The file must start with 'version:1' as the first line, and then contains lines in the form of:\n"
430
				"user@domain clrtxt:clear-text-password md5:md5-password sha256:sha256-password ;\n"
431
				"For example: \n"
432 433
				"bellesip@sip.linphone.org clrtxt:secret ;\n"
				"bellesip@sip.linphone.org md5:97ffb1c6af18e5687bf26cdf35e45d30 ;\n"
434
				"bellesip@sip.linphone.org clrtxt:secret md5:97ffb1c6af18e5687bf26cdf35e45d30 sha256:d7580069de562f5c7fd932cc986472669122da91a0f72f30ef1b20ad6e4f61a3 ;",
Mickaël Turnel's avatar
Mickaël Turnel committed
435
				""},
436

437
			{Integer, "nonce-expires", "Expiration time of nonces, in seconds.", "3600"},
438

439
			{Integer, "cache-expire", "Duration of the validity of the credentials added to the cache in seconds.",
Mickaël Turnel's avatar
Mickaël Turnel committed
440
				"1800"},
441

442
			{Boolean, "hashed-passwords",
Mickaël Turnel's avatar
Mickaël Turnel committed
443 444
				"True if retrieved passwords from the database are hashed. HA1=MD5(A1) = MD5(username:realm:pass).",
				"false"},
445

446
			{BooleanExpr, "no-403", "Don't reply 403, but 401 or 407 even in case of wrong authentication.", "false"},
447

448 449 450 451 452 453 454
			{Boolean, "reject-wrong-client-certificates",
				"If set to true, the module will simply reject with 403 forbidden any request coming from client"
				" who presented a bad TLS certificate (regardless of reason: improper signature, unmatched subjects)."
				" Otherwise, the module will fallback to a digest authentication.\n"
				"This policy applies only for transports configured with 'required-peer-certificate=1' parameter; indeed"
				" no certificate is requested to the client otherwise.",
				"false"},
455

456 457 458
			{String, "tls-client-certificate-required-subject", "An optional regular expression matched against subjects of presented"
				" client certificates. If this regular expression evaluates to false, the request is rejected. "
				"The matched subjects are, in order: subjectAltNames.DNS, subjectAltNames.URI, subjectAltNames.IP and CN.", ""},
459

460 461
			{Boolean, "new-auth-on-407",
				"When receiving a proxy authenticate challenge, generate a new challenge for this proxy.", "false"},
462

463 464 465 466 467
			{Boolean, "enable-test-accounts-creation",
				"Enable a feature useful for automatic tests, allowing a client to create a temporary account in the "
				"password database in memory."
				"This MUST not be used for production as it is a real security hole.",
				"false"},
468

469 470 471
			{Boolean, "disable-qop-auth",
				"Disable the QOP authentication method. Default is to use it, use this flag to disable it if needed.",
				"false"},
472

473 474
			/* We need this configuration because of old client that do not support multiple Authorization.
			 * When a user have a clear text password, it will be hashed into md5 and sha256.
475
			 * This will force the use of only the algorithm supported by them.
476
			 */
477 478 479 480
			{StringList, "available-algorithms",
				"List of algorithms, separated by whitespaces (valid values are MD5 and SHA-256).\n"
				"This feature allows to force the use of wanted algorithm(s).\n"
				"If the value is empty, then it will authorize all implemented algorithms.",
481
				"MD5"},
482

483
			{StringList, "trusted-client-certificates", "List of whitespace separated username or username@domain CN "
484 485
				"which will trusted. If no domain is given it is computed.",
				""},
486

487 488 489 490
			{Boolean, "trust-domain-certificates",
				"If enabled, all requests which have their request URI containing a trusted domain will be accepted.",
				"false"},

491 492 493
			config_item_end
		};

494 495 496
		mc->addChildrenValues(items);
		/* modify the default value for "enabled" */
		mc->get<ConfigBoolean>("enabled")->setDefault("false");
497
		mc->get<ConfigBoolean>("hashed-passwords")->setDeprecated(true);
498 499
		//we deprecate "trusted-client-certificates" because "tls-client-certificate-required-subject" can do more.
		mc->get<ConfigStringList>("trusted-client-certificates")->setDeprecated(true);
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515

		// Call declareConfig for backends
		AuthDbBackend::declareConfig(mc);

		mCountAsyncRetrieve = mc->createStat("count-async-retrieve", "Number of asynchronous retrieves.");
		mCountSyncRetrieve = mc->createStat("count-sync-retrieve", "Number of synchronous retrieves.");
		mCountPassFound = mc->createStat("count-password-found", "Number of passwords found.");
		mCountPassNotFound = mc->createStat("count-password-not-found", "Number of passwords not found.");
	}

	void onLoad(const GenericStruct *mc) {
		mDomains = mc->get<ConfigStringList>("auth-domains")->read();
		loadTrustedHosts(*mc->get<ConfigStringList>("trusted-hosts"));
		mImmediateRetrievePassword = true;
		mNewAuthOn407 = mc->get<ConfigBoolean>("new-auth-on-407")->read();
		mTrustedClientCertificates = mc->get<ConfigStringList>("trusted-client-certificates")->read();
516
		mTrustDomainCertificates = mc->get<ConfigBoolean>("trust-domain-certificates")->read();
517 518 519
		mNo403Expr = mc->get<ConfigBooleanExpression>("no-403")->read();
		mTestAccountsEnabled = mc->get<ConfigBoolean>("enable-test-accounts-creation")->read();
		mDisableQOPAuth = mc->get<ConfigBoolean>("disable-qop-auth")->read();
520
		int nonceExpires = mc->get<ConfigInt>("nonce-expires")->read();
521
		mNonceStore.setNonceExpires(nonceExpires);
522 523
		mAlgorithms = mc->get<ConfigStringList>("available-algorithms")->read();
		mAlgorithms.unique();
524

525 526 527 528 529 530
		for (auto it = mAlgorithms.begin(); it != mAlgorithms.end();) {
			if ((*it != "MD5") && (*it != "SHA-256")) {
				SLOGW << "Given algorithm '" << *it << "' is not valid. Must be either MD5 or SHA-256.";
				it = mAlgorithms.erase(it);
			} else {
				it++;
531 532 533
			}
		}

534
		if (mAlgorithms.empty()) {
535
			mAlgorithms.push_back("MD5");
536 537
			mAlgorithms.push_back("SHA-256");
		}
Mickaël Turnel's avatar
Mickaël Turnel committed
538

539 540
		for (const auto &domain : mDomains) {
			mAuthModules[domain] = createAuthModule(domain, nonceExpires);
541
			mAuthModules[domain]->am_algorithm = su_strdup(mAuthModules[domain]->am_home, mAlgorithms.front().c_str()); /* MD5 by default */
542
			auth_plugin_t *ap = AUTH_PLUGIN(mAuthModules[domain]);
543
			ap->mModule = this;
544
			SLOGI << "Found auth domain: " << domain;
545
		}
546

547 548
		string requiredSubject = mc->get<ConfigString>("tls-client-certificate-required-subject")->read();
		if (!requiredSubject.empty()){
549
			int res = regcomp(&mRequiredSubject, requiredSubject.c_str(),  REG_EXTENDED|REG_NOSUB);
550 551 552 553 554 555
			if (res != 0) {
				string err_msg(128,0);
				regerror(res, &mRequiredSubject, &err_msg[0], err_msg.capacity());
				LOGF("Could not compile regex for 'tls-client-certificate-required-subject' '%s': %s", requiredSubject.c_str(), err_msg.c_str());
			}else mRequiredSubjectCheckSet = true;
		}
556
		mRejectWrongClientCertificates = mc->get<ConfigBoolean>("reject-wrong-client-certificates")->read();
557
		AuthDbBackend::get();//force instanciation of the AuthDbBackend NOW, to force errors to arrive now if any.
558 559
	}

560
	auth_mod_t *findAuthModule(const string name) {
561 562 563
		auto it = mAuthModules.find(name);
		if (it == mAuthModules.end())
			it = mAuthModules.find("*");
564 565 566 567 568 569 570 571 572 573 574 575 576 577
		if (it == mAuthModules.end()) {
			for (auto it2 = mAuthModules.begin(); it2 != mAuthModules.end(); ++it2) {
				string domainName = it2->first;
				size_t wildcardPosition = domainName.find("*");
				// if domain has a wildcard in it, try to match
				if (wildcardPosition != string::npos) {
					size_t beforeWildcard = name.find(domainName.substr(0, wildcardPosition));
					size_t afterWildcard = name.find(domainName.substr(wildcardPosition + 1));
					if (beforeWildcard != string::npos && afterWildcard != string::npos) {
						return it2->second;
					}
				}
			}
		}
578 579 580 581 582
		if (it == mAuthModules.end()) {
			return NULL;
		}
		return it->second;
	}
583

584
	auth_mod_t *createAuthModule(const string &domain, int nonceExpires) {
585 586
		if (mDisableQOPAuth) {
			return auth_mod_create(NULL, AUTHTAG_METHOD("odbc"), AUTHTAG_REALM(domain.c_str()),
Mickaël Turnel's avatar
Mickaël Turnel committed
587 588
								AUTHTAG_OPAQUE("+GNywA=="), AUTHTAG_FORBIDDEN(1), AUTHTAG_ALLOW("ACK CANCEL BYE"),
								TAG_END());
589 590
		} else {
			return auth_mod_create(NULL, AUTHTAG_METHOD("odbc"), AUTHTAG_REALM(domain.c_str()),
Mickaël Turnel's avatar
Mickaël Turnel committed
591 592 593 594
								AUTHTAG_OPAQUE("+GNywA=="), AUTHTAG_QOP("auth"),
								AUTHTAG_EXPIRES(nonceExpires),      // in seconds
								AUTHTAG_NEXT_EXPIRES(nonceExpires), // in seconds
								AUTHTAG_FORBIDDEN(1), AUTHTAG_ALLOW("ACK CANCEL BYE"), TAG_END());
595 596
		}
	}
597

Mickaël Turnel's avatar
Mickaël Turnel committed
598 599 600 601
	static bool containsDomain(const list<string> &d, const char *name) {
		return find(d.cbegin(), d.cend(), "*") != d.end() || find(d.cbegin(), d.cend(), name) != d.end();
	}

602 603 604 605 606 607 608 609
	bool handleTestAccountCreationRequests(shared_ptr<RequestSipEvent> &ev) {
		sip_t *sip = ev->getSip();
		if (sip->sip_request->rq_method == sip_method_register) {
			sip_unknown_t *h = ModuleToolbox::getCustomHeaderByName(sip, "X-Create-Account");
			if (h && strcasecmp(h->un_value, "yes") == 0) {
				url_t *url = sip->sip_from->a_url;
				if (url) {
					sip_unknown_t *h2 = ModuleToolbox::getCustomHeaderByName(sip, "X-Phone-Alias");
Mickaël Turnel's avatar
Mickaël Turnel committed
610
					const char* phone_alias = h2 ? h2->un_value : NULL;
611 612
					phone_alias = phone_alias ? phone_alias : "";
					AuthDbBackend::get()->createAccount(url->url_user, url->url_host, url->url_user, url->url_password,
Mickaël Turnel's avatar
Mickaël Turnel committed
613
														sip->sip_expires->ex_delta, phone_alias);
614
					LOGD("Account created for %s@%s with password %s and expires %lu%s%s", url->url_user, url->url_host,
Mickaël Turnel's avatar
Mickaël Turnel committed
615
						url->url_password, sip->sip_expires->ex_delta, phone_alias ? " with phone alias " : "", phone_alias);
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
					return true;
				}
			}
		}
		return false;
	}

	bool isTrustedPeer(shared_ptr<RequestSipEvent> &ev) {
		sip_t *sip = ev->getSip();

		// Check for trusted host
		sip_via_t *via = sip->sip_via;
		list<BinaryIp>::const_iterator trustedHostsIt = mTrustedHosts.begin();
		const char *printableReceivedHost = !empty(via->v_received) ? via->v_received : via->v_host;

		BinaryIp receivedHost(printableReceivedHost, true);

		for (; trustedHostsIt != mTrustedHosts.end(); ++trustedHostsIt) {
			if (receivedHost == *trustedHostsIt) {
				LOGD("Allowing message from trusted host %s", printableReceivedHost);
				return true;
			}
		}
		return false;
	}
Mickaël Turnel's avatar
Mickaël Turnel committed
641

642 643 644 645 646 647 648 649 650 651 652 653
	bool tlsClientCertificatePostCheck(const shared_ptr<RequestSipEvent> &ev){
		if (mRequiredSubjectCheckSet){
			bool ret = ev->matchIncomingSubject(&mRequiredSubject);
			if (ret){
				SLOGD<<"TLS certificate postcheck successful.";
			}else{
				SLOGUE<<"TLS certificate postcheck failed.";
			}
			return ret;
		}
		return true;
	}
654

655 656 657 658 659
	/* This function returns
	 * true: if the tls authentication is handled (either successful or rejected)
	 * false: if we have to fallback to digest
	 */
	bool handleTlsClientAuthentication(shared_ptr<RequestSipEvent> &ev) {
660 661 662 663 664 665
		sip_t *sip = ev->getSip();
		shared_ptr<tport_t> inTport = ev->getIncomingTport();
		unsigned int policy = 0;

		tport_get_params(inTport.get(), TPTAG_TLS_VERIFY_POLICY_REF(policy), NULL);
		// Check TLS certificate
666
		if ((policy & TPTLS_VERIFY_INCOMING) && tport_is_server(inTport.get())){
667 668 669 670 671 672 673 674 675 676 677 678
			/* tls client certificate is required for this transport*/
			if (tport_is_verified(inTport.get())) {
				/*the certificate looks good, now match subjects*/
				const url_t *from = sip->sip_from->a_url;
				const char *fromDomain = from->url_host;
				const char *res = NULL;
				url_t searched_uri = URL_INIT_AS(sip);
				SofiaAutoHome home;
				char *searched;

				searched_uri.url_host = from->url_host;
				searched_uri.url_user = from->url_user;
679
				searched = url_as_string(home.home(), &searched_uri);
680

681
				if (ev->findIncomingSubject(searched)) {
682
					SLOGD << "Allowing message from matching TLS certificate";
683
					goto postcheck;
684 685 686 687 688 689 690 691 692 693 694 695
				} else if (sip->sip_request->rq_method != sip_method_register &&
					(res = findIncomingSubjectInTrusted(ev, fromDomain))) {
					SLOGD << "Found trusted TLS certificate " << res;
					goto postcheck;
				} else {
					/*case where the certificate would work for the entire domain*/
					searched_uri.url_user = NULL;
					searched = url_as_string(home.home(), &searched_uri);
					if (ev->findIncomingSubject(searched)) {
						SLOGD << "Found TLS certificate for entire domain";
						goto postcheck;
					}
696
				}
697 698 699 700 701 702 703 704 705 706 707

				if (sip->sip_request->rq_method != sip_method_register && mTrustDomainCertificates) {
					searched_uri.url_user = NULL;
					searched_uri.url_host = sip->sip_request->rq_url->url_host;
					searched = url_as_string(home.home(), &searched_uri);
					if (ev->findIncomingSubject(searched)) {
						SLOGD << "Found trusted TLS certificate for the request URI domain";
						goto postcheck;
					}
				}

708 709 710
				LOGE("Client is presenting a TLS certificate not matching its identity.");
				SLOGUE << "Registration failure for " << url_as_string(home.home(), from) << ", TLS certificate doesn't match its identity";
				goto bad_certificate;
711

712 713 714 715 716 717
				postcheck:
					if (tlsClientCertificatePostCheck(ev)){
						/*all is good, return true*/
						return true;
					}else goto bad_certificate;
			}else goto bad_certificate;
718

719 720 721 722
			bad_certificate:
			if (mRejectWrongClientCertificates){
				ev->reply(403, "Bad tls client certificate", SIPTAG_SERVER_STR(getAgent()->getServerString()), TAG_END());
				return true; /*the request is responded, no further processing required*/
723
			}
724
			/*fallback to digest*/
725
			return false;
726
		}
727
		/*no client certificate requested, go to digest auth*/
728 729 730
		return false;
	}

731
	void onRequest(shared_ptr<RequestSipEvent> &ev) {
732 733 734 735 736 737 738
		const shared_ptr<MsgSip> &ms = ev->getMsgSip();
		sip_t *sip = ms->getSip();
		sip_p_preferred_identity_t *ppi = NULL;

		// Do it first to make sure no transaction is created which
		// would send an unappropriate 100 trying response.
		if (sip->sip_request->rq_method == sip_method_ack || sip->sip_request->rq_method == sip_method_cancel ||
Mickaël Turnel's avatar
Mickaël Turnel committed
739 740
			sip->sip_request->rq_method == sip_method_bye // same as in the sofia auth modules
			) {
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
			/*ack and cancel shall never be challenged according to the RFC.*/
			return;
		}

		// handle account creation request (test feature only)
		if (mTestAccountsEnabled && handleTestAccountCreationRequests(ev)) {
			ev->reply(200, "Test account created", SIPTAG_SERVER_STR(getAgent()->getServerString()), SIPTAG_CONTACT(sip->sip_contact), SIPTAG_EXPIRES_STR("0"), TAG_END());
			return;
		}

		// Check trusted peer
		if (isTrustedPeer(ev))
			return;

		// Check for auth module for this domain, this will also tell us if this domain is allowed (auth-domains config
		// item)
		const char *fromDomain = sip->sip_from->a_url[0].url_host;
		if (fromDomain && strcmp(fromDomain, "anonymous.invalid") == 0) {
			ppi = sip_p_preferred_identity(sip);
			if (ppi)
				fromDomain = ppi->ppid_url->url_host;
			else
				LOGD("There is no p-preferred-identity");
		}
765

766 767 768 769 770 771 772 773 774
		auth_mod_t *am = findAuthModule(fromDomain);
		if (am == NULL) {
			LOGI("Unknown domain [%s]", fromDomain);
			SLOGUE << "Registration failure, domain is forbidden: " << fromDomain;
			ev->reply(403, "Domain forbidden", SIPTAG_SERVER_STR(getAgent()->getServerString()), TAG_END());
			return;
		}

		// check if TLS client certificate provides sufficent authentication for this request.
775
		if (handleTlsClientAuthentication(ev))
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
			return;

		// Check for the existence of username, which is required for proceeding with digest authentication in flexisip.
		// Reject if absent.
		if (sip->sip_from->a_url->url_user == NULL) {
			LOGI("From has no username, cannot authenticate.");
			SLOGUE << "Registration failure, username not found: " << url_as_string(ms->getHome(), sip->sip_from->a_url);
			ev->reply(403, "Username must be provided", SIPTAG_SERVER_STR(getAgent()->getServerString()), TAG_END());
			return;
		}

		// Create incoming transaction if not already exists
		// Necessary in qop=auth to prevent nonce count chaos
		// with retransmissions.
		ev->createIncomingTransaction();

		auth_status_t *as;
		as = auth_status_new(ms->getHome());
		as->as_method = sip->sip_request->rq_method_name;
		as->as_source = msg_addrinfo(ms->getMsg());
		as->as_user_uri = ppi ? ppi->ppid_url : sip->sip_from->a_url;
		as->as_realm = as->as_user_uri->url_host;
		as->as_display = sip->sip_from->a_display;
		if (sip->sip_payload)
			as->as_body = sip->sip_payload->pl_data, as->as_bodylen = sip->sip_payload->pl_len;

802
		AuthenticationListener *listener = new AuthenticationListener(this, ev);
803 804
		listener->mImmediateRetrievePass = mImmediateRetrievePassword;
		listener->mNo403 = mNo403Expr->eval(ev->getSip());
805
		listener->mAlgoUsed = mAlgorithms;
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
		as->as_magic = mCurrentAuthOp = listener;

		// Attention: the auth_mod_verify method should not send by itself any message but
		// return after having set the as status and phrase.
		// Another point in asynchronous mode is that the asynchronous callbacks MUST be called
		// AFTER the nta_msg_treply bellow. Otherwise the as would be already destroyed.
		if (sip->sip_request->rq_method == sip_method_register) {
			auth_mod_verify(am, as, sip->sip_authorization, &mRegistrarChallenger);
		} else {
			auth_mod_verify(am, as, sip->sip_proxy_authorization, &mProxyChallenger);
		}
		if (mCurrentAuthOp) {
			/*it has not been cleared by the listener itself, so password checking is still in progress. We need to
			 * suspend the event*/
			// Send pending message, needed data will be kept as long
			// as SipEvent is held in the listener.
			ev->suspendProcessing();
		}
	}
825

826
	void onResponse(shared_ptr<ResponseSipEvent> &ev) {
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
		if (!mNewAuthOn407)
			return; /*nop*/

		shared_ptr<OutgoingTransaction> transaction = dynamic_pointer_cast<OutgoingTransaction>(ev->getOutgoingAgent());
		if (transaction == NULL)
			return;

		shared_ptr<string> proxyRealm = transaction->getProperty<string>("this_proxy_realm");
		if (proxyRealm == NULL)
			return;

		sip_t *sip = ev->getMsgSip()->getSip();
		if (sip->sip_status->st_status == 407 && sip->sip_proxy_authenticate) {
			auth_status_t *as = auth_status_new(ev->getMsgSip()->getHome());
			as->as_realm = proxyRealm.get()->c_str();
			as->as_user_uri = sip->sip_from->a_url;
			auth_mod_t *am = findAuthModule(as->as_realm);
			if (am) {
				auth_challenge_digest(am, as, &mProxyChallenger);
				mNonceStore.insert(as->as_response);
				msg_header_insert(ev->getMsgSip()->getMsg(), (msg_pub_t *)sip, (msg_header_t *)as->as_response);
			} else {
				LOGD("Authentication module for %s not found", as->as_realm);
			}
		} else {
			LOGD("not handled newauthon401");
		}
	}

	void onIdle() {
		mNonceStore.cleanExpired();
	}

	virtual bool doOnConfigStateChanged(const ConfigValue &conf, ConfigState state) {
		if (conf.getName() == "trusted-hosts" && state == ConfigState::Commited) {
			loadTrustedHosts((const ConfigStringList &)conf);
			LOGD("Trusted hosts updated");
			return true;
		} else {
			return Module::doOnConfigStateChanged(conf, state);
		}
	}
};

ModuleInfo<Authentication> Authentication::sInfo(
872 873 874 875 876 877 878 879 880 881 882 883 884 885
	"Authentication",
	"The authentication module challenges and authenticates SIP requests using two possible methods: \n"
	" * if the request is received via a TLS transport and 'require-peer-certificate' is set in transport definition "
	"in [Global] section for this transport, "
	" then the From header of the request is matched with the CN claimed by the client certificate. The CN must "
	"contain sip:user@domain or alternate name with URI=sip:user@domain"
	" corresponding to the URI in the from header for the request to be accepted. Optionnaly, the property"
	" tls-client-certificate-required-subject may contain a regular expression for additional checks to execute on certificate subjects.\n"
	" * if no TLS client based authentication can be performed, or is failed, then a SIP digest authentication is "
	"performed. The password verification is made by querying"
	" a database or a password file on disk.",
	{ "NatHelper" },
	ModuleInfoBase::ModuleOid::Authentication
);
886

887 888
Authentication::AuthenticationListener::AuthenticationListener(Authentication *module, shared_ptr<RequestSipEvent> ev)
	: mModule(module), mEv(ev), mAm(NULL), mAs(NULL), mAch(NULL), mPasswordFound(false) {
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
	memset(&mAr, '\0', sizeof(mAr)), mAr.ar_size = sizeof(mAr);
	mNo403 = false;
}

void Authentication::AuthenticationListener::setData(auth_mod_t *am, auth_status_t *as, auth_challenger_t const *ach) {
	this->mAm = am;
	this->mAs = as;
	this->mAch = ach;
}

void Authentication::AuthenticationListener::main_thread_async_response_cb(su_root_magic_t *rm, su_msg_r msg, void *u) {
	AuthenticationListener **listenerStorage = (AuthenticationListener **)su_msg_data(msg);
	AuthenticationListener *listener = *listenerStorage;
	listener->processResponse();
}

905
void Authentication::AuthenticationListener::onResult(AuthDbResult result, const vector<passwd_algo_t> &passwd) {
906 907 908
	// invoke callback on main thread (sofia-sip)
	su_msg_r mamc = SU_MSG_R_INIT;
	if (-1 == su_msg_create(mamc, su_root_task(getRoot()), su_root_task(getRoot()), main_thread_async_response_cb,
909
							sizeof(AuthenticationListener *))) {
910 911 912
		LOGF("Couldn't create auth async message");
	}

913
	string algo = "";
914 915 916 917 918 919
	AuthenticationListener **listenerStorage = (AuthenticationListener **)su_msg_data(mamc);
	*listenerStorage = this;

	switch (result) {
		case PASSWORD_FOUND:
			mResult = AuthDbResult::PASSWORD_FOUND;
920 921 922 923 924 925 926 927

			if (mAr.ar_algorithm == NULL || !strcmp(mAr.ar_algorithm, "MD5"))
				algo = "MD5";
			else if (!strcmp(mAr.ar_algorithm, "SHA-256"))
				algo = "SHA-256";
			else {
				mResult = AuthDbResult::AUTH_ERROR;
				break;
928 929
			}

930 931 932 933 934
			for (const auto &password : passwd)
				if (password.algo == algo)
					mPassword = password.pass;

			if(mPassword.empty()) {
935 936
				mResult = AuthDbResult::PASSWORD_NOT_FOUND;
			}
937

938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
			break;
		case PASSWORD_NOT_FOUND:
			mResult = AuthDbResult::PASSWORD_NOT_FOUND;
			mPassword = "";
			break;
		case AUTH_ERROR:
			/*in that case we can fallback to the cached password previously set*/
			break;
		case PENDING:
			LOGF("unhandled case PENDING");
			break;
	}
	if (-1 == su_msg_send(mamc)) {
		LOGF("Couldn't send auth async message to main thread.");
	}
}

955
void Authentication::AuthenticationListener::onResult(AuthDbResult result, const string &passwd) {
956 957 958
	// invoke callback on main thread (sofia-sip)
	su_msg_r mamc = SU_MSG_R_INIT;
	if (-1 == su_msg_create(mamc, su_root_task(getRoot()), su_root_task(getRoot()), main_thread_async_response_cb,
959
							sizeof(AuthenticationListener *))) {
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
		LOGF("Couldn't create auth async message");
	}

	AuthenticationListener **listenerStorage = (AuthenticationListener **)su_msg_data(mamc);
	*listenerStorage = this;

	switch (result) {
		case PASSWORD_FOUND:
			mResult = AuthDbResult::PASSWORD_FOUND;
			mPassword = passwd;
			break;
		case PASSWORD_NOT_FOUND:
			mResult = AuthDbResult::PASSWORD_NOT_FOUND;
			mPassword = "";
			break;
		case AUTH_ERROR:
			/*in that case we can fallback to the cached password previously set*/
			break;
		case PENDING:
			LOGF("unhandled case PENDING");
			break;
	}
	if (-1 == su_msg_send(mamc)) {
		LOGF("Couldn't send auth async message to main thread.");
	}
}

987 988 989
void Authentication::AuthenticationListener::finishForAlgorithm () {
	if ((mAlgoUsed.size() > 1) && (mAs->as_status == 401)) {
		msg_header_t* response;
990
		response = msg_header_copy(mAs->as_home, mAs->as_response);
991 992
		msg_header_remove_param((msg_common_t *)response, "algorithm=MD5");
		msg_header_replace_item(mAs->as_home, (msg_common_t *)response, "algorithm=SHA-256");
993
		mEv->reply(mAs->as_status, mAs->as_phrase, SIPTAG_HEADER((const sip_header_t *)mAs->as_info),
994 995 996
				SIPTAG_HEADER((const sip_header_t *)response),
				SIPTAG_HEADER((const sip_header_t *)mAs->as_response),
				SIPTAG_SERVER_STR(getAgent()->getServerString()), TAG_END());
997 998
	} else {
		mEv->reply(mAs->as_status, mAs->as_phrase, SIPTAG_HEADER((const sip_header_t *)mAs->as_info),
999 1000
				SIPTAG_HEADER((const sip_header_t *)mAs->as_response),
				SIPTAG_SERVER_STR(getAgent()->getServerString()), TAG_END());
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
	}
}

/**
 * return true if the event is terminated
 */
void Authentication::AuthenticationListener::finish() {
	const shared_ptr<MsgSip> &ms = mEv->getMsgSip();
	const sip_t *sip = ms->getSip();
	if (mAs->as_status) {
		if (mAs->as_status != 401 && mAs->as_status != 407) {
			auto log = make_shared<AuthLog>(sip, mPasswordFound);
			log->setStatusCode(mAs->as_status, mAs->as_phrase);
			log->setCompleted();
			mEv->setEventLog(log);
		}
1017
		finishForAlgorithm();
1018 1019 1020 1021
	} else {
		// Success
		if (sip->sip_request->rq_method == sip_method_register) {
			msg_auth_t *au =
1022
			ModuleToolbox::findAuthorizationForRealm(ms->getHome(), sip->sip_authorization, mAs->as_realm);
1023 1024 1025
			if (au)
				msg_header_remove(ms->getMsg(), (msg_pub_t *)sip, (msg_header_t *)au);
		} else {
1026
			msg_auth_t *au = ModuleToolbox::findAuthorizationForRealm(ms->getHome(), sip->sip_proxy_authorization, mAs->as_realm);
1027 1028
			if(au->au_next)
				msg_header_remove(ms->getMsg(), (msg_pub_t *)sip, (msg_header_t *)au->au_next);
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
			if (au)
				msg_header_remove(ms->getMsg(), (msg_pub_t *)sip, (msg_header_t *)au);
		}
		if (mEv->isSuspended()) {
			// The event is re-injected
			getAgent()->injectRequestEvent(mEv);
		}
	}
	if (mModule->mCurrentAuthOp == this) {
		mModule->mCurrentAuthOp = NULL;
	}
	delete this;
}

1043
void Authentication::AuthenticationListener::finishVerifyAlgos(const vector<passwd_algo_t> &pass) {
1044 1045 1046
	mAlgoUsed.remove_if([&pass](string algo) {
		bool found = false;

1047
		for (const auto &password : pass) {
1048 1049 1050 1051
			if (password.algo == algo) {
				found = true;
				break;
			}
1052
		}
Mickaël Turnel's avatar
Mickaël Turnel committed
1053

1054 1055 1056 1057
		return !found;
	});

	finish();
1058
}
Mickaël Turnel's avatar
Mickaël Turnel committed
1059

1060
int Authentication::AuthenticationListener::checkPasswordMd5(const char *passwd){
1061 1062 1063 1064 1065 1066 1067 1068 1069
	char const *a1;
	auth_hexmd5_t a1buf, response;

	if (passwd && passwd[0] == '\0')
		passwd = NULL;

	if (passwd) {
		mPasswordFound = true;
		++*getModule()->mCountPassFound;
Ghislain MARY's avatar
Ghislain MARY committed
1070
		strncpy(a1buf, passwd, sizeof(a1buf) - 1); // remove trailing NULL character
1071
		a1 = a1buf;
1072 1073 1074 1075 1076 1077 1078
	} else {
		++*getModule()->mCountPassNotFound;
		auth_digest_a1(&mAr, a1buf, "xyzzy"), a1 = a1buf;
	}

	if (mAr.ar_md5sess)
		auth_digest_a1sess(&mAr, a1buf, a1), a1 = a1buf;
Mickaël Turnel's avatar
Mickaël Turnel committed
1079

1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
	auth_digest_response(&mAr, response, a1, mAs->as_method, mAs->as_body, mAs->as_bodylen);
	return !passwd || strcmp(response, mAr.ar_response);
}

int Authentication::AuthenticationListener::checkPasswordForAlgorithm(const char *passwd) {
	if ((mAr.ar_algorithm == NULL) || (!strcmp(mAr.ar_algorithm, "MD5"))) {
		return checkPasswordMd5(passwd);
	} else if (!strcmp(mAr.ar_algorithm, "SHA-256")) {
		char a1[65];
		char response[65];

		if (passwd && passwd[0] == '\0')
			passwd = NULL;

		if (passwd) {
			mPasswordFound = true;
			++*getModule()->mCountPassFound;
Ghislain MARY's avatar
Ghislain MARY committed
1097
			strncpy(a1, passwd, sizeof(a1) - 1); // remove trailing NULL character
1098 1099 1100 1101 1102
		} else {
			++*getModule()->mCountPassNotFound;
			auth_digest_a1_for_algorithm(&mAr, "xyzzy", a1);
		}

1103
		if (mAr.ar_md5sess)
1104
			auth_digest_a1sess_for_algorithm(&mAr, a1);
1105

1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
		auth_digest_response_for_algorithm(&mAr, mAs->as_method, mAs->as_body, mAs->as_bodylen, response, a1);
		return !passwd || strcmp(response, mAr.ar_response);
	}
	return -1;
}

/**
 * NULL if passwd not found.
 */
void Authentication::AuthenticationListener::checkPassword(const char *passwd) {
	if (checkPasswordForAlgorithm(passwd)) {
		if (mAm->am_forbidden && !mNo403) {
			mAs->as_status = 403, mAs->as_phrase = "Forbidden";
			mAs->as_response = NULL;
			mAs->as_blacklist = mAm->am_blacklist;
		} else {
			auth_challenge_digest(mAm, mAs, mAch);
			getModule()->mNonceStore.insert(mAs->as_response);
			mAs->as_blacklist = mAm->am_blacklist;
		}
		if (passwd) {
			SLOGUE << "Registration failure, password did not match";
			LOGD("auth_method_digest: password '%s' did not match", passwd);
		} else {
			SLOGUE << "Registration failure, no password";
			LOGD("auth_method_digest: no password");
		}

		return;
	}

	// assert(apw);
	mAs->as_user = mAr.ar_username;
	mAs->as_anonymous = false;

	if (mAm->am_nextnonce || mAm->am_mutual)
		auth_info_digest(mAm, mAs, mAch);

	if (mAm->am_challenge)
		auth_challenge_digest(mAm, mAs, mAch);

	LOGD("auth_method_digest: successful authentication");

	mAs->as_status = 0; /* Successful authentication! */
	mAs->as_phrase = "";
}

void Authentication::AuthenticationListener::processResponse() {
	switch (mResult) {
		case PASSWORD_FOUND:
		case PASSWORD_NOT_FOUND:
			checkPassword(mPassword.c_str());
			finish();
			break;
		case AUTH_ERROR:
			onError();
			break;
		default:
			LOGE("Unhandled asynchronous response %u", mResult);
			onError();
	}
}

void Authentication::AuthenticationListener::onError() {
	if (!mAs->as_status) {
		mAs->as_status = 500, mAs->as_phrase = "Internal error";
		mAs->as_response = NULL;
	}
	finish();
}

#define PA "Authorization missing "

/** Verify digest authentication */
void Authentication::flexisip_auth_check_digest(auth_mod_t *am, auth_status_t *as, auth_response_t *ar,
1181
												auth_challenger_t const *ach) {
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195

	AuthenticationListener *listener = (AuthenticationListener *)as->as_magic;

	if (am == NULL || as == NULL || ar == NULL || ach == NULL) {
		if (as) {
			as->as_status = 500, as->as_phrase = "Internal Server Error";
			as->as_response = NULL;
		}
		listener->finish();
		return;
	}

	char const *phrase = "Bad authorization ";
	if ((!ar->ar_username && (phrase = PA "username")) || (!ar->ar_nonce && (phrase = PA "nonce")) ||
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
		(!listener->mModule->mDisableQOPAuth && !ar->ar_nc && (phrase = PA "nonce count")) ||
		(!ar->ar_uri && (phrase = PA "URI")) || (!ar->ar_response && (phrase = PA "response")) ||
		/* (!ar->ar_opaque && (phrase = PA "opaque")) || */
		/* Check for qop */
		(ar->ar_qop &&
		((ar->ar_auth && !strcasecmp(ar->ar_qop, "auth") && !strcasecmp(ar->ar_qop, "\"auth\"")) ||
		(ar->ar_auth_int && !strcasecmp(ar->ar_qop, "auth-int") && !strcasecmp(ar->ar_qop, "\"auth-int\""))) &&
		(phrase = PA "has invalid qop"))) {
			// assert(phrase);
			LOGD("auth_method_digest: 400 %s", phrase);
			as->as_status = 400, as->as_phrase = phrase;
			as->as_response = NULL;
			listener->finish();
			return;
		}
1211 1212 1213 1214

	if (!ar->ar_username || !as->as_user_uri->url_user || !ar->ar_realm || !as->as_user_uri->url_host) {
		as->as_status = 403, as->as_phrase = "Authentication info missing";
		SLOGUE << "Registration failure, authentication info are missing: usernames " <<
1215
		ar->ar_username << "/" << as->as_user_uri->url_user << ", hosts " << ar->ar_realm << "/" << as->as_user_uri->url_host;
1216
		LOGD("from and authentication usernames [%s/%s] or from and authentication hosts [%s/%s] empty",
1217
			ar->ar_username, as->as_user_uri->url_user, ar->ar_realm, as->as_user_uri->url_host);
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
		as->as_response = NULL;
		listener->finish();
		return;
	}

	Authentication *module = listener->getModule();
	msg_time_t now = msg_now();
	if (as->as_nonce_issued == 0 /* Already validated nonce */ && auth_validate_digest_nonce(am, as, ar, now) < 0) {
		as->as_blacklist = am->am_blacklist;
		auth_challenge_digest(am, as, ach);
		module->mNonceStore.insert(as->as_response);
		listener->finish();
		return;
	}

	if (as->as_stale) {
		auth_challenge_digest(am, as, ach);
		module->mNonceStore.insert(as->as_response);
		listener->finish();
		return;
	}

	if (!listener->mModule->mDisableQOPAuth) {
		int pnc = module->mNonceStore.getNc(ar->ar_nonce);
		int nnc = (int)strtoul(ar->ar_nc, NULL, 16);
		if (pnc == -1 || pnc >= nnc) {
			LOGE("Bad nonce count %d -> %d for %s", pnc, nnc, ar->ar_nonce);
			as->as_blacklist = am->am_blacklist;
			auth_challenge_digest(am, as, ach);
			module->mNonceStore.insert(as->as_response);
			listener->finish();
			return;
		} else {
			module->mNonceStore.updateNc(ar->ar_nonce, nnc);
		}
	}

	AuthDbBackend::get()->getPassword(as->as_user_uri->url_user, as->as_user_uri->url_host, ar->ar_username, listener);
}

/** Authenticate a request with @b Digest authentication scheme.
 */
void Authentication::flexisip_auth_method_digest(auth_mod_t *am, auth_status_t *as, msg_auth_t *au,
1261
												auth_challenger_t const *ach) {
1262 1263 1264 1265 1266 1267
	AuthenticationListener *listener = (AuthenticationListener *)as->as_magic;
	listener->setData(am, as, ach);

	as->as_allow = as->as_allow || auth_allow_check(am, as) == 0;

	if (as->as_realm) {
1268 1269 1270 1271
		/* Workaround for old linphone client that don't check whether algorithm is MD5 or SHA256.
		 * They then answer for both, but the first one for SHA256 is of course wrong.
		 * We workaround by selecting the second digest response.
		 */
1272 1273 1274 1275 1276
		if (au && au->au_next) {
			auth_response_t r;
			memset(&r, 0, sizeof(r));
			r.ar_size = sizeof(r);
			auth_digest_response_get(as->as_home, &r, au->au_next->au_params);
1277

1278
			if (r.ar_algorithm == NULL || !strcasecmp(r.ar_algorithm, "MD5")) {
1279
				au = au->au_next;
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
			}
		}
		/* After auth_digest_credentials, there is no more au->au_next. */
		au = auth_digest_credentials(au, as->as_realm, am->am_opaque);
	} else
		au = NULL;

	if (as->as_allow) {
		LOGD("%s: allow unauthenticated %s", __func__, as->as_method);
		as->as_status = 0, as->as_phrase = NULL;
		as->as_match = (msg_header_t *)au;
		return;
	}

	if (au) {
		SLOGD << "Searching for auth digest response for this proxy";
		msg_auth_t *matched_au = ModuleToolbox::findAuthorizationForRealm(as->as_home, au, as->as_realm);
		if (matched_au)
			au = matched_au;
		auth_digest_response_get(as->as_home, &listener->mAr, au->au_params);
		SLOGD << "Using auth digest response for realm " << listener->mAr.ar_realm;
		as->as_match = (msg_header_t *)au;
		flexisip_auth_check_digest(am, as, &listener->mAr, ach);
	} else {
		/* There was no realm or credentials, send challenge */
		SLOGD << __func__ << ": no credentials matched realm or no realm";
		auth_challenge_digest(am, as, ach);
		listener->getModule()->mNonceStore.insert(as->as_response);

		// Retrieve the password in the hope it will be in cache when the remote UAC
		// sends back its request; this time with the expected authentication credentials.
		if (listener->mImmediateRetrievePass) {
			SLOGD << "Searching for " << as->as_user_uri->url_user
1313
			<< " password to have it when the authenticated request comes";
1314 1315
			AuthDbBackend::get()->getPassword(as->as_user_uri->url_user, as->as_user_uri->url_host, as->as_user_uri->url_user, NULL);
			//AuthDbBackend::get()->getPasswordForAlgo(as->as_user_uri->url_user, as->as_user_uri->url_host, as->as_user_uri->url_user, NULL, listener);
1316
		}
1317
		listener->finish();
1318 1319 1320
		return;
	}
}