bug 3651 followup: updated for new GetMember() parameter style
[koha.git] / C4 / Auth_with_ldap.pm
1 package C4::Auth_with_ldap;
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20 use strict;
21 # use warnings; almost?
22 use Digest::MD5 qw(md5_base64);
23
24 use C4::Debug;
25 use C4::Context;
26 use C4::Members qw(AddMember changepassword);
27 use C4::Members::Attributes;
28 use C4::Members::AttributeTypes;
29 use C4::Utils qw( :all );
30 use List::MoreUtils qw( any );
31 use Net::LDAP;
32 use Net::LDAP::Filter;
33
34 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug);
35
36 BEGIN {
37         require Exporter;
38         $VERSION = 3.10;        # set the version for version checking
39         @ISA    = qw(Exporter);
40         @EXPORT = qw( checkpw_ldap );
41 }
42
43 # Redefine checkpw_ldap:
44 # connect to LDAP (named or anonymous)
45 # ~ retrieves $userid from KOHA_CONF mapping
46 # ~ then compares $password with userPassword 
47 # ~ then gets the LDAP entry
48 # ~ and calls the memberadd if necessary
49
50 sub ldapserver_error ($) {
51         return sprintf('No ldapserver "%s" defined in KOHA_CONF: ' . $ENV{KOHA_CONF}, shift);
52 }
53
54 use vars qw($mapping @ldaphosts $base $ldapname $ldappassword);
55 my $context = C4::Context->new()        or die 'C4::Context->new failed';
56 my $ldap = C4::Context->config("ldapserver") or die 'No "ldapserver" in server hash from KOHA_CONF: ' . $ENV{KOHA_CONF};
57 my $prefhost  = $ldap->{hostname}       or die ldapserver_error('hostname');
58 my $base      = $ldap->{base}           or die ldapserver_error('base');
59 $ldapname     = $ldap->{user}           ;
60 $ldappassword = $ldap->{pass}           ;
61 our %mapping  = %{$ldap->{mapping}} || (); #    or die ldapserver_error('mapping');
62 my @mapkeys = keys %mapping;
63 $debug and print STDERR "Got ", scalar(@mapkeys), " ldap mapkeys (  total  ): ", join ' ', @mapkeys, "\n";
64 @mapkeys = grep {defined $mapping{$_}->{is}} @mapkeys;
65 $debug and print STDERR "Got ", scalar(@mapkeys), " ldap mapkeys (populated): ", join ' ', @mapkeys, "\n";
66
67 my %config = (
68         anonymous => ($ldapname and $ldappassword) ? 0 : 1,
69     replicate => defined($ldap->{replicate}) ? $ldap->{replicate} : 1,  #    add from LDAP to Koha database for new user
70        update => defined($ldap->{update}   ) ? $ldap->{update}    : 1,  # update from LDAP to Koha database for existing user
71 );
72
73 sub description ($) {
74         my $result = shift or return undef;
75         return "LDAP error #" . $result->code
76                         . ": " . $result->error_name . "\n"
77                         . "# " . $result->error_text . "\n";
78 }
79
80 sub search_method {
81     my $db     = shift or return;
82     my $userid = shift or return;
83         my $uid_field = $mapping{userid}->{is} or die ldapserver_error("mapping for 'userid'");
84         my $filter = Net::LDAP::Filter->new("$uid_field=$userid") or die "Failed to create new Net::LDAP::Filter";
85     my $res = ($config{anonymous}) ? $db->bind : $db->bind($ldapname, password=>$ldappassword);
86     if ($res->code) {           # connection refused
87         warn "LDAP bind failed as ldapuser " . ($ldapname || '[ANONYMOUS]') . ": " . description($res);
88         return 0;
89     }
90         my $search = $db->search(
91                   base => $base,
92                 filter => $filter,
93                 # attrs => ['*'],
94         ) or die "LDAP search failed to return object.";
95         my $count = $search->count;
96         if ($search->code > 0) {
97                 warn sprintf("LDAP Auth rejected : %s gets %d hits\n", $filter->as_string, $count) . description($search);
98                 return 0;
99         }
100         if ($count != 1) {
101                 warn sprintf("LDAP Auth rejected : %s gets %d hits\n", $filter->as_string, $count);
102                 return 0;
103         }
104     return $search;
105 }
106
107 sub checkpw_ldap {
108     my ($dbh, $userid, $password) = @_;
109     my @hosts = split(',', $prefhost);
110     my $db = Net::LDAP->new(\@hosts);
111         #$debug and $db->debug(5);
112     my $userldapentry;
113         if ( $ldap->{auth_by_bind} ) {
114         my $principal_name = $ldap->{principal_name};
115         if ($principal_name and $principal_name =~ /\%/) {
116             $principal_name = sprintf($principal_name,$userid);
117         } else {
118             $principal_name = $userid;
119         }
120                 my $res = $db->bind( $principal_name, password => $password );
121         if ( $res->code ) {
122             $debug and warn "LDAP bind failed as kohauser $principal_name: ". description($res);
123             return 0;
124         }
125         } else {
126         my $search = search_method($db, $userid) or return 0;   # warnings are in the sub
127         $userldapentry = $search->shift_entry;
128                 my $cmpmesg = $db->compare( $userldapentry, attr=>'userpassword', value => $password );
129                 if ($cmpmesg->code != 6) {
130                         warn "LDAP Auth rejected : invalid password for user '$userid'. " . description($cmpmesg);
131                         return 0;
132                 }
133         }
134
135     # To get here, LDAP has accepted our user's login attempt.
136     # But we still have work to do.  See perldoc below for detailed breakdown.
137
138     my (%borrower);
139         my ($borrowernumber,$cardnumber,$local_userid,$savedpw) = exists_local($userid);
140
141     if (( $borrowernumber and $config{update}   ) or
142         (!$borrowernumber and $config{replicate})   ) {
143         %borrower = ldap_entry_2_hash($userldapentry,$userid);
144         $debug and print STDERR "checkpw_ldap received \%borrower w/ " . keys(%borrower), " keys: ", join(' ', keys %borrower), "\n";
145     }
146
147     if ($borrowernumber) {
148         if ($config{update}) { # A1, B1
149             my $c2 = &update_local($local_userid,$password,$borrowernumber,\%borrower) || '';
150             ($cardnumber eq $c2) or warn "update_local returned cardnumber '$c2' instead of '$cardnumber'";
151         } else { # C1, D1
152             # maybe update just the password?
153         }
154     } elsif ($config{replicate}) { # A2, C2
155         $borrowernumber = AddMember(%borrower) or die "AddMember failed";
156    } else {
157         return 0;   # B2, D2
158     }
159         if (C4::Context->preference('ExtendedPatronAttributes') && $borrowernumber && ($config{update} ||$config{replicate})) {
160                 my @types = C4::Members::AttributeTypes::GetAttributeTypes();
161                 my @attributes = grep{my $key=$_; any{$_ eq $key}@types;} keys %borrower;
162                 my $extended_patron_attributes = map{{code=>$_,value=>$borrower{$_}}}@attributes;
163                 my @errors;
164                 #Check before add
165                 for (my $i; $i< scalar(@$extended_patron_attributes)-1;$i++) {
166                         my $attr=$extended_patron_attributes->[$i];
167                         unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
168                                 unshift @errors, $i;
169                                 warn "ERROR_extended_unique_id_failed $attr->{code} $attr->{value}";
170                         }
171                 }
172                 #Removing erroneous attributes
173                 foreach my $index (@errors){
174                         @$extended_patron_attributes=splice(@$extended_patron_attributes,$index,1);
175                 }
176            C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
177         }
178 return(1, $cardnumber);
179 }
180
181 # Pass LDAP entry object and local cardnumber (userid).
182 # Returns borrower hash.
183 # Edit KOHA_CONF so $memberhash{'xxx'} fits your ldap structure.
184 # Ensure that mandatory fields are correctly filled!
185 #
186 sub ldap_entry_2_hash ($$) {
187         my $userldapentry = shift;
188         my %borrower = ( cardnumber => shift );
189         my %memberhash;
190         $userldapentry->exists('uid');  # This is bad, but required!  By side-effect, this initializes the attrs hash. 
191         if ($debug) {
192                 print STDERR "\nkeys(\%\$userldapentry) = " . join(', ', keys %$userldapentry), "\n", $userldapentry->dump();
193                 foreach (keys %$userldapentry) {
194                         print STDERR "\n\nLDAP key: $_\t", sprintf('(%s)', ref $userldapentry->{$_}), "\n";
195                         hashdump("LDAP key: ",$userldapentry->{$_});
196                 }
197         }
198         my $x = $userldapentry->{attrs} or return undef;
199         foreach (keys %$x) {
200                 $memberhash{$_} = join ' ', @{$x->{$_}};        
201                 $debug and print STDERR sprintf("building \$memberhash{%s} = ", $_, join(' ', @{$x->{$_}})), "\n";
202         }
203         $debug and print STDERR "Finsihed \%memberhash has ", scalar(keys %memberhash), " keys\n",
204                                         "Referencing \%mapping with ", scalar(keys %mapping), " keys\n";
205         foreach my $key (keys %mapping) {
206                 my  $data = $memberhash{$mapping{$key}->{is}}; 
207                 $debug and printf STDERR "mapping %20s ==> %-20s (%s)\n", $key, $mapping{$key}->{is}, $data;
208                 unless (defined $data) { 
209                         $data = $mapping{$key}->{content} || '';        # default or failsafe ''
210                 }
211                 $borrower{$key} = ($data ne '') ? $data : ' ' ;
212         }
213         $borrower{initials} = $memberhash{initials} || 
214                 ( substr($borrower{'firstname'},0,1)
215                 . substr($borrower{ 'surname' },0,1)
216                 . " ");
217         return %borrower;
218 }
219
220 sub exists_local($) {
221         my $arg = shift;
222         my $dbh = C4::Context->dbh;
223         my $select = "SELECT borrowernumber,cardnumber,userid,password FROM borrowers ";
224
225         my $sth = $dbh->prepare("$select WHERE userid=?");      # was cardnumber=?
226         $sth->execute($arg);
227         $debug and printf STDERR "Userid '$arg' exists_local? %s\n", $sth->rows;
228         ($sth->rows == 1) and return $sth->fetchrow;
229
230         $sth = $dbh->prepare("$select WHERE cardnumber=?");
231         $sth->execute($arg);
232         $debug and printf STDERR "Cardnumber '$arg' exists_local? %s\n", $sth->rows;
233         ($sth->rows == 1) and return $sth->fetchrow;
234         return 0;
235 }
236
237 sub _do_changepassword {
238     my ($userid, $borrowerid, $digest) = @_;
239     $debug and print STDERR "changing local password for borrowernumber=$borrowerid to '$digest'\n";
240     changepassword($userid, $borrowerid, $digest);
241
242         # Confirm changes
243         my $sth = C4::Context->dbh->prepare("SELECT password,cardnumber FROM borrowers WHERE borrowernumber=? ");
244         $sth->execute($borrowerid);
245         if ($sth->rows) {
246                 my ($md5password, $cardnum) = $sth->fetchrow;
247         ($digest eq $md5password) and return $cardnum;
248                 warn "Password mismatch after update to cardnumber=$cardnum (borrowernumber=$borrowerid)";
249                 return undef;
250         }
251         die "Unexpected error after password update to userid/borrowernumber: $userid / $borrowerid.";
252 }
253
254 sub update_local($$$$) {
255         my   $userid   = shift             or return undef;
256         my   $digest   = md5_base64(shift) or return undef;
257         my $borrowerid = shift             or return undef;
258         my $borrower   = shift             or return undef;
259         my @keys = keys %$borrower;
260         my $dbh = C4::Context->dbh;
261         my $query = "UPDATE  borrowers\nSET     " . 
262                 join(',', map {"$_=?"} @keys) .
263                 "\nWHERE   borrowernumber=? "; 
264         my $sth = $dbh->prepare($query);
265         if ($debug) {
266                 print STDERR $query, "\n",
267                         join "\n", map {"$_ = '" . $borrower->{$_} . "'"} @keys;
268                 print STDERR "\nuserid = $userid\n";
269         }
270         $sth->execute(
271                 ((map {$borrower->{$_}} @keys), $borrowerid)
272         );
273
274         # MODIFY PASSWORD/LOGIN
275         _do_changepassword($userid, $borrowerid, $digest);
276 }
277
278 1;
279 __END__
280
281 =head1 NAME
282
283 C4::Auth - Authenticates Koha users
284
285 =head1 SYNOPSIS
286
287   use C4::Auth_with_ldap;
288
289 =head1 LDAP Configuration
290
291     This module is specific to LDAP authentification. It requires Net::LDAP package and one or more
292         working LDAP servers.
293         To use it :
294            * Modify ldapserver element in KOHA_CONF
295            * Establish field mapping in <mapping> element.
296
297         For example, if your user records are stored according to the inetOrgPerson schema, RFC#2798,
298         the username would match the "uid" field, and the password should match the "userpassword" field.
299
300         Make sure that ALL required fields are populated by your LDAP database (and mapped in KOHA_CONF).  
301         What are the required fields?  Well, in mysql you can check the database table "borrowers" like this:
302
303         mysql> show COLUMNS from borrowers;
304                 +------------------+--------------+------+-----+---------+----------------+
305                 | Field            | Type         | Null | Key | Default | Extra          |
306                 +------------------+--------------+------+-----+---------+----------------+
307                 | borrowernumber   | int(11)      | NO   | PRI | NULL    | auto_increment | 
308                 | cardnumber       | varchar(16)  | YES  | UNI | NULL    |                | 
309                 | surname          | mediumtext   | NO   |     |         |                | 
310                 | firstname        | text         | YES  |     | NULL    |                | 
311                 | title            | mediumtext   | YES  |     | NULL    |                | 
312                 | othernames       | mediumtext   | YES  |     | NULL    |                | 
313                 | initials         | text         | YES  |     | NULL    |                | 
314                 | streetnumber     | varchar(10)  | YES  |     | NULL    |                | 
315                 | streettype       | varchar(50)  | YES  |     | NULL    |                | 
316                 | address          | mediumtext   | NO   |     |         |                | 
317                 | address2         | text         | YES  |     | NULL    |                | 
318                 | city             | mediumtext   | NO   |     |         |                | 
319                 | zipcode          | varchar(25)  | YES  |     | NULL    |                | 
320                 | email            | mediumtext   | YES  |     | NULL    |                | 
321                 | phone            | text         | YES  |     | NULL    |                | 
322                 | mobile           | varchar(50)  | YES  |     | NULL    |                | 
323                 | fax              | mediumtext   | YES  |     | NULL    |                | 
324                 | emailpro         | text         | YES  |     | NULL    |                | 
325                 | phonepro         | text         | YES  |     | NULL    |                | 
326                 | B_streetnumber   | varchar(10)  | YES  |     | NULL    |                | 
327                 | B_streettype     | varchar(50)  | YES  |     | NULL    |                | 
328                 | B_address        | varchar(100) | YES  |     | NULL    |                | 
329                 | B_city           | mediumtext   | YES  |     | NULL    |                | 
330                 | B_zipcode        | varchar(25)  | YES  |     | NULL    |                | 
331                 | B_email          | text         | YES  |     | NULL    |                | 
332                 | B_phone          | mediumtext   | YES  |     | NULL    |                | 
333                 | dateofbirth      | date         | YES  |     | NULL    |                | 
334                 | branchcode       | varchar(10)  | NO   | MUL |         |                | 
335                 | categorycode     | varchar(10)  | NO   | MUL |         |                | 
336                 | dateenrolled     | date         | YES  |     | NULL    |                | 
337                 | dateexpiry       | date         | YES  |     | NULL    |                | 
338                 | gonenoaddress    | tinyint(1)   | YES  |     | NULL    |                | 
339                 | lost             | tinyint(1)   | YES  |     | NULL    |                | 
340                 | debarred         | tinyint(1)   | YES  |     | NULL    |                | 
341                 | contactname      | mediumtext   | YES  |     | NULL    |                | 
342                 | contactfirstname | text         | YES  |     | NULL    |                | 
343                 | contacttitle     | text         | YES  |     | NULL    |                | 
344                 | guarantorid      | int(11)      | YES  |     | NULL    |                | 
345                 | borrowernotes    | mediumtext   | YES  |     | NULL    |                | 
346                 | relationship     | varchar(100) | YES  |     | NULL    |                | 
347                 | ethnicity        | varchar(50)  | YES  |     | NULL    |                | 
348                 | ethnotes         | varchar(255) | YES  |     | NULL    |                | 
349                 | sex              | varchar(1)   | YES  |     | NULL    |                | 
350                 | password         | varchar(30)  | YES  |     | NULL    |                | 
351                 | flags            | int(11)      | YES  |     | NULL    |                | 
352                 | userid           | varchar(30)  | YES  | MUL | NULL    |                |  # UNIQUE in next release.
353                 | opacnote         | mediumtext   | YES  |     | NULL    |                | 
354                 | contactnote      | varchar(255) | YES  |     | NULL    |                | 
355                 | sort1            | varchar(80)  | YES  |     | NULL    |                | 
356                 | sort2            | varchar(80)  | YES  |     | NULL    |                | 
357                 +------------------+--------------+------+-----+---------+----------------+
358                 50 rows in set (0.01 sec)
359         
360                 Where Null="NO", the field is required.
361
362 =head1 KOHA_CONF and field mapping
363
364 Example XML stanza for LDAP configuration in KOHA_CONF.
365
366  <config>
367   ...
368   <useldapserver>1</useldapserver>
369   <!-- LDAP SERVER (optional) -->
370   <ldapserver id="ldapserver">
371     <hostname>localhost</hostname>
372     <base>dc=metavore,dc=com</base>
373     <user>cn=Manager,dc=metavore,dc=com</user>             <!-- DN, if not anonymous -->
374     <pass>metavore</pass>          <!-- password, if not anonymous -->
375     <replicate>1</replicate>       <!-- add new users from LDAP to Koha database -->
376     <update>1</update>             <!-- update existing users in Koha database -->
377     <auth_by_bind>0</auth_by_bind> <!-- set to 1 to authenticate by binding instead of
378                                         password comparison, e.g., to use Active Directory -->
379     <principal_name>%s@my_domain.com</principal_name>
380                                    <!-- optional, for auth_by_bind: a printf format to make userPrincipalName from koha userid -->
381     <mapping>                  <!-- match koha SQL field names to your LDAP record field names -->
382       <firstname    is="givenname"      ></firstname>
383       <surname      is="sn"             ></surname>
384       <address      is="postaladdress"  ></address>
385       <city         is="l"              >Athens, OH</city>
386       <zipcode      is="postalcode"     ></zipcode>
387       <branchcode   is="branch"         >MAIN</branchcode>
388       <userid       is="uid"            ></userid>
389       <password     is="userpassword"   ></password>
390       <email        is="mail"           ></email>
391       <categorycode is="employeetype"   >PT</categorycode>
392       <phone        is="telephonenumber"></phone>
393     </mapping> 
394   </ldapserver> 
395  </config>
396
397 The <mapping> subelements establish the relationship between mysql fields and LDAP attributes. The element name
398 is the column in mysql, with the "is" characteristic set to the LDAP attribute name.  Optionally, any content
399 between the element tags is taken as the default value.  In this example, the default categorycode is "PT" (for
400 patron).  
401
402 =head1 CONFIGURATION
403
404 Once a user has been accepted by the LDAP server, there are several possibilities for how Koha will behave, depending on 
405 your configuration and the presence of a matching Koha user in your local DB:
406
407                          LOCAL_USER
408  OPTION UPDATE REPLICATE  EXISTS?  RESULT
409    A1      1       1        1      OK : We're updating them anyway.
410    A2      1       1        0      OK : We're adding them anyway.
411    B1      1       0        1      OK : We update them.
412    B2      1       0        0     FAIL: We cannot add new user.
413    C1      0       1        1      OK : We do nothing.  (maybe should update password?)
414    C2      0       1        0      OK : We add the new user.
415    D1      0       0        1      OK : We do nothing.  (maybe should update password?)
416    D2      0       0        0     FAIL: We cannot add new user.
417
418 Note: failure here just means that Koha will fallback to checking the local DB.  That is, a given user could login with
419 their LDAP password OR their local one.  If this is a problem, then you should enable update and supply a mapping for 
420 password.  Then the local value will be updated at successful LDAP login and the passwords will be synced.
421
422 If you choose NOT to update local users, the borrowers table will not be affected at all.
423 Note that this means that patron passwords may appear to change if LDAP is ever disabled, because
424 the local table never contained the LDAP values.  
425
426 =head2 auth_by_bind
427
428 Binds as the user instead of retrieving their record.  Recommended if update disabled.
429
430 =head2 principal_name
431
432 Provides an optional sprintf-style format for manipulating the userid before the bind.
433 Even though the userPrincipalName is one intended target, any uniquely identifying
434 attribute that the server allows to be used for binding could be used.
435
436 Currently, principal_name only operates when auth_by_bind is enabled.
437
438 =head2 Active Directory 
439
440 The auth_by_bind and principal_name settings are recommended for Active Directory.
441
442 Under default Active Directory rules, we cannot determine the distinguishedName attribute from the Koha userid as reliably as
443 we would typically under openldap.  Instead of:
444
445     distinguishedName: CN=barnes.7,DC=my_company,DC=com
446
447 We might get:
448
449     distinguishedName: CN=Barnes\, Jim,OU=Test Accounts,OU=User Accounts,DC=my_company,DC=com
450
451 Matching that would require us to know more info about the account (firstname, surname) and to include punctuation and whitespace
452 in Koha userids.  But the userPrincipalName should be consistent, something like:
453
454     userPrincipalName: barnes.7@my_company.com
455
456 Therefore it is often easier to bind to Active Directory with userPrincipalName, effectively the
457 canonical email address for that user, or what it would be if email were enabled for them.  If Koha userid values 
458 will match the username portion of the userPrincipalName, and the domain suffix is the same for all users, then use principal_name
459 like this:
460     <principal_name>%s@core.my_company.com</principal_name>
461
462 The user of the previous example, barnes.7, would then attempt to bind as:
463     barnes.7@core.my_company.com
464
465 =head1 SEE ALSO
466
467 CGI(3)
468
469 Net::LDAP()
470
471 XML::Simple()
472
473 Digest::MD5(3)
474
475 sprintf()
476
477 =cut
478
479 # For reference, here's an important difference in the data structure we rely on.
480 # ========================================
481 # Using attrs instead of {asn}->attributes
482 # ========================================
483 #
484 #       LDAP key: ->{             cn} = ARRAY w/ 3 members.
485 #       LDAP key: ->{             cn}->{           sss} = sss
486 #       LDAP key: ->{             cn}->{   Steve Smith} = Steve Smith
487 #       LDAP key: ->{             cn}->{Steve S. Smith} = Steve S. Smith
488 #
489 #       LDAP key: ->{      givenname} = ARRAY w/ 1 members.
490 #       LDAP key: ->{      givenname}->{Steve} = Steve
491 #