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