OSDN Git Service

Merge branch 'bugtrack2374_record_page_author' into branch_r1_5
[pukiwiki/pukiwiki.git] / lib / auth.php
1 <?php
2 // PukiWiki - Yet another WikiWikiWeb clone
3 // $Id: auth.php,v 1.22 2011/01/25 15:01:01 henoheno Exp $
4 // Copyright (C) 2003-2005, 2007 PukiWiki Developers Team
5 // License: GPL v2 or (at your option) any later version
6 //
7 // Authentication related functions
8
9 define('PKWK_PASSPHRASE_LIMIT_LENGTH', 512);
10
11 /////////////////////////////////////////////////
12 // Auth type
13
14 define('AUTH_TYPE_NONE', 0);
15 define('AUTH_TYPE_BASIC', 1);
16 define('AUTH_TYPE_EXTERNAL', 2);
17 define('AUTH_TYPE_FORM', 3);
18
19 define('AUTH_TYPE_EXTERNAL_REMOTE_USER', 4);
20 define('AUTH_TYPE_EXTERNAL_X_FORWARDED_USER', 5);
21
22
23 // Passwd-auth related ----
24
25 function pkwk_login($pass = '')
26 {
27         global $adminpass;
28
29         if (! PKWK_READONLY && isset($adminpass) &&
30                 pkwk_hash_compute($pass, $adminpass) === $adminpass) {
31                 return TRUE;
32         } else {
33                 sleep(2);       // Blocking brute force attack
34                 return FALSE;
35         }
36 }
37
38 // Compute RFC2307 'userPassword' value, like slappasswd (OpenLDAP)
39 // $phrase : Pass-phrase
40 // $scheme : Specify '{scheme}' or '{scheme}salt'
41 // $prefix : Output with a scheme-prefix or not
42 // $canonical : Correct or Preserve $scheme prefix
43 function pkwk_hash_compute($phrase = '', $scheme = '{x-php-md5}', $prefix = TRUE, $canonical = FALSE)
44 {
45         if (! is_string($phrase) || ! is_string($scheme)) return FALSE;
46
47         if (strlen($phrase) > PKWK_PASSPHRASE_LIMIT_LENGTH)
48                 die('pkwk_hash_compute(): malicious message length');
49
50         // With a {scheme}salt or not
51         $matches = array();
52         if (preg_match('/^(\{.+\})(.*)$/', $scheme, $matches)) {
53                 $scheme = & $matches[1];
54                 $salt   = & $matches[2];
55         } else if ($scheme != '') {
56                 $scheme  = ''; // Cleartext
57                 $salt    = '';
58         }
59
60         // Compute and add a scheme-prefix
61         switch (strtolower($scheme)) {
62
63         // PHP crypt()
64         case '{x-php-crypt}' :
65                 $hash = ($prefix ? ($canonical ? '{x-php-crypt}' : $scheme) : '') .
66                         ($salt != '' ? crypt($phrase, $salt) : crypt($phrase));
67                 break;
68
69         // PHP md5()
70         case '{x-php-md5}'   :
71                 $hash = ($prefix ? ($canonical ? '{x-php-md5}' : $scheme) : '') .
72                         md5($phrase);
73                 break;
74
75         // PHP sha1()
76         case '{x-php-sha1}'  :
77                 $hash = ($prefix ? ($canonical ? '{x-php-sha1}' : $scheme) : '') .
78                         sha1($phrase);
79                 break;
80
81         // LDAP CRYPT
82         case '{crypt}'       :
83                 $hash = ($prefix ? ($canonical ? '{CRYPT}' : $scheme) : '') .
84                         ($salt != '' ? crypt($phrase, $salt) : crypt($phrase));
85                 break;
86
87         // LDAP MD5
88         case '{md5}'         :
89                 $hash = ($prefix ? ($canonical ? '{MD5}' : $scheme) : '') .
90                         base64_encode(pkwk_hex2bin(md5($phrase)));
91                 break;
92
93         // LDAP SMD5
94         case '{smd5}'        :
95                 // MD5 Key length = 128bits = 16bytes
96                 $salt = ($salt != '' ? substr(base64_decode($salt), 16) : substr(crypt(''), -8));
97                 $hash = ($prefix ? ($canonical ? '{SMD5}' : $scheme) : '') .
98                         base64_encode(pkwk_hex2bin(md5($phrase . $salt)) . $salt);
99                 break;
100
101         // LDAP SHA
102         case '{sha}'         :
103                 $hash = ($prefix ? ($canonical ? '{SHA}' : $scheme) : '') .
104                         base64_encode(pkwk_hex2bin(sha1($phrase)));
105                 break;
106
107         // LDAP SSHA
108         case '{ssha}'        :
109                 // SHA-1 Key length = 160bits = 20bytes
110                 $salt = ($salt != '' ? substr(base64_decode($salt), 20) : substr(crypt(''), -8));
111                 $hash = ($prefix ? ($canonical ? '{SSHA}' : $scheme) : '') .
112                         base64_encode(pkwk_hex2bin(sha1($phrase . $salt)) . $salt);
113                 break;
114
115         // LDAP CLEARTEXT and just cleartext
116         case '{cleartext}'   : /* FALLTHROUGH */
117         case ''              :
118                 $hash = ($prefix ? ($canonical ? '{CLEARTEXT}' : $scheme) : '') .
119                         $phrase;
120                 break;
121
122         // Invalid scheme
123         default:
124                 $hash = FALSE;
125                 break;
126         }
127
128         return $hash;
129 }
130
131
132 // Basic-auth related ----
133
134 // Check edit-permission
135 function check_editable($page, $auth_flag = TRUE, $exit_flag = TRUE)
136 {
137         global $script, $_title_cannotedit, $_msg_unfreeze;
138
139         if (edit_auth($page, $auth_flag, $exit_flag) && is_editable($page)) {
140                 // Editable
141                 return TRUE;
142         } else {
143                 // Not editable
144                 if ($exit_flag === FALSE) {
145                         return FALSE; // Without exit
146                 } else {
147                         // With exit
148                         $body = $title = str_replace('$1',
149                                 htmlsc(strip_bracket($page)), $_title_cannotedit);
150                         if (is_freeze($page))
151                                 $body .= '(<a href="' . $script . '?cmd=unfreeze&amp;page=' .
152                                         rawurlencode($page) . '">' . $_msg_unfreeze . '</a>)';
153                         $page = str_replace('$1', make_search($page), $_title_cannotedit);
154                         catbody($title, $page, $body);
155                         exit;
156                 }
157         }
158 }
159
160 // Check read-permission
161 function check_readable($page, $auth_flag = TRUE, $exit_flag = TRUE)
162 {
163         return read_auth($page, $auth_flag, $exit_flag);
164 }
165
166 function edit_auth($page, $auth_flag = TRUE, $exit_flag = TRUE)
167 {
168         global $edit_auth, $edit_auth_pages, $_title_cannotedit;
169         return $edit_auth ?  basic_auth($page, $auth_flag, $exit_flag,
170                 $edit_auth_pages, $_title_cannotedit) : TRUE;
171 }
172
173 function read_auth($page, $auth_flag = TRUE, $exit_flag = TRUE)
174 {
175         global $read_auth, $read_auth_pages, $_title_cannotread;
176         return $read_auth ?  basic_auth($page, $auth_flag, $exit_flag,
177                 $read_auth_pages, $_title_cannotread) : TRUE;
178 }
179
180 // Basic authentication
181 function basic_auth($page, $auth_flag, $exit_flag, $auth_pages, $title_cannot)
182 {
183         global $auth_method_type, $auth_users, $_msg_auth, $auth_user, $auth_groups;
184         global $auth_user_groups, $auth_type, $g_query_string;
185         // Checked by:
186         $target_str = '';
187         if ($auth_method_type == 'pagename') {
188                 $target_str = $page; // Page name
189         } else if ($auth_method_type == 'contents') {
190                 $target_str = join('', get_source($page)); // Its contents
191         }
192
193         $user_list = array();
194         foreach($auth_pages as $key=>$val)
195                 if (preg_match($key, $target_str))
196                         $user_list = array_merge($user_list, explode(',', $val));
197
198         if (empty($user_list)) return TRUE; // No limit
199
200         $matches = array();
201         if (PKWK_READONLY ||
202                 ! $auth_user ||
203                 count(array_intersect($auth_user_groups, $user_list)) === 0)
204         {
205                 // Auth failed
206                 pkwk_common_headers();
207                 if ($auth_flag && !$auth_user) {
208                         if (AUTH_TYPE_BASIC === $auth_type) {
209                                 header('WWW-Authenticate: Basic realm="' . $_msg_auth . '"');
210                                 header('HTTP/1.0 401 Unauthorized');
211                         } elseif (AUTH_TYPE_FORM === $auth_type) {
212                                 $url_after_login = get_script_uri() . '?' . $g_query_string;
213                                 $loginurl = get_script_uri() . '?plugin=loginform'
214                                         . '&page=' . rawurlencode($page)
215                                         . '&url_after_login=' . rawurlencode($url_after_login);
216                                 header('HTTP/1.0 302 Found');
217                                 header('Location: ' . $loginurl);
218                         } elseif (AUTH_TYPE_EXTERNAL === $auth_type) {
219                                 $url_after_login = get_script_uri() . '?' . $g_query_string;
220                                 $loginurl = get_auth_external_login_url($page, $url_after_login);
221                                 header('HTTP/1.0 302 Found');
222                                 header('Location: ' . $loginurl);
223                         }
224                 }
225                 if ($exit_flag) {
226                         $body = $title = str_replace('$1',
227                                 htmlsc(strip_bracket($page)), $title_cannot);
228                         $page = str_replace('$1', make_search($page), $title_cannot);
229                         catbody($title, $page, $body);
230                         exit;
231                 }
232                 return FALSE;
233         } else {
234                 return TRUE;
235         }
236 }
237
238 /**
239  * Send 401 if client send a invalid credentials
240  *
241  * @return true if valid, false if invalid credentials
242  */
243 function ensure_valid_auth_user()
244 {
245         global $auth_type, $auth_users, $_msg_auth, $auth_user, $auth_groups;
246         global $auth_user_groups, $auth_user_fullname;
247         global $auth_provider_user_prefix;
248         switch ($auth_type) {
249                 case AUTH_TYPE_BASIC:
250                 {
251                         if (isset($_SERVER['PHP_AUTH_USER'])) {
252                                 $user = $_SERVER['PHP_AUTH_USER'];
253                                 if (in_array($user, array_keys($auth_users))) {
254                                         if (pkwk_hash_compute(
255                                                 $_SERVER['PHP_AUTH_PW'],
256                                                 $auth_users[$user]) === $auth_users[$user]) {
257                                                 $auth_user = $user;
258                                                 $auth_user_fullname = $auth_user;
259                                                 $auth_user_groups = get_groups_from_username($user);
260                                                 return true;
261                                         }
262                                 }
263                                 header('WWW-Authenticate: Basic realm="' . $_msg_auth . '"');
264                                 header('HTTP/1.0 401 Unauthorized');
265                         }
266                         $auth_user = '';
267                         $auth_user_groups = get_groups_from_username($user);
268                         return true; // no auth input
269                 }
270                 case AUTH_TYPE_FORM:
271                 case AUTH_TYPE_EXTERNAL:
272                 {
273                         session_start();
274                         $user = '';
275                         $fullname = '';
276                         if (isset($_SESSION['authenticated_user'])) {
277                                 $user = $_SESSION['authenticated_user'];
278                                 if (isset($_SESSION['authenticated_user_fullname'])) {
279                                         $fullname = $_SESSION['authenticated_user_fullname'];
280                                 } else {
281                                         if ($auth_type === AUTH_TYPE_EXTERNAL && $ldap_user_account) {
282                                                 $ldap_user_info = ldap_get_simple_user_info($user);
283                                                 if ($ldap_user_info) {
284                                                         $fullname = $ldap_user_info['fullname'];
285                                                         $_SESSION['authenticated_user_fullname'] = $fullname;
286                                                 }
287                                         }
288                                 }
289                         }
290                         $auth_user = $user;
291                         $auth_user_fullname = $fullname;
292                         break;
293                 }
294                 case AUTH_TYPE_EXTERNAL_REMOTE_USER:
295                         $auth_user = $_SERVER['REMOTE_USER'];
296                         $auth_user_fullname = $auth_user;
297                         break;
298                 case AUTH_TYPE_EXTERNAL_X_FORWARDED_USER:
299                         $auth_user =  $_SERVER['HTTP_X_FORWARDED_USER'];
300                         $auth_user_fullname = $auth_user;
301                         break;
302                 default: // AUTH_TYPE_NONE
303                         $auth_user = '';
304                         $auth_user_fullname = '';
305                         break;
306         }
307         $auth_user_groups = get_groups_from_username($auth_user);
308         return true; // is not basic auth
309 }
310
311 /**
312  * Return group name array whose group contains the user
313  *
314  * Result array contains reserved 'valid-user' group for all authenticated user
315  * @global array $auth_groups
316  * @param string $user
317  * @return array
318  */
319 function get_groups_from_username($user)
320 {
321         global $auth_groups;
322         if ($user !== '') {
323                 $groups = array();
324                 foreach ($auth_groups as $group=>$users) {
325                         $sp = explode(',', $users);
326                         if (in_array($user, $sp)) {
327                                 $groups[] = $group;
328                         }
329                 }
330                 // Implecit group that has same name as user itself
331                 $groups[] = $user;
332                 // 'valid-user' group for
333                 $valid_user = 'valid-user';
334                 if (!in_array($valid_user, $groups)) {
335                         $groups[] = $valid_user;
336                 }
337                 return $groups;
338         }
339         return array();
340 }
341
342 /**
343  * Get authenticated user name.
344  *
345  * @global type $auth_user
346  * @return type
347  */
348 function get_auth_user()
349 {
350         global $auth_user;
351         return $auth_user;
352 }
353
354 /**
355  * Sign in with username and password
356  *
357  * @param String username
358  * @param String password
359  * @return true is sign in is OK
360  */
361 function form_auth($username, $password)
362 {
363         global $ldap_user_account, $auth_users;
364         $user = $username;
365         if ($ldap_user_account) {
366                 // LDAP account
367                 return ldap_auth($username, $password);
368         } else {
369                 // Defined users in pukiwiki.ini.php
370                 if (in_array($user, array_keys($auth_users))) {
371                         if (pkwk_hash_compute(
372                                 $password,
373                                 $auth_users[$user]) === $auth_users[$user]) {
374                                 session_start();
375                                 session_regenerate_id(true); // require: PHP5.1+
376                                 $_SESSION['authenticated_user'] = $user;
377                                 $_SESSION['authenticated_user_fullname'] = $user;
378                                 return true;
379                         }
380                 }
381         }
382         return false;
383 }
384
385 function ldap_auth($username, $password)
386 {
387         global $ldap_url, $ldap_bind_dn, $ldap_bind_password;
388         if (preg_match('#^(ldap\:\/\/[^/]+/)(.*)$#', $ldap_url, $m)) {
389                 $ldap_server = $m[1];
390                 $ldap_base_dn = $m[2];
391                 $ldapconn = ldap_connect($ldap_server);
392                 if ($ldapconn) {
393                         ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
394                         if (preg_match('#\$login\b#', $ldap_bind_dn)) {
395                                 // Bind by user credential
396                                 $bind_dn_user = preg_replace('#\$login#', $username, $ldap_bind_dn);
397                                 $ldap_bind_user = ldap_bind($ldapconn, $bind_dn_user, $password);
398                                 if ($ldap_bind_user) {
399                                         $user_info = get_ldap_user_info($ldapconn, $username, $ldap_base_dn);
400                                         if ($user_info) {
401                                                 session_regenerate_id(true); // require: PHP5.1+
402                                                 $_SESSION['authenticated_user'] = $user_info['uid'];
403                                                 $_SESSION['authenticated_user_fullname'] = $user_info['fullname'];
404                                                 return true;
405                                         }
406                                 }
407                         } else {
408                                 // Bind by bind dn
409                                 $ldap_bind = ldap_bind($ldapconn, $ldap_bind_dn, $ldap_bind_password);
410                                 if ($ldap_bind) {
411                                         $user_info = get_ldap_user_info($ldapconn, $username, $ldap_base_dn);
412                                         if ($user_info) {
413                                                 $ldap_bind_user2 = ldap_bind($ldapconn, $user_info['dn'], $password);
414                                                 if ($ldap_bind_user2) {
415                                                         session_regenerate_id(true); // require: PHP5.1+
416                                                         $_SESSION['authenticated_user'] = $user_info['uid'];
417                                                         $_SESSION['authenticated_user_fullname'] = $user_info['fullname'];
418                                                         return true;
419                                                 }
420                                         }
421                                 }
422                         }
423                 }
424         }
425         return false;
426 }
427
428 // Get LDAP user info via bind DN
429 function ldap_get_simple_user_info($username)
430 {
431         global $ldap_url, $ldap_bind_dn, $ldap_bind_password;
432         if (preg_match('#^(ldap\:\/\/[^/]+/)(.*)$#', $ldap_url, $m)) {
433                 $ldap_server = $m[1];
434                 $ldap_base_dn = $m[2];
435                 $ldapconn = ldap_connect($ldap_server);
436                 if ($ldapconn) {
437                         ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
438                         // Bind by bind dn
439                         $ldap_bind = ldap_bind($ldapconn, $ldap_bind_dn, $ldap_bind_password);
440                         if ($ldap_bind) {
441                                 $user_info = get_ldap_user_info($ldapconn, $username, $ldap_base_dn);
442                                 if ($user_info) {
443                                         return $user_info;
444                                 }
445                         }
446                 }
447         }
448         return false;
449 }
450
451 /**
452  * Search user and get 'dn', 'uid', 'fullname' and 'mail'
453  * @param type $ldapconn
454  * @param type $username
455  * @param type $base_dn
456  * @return boolean
457  */
458 function get_ldap_user_info($ldapconn, $username, $base_dn) {
459         $filter = "(|(uid=$username)(sAMAccountName=$username))";
460         $result1 = ldap_search($ldapconn, $base_dn, $filter, array('dn', 'uid', 'cn', 'samaccountname', 'displayname', 'mail'));
461         $entries = ldap_get_entries($ldapconn, $result1);
462         $info = $entries[0];
463         if (isset($info['dn'])) {
464                 $user_dn = $info['dn'];
465                 $cano_username = $username;
466                 if (isset($info['uid'][0])) {
467                         $cano_username = $info['uid'][0];
468                 } elseif (isset($info['samaccountname'][0])) {
469                         $cano_username = $info['samaccountname'][0];
470                 }
471                 $cano_fullname = $username;
472                 if (isset($info['displayname'][0])) {
473                         $cano_fullname = $info['displayname'][0];
474                 } elseif (isset($info['cn'][0])) {
475                         $cano_fullname = $info['cn'][0];
476                 }
477                 return array(
478                         'dn' => $user_dn,
479                         'uid' => $cano_username,
480                         'fullname' => $cano_fullname,
481                         'mail' => $info['mail'][0]
482                 );
483         }
484         return false;
485 }
486
487 /**
488  * Redirect after login. Need to assing location or page
489  *
490  * @param type $location
491  * @param type $page
492  */
493 function form_auth_redirect($location, $page)
494 {
495         header('HTTP/1.0 302 Found');
496         if ($location) {
497                 header('Location: ' . $location);
498         } else {
499                 $url = get_script_uri() . '?' . $page;
500                 header('Location: ' . $url);
501         }
502 }
503
504 /**
505  * Get External Auth log-in URL
506  */
507 function get_auth_external_login_url($page, $url_after_login) {
508         global $auth_external_login_url_base;
509         $sep = '&';
510         if (strpos($auth_external_login_url_base, '?') === FALSE) {
511                 $sep = '?';
512         }
513         $url = $auth_external_login_url_base . $sep
514                 . 'page=' . rawurlencode($page)
515                 . '&url_after_login=' . rawurlencode($url_after_login);
516         return $url;
517 }