77d963c07f99eb0659d3709d9341f556a1e53106
[friendica-addons.git/.git] / ldapauth / ldapauth.php
1 <?php
2
3 /**
4  * Name: LDAP Authenticate
5  * Description: Authenticate a user against an LDAP directory
6  * Version: 1.1
7  * Author: Mike Macgirvin <http://macgirvin.com/profile/mike>
8  * Author: aymhce
9  */
10
11 /**
12  * Friendica addon
13  *
14  * Module: LDAP Authenticate
15  *
16  * Authenticate a user against an LDAP directory
17  * Useful for Windows Active Directory and other LDAP-based organisations
18  * to maintain a single password across the organisation.
19  *
20  * Optionally authenticates only if a member of a given group in the directory.
21  *
22  * By default, the person must have registered with Friendica using the normal registration
23  * procedures in order to have a Friendica user record, contact, and profile.
24  * However, it's possible with an option to automate the creation of a Friendica basic account.
25  *
26  * Note when using with Windows Active Directory: you may need to set TLS_CACERT in your site
27  * ldap.conf file to the signing cert for your LDAP server.
28  *
29  * The configuration options for this module may be set in the config/addon.config.php file
30  * e.g.:
31  *
32  * [ldapauth]
33  * ; ldap hostname server - required
34  * ldap_server = host.example.com
35  * ; dn to search users - required
36  * ldap_searchdn = ou=users,dc=example,dc=com
37  * ; attribute to find username - required
38  * ldap_userattr = uid
39  *
40  * ; admin dn - optional - only if ldap server dont have anonymous access
41  * ldap_binddn = cn=admin,dc=example,dc=com
42  * ; admin password - optional - only if ldap server dont have anonymous access
43  * ldap_bindpw = password
44  *
45  * ; for create Friendica account if user exist in ldap
46  * ;     required an email and a simple (beautiful) nickname on user ldap object
47  * ;   active account creation - optional - default none
48  * ldap_autocreateaccount = true
49  * ;   attribute to get email - optional - default : 'mail'
50  * ldap_autocreateaccount_emailattribute = mail
51  * ;   attribute to get nickname - optional - default : 'givenName'
52  * ldap_autocreateaccount_nameattribute = cn
53  *
54  * ...etc.
55  */
56 use Friendica\Core\Addon;
57 use Friendica\Core\Config;
58 use Friendica\Core\Logger;
59 use Friendica\Model\User;
60
61 function ldapauth_install()
62 {
63         Addon::registerHook('load_config',  'addon/ldapauth/ldapauth.php', 'ldapauth_load_config');
64         Addon::registerHook('authenticate', 'addon/ldapauth/ldapauth.php', 'ldapauth_hook_authenticate');
65 }
66
67 function ldapauth_uninstall()
68 {
69         Addon::unregisterHook('load_config',  'addon/ldapauth/ldapauth.php', 'ldapauth_load_config');
70         Addon::unregisterHook('authenticate', 'addon/ldapauth/ldapauth.php', 'ldapauth_hook_authenticate');
71 }
72
73 function ldapauth_load_config(\Friendica\App $a)
74 {
75         $a->loadConfigFile(__DIR__ . '/config/ldapauth.config.php');
76 }
77
78 function ldapauth_hook_authenticate($a, &$b)
79 {
80         if (ldapauth_authenticate($b['username'], $b['password'])) {
81                 $results = get_existing_account($b['username']);
82                 if (!empty($results)) {
83                         $b['user_record'] = $results[0];
84                         $b['authenticated'] = 1;
85                 }
86         }
87         return;
88 }
89
90 function ldapauth_authenticate($username, $password)
91 {
92         $ldap_server   = Config::get('ldapauth', 'ldap_server');
93         $ldap_binddn   = Config::get('ldapauth', 'ldap_binddn');
94         $ldap_bindpw   = Config::get('ldapauth', 'ldap_bindpw');
95         $ldap_searchdn = Config::get('ldapauth', 'ldap_searchdn');
96         $ldap_userattr = Config::get('ldapauth', 'ldap_userattr');
97         $ldap_group    = Config::get('ldapauth', 'ldap_group');
98         $ldap_autocreateaccount = Config::get('ldapauth', 'ldap_autocreateaccount');
99         $ldap_autocreateaccount_emailattribute = Config::get('ldapauth', 'ldap_autocreateaccount_emailattribute');
100         $ldap_autocreateaccount_nameattribute  = Config::get('ldapauth', 'ldap_autocreateaccount_nameattribute');
101
102         if (!(strlen($password) && function_exists('ldap_connect') && strlen($ldap_server))) {
103                 Logger::log("ldapauth: not configured or missing php-ldap module");
104                 return false;
105         }
106
107         $connect = @ldap_connect($ldap_server);
108
109         if ($connect === false) {
110                 Logger::log("ldapauth: could not connect to $ldap_server");
111                 return false;
112         }
113
114         @ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
115         @ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
116         if ((@ldap_bind($connect, $ldap_binddn, $ldap_bindpw)) === false) {
117                 Logger::log("ldapauth: could not bind $ldap_server as $ldap_binddn");
118                 return false;
119         }
120
121         $res = @ldap_search($connect, $ldap_searchdn, $ldap_userattr . '=' . $username);
122
123         if (!$res) {
124                 Logger::log("ldapauth: $ldap_userattr=$username,$ldap_searchdn not found");
125                 return false;
126         }
127
128         $id = @ldap_first_entry($connect, $res);
129
130         if (!$id) {
131                 return false;
132         }
133
134         $dn = @ldap_get_dn($connect, $id);
135
136         if (!@ldap_bind($connect, $dn, $password)) {
137                 return false;
138         }
139
140         $emailarray = [];
141         $namearray = [];
142         if ($ldap_autocreateaccount == "true") {
143                 if (!strlen($ldap_autocreateaccount_emailattribute)) {
144                         $ldap_autocreateaccount_emailattribute = "mail";
145                 }
146                 if (!strlen($ldap_autocreateaccount_nameattribute)) {
147                         $ldap_autocreateaccount_nameattribute = "givenName";
148                 }
149                 $emailarray = @ldap_get_values($connect, $id, $ldap_autocreateaccount_emailattribute);
150                 $namearray = @ldap_get_values($connect, $id, $ldap_autocreateaccount_nameattribute);
151         }
152
153         if (!strlen($ldap_group)) {
154                 ldap_autocreateaccount($ldap_autocreateaccount, $username, $password, $emailarray[0], $namearray[0]);
155                 return true;
156         }
157
158         $r = @ldap_compare($connect, $ldap_group, 'member', $dn);
159         if ($r === -1) {
160                 $err = @ldap_error($connect);
161                 $eno = @ldap_errno($connect);
162                 @ldap_close($connect);
163
164                 if ($eno === 32) {
165                         Logger::log("ldapauth: access control group Does Not Exist");
166                         return false;
167                 } elseif ($eno === 16) {
168                         Logger::log('ldapauth: membership attribute does not exist in access control group');
169                         return false;
170                 } else {
171                         Logger::log('ldapauth: error: ' . $err);
172                         return false;
173                 }
174         } elseif ($r === false) {
175                 @ldap_close($connect);
176                 return false;
177         }
178
179         ldap_autocreateaccount($ldap_autocreateaccount, $username, $password, $emailarray[0], $namearray[0]);
180         return true;
181 }
182
183 function ldap_autocreateaccount($ldap_autocreateaccount, $username, $password, $email, $name)
184 {
185         if ($ldap_autocreateaccount == "true") {
186                 $results = get_existing_account($username);
187                 if (empty($results)) {
188                         if (strlen($email) > 0 && strlen($name) > 0) {
189                                 $arr = ['username' => $name, 'nickname' => $username, 'email' => $email, 'password' => $password, 'verified' => 1];
190
191                                 try {
192                                         User::create($arr);
193                                         Logger::log("ldapauth: account " . $username . " created");
194                                 } catch (Exception $ex) {
195                                         Logger::log("ldapauth: account " . $username . " was not created ! : " . $ex->getMessage());
196                                 }
197                         } else {
198                                 Logger::log("ldapauth: unable to create account, no email or nickname found");
199                         }
200                 }
201         }
202 }
203
204 function get_existing_account($username)
205 {
206         return q("SELECT * FROM `user` WHERE `nickname` = '%s' AND `blocked` = 0 AND `verified` = 1 LIMIT 1", $username);
207 }