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