]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ldapauth.cpp
Fix initialization of SSL certificate field on connect
[user/henk/code/inspircd.git] / src / modules / extra / m_ldapauth.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2010 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  *
13  * Taken from the UnrealIRCd 4.0 SVN version, based on
14  * InspIRCd 1.1.x.
15  *
16  * UnrealIRCd 4.0 (C) 2007 Carsten Valdemar Munk
17  * This program is free but copyrighted software; see
18  *          the file COPYING for details.
19  *
20  * ---------------------------------------------------
21  * Heavily based on SQLauth
22  */
23
24 #include "inspircd.h"
25 #include "users.h"
26 #include "channels.h"
27 #include "modules.h"
28
29 #include <ldap.h>
30
31 #ifdef WINDOWS
32 # pragma comment(lib, "ldap.lib")
33 # pragma comment(lib, "lber.lib")
34 #endif
35
36 /* $ModDesc: Allow/Deny connections based upon answer from LDAP server */
37 /* $LinkerFlags: -lldap */
38
39 class ModuleLDAPAuth : public Module
40 {
41         LocalIntExt ldapAuthed;
42         std::string base;
43         std::string attribute;
44         std::string ldapserver;
45         std::string allowpattern;
46         std::string killreason;
47         std::string username;
48         std::string password;
49         int searchscope;
50         bool verbose;
51         bool useusername;
52         LDAP *conn;
53
54 public:
55         ModuleLDAPAuth() : ldapAuthed("ldapauth", this)
56         {
57                 conn = NULL;
58         }
59
60         void init()
61         {
62                 Implementation eventlist[] = { I_OnCheckReady, I_OnRehash, I_OnUserRegister };
63                 ServerInstance->Modules->Attach(eventlist, this, 3);
64                 OnRehash(NULL);
65         }
66
67         ~ModuleLDAPAuth()
68         {
69                 if (conn)
70                         ldap_unbind_ext(conn, NULL, NULL);
71         }
72
73         void OnRehash(User* user)
74         {
75                 ConfigReader Conf;
76
77                 base                    = Conf.ReadValue("ldapauth", "baserdn", 0);
78                 attribute               = Conf.ReadValue("ldapauth", "attribute", 0);
79                 ldapserver              = Conf.ReadValue("ldapauth", "server", 0);
80                 allowpattern            = Conf.ReadValue("ldapauth", "allowpattern", 0);
81                 killreason              = Conf.ReadValue("ldapauth", "killreason", 0);
82                 std::string scope       = Conf.ReadValue("ldapauth", "searchscope", 0);
83                 username                = Conf.ReadValue("ldapauth", "binddn", 0);
84                 password                = Conf.ReadValue("ldapauth", "bindauth", 0);
85                 verbose                 = Conf.ReadFlag("ldapauth", "verbose", 0);              /* Set to true if failed connects should be reported to operators */
86                 useusername             = Conf.ReadFlag("ldapauth", "userfield", 0);
87
88                 if (scope == "base")
89                         searchscope = LDAP_SCOPE_BASE;
90                 else if (scope == "onelevel")
91                         searchscope = LDAP_SCOPE_ONELEVEL;
92                 else searchscope = LDAP_SCOPE_SUBTREE;
93
94                 Connect();
95         }
96
97         bool Connect()
98         {
99                 if (conn != NULL)
100                         ldap_unbind_ext(conn, NULL, NULL);
101                 int res, v = LDAP_VERSION3;
102                 res = ldap_initialize(&conn, ldapserver.c_str());
103                 if (res != LDAP_SUCCESS)
104                 {
105                         if (verbose)
106                                 ServerInstance->SNO->WriteToSnoMask('c', "LDAP connection failed: %s", ldap_err2string(res));
107                         conn = NULL;
108                         return false;
109                 }
110
111                 res = ldap_set_option(conn, LDAP_OPT_PROTOCOL_VERSION, (void *)&v);
112                 if (res != LDAP_SUCCESS)
113                 {
114                         if (verbose)
115                                 ServerInstance->SNO->WriteToSnoMask('c', "LDAP set protocol to v3 failed: %s", ldap_err2string(res));
116                         ldap_unbind_ext(conn, NULL, NULL);
117                         conn = NULL;
118                         return false;
119                 }
120                 return true;
121         }
122
123         ModResult OnUserRegister(LocalUser* user)
124         {
125                 if ((!allowpattern.empty()) && (InspIRCd::Match(user->nick,allowpattern)))
126                 {
127                         ldapAuthed.set(user,1);
128                         return MOD_RES_PASSTHRU;
129                 }
130
131                 if (!CheckCredentials(user))
132                 {
133                         ServerInstance->Users->QuitUser(user, killreason);
134                         return MOD_RES_DENY;
135                 }
136                 return MOD_RES_PASSTHRU;
137         }
138
139         bool CheckCredentials(LocalUser* user)
140         {
141                 if (conn == NULL)
142                         if (!Connect())
143                                 return false;
144
145                 if (user->password.empty())
146                 {
147                         if (verbose)
148                                 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());
149                         return false;
150                 }
151
152                 int res;
153                 // bind anonymously if no bind DN and authentication are given in the config
154                 struct berval cred;
155                 cred.bv_val = const_cast<char*>(password.c_str());
156                 cred.bv_len = password.length();
157
158                 if ((res = ldap_sasl_bind_s(conn, username.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL)) != LDAP_SUCCESS)
159                 {
160                         if (res == LDAP_SERVER_DOWN)
161                         {
162                                 // Attempt to reconnect if the connection dropped
163                                 if (verbose)
164                                         ServerInstance->SNO->WriteToSnoMask('a', "LDAP server has gone away - reconnecting...");
165                                 Connect();
166                                 res = ldap_sasl_bind_s(conn, username.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
167                         }
168
169                         if (res != LDAP_SUCCESS)
170                         {
171                                 if (verbose)
172                                         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));
173                                 ldap_unbind_ext(conn, NULL, NULL);
174                                 conn = NULL;
175                                 return false;
176                         }
177                 }
178
179                 LDAPMessage *msg, *entry;
180                 std::string what = (attribute + "=" + (useusername ? user->ident : user->nick));
181                 if ((res = ldap_search_ext_s(conn, base.c_str(), searchscope, what.c_str(), NULL, 0, NULL, NULL, NULL, 0, &msg)) != LDAP_SUCCESS)
182                 {
183                         // Do a second search, based on password, if it contains a :
184                         // That is, PASS <user>:<password> will work.
185                         size_t pos = user->password.find(":");
186                         if (pos != std::string::npos)
187                         {
188                                 res = ldap_search_ext_s(conn, base.c_str(), searchscope, user->password.substr(0, pos).c_str(), NULL, 0, NULL, NULL, NULL, 0, &msg);
189
190                                 if (res)
191                                 {
192                                         // Trim the user: prefix, leaving just 'pass' for later password check
193                                         user->password = user->password.substr(pos + 1);
194                                 }
195                         }
196
197                         // It may have found based on user:pass check above.
198                         if (!res)
199                         {
200                                 if (verbose)
201                                         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));
202                                 return false;
203                         }
204                 }
205                 if (ldap_count_entries(conn, msg) > 1)
206                 {
207                         if (verbose)
208                                 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));
209                         ldap_msgfree(msg);
210                         return false;
211                 }
212                 if ((entry = ldap_first_entry(conn, msg)) == NULL)
213                 {
214                         if (verbose)
215                                 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));
216                         ldap_msgfree(msg);
217                         return false;
218                 }
219                 cred.bv_val = (char*)user->password.data();
220                 cred.bv_len = user->password.length();
221                 if ((res = ldap_sasl_bind_s(conn, ldap_get_dn(conn, entry), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL)) == LDAP_SUCCESS)
222                 {
223                         ldap_msgfree(msg);
224                         ldapAuthed.set(user,1);
225                         return true;
226                 }
227                 else
228                 {
229                         if (verbose)
230                                 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));
231                         ldap_msgfree(msg);
232                         return false;
233                 }
234         }
235
236         ModResult OnCheckReady(LocalUser* user)
237         {
238                 return ldapAuthed.get(user) ? MOD_RES_PASSTHRU : MOD_RES_DENY;
239         }
240
241         Version GetVersion()
242         {
243                 return Version("Allow/Deny connections based upon answer from LDAP server", VF_VENDOR);
244         }
245
246 };
247
248 MODULE_INIT(ModuleLDAPAuth)