]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ldapauth.cpp
5d71e7389b6efb6b1c7619c6bd1c2cfbb5fc929e
[user/henk/code/inspircd.git] / src / modules / extra / m_ldapauth.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2011 Pierre Carrier <pierre@spotify.com>
5  *   Copyright (C) 2009-2010 Robin Burchell <robin+git@viroteck.net>
6  *   Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
7  *   Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
8  *   Copyright (C) 2008 Craig Edwards <craigedwards@brainbox.cc>
9  *   Copyright (C) 2008 Dennis Friis <peavey@inspircd.org>
10  *   Copyright (C) 2007 Carsten Valdemar Munk <carsten.munk+inspircd@gmail.com>
11  *
12  * This file is part of InspIRCd.  InspIRCd is free software: you can
13  * redistribute it and/or modify it under the terms of the GNU General Public
14  * License as published by the Free Software Foundation, version 2.
15  *
16  * This program is distributed in the hope that it will be useful, but WITHOUT
17  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
19  * details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23  */
24
25
26 #include "inspircd.h"
27 #include "users.h"
28 #include "channels.h"
29 #include "modules.h"
30
31 #include <ldap.h>
32
33 #ifdef WINDOWS
34 # pragma comment(lib, "ldap.lib")
35 # pragma comment(lib, "lber.lib")
36 #endif
37
38 /* $ModDesc: Allow/Deny connections based upon answer from LDAP server */
39 /* $LinkerFlags: -lldap */
40
41 class ModuleLDAPAuth : public Module
42 {
43         LocalIntExt ldapAuthed;
44         std::string base;
45         std::string attribute;
46         std::string ldapserver;
47         std::string allowpattern;
48         std::string killreason;
49         std::string username;
50         std::string password;
51         std::vector<std::string> whitelistedcidrs;
52         int searchscope;
53         bool verbose;
54         bool useusername;
55         LDAP *conn;
56
57 public:
58         ModuleLDAPAuth() : ldapAuthed("ldapauth", this)
59         {
60                 conn = NULL;
61         }
62
63         void init()
64         {
65                 Implementation eventlist[] = { I_OnCheckReady, I_OnRehash, I_OnUserRegister };
66                 ServerInstance->Modules->Attach(eventlist, this, 3);
67                 OnRehash(NULL);
68         }
69
70         ~ModuleLDAPAuth()
71         {
72                 if (conn)
73                         ldap_unbind_ext(conn, NULL, NULL);
74         }
75
76         void OnRehash(User* user)
77         {
78                 ConfigReader Conf;
79                 whitelistedcidrs.clear();
80
81                 base                    = Conf.ReadValue("ldapauth", "baserdn", 0);
82                 attribute               = Conf.ReadValue("ldapauth", "attribute", 0);
83                 ldapserver              = Conf.ReadValue("ldapauth", "server", 0);
84                 allowpattern            = Conf.ReadValue("ldapauth", "allowpattern", 0);
85                 killreason              = Conf.ReadValue("ldapauth", "killreason", 0);
86                 std::string scope       = Conf.ReadValue("ldapauth", "searchscope", 0);
87                 username                = Conf.ReadValue("ldapauth", "binddn", 0);
88                 password                = Conf.ReadValue("ldapauth", "bindauth", 0);
89                 verbose                 = Conf.ReadFlag("ldapauth", "verbose", 0);              /* Set to true if failed connects should be reported to operators */
90                 useusername             = Conf.ReadFlag("ldapauth", "userfield", 0);
91
92                 ConfigTagList whitelisttags = ServerInstance->Config->ConfTags("ldapwhitelist");
93
94                 for (ConfigIter i = whitelisttags.first; i != whitelisttags.second; ++i)
95                 {
96                         std::string cidr = i->second->getString("cidr");
97                         if (!cidr.empty()) {
98                                 whitelistedcidrs.push_back(cidr);
99                         }
100                 }
101
102                 if (scope == "base")
103                         searchscope = LDAP_SCOPE_BASE;
104                 else if (scope == "onelevel")
105                         searchscope = LDAP_SCOPE_ONELEVEL;
106                 else searchscope = LDAP_SCOPE_SUBTREE;
107
108                 Connect();
109         }
110
111         bool Connect()
112         {
113                 if (conn != NULL)
114                         ldap_unbind_ext(conn, NULL, NULL);
115                 int res, v = LDAP_VERSION3;
116                 res = ldap_initialize(&conn, ldapserver.c_str());
117                 if (res != LDAP_SUCCESS)
118                 {
119                         if (verbose)
120                                 ServerInstance->SNO->WriteToSnoMask('c', "LDAP connection failed: %s", ldap_err2string(res));
121                         conn = NULL;
122                         return false;
123                 }
124
125                 res = ldap_set_option(conn, LDAP_OPT_PROTOCOL_VERSION, (void *)&v);
126                 if (res != LDAP_SUCCESS)
127                 {
128                         if (verbose)
129                                 ServerInstance->SNO->WriteToSnoMask('c', "LDAP set protocol to v3 failed: %s", ldap_err2string(res));
130                         ldap_unbind_ext(conn, NULL, NULL);
131                         conn = NULL;
132                         return false;
133                 }
134                 return true;
135         }
136
137         ModResult OnUserRegister(LocalUser* user)
138         {
139                 if ((!allowpattern.empty()) && (InspIRCd::Match(user->nick,allowpattern)))
140                 {
141                         ldapAuthed.set(user,1);
142                         return MOD_RES_PASSTHRU;
143                 }
144
145                 for (std::vector<std::string>::iterator i = whitelistedcidrs.begin(); i != whitelistedcidrs.end(); i++)
146                 {
147                         if (InspIRCd::MatchCIDR(user->GetIPString(), *i, ascii_case_insensitive_map))
148                         {
149                                 ldapAuthed.set(user,1);
150                                 return MOD_RES_PASSTHRU;
151                         }
152                 }
153
154                 if (!CheckCredentials(user))
155                 {
156                         ServerInstance->Users->QuitUser(user, killreason);
157                         return MOD_RES_DENY;
158                 }
159                 return MOD_RES_PASSTHRU;
160         }
161
162         bool CheckCredentials(LocalUser* user)
163         {
164                 if (conn == NULL)
165                         if (!Connect())
166                                 return false;
167
168                 if (user->password.empty())
169                 {
170                         if (verbose)
171                                 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s!%s@%s (No password provided)", user->nick.c_str(), user->ident.c_str(), user->host.c_str());
172                         return false;
173                 }
174
175                 int res;
176                 // bind anonymously if no bind DN and authentication are given in the config
177                 struct berval cred;
178                 cred.bv_val = const_cast<char*>(password.c_str());
179                 cred.bv_len = password.length();
180
181                 if ((res = ldap_sasl_bind_s(conn, username.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL)) != LDAP_SUCCESS)
182                 {
183                         if (res == LDAP_SERVER_DOWN)
184                         {
185                                 // Attempt to reconnect if the connection dropped
186                                 if (verbose)
187                                         ServerInstance->SNO->WriteToSnoMask('a', "LDAP server has gone away - reconnecting...");
188                                 Connect();
189                                 res = ldap_sasl_bind_s(conn, username.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
190                         }
191
192                         if (res != LDAP_SUCCESS)
193                         {
194                                 if (verbose)
195                                         ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s!%s@%s (LDAP bind failed: %s)", user->nick.c_str(), user->ident.c_str(), user->host.c_str(), ldap_err2string(res));
196                                 ldap_unbind_ext(conn, NULL, NULL);
197                                 conn = NULL;
198                                 return false;
199                         }
200                 }
201
202                 LDAPMessage *msg, *entry;
203                 std::string what = (attribute + "=" + (useusername ? user->ident : user->nick));
204                 if ((res = ldap_search_ext_s(conn, base.c_str(), searchscope, what.c_str(), NULL, 0, NULL, NULL, NULL, 0, &msg)) != LDAP_SUCCESS)
205                 {
206                         // Do a second search, based on password, if it contains a :
207                         // That is, PASS <user>:<password> will work.
208                         size_t pos = user->password.find(":");
209                         if (pos != std::string::npos)
210                         {
211                                 std::string cutpassword = user->password.substr(0, pos);
212                                 res = ldap_search_ext_s(conn, base.c_str(), searchscope, cutpassword.c_str(), NULL, 0, NULL, NULL, NULL, 0, &msg);
213
214                                 if (res == LDAP_SUCCESS)
215                                 {
216                                         // Trim the user: prefix, leaving just 'pass' for later password check
217                                         user->password = user->password.substr(pos + 1);
218                                 }
219                         }
220
221                         // It may have found based on user:pass check above.
222                         if (res != LDAP_SUCCESS)
223                         {
224                                 if (verbose)
225                                         ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s!%s@%s (LDAP search failed: %s)", user->nick.c_str(), user->ident.c_str(), user->host.c_str(), ldap_err2string(res));
226                                 return false;
227                         }
228                 }
229                 if (ldap_count_entries(conn, msg) > 1)
230                 {
231                         if (verbose)
232                                 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s!%s@%s (LDAP search returned more than one result: %s)", user->nick.c_str(), user->ident.c_str(), user->host.c_str(), ldap_err2string(res));
233                         ldap_msgfree(msg);
234                         return false;
235                 }
236                 if ((entry = ldap_first_entry(conn, msg)) == NULL)
237                 {
238                         if (verbose)
239                                 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s!%s@%s (LDAP search returned no results: %s)", user->nick.c_str(), user->ident.c_str(), user->host.c_str(), ldap_err2string(res));
240                         ldap_msgfree(msg);
241                         return false;
242                 }
243                 cred.bv_val = (char*)user->password.data();
244                 cred.bv_len = user->password.length();
245                 if ((res = ldap_sasl_bind_s(conn, ldap_get_dn(conn, entry), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL)) == LDAP_SUCCESS)
246                 {
247                         ldap_msgfree(msg);
248                         ldapAuthed.set(user,1);
249                         return true;
250                 }
251                 else
252                 {
253                         if (verbose)
254                                 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s!%s@%s (%s)", user->nick.c_str(), user->ident.c_str(), user->host.c_str(), ldap_err2string(res));
255                         ldap_msgfree(msg);
256                         return false;
257                 }
258         }
259
260         ModResult OnCheckReady(LocalUser* user)
261         {
262                 return ldapAuthed.get(user) ? MOD_RES_PASSTHRU : MOD_RES_DENY;
263         }
264
265         Version GetVersion()
266         {
267                 return Version("Allow/Deny connections based upon answer from LDAP server", VF_VENDOR);
268         }
269
270 };
271
272 MODULE_INIT(ModuleLDAPAuth)