]> git.donarmstrong.com Git - roundcube.git/blob - plugins/password/drivers/ldap.php
3ea30a69c6b1eea5e24e67c10330eb4dff979caf
[roundcube.git] / plugins / password / drivers / ldap.php
1 <?php
2
3 /**
4  * LDAP Password Driver
5  *
6  * Driver for passwords stored in LDAP
7  * This driver use the PEAR Net_LDAP2 class (http://pear.php.net/package/Net_LDAP2).
8  *
9  * @version 1.1 (2010-04-07)
10  * @author Edouard MOREAU <edouard.moreau@ensma.fr>
11  *
12  * function hashPassword based on code from the phpLDAPadmin development team (http://phpldapadmin.sourceforge.net/).
13  * function randomSalt based on code from the phpLDAPadmin development team (http://phpldapadmin.sourceforge.net/).
14  *
15  */
16
17 function password_save($curpass, $passwd)
18 {
19     $rcmail = rcmail::get_instance();
20     require_once ('Net/LDAP2.php');
21
22     // Building user DN
23     if ($userDN = $rcmail->config->get('password_ldap_userDN_mask')) {
24         $userDN = substitute_vars($userDN);
25     } else {
26         $userDN = search_userdn($rcmail);
27     }
28
29     if (empty($userDN)) {
30         return PASSWORD_CONNECT_ERROR;
31     }
32
33     // Connection Method
34     switch($rcmail->config->get('password_ldap_method')) {
35         case 'admin':
36             $binddn = $rcmail->config->get('password_ldap_adminDN');
37             $bindpw = $rcmail->config->get('password_ldap_adminPW');
38             break;
39         case 'user':
40         default:
41             $binddn = $userDN;
42             $bindpw = $curpass;
43             break;
44     }
45
46     // Configuration array
47     $ldapConfig = array (
48         'binddn'    => $binddn,
49         'bindpw'    => $bindpw,
50         'basedn'    => $rcmail->config->get('password_ldap_basedn'),
51         'host'      => $rcmail->config->get('password_ldap_host'),
52         'port'      => $rcmail->config->get('password_ldap_port'),
53         'starttls'  => $rcmail->config->get('password_ldap_starttls'),
54         'version'   => $rcmail->config->get('password_ldap_version'),
55     );
56
57     // Connecting using the configuration array
58     $ldap = Net_LDAP2::connect($ldapConfig);
59
60     // Checking for connection error
61     if (PEAR::isError($ldap)) {
62         return PASSWORD_CONNECT_ERROR;
63     }
64
65     $crypted_pass = hashPassword($passwd, $rcmail->config->get('password_ldap_encodage'));
66     $force        = $rcmail->config->get('password_ldap_force_replace');
67     $pwattr       = $rcmail->config->get('password_ldap_pwattr');
68     $lchattr      = $rcmail->config->get('password_ldap_lchattr');
69     $smbpwattr    = $rcmail->config->get('password_ldap_samba_pwattr');
70     $smblchattr   = $rcmail->config->get('password_ldap_samba_lchattr');
71     $samba        = $rcmail->config->get('password_ldap_samba');
72
73     // Support password_ldap_samba option for backward compat.
74     if ($samba && !$smbpwattr) {
75         $smbpwattr  = 'sambaNTPassword';
76         $smblchattr = 'sambaPwdLastSet';
77     }
78
79     // Crypt new password
80     if (!$crypted_pass) {
81         return PASSWORD_CRYPT_ERROR;
82     }
83
84     // Crypt new samba password
85     if ($smbpwattr && !($samba_pass = hashPassword($passwd, 'samba'))) {
86             return PASSWORD_CRYPT_ERROR;
87     }
88
89     // Writing new crypted password to LDAP
90     $userEntry = $ldap->getEntry($userDN);
91     if (Net_LDAP2::isError($userEntry)) {
92         return PASSWORD_CONNECT_ERROR;
93     }
94
95     if (!$userEntry->replace(array($pwattr => $crypted_pass), $force)) {
96         return PASSWORD_CONNECT_ERROR;
97     }
98
99     // Updating PasswordLastChange Attribute if desired
100     if ($lchattr) {
101        $current_day = (int)(time() / 86400);
102        if (!$userEntry->replace(array($lchattr => $current_day), $force)) {
103            return PASSWORD_CONNECT_ERROR;
104        }
105     }
106
107     // Update Samba password and last change fields
108     if ($smbpwattr) {
109         $userEntry->replace(array($smbpwattr => $samba_pass), $force);
110     }
111     // Update Samba password last change field
112     if ($smblchattr) {
113         $userEntry->replace(array($smblchattr => time()), $force);
114     }
115
116     if (Net_LDAP2::isError($userEntry->update())) {
117         return PASSWORD_CONNECT_ERROR;
118     }
119
120     // All done, no error
121     return PASSWORD_SUCCESS;
122 }
123
124 /**
125  * Bind with searchDN and searchPW and search for the user's DN.
126  * Use search_base and search_filter defined in config file.
127  * Return the found DN.
128  */
129 function search_userdn($rcmail)
130 {
131     $ldapConfig = array (
132         'binddn'    => $rcmail->config->get('password_ldap_searchDN'),
133         'bindpw'    => $rcmail->config->get('password_ldap_searchPW'),
134         'basedn'    => $rcmail->config->get('password_ldap_basedn'),
135         'host'      => $rcmail->config->get('password_ldap_host'),
136         'port'      => $rcmail->config->get('password_ldap_port'),
137         'starttls'  => $rcmail->config->get('password_ldap_starttls'),
138         'version'   => $rcmail->config->get('password_ldap_version'),
139     );
140
141     $ldap = Net_LDAP2::connect($ldapConfig);
142
143     if (PEAR::isError($ldap)) {
144         return '';
145     }
146
147     $base = $rcmail->config->get('password_ldap_search_base');
148     $filter = substitute_vars($rcmail->config->get('password_ldap_search_filter'));
149     $options = array (
150             'scope' => 'sub',
151             'attributes' => array(),
152     );
153
154     $result = $ldap->search($base, $filter, $options);
155     $ldap->done();
156     if (PEAR::isError($result) || ($result->count() != 1)) {
157         return '';
158     }
159
160     return $result->current()->dn();
161 }
162
163 /**
164  * Substitute %login, %name, %domain, %dc in $str.
165  * See plugin config for details.
166  */
167 function substitute_vars($str)
168 {
169     $rcmail = rcmail::get_instance();
170     $domain = $rcmail->user->get_username('domain');
171     $dc     = 'dc='.strtr($domain, array('.' => ',dc=')); // hierarchal domain string
172
173     $str = str_replace(array(
174             '%login',
175             '%name',
176             '%domain',
177             '%dc',
178         ), array(
179             $_SESSION['username'],
180             $rcmail->user->get_username('local'),
181             $domain,
182             $dc,
183         ), $str
184     );
185
186     return $str;
187 }
188
189
190 /**
191  * Code originaly from the phpLDAPadmin development team
192  * http://phpldapadmin.sourceforge.net/
193  *
194  * Hashes a password and returns the hash based on the specified enc_type.
195  *
196  * @param string $passwordClear The password to hash in clear text.
197  * @param string $encodageType Standard LDAP encryption type which must be one of
198  *        crypt, ext_des, md5crypt, blowfish, md5, sha, smd5, ssha, or clear.
199  * @return string The hashed password.
200  *
201  */
202
203 function hashPassword( $passwordClear, $encodageType )
204 {
205     $encodageType = strtolower( $encodageType );
206     switch( $encodageType ) {
207         case 'crypt': 
208             $cryptedPassword = '{CRYPT}' . crypt($passwordClear,randomSalt(2)); 
209             break;
210
211         case 'ext_des':
212             // extended des crypt. see OpenBSD crypt man page.
213             if ( ! defined( 'CRYPT_EXT_DES' ) || CRYPT_EXT_DES == 0 ) {
214                 // Your system crypt library does not support extended DES encryption.
215                 return FALSE;
216             }
217             $cryptedPassword = '{CRYPT}' . crypt( $passwordClear, '_' . randomSalt(8) );
218             break;
219
220         case 'md5crypt':
221             if( ! defined( 'CRYPT_MD5' ) || CRYPT_MD5 == 0 ) {
222                 // Your system crypt library does not support md5crypt encryption.
223                 return FALSE;
224             }
225             $cryptedPassword = '{CRYPT}' . crypt( $passwordClear , '$1$' . randomSalt(9) );
226             break;
227
228         case 'blowfish':
229             if( ! defined( 'CRYPT_BLOWFISH' ) || CRYPT_BLOWFISH == 0 ) {
230                 // Your system crypt library does not support blowfish encryption.
231                 return FALSE;
232             }
233             // hardcoded to second blowfish version and set number of rounds
234             $cryptedPassword = '{CRYPT}' . crypt( $passwordClear , '$2a$12$' . randomSalt(13) );
235             break;
236
237         case 'md5':
238             $cryptedPassword = '{MD5}' . base64_encode( pack( 'H*' , md5( $passwordClear) ) );
239             break;
240
241         case 'sha':
242             if( function_exists('sha1') ) {
243                 // use php 4.3.0+ sha1 function, if it is available.
244                 $cryptedPassword = '{SHA}' . base64_encode( pack( 'H*' , sha1( $passwordClear) ) );
245             } elseif( function_exists( 'mhash' ) ) {
246                 $cryptedPassword = '{SHA}' . base64_encode( mhash( MHASH_SHA1, $passwordClear) );
247             } else {
248                 return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
249             }
250             break;
251
252         case 'ssha':
253             if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
254                 mt_srand( (double) microtime() * 1000000 );
255                 $salt = mhash_keygen_s2k( MHASH_SHA1, $passwordClear, substr( pack( 'h*', md5( mt_rand() ) ), 0, 8 ), 4 );
256                 $cryptedPassword = '{SSHA}'.base64_encode( mhash( MHASH_SHA1, $passwordClear.$salt ).$salt );
257             } else {
258                 return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
259             }
260             break;
261
262         case 'smd5':
263             if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
264                 mt_srand( (double) microtime() * 1000000 );
265                 $salt = mhash_keygen_s2k( MHASH_MD5, $passwordClear, substr( pack( 'h*', md5( mt_rand() ) ), 0, 8 ), 4 );
266                 $cryptedPassword = '{SMD5}'.base64_encode( mhash( MHASH_MD5, $passwordClear.$salt ).$salt );
267             } else {
268                 return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
269             }
270             break;
271
272         case 'samba':
273             if (function_exists('hash')) {
274                 $cryptedPassword = hash('md4', rcube_charset_convert($passwordClear, RCMAIL_CHARSET, 'UTF-16LE'));
275             } else {
276                                 /* Your PHP install does not have the hash() function */
277                                 return false;
278             }
279             break;
280
281         case 'clear':
282         default:
283             $cryptedPassword = $passwordClear;
284     }
285
286     return $cryptedPassword;
287 }
288
289 /**
290  * Code originaly from the phpLDAPadmin development team
291  * http://phpldapadmin.sourceforge.net/
292  *
293  * Used to generate a random salt for crypt-style passwords. Salt strings are used
294  * to make pre-built hash cracking dictionaries difficult to use as the hash algorithm uses
295  * not only the user's password but also a randomly generated string. The string is
296  * stored as the first N characters of the hash for reference of hashing algorithms later.
297  *
298  * --- added 20021125 by bayu irawan <bayuir@divnet.telkom.co.id> ---
299  * --- ammended 20030625 by S C Rigler <srigler@houston.rr.com> ---
300  *
301  * @param int $length The length of the salt string to generate.
302  * @return string The generated salt string.
303  */
304 function randomSalt( $length )
305 {
306     $possible = '0123456789'.
307         'abcdefghijklmnopqrstuvwxyz'.
308         'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
309         './';
310     $str = '';
311 //    mt_srand((double)microtime() * 1000000);
312
313     while (strlen($str) < $length)
314         $str .= substr($possible, (rand() % strlen($possible)), 1);
315
316     return $str;
317 }