ocs /plugins/auth/ldap/LDAPAuthPlugin.inc.php

Language PHP Lines 390
MD5 Hash 5148939cdd2c543f08595bf494f95002
Repository https://github.com/mcrider/ocs.git View Raw File View Project SPDX
  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
<?php

/**
 * @file LDAPAuthPlugin.inc.php
 *
 * Copyright (c) 2000-2010 John Willinsky
 * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
 *
 * @class LDAPAuthPlugin
 * @ingroup plugins_auth_ldap
 *
 * @brief LDAP authentication plugin.
 */

// $Id$


import('classes.plugins.AuthPlugin');

class LDAPAuthPlugin extends AuthPlugin {
	/**
	 * Called as a plugin is registered to the registry
	 * @param $category String Name of category plugin was registered to
	 * @return boolean True iff plugin initialized successfully; if false,
	 * 	the plugin will not be registered.
	 */
	function register($category, $path) {
		$success = parent::register($category, $path);
		$this->addLocaleData();
		return $success;
	}

	// LDAP-specific configuration settings:
	// - hostname
	// - port
	// - basedn
	// - managerdn
	// - managerpwd
	// - pwhash
	// - SASL: sasl, saslmech, saslrealm, saslauthzid, saslprop

	/** @var $conn resource the LDAP connection */
	var $conn;

	/**
	 * Return the name of this plugin.
	 * @return string
	 */
	function getName() {
		return 'ldap';
	}

	/**
	 * Return the localized name of this plugin.
	 * @return string
	 */
	function getDisplayName() {
		return Locale::translate('plugins.auth.ldap.displayName');
	}

	/**
	 * Return the localized description of this plugin.
	 * @return string
	 */
	function getDescription() {
		return Locale::translate('plugins.auth.ldap.description');
	}


	//
	// Core Plugin Functions
	// (Must be implemented by every authentication plugin)
	//

	/**
	 * Returns an instance of the authentication plugin
	 * @param $settings array settings specific to this instance.
	 * @param $authId int identifier for this instance
	 * @return LDAPuthPlugin
	 */
	function &getInstance($settings, $authId) {
		$returner = new LDAPAuthPlugin($settings, $authId);
		return $returner;
	}

	/**
	 * Authenticate a username and password.
	 * @param $username string
	 * @param $password string
	 * @return boolean true if authentication is successful
	 */
	function authenticate($username, $password) {
		$valid = false;
		if ($this->open()) {
			if ($entry = $this->getUserEntry($username)) {
				$userdn = ldap_get_dn($this->conn, $entry);
				if ($this->bind($userdn, $password)) {
					$valid = true;
				}
			}
			$this->close();
		}
		return $valid;
	}


	//
	// Optional Plugin Functions
	//

	/**
	 * Check if a username exists.
	 * @param $username string
	 * @return boolean
	 */
	function userExists($username) {
		$exists = true;
		if ($this->open()) {
			if ($this->bind()) {
				$result = ldap_search($this->conn, $this->settings['basedn'], $this->settings['uid'] . '=' . $username);
				$exists = (ldap_count_entries($this->conn, $result) != 0);
			}
			$this->close();
		}
		return $exists;
	}

	/**
	 * Retrieve user profile information from the LDAP server.
	 * @param $user User to update
	 * @return boolean true if successful
	 */
	function getUserInfo(&$user) {
		$valid = false;
		if ($this->open()) {
			if ($entry = $this->getUserEntry($user->getUsername())) {
				$valid = true;
				$attr = ldap_get_attributes($this->conn, $entry);
				$this->userFromAttr($user, $attr);
			}
			$this->close();
		}
		return $valid;
	}

	/**
	 * Store user profile information on the LDAP server.
	 * @param $user User to store
	 * @return boolean true if successful
	 */
	function setUserInfo(&$user) {
		$valid = false;
		if ($this->open()) {
			if ($entry = $this->getUserEntry($user->getUsername())) {
				$userdn = ldap_get_dn($this->conn, $entry);
				if ($this->bind($this->settings['managerdn'], $this->settings['managerpwd'])) {
					$attr = array();
					$this->userToAttr($user, $attr);
					$valid = ldap_modify($this->conn, $userdn, $attr);
				}
			}
			$this->close();
		}
		return $valid;
	}

	/**
	 * Change a user's password on the LDAP server.
	 * @param $username string user to update
	 * @param $password string the new password
	 * @return boolean true if successful
	 */
	function setUserPassword($username, $password) {
		if ($this->open()) {
			if ($entry = $this->getUserEntry($username)) {
				$userdn = ldap_get_dn($this->conn, $entry);
				if ($this->bind($this->settings['managerdn'], $this->settings['managerpwd'])) {
					$attr = array('userPassword' => $this->encodePassword($password));
					$valid = ldap_modify($this->conn, $userdn, $attr);
				}
			}
			$this->close();
		}
	}

	/**
	 * Create a user on the LDAP server.
	 * @param $user User to create
	 * @return boolean true if successful
	 */
	function createUser(&$user) {
		$valid = false;
		if ($this->open()) {
			if (!($entry = $this->getUserEntry($user->getUsername()))) {
				if ($this->bind($this->settings['managerdn'], $this->settings['managerpwd'])) {
					$userdn = $this->settings['uid'] . '=' . $user->getUsername() . ',' . $this->settings['basedn'];
					$attr = array(
						'objectclass' => array('top', 'person', 'organizationalPerson', 'inetorgperson'),
						$this->settings['uid'] => $user->getUsername(),
						'userPassword' => $this->encodePassword($user->getPassword())
					);
					$this->userToAttr($user, $attr);
					$valid = ldap_add($this->conn, $userdn, $attr);
				}
			}
			$this->close();
		}
		return $valid;
	}

	/**
	 * Delete a user from the LDAP server.
	 * @param $username string user to delete
	 * @return boolean true if successful
	 */
	function deleteUser($username) {
		$valid = false;
		if ($this->open()) {
			if ($entry = $this->getUserEntry($username)) {
				$userdn = ldap_get_dn($this->conn, $entry);
				if ($this->bind($this->settings['managerdn'], $this->settings['managerpwd'])) {
					$valid = ldap_delete($this->conn, $userdn);
				}
			}
			$this->close();
		}
		return $valid;
	}


	//
	// LDAP Helper Functions
	//

	/**
	 * Open connection to the server.
	 */
	function open() {
		$this->conn = ldap_connect($this->settings['hostname'], (int)$this->settings['port']);
		ldap_set_option($this->conn, LDAP_OPT_PROTOCOL_VERSION, 3);
		return $this->conn;
	}

	/**
	 * Close connection.
	 */
	function close() {
		ldap_close($this->conn);
		$this->conn = null;
	}

	/**
	 * Bind to a directory.
	 * $binddn string directory to bind (optional)
	 * $password string (optional)
	 */
	function bind($binddn = null, $password = null) {
		if (isset($this->settings['sasl'])) {
			// FIXME ldap_sasl_bind requires PHP5, haven't tested this
			return @ldap_sasl_bind($this->conn, $binddn, $password, $this->settings['saslmech'], $this->settings['saslrealm'], $this->settings['saslauthzid'], $this->settings['saslprop']);
		}
		return @ldap_bind($this->conn, $binddn, $password);
	}

	/**
	 * Lookup a user entry in the directory.
	 * @param $username string
	 */
	function getUserEntry($username) {
		$entry = false;
		if ($this->bind($this->settings['managerdn'], $this->settings['managerpwd'])) {
			$result = ldap_search($this->conn, $this->settings['basedn'], $this->settings['uid'] . '=' . $username);
			if (ldap_count_entries($this->conn, $result) == 1) {
				$entry = ldap_first_entry($this->conn, $result);
			}
		}
		return $entry;
	}

	/**
	 * Update User object from entry attributes.
	 * TODO Abstract this to allow arbitrary LDAP <-> OJS schema mappings.
	 * For now must be subclassed for other schemas.
	 * TODO How to deal with deleted fields.
	 * @param $user User
	 * @param $uattr array
	 */
	function userFromAttr(&$user, &$uattr) {
		$attr = array_change_key_case($uattr, CASE_LOWER); // Note:  array_change_key_case requires PHP >= 4.2.0
		$firstName = @$attr['givenname'][0];
		$middleName = null;
		$initials = null;
		$lastName = @$attr['sn'][0];
		if (!isset($lastName))
			$lastName = @$attr['surname'][0];
		$affiliation = @$attr['o'][0];
		if (!isset($affiliation))
			$affiliation = @$attr['organizationname'][0];
		$email = @$attr['mail'][0];
		if (!isset($email))
			$email = @$attr['email'][0];
		$phone = @$attr['telephonenumber'][0];
		$fax = @$attr['facsimiletelephonenumber'][0];
		if (!isset($fax))
			$fax = @$attr['fax'][0];
		$mailingAddress = @$attr['postaladdress'][0];
		if (!isset($mailingAddress))
			$mailingAddress = @$attr['registeredAddress'][0];
		$biography = null;
		$interests = null;

		// Only update fields that exist
		if (isset($firstName))
			$user->setFirstName($firstName);
		if (isset($middleName))
			$user->setMiddleName($middleName);
		if (isset($initials))
			$user->setInitials($initials);
		if (isset($lastName))
			$user->setLastName($lastName);
		if (isset($affiliation))
			$user->setAffiliation($affiliation);
		if (isset($email))
			$user->setEmail($email);
		if (isset($phone))
			$user->setPhone($phone);
		if (isset($fax))
			$user->setFax($fax);
		if (isset($mailingAddress))
			$user->setMailingAddress($mailingAddress);
		if (isset($biography))
			$user->setBiography($biography, Locale::getLocale());
		if (isset($interests))
			$user->setInterests($interests, Locale::getLocale());
	}

	/**
	 * Update entry attributes from User object.
	 * TODO How to deal with deleted fields.
	 * @param $user User
	 * @param $attr array
	 */
	function userToAttr(&$user, &$attr) {
		// FIXME empty strings for unset fields?
		if ($user->getFullName())
			$attr['cn'] = $user->getFullName();
		if ($user->getFirstName())
			$attr['givenName'] = $user->getFirstName();
		if ($user->getLastName())
			$attr['sn'] = $user->getLastName();
		if ($user->getAffiliation())
			$attr['organizationName'] = $user->getAffiliation();
		if ($user->getEmail())
			$attr['mail'] = $user->getEmail();
		if ($user->getPhone())
			$attr['telephoneNumber'] = $user->getPhone();
		if ($user->getFax())
			$attr['facsimileTelephoneNumber'] = $user->getFax();
		if ($user->getMailingAddress())
			$attr['postalAddress'] = $user->getMailingAddress();
	}

	/**
	 * Encode password for the 'userPassword' field using the specified hash.
	 * @param $password string
	 * @return string hashed string (with prefix).
	 */
	function encodePassword($password) {
		switch ($this->settings['pwhash']) {
			case 'md5':
				return '{MD5}' . base64_encode(pack('H*', md5($password)));
			case 'smd5':
				$salt = pack('C*', mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand());
				return '{SMD5}' . base64_encode(pack('H*', md5($password . $salt)) . $salt);
			case 'sha':
				return '{SHA}' . base64_encode(pack('H*', sha1($password))); // Note: sha1 requres PHP >= 4.3.0
			case 'ssha':
				$salt = pack('C*', mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand());
				return '{SSHA}' . base64_encode(pack('H*', sha1($password . $salt)) . $salt);
			case 'crypt':
				return '{CRYPT}' . crypt($password);
			default:
				//return '{CLEARTEXT}'. $password;
				return $password;
		}
	}
}

?>
Back to Top