summaryrefslogtreecommitdiff
path: root/inc/auth_ldap.php
blob: 6c456231399b51594da3cc76b3d64a6f6d7a6604 (plain)
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
<?php
/**
 * LDAP authentication backend
 * 
 * tested with openldap 2.x on Debian only
 *
 * PHPs LDAP extension is needed
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Andreas Gohr <andi@splitbrain.org>
 */

//check for LDAP extension on load
if(!function_exists('ldap_connect'))
  msg("LDAP extension not found",-1);

/**
 * Connect to the LDAP server
 *
 * Holds the connection in global scope for multiple use
 *
 * @author  Andreas Gohr <andi@splitbrain.org>
 */
function auth_ldap_connect(){
  global $LDAP_CONNECTION;
  global $conf;
  $cnf = $conf['auth']['ldap'];

  if(!$LDAP_CONNECTION){
    $LDAP_CONNECTION = @ldap_connect($cnf['server']);
    if(!$LDAP_CONNECTION){
      msg("LDAP: couldn't connect to LDAP server",-1);
      return false;
    }
    //set protocol version
    if($cnf['version']){
      if(!@ldap_set_option($LDAP_CONNECTION,
                           LDAP_OPT_PROTOCOL_VERSION,
                           $cnf['version'])){
        msg('Setting LDAP Protocol version '.$cnf['version'].' failed',-1);
        if($cnf['debug'])
          msg('LDAP errstr: '.htmlspecialchars(ldap_error($LDAP_CONNECTION)),0);

        //use TLS (needs version 3)
        if ($cnf['starttls']) {
          if (!@ldap_start_tls($LDAP_CONNECTION)){
            msg('Starting TLS failed',-1);
            if($cnf['debug'])
              msg('LDAP errstr: '.htmlspecialchars(ldap_error($LDAP_CONNECTION)),0);
          }
        }
      }
    }
  }
  return $LDAP_CONNECTION;
}

/**
 * Check user+password [required auth function]
 *
 * Checks if the given user exists and the given
 * plaintext password is correct by trying to bind
 * to the LDAP server
 *
 * @author  Andreas Gohr <andi@splitbrain.org>
 * @return  bool
 */
function auth_checkPass($user,$pass){
  global $conf;
  $cnf = $conf['auth']['ldap'];

  //reject empty password
  if(empty($pass)) return false;

  //connect to LDAP Server
  $conn = auth_ldap_connect();
  if(!$conn) return false;

  if(!empty($cnf['userfilter'])) {
    //get dn for given user
    $info = auth_getUserData($user);
    $dn   = $info['dn'];  
    if(!$dn) return false;
  } else {
    // dn is defined in the usertree
    $dn = auth_ldap_makeFilter($cnf['usertree'], array('user'=>$user)); 
  }
  //try to bind with dn
  if(@ldap_bind($conn,$dn,$pass)){
    if($cnf['debug']) msg('LDAP errstr: '.htmlspecialchars(ldap_error($conn)),0);
    return true;
  }
  return false;
}

/**
 * Return user info [required auth function]
 *
 * Returns info about the given user needs to contain
 * at least these fields:
 *
 * name string  full name of the user
 * mail string  email addres of the user
 * grps array   list of groups the user is in
 *
 * This LDAP specific function returns the following
 * addional fields:
 *
 * dn   string  distinguished name (DN)
 * uid  string  Posix User ID
 *
 * @author  Andreas Gohr <andi@splitbrain.org>
 * @author  Trouble
 * @author  Dan Allen <dan.j.allen@gmail.com>
 * @auhtor  <evaldas.auryla@pheur.org>
 */
function auth_getUserData($user){
  global $conf;
  $cnf = $conf['auth']['ldap'];

  //connect to LDAP Server
  $conn = auth_ldap_connect();
  if(!$conn) return false;

  //bind to server to lookup userdata
  if ($cnf['binddn']) {
    //use superuser credentials
    if(!@ldap_bind($conn,$cnf['binddn'],$cnf['bindpw'])){
      msg("LDAP: can not bind as superuser",-1);
      if($cnf['debug']) msg('LDAP errstr: '.htmlspecialchars(ldap_error($conn)),0);
      return false;
    }
  }elseif(!empty($cnf['userfilter'])){
    //bind anonymous if we need to do a search for the dn
    if(!@ldap_bind($conn)){
      msg("LDAP: can not bind anonymously",-1);
      if($cnf['debug']) msg('LDAP errstr: '.htmlspecialchars(ldap_error($conn)),0);
      return false;
    }
  }
  $info['user']= $user;

  //get info for given user
  $base = auth_ldap_makeFilter($cnf['usertree'], $info); 
  if(!empty($cnf['userfilter'])) {
    $filter = auth_ldap_makeFilter($cnf['userfilter'], $info); 
  } else {
    $filter = "(ObjectClass=*)";
  }
  $sr     = ldap_search($conn, $base, $filter);;
  $result = ldap_get_entries($conn, $sr);
  $user_result = $result[0]; 
  if($result['count'] != 1){
    return false; //user not found
  }

  //general user info
  $info['dn']= $user_result['dn'];
  $info['mail']= $user_result['mail'][0];
  $info['name']= $user_result['cn'][0];

  //use ActiveDirectory sAMAccountName as uid
  if(isset($result[0]['sAMAccountName'][0])){
    $info['uid'] = $result[0]['sAMAccountName'][0];
  }else{
    $info['uid'] = $result[0]['uid'][0];
  }

  //get primary group id
  $gid = $result[0]['gidnumber'][0];

  //handle ActiveDirectory memberOf
  if(is_array($result[0]['memberof'])){
    foreach($result[0]['memberof'] as $grp){
      if (preg_match("/CN=(.+?),/i",$grp,$match)) {
        $info['grps'][] = trim($match[1]);
      }
    }
  }

  //get groups for given user if grouptree is given
  if (!empty($cnf['grouptree'])) {
    $base = auth_ldap_makeFilter($cnf['grouptree'], $user_result); 
    $filter = auth_ldap_makeFilter($cnf['groupfilter'], $user_result); 

    $sr = @ldap_search($conn, $base, $filter);
    if(!$sr){
      msg("LDAP: Reading group memberships failed",-1);
      if($cnf['debug']) msg('LDAP errstr: '.htmlspecialchars(ldap_error($conn)),0);
      return false;
    }
    $result = ldap_get_entries($conn, $sr);
    foreach($result as $grp){
      if(!empty($grp['cn'][0]))
        $info['grps'][] = $grp['cn'][0];
    }
  }

  //if no groups were found always return the default group
  if(!count($info['grps'])) $info['grps'][] = $conf['defaultgroup'];
  
  return $info;
}

/**
 * Create a new User [required auth function]
 *
 * Not implemented
 *
 * @author  Andreas Gohr <andi@splitbrain.org>
 */
function auth_createUser($user,$pass,$name,$mail){
  msg("Sorry. Creating users is not supported by the LDAP backend",-1);
  return null;
}


/**
 * Make ldap filter strings.
 *
 * Used by auth_getUserData to make the filter
 * strings for grouptree and groupfilter
 *
 * filter      string  ldap search filter with placeholders
 * placeholders array   array with the placeholders
 * 
 * @author  Troels Liebe Bentsen <tlb@rapanden.dk>
 * @return  string
 */
function auth_ldap_makeFilter($filter, $placeholders) {
  preg_match_all("/%{([^}]+)/", $filter, $matches, PREG_PATTERN_ORDER);
  //replace each match
  foreach ($matches[1] as $match) {
    //take first element if array
    if(is_array($placeholders[$match])) {
      $value = $placeholders[$match][0];
    } else {
      $value = $placeholders[$match];
    }
    $filter = str_replace('%{'.$match.'}', $value, $filter);
  }
  return $filter;
}

//Setup VIM: ex: et ts=2 enc=utf-8 :