summaryrefslogtreecommitdiff
path: root/src/modules/extra/m_ldap.cpp
blob: 58dfc8db46da60132f52d3e229159fae2d7fff79 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
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
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
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
313
314
315
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
/*
 * InspIRCd -- Internet Relay Chat Daemon
 *
 *   Copyright (C) 2020 Joel Sing <joel@sing.id.au>
 *   Copyright (C) 2019 linuxdaemon <linuxdaemon.irc@gmail.com>
 *   Copyright (C) 2016-2020 Sadie Powell <sadie@witchery.services>
 *   Copyright (C) 2014, 2016 Attila Molnar <attilamolnar@hush.com>
 *   Copyright (C) 2013-2016 Adam <Adam@anope.org>
 *
 * This file is part of InspIRCd.  InspIRCd 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, version 2.
 *
 * 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/>.
 */

/// $LinkerFlags: -llber -lldap_r

/// $PackageInfo: require_system("arch") libldap
/// $PackageInfo: require_system("centos") openldap-devel
/// $PackageInfo: require_system("debian") libldap2-dev
/// $PackageInfo: require_system("ubuntu") libldap2-dev

#include "inspircd.h"
#include "modules/ldap.h"

// Ignore OpenLDAP deprecation warnings on OS X Yosemite and newer.
#if defined __APPLE__
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif

#include <ldap.h>

#ifdef __APPLE__
# pragma GCC diagnostic pop
#endif

#ifdef _WIN32
# pragma comment(lib, "libldap_r.lib")
# pragma comment(lib, "liblber.lib")
#endif

class LDAPService;

class LDAPRequest
{
 public:
	LDAPService* service;
	LDAPInterface* inter;
	LDAPMessage* message; /* message returned by ldap_ */
	LDAPResult* result; /* final result */
	struct timeval tv;
	QueryType type;

	LDAPRequest(LDAPService* s, LDAPInterface* i)
		: service(s)
		, inter(i)
		, message(NULL)
		, result(NULL)
	{
		type = QUERY_UNKNOWN;
		tv.tv_sec = 0;
		tv.tv_usec = 100000;
	}

	virtual ~LDAPRequest()
	{
		delete result;
		if (message != NULL)
			ldap_msgfree(message);
	}

	virtual int run() = 0;
	virtual std::string info() = 0;
};

class LDAPBind : public LDAPRequest
{
	std::string who, pass;

 public:
	LDAPBind(LDAPService* s, LDAPInterface* i, const std::string& w, const std::string& p)
		: LDAPRequest(s, i)
		, who(w)
		, pass(p)
	{
		type = QUERY_BIND;
	}

	int run() CXX11_OVERRIDE;
	std::string info() CXX11_OVERRIDE;
};

class LDAPSearch : public LDAPRequest
{
	std::string base;
	int searchscope;
	std::string filter;

 public:
	LDAPSearch(LDAPService* s, LDAPInterface* i, const std::string& b, int se, const std::string& f)
		: LDAPRequest(s, i)
		, base(b)
		, searchscope(se)
		, filter(f)
	{
		type = QUERY_SEARCH;
	}

	int run() CXX11_OVERRIDE;
	std::string info() CXX11_OVERRIDE;
};

class LDAPAdd : public LDAPRequest
{
	std::string dn;
	LDAPMods attributes;

 public:
	LDAPAdd(LDAPService* s, LDAPInterface* i, const std::string& d, const LDAPMods& attr)
		: LDAPRequest(s, i)
		, dn(d)
		, attributes(attr)
	{
		type = QUERY_ADD;
	}

	int run() CXX11_OVERRIDE;
	std::string info() CXX11_OVERRIDE;
};

class LDAPDel : public LDAPRequest
{
	std::string dn;

 public:
	LDAPDel(LDAPService* s, LDAPInterface* i, const std::string& d)
		: LDAPRequest(s, i)
		, dn(d)
	{
		type = QUERY_DELETE;
	}

	int run() CXX11_OVERRIDE;
	std::string info() CXX11_OVERRIDE;
};

class LDAPModify : public LDAPRequest
{
	std::string base;
	LDAPMods attributes;

 public:
	LDAPModify(LDAPService* s, LDAPInterface* i, const std::string& b, const LDAPMods& attr)
		: LDAPRequest(s, i)
		, base(b)
		, attributes(attr)
	{
		type = QUERY_MODIFY;
	}

	int run() CXX11_OVERRIDE;
	std::string info() CXX11_OVERRIDE;
};

class LDAPCompare : public LDAPRequest
{
	std::string dn, attr, val;

 public:
	LDAPCompare(LDAPService* s, LDAPInterface* i, const std::string& d, const std::string& a, const std::string& v)
		: LDAPRequest(s, i)
		, dn(d)
		, attr(a)
		, val(v)
	{
		type = QUERY_COMPARE;
	}

	int run() CXX11_OVERRIDE;
	std::string info() CXX11_OVERRIDE;
};

class LDAPService : public LDAPProvider, public SocketThread
{
	LDAP* con;
	reference<ConfigTag> config;
	time_t last_connect;
	int searchscope;
	time_t timeout;

 public:
	static LDAPMod** BuildMods(const LDAPMods& attributes)
	{
		LDAPMod** mods = new LDAPMod*[attributes.size() + 1];
		memset(mods, 0, sizeof(LDAPMod*) * (attributes.size() + 1));
		for (unsigned int x = 0; x < attributes.size(); ++x)
		{
			const LDAPModification& l = attributes[x];
			LDAPMod* mod = new LDAPMod;
			mods[x] = mod;

			if (l.op == LDAPModification::LDAP_ADD)
				mod->mod_op = LDAP_MOD_ADD;
			else if (l.op == LDAPModification::LDAP_DEL)
				mod->mod_op = LDAP_MOD_DELETE;
			else if (l.op == LDAPModification::LDAP_REPLACE)
				mod->mod_op = LDAP_MOD_REPLACE;
			else if (l.op != 0)
			{
				FreeMods(mods);
				throw LDAPException("Unknown LDAP operation");
			}
			mod->mod_type = strdup(l.name.c_str());
			mod->mod_values = new char*[l.values.size() + 1];
			memset(mod->mod_values, 0, sizeof(char*) * (l.values.size() + 1));
			for (unsigned int j = 0, c = 0; j < l.values.size(); ++j)
				if (!l.values[j].empty())
					mod->mod_values[c++] = strdup(l.values[j].c_str());
		}
		return mods;
	}

	static void FreeMods(LDAPMod** mods)
	{
		for (unsigned int i = 0; mods[i] != NULL; ++i)
		{
			LDAPMod* mod = mods[i];
			if (mod->mod_type != NULL)
				free(mod->mod_type);
			if (mod->mod_values != NULL)
			{
				for (unsigned int j = 0; mod->mod_values[j] != NULL; ++j)
					free(mod->mod_values[j]);
				delete[] mod->mod_values;
			}
		}
		delete[] mods;
	}

 private:
	void Reconnect()
	{
		// Only try one connect a minute. It is an expensive blocking operation
		if (last_connect > ServerInstance->Time() - 60)
			throw LDAPException("Unable to connect to LDAP service " + this->name + ": reconnecting too fast");
		last_connect = ServerInstance->Time();

		ldap_unbind_ext(this->con, NULL, NULL);
		Connect();
	}

	int SetOption(int option, const void* value)
	{
		int ret = ldap_set_option(this->con, option, value);
		if (ret != LDAP_OPT_SUCCESS)
		{
			ldap_unbind_ext(this->con, NULL, NULL);
			this->con = NULL;
		}
		return ret;
	}

	void QueueRequest(LDAPRequest* r)
	{
		this->LockQueue();
		this->queries.push_back(r);
		this->UnlockQueueWakeup();
	}

 public:
	typedef std::vector<LDAPRequest*> query_queue;
	query_queue queries, results;
	Mutex process_mutex; /* held when processing requests not in either queue */

	LDAPService(Module* c, ConfigTag* tag)
		: LDAPProvider(c, "LDAP/" + tag->getString("id"))
		, con(NULL), config(tag), last_connect(0)
	{
		std::string scope = config->getString("searchscope");
		if (stdalgo::string::equalsci(scope, "base"))
			searchscope = LDAP_SCOPE_BASE;
		else if (stdalgo::string::equalsci(scope, "onelevel"))
			searchscope = LDAP_SCOPE_ONELEVEL;
		else
			searchscope = LDAP_SCOPE_SUBTREE;
		timeout = config->getDuration("timeout", 5);

		Connect();
	}

	~LDAPService()
	{
		this->LockQueue();

		for (unsigned int i = 0; i < this->queries.size(); ++i)
		{
			LDAPRequest* req = this->queries[i];

			/* queries have no results yet */
			req->result = new LDAPResult();
			req->result->type = req->type;
			req->result->error = "LDAP Interface is going away";
			req->inter->OnError(*req->result);

			delete req;
		}
		this->queries.clear();

		for (unsigned int i = 0; i < this->results.size(); ++i)
		{
			LDAPRequest* req = this->results[i];

			/* even though this may have already finished successfully we return that it didn't */
			req->result->error = "LDAP Interface is going away";
			req->inter->OnError(*req->result);

			delete req;
		}
		this->results.clear();

		this->UnlockQueue();

		ldap_unbind_ext(this->con, NULL, NULL);
	}

	void Connect()
	{
		std::string server = config->getString("server");
		int i = ldap_initialize(&this->con, server.c_str());
		if (i != LDAP_SUCCESS)
			throw LDAPException("Unable to connect to LDAP service " + this->name + ": " + ldap_err2string(i));

		const int version = LDAP_VERSION3;
		i = SetOption(LDAP_OPT_PROTOCOL_VERSION, &version);
		if (i != LDAP_OPT_SUCCESS)
			throw LDAPException("Unable to set protocol version for " + this->name + ": " + ldap_err2string(i));

		const struct timeval tv = { 0, 0 };
		i = SetOption(LDAP_OPT_NETWORK_TIMEOUT, &tv);
		if (i != LDAP_OPT_SUCCESS)
			throw LDAPException("Unable to set timeout for " + this->name + ": " + ldap_err2string(i));
	}

	void BindAsManager(LDAPInterface* i) CXX11_OVERRIDE
	{
		std::string binddn = config->getString("binddn");
		std::string bindauth = config->getString("bindauth");
		this->Bind(i, binddn, bindauth);
	}

	void Bind(LDAPInterface* i, const std::string& who, const std::string& pass) CXX11_OVERRIDE
	{
		LDAPBind* b = new LDAPBind(this, i, who, pass);
		QueueRequest(b);
	}

	void Search(LDAPInterface* i, const std::string& base, const std::string& filter) CXX11_OVERRIDE
	{
		if (i == NULL)
			throw LDAPException("No interface");

		LDAPSearch* s = new LDAPSearch(this, i, base, searchscope, filter);
		QueueRequest(s);
	}

	void Add(LDAPInterface* i, const std::string& dn, LDAPMods& attributes) CXX11_OVERRIDE
	{
		LDAPAdd* add = new LDAPAdd(this, i, dn, attributes);
		QueueRequest(add);
	}

	void Del(LDAPInterface* i, const std::string& dn) CXX11_OVERRIDE
	{
		LDAPDel* del = new LDAPDel(this, i, dn);
		QueueRequest(del);
	}

	void Modify(LDAPInterface* i, const std::string& base, LDAPMods& attributes) CXX11_OVERRIDE
	{
		LDAPModify* mod = new LDAPModify(this, i, base, attributes);
		QueueRequest(mod);
	}

	void Compare(LDAPInterface* i, const std::string& dn, const std::string& attr, const std::string& val) CXX11_OVERRIDE
	{
		LDAPCompare* comp = new LDAPCompare(this, i, dn, attr, val);
		QueueRequest(comp);
	}

 private:
	void BuildReply(int res, LDAPRequest* req)
	{
		LDAPResult* ldap_result = req->result = new LDAPResult();
		req->result->type = req->type;

		if (res != LDAP_SUCCESS)
		{
			ldap_result->error = InspIRCd::Format("%s (%s)", ldap_err2string(res), req->info().c_str());
			return;
		}

		if (req->message == NULL)
		{
			return;
		}

		/* a search result */

		for (LDAPMessage* cur = ldap_first_message(this->con, req->message); cur; cur = ldap_next_message(this->con, cur))
		{
			LDAPAttributes attributes;

			char* dn = ldap_get_dn(this->con, cur);
			if (dn != NULL)
			{
				attributes["dn"].push_back(dn);
				ldap_memfree(dn);
				dn = NULL;
			}

			BerElement* ber = NULL;

			for (char* attr = ldap_first_attribute(this->con, cur, &ber); attr; attr = ldap_next_attribute(this->con, cur, ber))
			{
				berval** vals = ldap_get_values_len(this->con, cur, attr);
				int count = ldap_count_values_len(vals);

				std::vector<std::string> attrs;
				for (int j = 0; j < count; ++j)
					attrs.push_back(vals[j]->bv_val);
				attributes[attr] = attrs;

				ldap_value_free_len(vals);
				ldap_memfree(attr);
			}
			if (ber != NULL)
				ber_free(ber, 0);

			ldap_result->messages.push_back(attributes);
		}
	}

	void SendRequests()
	{
		process_mutex.Lock();

		query_queue q;
		this->LockQueue();
		queries.swap(q);
		this->UnlockQueue();

		if (q.empty())
		{
			process_mutex.Unlock();
			return;
		}

		for (unsigned int i = 0; i < q.size(); ++i)
		{
			LDAPRequest* req = q[i];
			int ret = req->run();

			if (ret == LDAP_SERVER_DOWN || ret == LDAP_TIMEOUT)
			{
				/* try again */
				try
				{
					Reconnect();
				}
				catch (const LDAPException &)
				{
				}

				ret = req->run();
			}

			BuildReply(ret, req);

			this->LockQueue();
			this->results.push_back(req);
			this->UnlockQueue();
		}

		this->NotifyParent();

		process_mutex.Unlock();
	}

 public:
	void Run() CXX11_OVERRIDE
	{
		while (!this->GetExitFlag())
		{
			this->LockQueue();
			if (this->queries.empty())
				this->WaitForQueue();
			this->UnlockQueue();

			SendRequests();
		}
	}

	void OnNotify() CXX11_OVERRIDE
	{
		query_queue r;

		this->LockQueue();
		this->results.swap(r);
		this->UnlockQueue();

		for (unsigned int i = 0; i < r.size(); ++i)
		{
			LDAPRequest* req = r[i];
			LDAPInterface* li = req->inter;
			LDAPResult* res = req->result;

			if (!res->error.empty())
				li->OnError(*res);
			else
				li->OnResult(*res);

			delete req;
		}
	}

	LDAP* GetConnection()
	{
		return con;
	}
};

class ModuleLDAP : public Module
{
	typedef insp::flat_map<std::string, LDAPService*> ServiceMap;
	ServiceMap LDAPServices;

 public:
	void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
	{
		ServiceMap conns;

		ConfigTagList tags = ServerInstance->Config->ConfTags("database");
		for (ConfigIter i = tags.first; i != tags.second; i++)
		{
			const reference<ConfigTag>& tag = i->second;

			if (!stdalgo::string::equalsci(tag->getString("module"), "ldap"))
				continue;

			std::string id = tag->getString("id");

			ServiceMap::iterator curr = LDAPServices.find(id);
			if (curr == LDAPServices.end())
			{
				LDAPService* conn = new LDAPService(this, tag);
				conns[id] = conn;

				ServerInstance->Modules->AddService(*conn);
				ServerInstance->Threads.Start(conn);
			}
			else
			{
				conns.insert(*curr);
				LDAPServices.erase(curr);
			}
		}

		for (ServiceMap::iterator i = LDAPServices.begin(); i != LDAPServices.end(); ++i)
		{
			LDAPService* conn = i->second;
			ServerInstance->Modules->DelService(*conn);
			conn->join();
			conn->OnNotify();
			delete conn;
		}

		LDAPServices.swap(conns);
	}

	void OnUnloadModule(Module* m) CXX11_OVERRIDE
	{
		for (ServiceMap::iterator it = this->LDAPServices.begin(); it != this->LDAPServices.end(); ++it)
		{
			LDAPService* s = it->second;

			s->process_mutex.Lock();
			s->LockQueue();

			for (unsigned int i = s->queries.size(); i > 0; --i)
			{
				LDAPRequest* req = s->queries[i - 1];
				LDAPInterface* li = req->inter;

				if (li->creator == m)
				{
					s->queries.erase(s->queries.begin() + i - 1);
					delete req;
				}
			}

			for (unsigned int i = s->results.size(); i > 0; --i)
			{
				LDAPRequest* req = s->results[i - 1];
				LDAPInterface* li = req->inter;

				if (li->creator == m)
				{
					s->results.erase(s->results.begin() + i - 1);
					delete req;
				}
			}

			s->UnlockQueue();
			s->process_mutex.Unlock();
		}
	}

	~ModuleLDAP()
	{
		for (ServiceMap::iterator i = LDAPServices.begin(); i != LDAPServices.end(); ++i)
		{
			LDAPService* conn = i->second;
			conn->join();
			conn->OnNotify();
			delete conn;
		}
	}

	Version GetVersion() CXX11_OVERRIDE
	{
		return Version("Provides the ability for LDAP modules to query a LDAP directory.", VF_VENDOR);
	}
};

int LDAPBind::run()
{
	berval cred;
	cred.bv_val = strdup(pass.c_str());
	cred.bv_len = pass.length();

	int i = ldap_sasl_bind_s(service->GetConnection(), who.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);

	free(cred.bv_val);

	return i;
}

std::string LDAPBind::info()
{
	return "bind dn=" + who;
}

int LDAPSearch::run()
{
	return ldap_search_ext_s(service->GetConnection(), base.c_str(), searchscope, filter.c_str(), NULL, 0, NULL, NULL, &tv, 0, &message);
}

std::string LDAPSearch::info()
{
	return "search base=" + base + " filter=" + filter;
}

int LDAPAdd::run()
{
	LDAPMod** mods = LDAPService::BuildMods(attributes);
	int i = ldap_add_ext_s(service->GetConnection(), dn.c_str(), mods, NULL, NULL);
	LDAPService::FreeMods(mods);
	return i;
}

std::string LDAPAdd::info()
{
	return "add dn=" + dn;
}

int LDAPDel::run()
{
	return ldap_delete_ext_s(service->GetConnection(), dn.c_str(), NULL, NULL);
}

std::string LDAPDel::info()
{
	return "del dn=" + dn;
}

int LDAPModify::run()
{
	LDAPMod** mods = LDAPService::BuildMods(attributes);
	int i = ldap_modify_ext_s(service->GetConnection(), base.c_str(), mods, NULL, NULL);
	LDAPService::FreeMods(mods);
	return i;
}

std::string LDAPModify::info()
{
	return "modify base=" + base;
}

int LDAPCompare::run()
{
	berval cred;
	cred.bv_val = strdup(val.c_str());
	cred.bv_len = val.length();

	int ret = ldap_compare_ext_s(service->GetConnection(), dn.c_str(), attr.c_str(), &cred, NULL, NULL);

	free(cred.bv_val);

	return ret;
}

std::string LDAPCompare::info()
{
	return "compare dn=" + dn + " attr=" + attr;
}

MODULE_INIT(ModuleLDAP)