Bug 24065: Fail shib login if multiple users matched
[koha-ffzg.git] / C4 / Auth_with_shibboleth.pm
1 package C4::Auth_with_shibboleth;
2
3 # Copyright 2014 PTFS Europe
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 use C4::Debug;
23 use C4::Context;
24 use Koha::AuthUtils qw(get_script_name);
25 use Koha::Database;
26 use Koha::Patrons;
27 use C4::Members::Messaging;
28 use Carp;
29 use CGI;
30 use List::MoreUtils qw(any);
31
32 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug);
33
34 BEGIN {
35     require Exporter;
36     $debug   = $ENV{DEBUG};
37     @ISA     = qw(Exporter);
38     @EXPORT =
39       qw(shib_ok logout_shib login_shib_url checkpw_shib get_login_shib);
40 }
41
42 # Check that shib config is not malformed
43 sub shib_ok {
44     my $config = _get_shib_config();
45
46     if ($config) {
47         return 1;
48     }
49
50     return 0;
51 }
52
53 # Logout from Shibboleth
54 sub logout_shib {
55     my ($query) = @_;
56     my $uri = _get_uri();
57     print $query->redirect( $uri . "/Shibboleth.sso/Logout?return=$uri" );
58 }
59
60 # Returns Shibboleth login URL with callback to the requesting URL
61 sub login_shib_url {
62     my ($query) = @_;
63
64     my $param = _get_uri() . get_script_name();
65     if ( $query->query_string() ) {
66         $param = $param . '?' . $query->query_string();
67     }
68     my $uri = _get_uri() . "/Shibboleth.sso/Login?target=$param";
69     return $uri;
70 }
71
72 # Returns shibboleth user login
73 sub get_login_shib {
74
75 # In case of a Shibboleth authentication, we expect a shibboleth user attribute
76 # to contain the login match point of the shibboleth-authenticated user. This match
77 # point is configured in koha-conf.xml
78
79 # Shibboleth attributes are mapped into http environmement variables, so we're getting
80 # the match point of the user this way
81
82     # Get shibboleth config
83     my $config = _get_shib_config();
84
85     my $matchAttribute = $config->{mapping}->{ $config->{matchpoint} }->{is};
86
87     if ( any { /(^psgi\.|^plack\.)/i } keys %ENV ) {
88       $debug and warn $matchAttribute . " value: " . $ENV{"HTTP_".uc($matchAttribute)};
89       return $ENV{"HTTP_".uc($matchAttribute)} || '';
90     } else {
91       $debug and warn $matchAttribute . " value: " . $ENV{$matchAttribute};
92       return $ENV{$matchAttribute} || '';
93     }
94 }
95
96 # Checks for password correctness
97 # In our case : does the given attribute match one of our users ?
98 sub checkpw_shib {
99     $debug and warn "checkpw_shib";
100
101     my ( $match ) = @_;
102     my $config = _get_shib_config();
103     $debug and warn "User Shibboleth-authenticated as: $match";
104
105     # Does the given shibboleth attribute value ($match) match a valid koha user ?
106     my $borrowers = Koha::Patrons->search( { $config->{matchpoint} => $match } );
107     if ( $borrowers->count > 1 ){
108         # If we have more than 1 borrower the matchpoint is not unique
109         # we cannot know which patron is the correct one, so we should fail
110          $debug and warn "There are several users with $config->{matchpoint} of $match, matchpoints must be unique";
111         return 0;
112     }
113     my $borrower = $borrowers->next;
114     if ( defined($borrower) ) {
115         if ($config->{'sync'}) {
116             _sync($borrower->borrowernumber, $config, $match);
117         }
118         return ( 1, $borrower->get_column('cardnumber'), $borrower->get_column('userid') );
119     }
120
121     if ( $config->{'autocreate'} ) {
122         return _autocreate( $config, $match );
123     } else {
124         # If we reach this point, the user is not a valid koha user
125          $debug and warn "User with $config->{matchpoint} of $match is not a valid Koha user";
126         return 0;
127     }
128 }
129
130 sub _autocreate {
131     my ( $config, $match ) = @_;
132
133     my %borrower = ( $config->{matchpoint} => $match );
134
135     while ( my ( $key, $entry ) = each %{$config->{'mapping'}} ) {
136         if ( any { /(^psgi|^plack)/i } keys %ENV ) {
137             $borrower{$key} = ( $entry->{'is'} && $ENV{"HTTP_" . uc($entry->{'is'}) } ) || $entry->{'content'} || '';
138         } else {
139             $borrower{$key} = ( $entry->{'is'} && $ENV{ $entry->{'is'} } ) || $entry->{'content'} || '';
140         }
141     }
142
143     my $patron = Koha::Patron->new( \%borrower )->store;
144     C4::Members::Messaging::SetMessagingPreferencesFromDefaults( { borrowernumber => $patron->borrowernumber, categorycode => $patron->categorycode } );
145
146     return ( 1, $patron->cardnumber, $patron->userid );
147 }
148
149 sub _sync {
150     my ($borrowernumber, $config, $match ) = @_;
151     my %borrower;
152     $borrower{'borrowernumber'} = $borrowernumber;
153     while ( my ( $key, $entry ) = each %{$config->{'mapping'}} ) {
154         if ( any { /(^psgi|^plack)/i } keys %ENV ) {
155             $borrower{$key} = ( $entry->{'is'} && $ENV{"HTTP_" . uc($entry->{'is'}) } ) || $entry->{'content'} || '';
156         } else {
157             $borrower{$key} = ( $entry->{'is'} && $ENV{ $entry->{'is'} } ) || $entry->{'content'} || '';
158         }
159     }
160     my $patron = Koha::Patrons->find( $borrowernumber );
161     $patron->set(\%borrower)->store;
162 }
163
164 sub _get_uri {
165
166     my $protocol = "https://";
167     my $interface = C4::Context->interface;
168     $debug and warn "shibboleth interface: " . $interface;
169
170     my $uri;
171     if ( $interface eq 'intranet' ) {
172
173         $uri = C4::Context->preference('staffClientBaseURL') // '';
174         if ($uri eq '') {
175             $debug and warn 'staffClientBaseURL not set!';
176         }
177     } else {
178         $uri = C4::Context->preference('OPACBaseURL') // '';
179         if ($uri eq '') {
180             $debug and warn 'OPACBaseURL not set!';
181         }
182     }
183
184     if ($uri =~ /(.*):\/\/(.*)/) {
185         my $oldprotocol = $1;
186         if ($oldprotocol ne 'https') {
187             $debug
188                 and warn
189                   'Shibboleth requires OPACBaseURL/staffClientBaseURL to use the https protocol!';
190         }
191         $uri = $2;
192     }
193     my $return = $protocol . $uri;
194     return $return;
195 }
196
197 sub _get_shib_config {
198     my $config = C4::Context->config('shibboleth');
199
200     if ( !$config ) {
201         carp 'shibboleth config not defined' if $debug;
202         return 0;
203     }
204
205     if ( $config->{matchpoint}
206         && defined( $config->{mapping}->{ $config->{matchpoint} }->{is} ) )
207     {
208         if ($debug) {
209             warn "koha borrower field to match: " . $config->{matchpoint};
210             warn "shibboleth attribute to match: "
211               . $config->{mapping}->{ $config->{matchpoint} }->{is};
212         }
213         return $config;
214     }
215     else {
216         if ( !$config->{matchpoint} ) {
217             carp 'shibboleth matchpoint not defined';
218         }
219         else {
220             carp 'shibboleth matchpoint not mapped';
221         }
222         return 0;
223     }
224 }
225
226 1;
227 __END__
228
229 =head1 NAME
230
231 C4::Auth_with_shibboleth
232
233 =head1 SYNOPSIS
234
235 use C4::Auth_with_shibboleth;
236
237 =head1 DESCRIPTION
238
239 This module is specific to Shibboleth authentication in koha and relies heavily upon the native shibboleth service provider package in your operating system.
240
241 =head1 CONFIGURATION
242
243 To use this type of authentication these additional packages are required:
244
245 =over
246
247 =item *
248
249 libapache2-mod-shib2
250
251 =item *
252
253 libshibsp5:amd64
254
255 =item *
256
257 shibboleth-sp2-schemas
258
259 =back
260
261 We let the native shibboleth service provider packages handle all the complexities of shibboleth negotiation for us, and configuring this is beyond the scope of this documentation.
262
263 But to sum up, to get shibboleth working in koha, as a minimum you will need to:
264
265 =over
266
267 =item 1.
268
269 Create some metadata for your koha instance (if you're in a single instance setup then the default metadata available at https://youraddress.com/Shibboleth.sso/Metadata should be adequate)
270
271 =item 2.
272
273 Swap metadata with your Identidy Provider (IdP)
274
275 =item 3.
276
277 Map their attributes to what you want to see in koha
278
279 =item 4.
280
281 Tell apache that we wish to allow koha to authenticate via shibboleth.
282
283 This is as simple as adding the below to your virtualhost config (for CGI running):
284
285  <Location />
286    AuthType shibboleth
287    Require shibboleth
288  </Location>
289
290 Or (for Plack running):
291
292  <Location />
293    AuthType shibboleth
294    Require shibboleth
295    ShibUseEnvironment Off
296    ShibUseHeaders On
297  </Location>
298
299 IMPORTANT: Please note, if you are running in the plack configuration you should consult https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPSpoofChecking for security advice regarding header spoof checking settings. (See also bug 17776 on Bugzilla about enabling ShibUseHeaders.)
300
301 =item 5.
302
303 Configure koha to listen for shibboleth environment variables.
304
305 This is as simple as enabling B<useshibboleth> in koha-conf.xml:
306
307  <useshibboleth>1</useshibboleth>
308
309 =item 6.
310
311 Map shibboleth attributes to koha fields, and configure authentication match point in koha-conf.xml.
312
313  <shibboleth>
314    <matchpoint>userid</matchpoint> <!-- koha borrower field to match upon -->
315    <mapping>
316      <userid is="eduPersonID"></userid> <!-- koha borrower field to shibboleth attribute mapping -->
317    </mapping>
318  </shibboleth>
319
320 Note: The minimum you need here is a <matchpoint> block, containing a valid column name from the koha borrowers table, and a <mapping> block containing a relation between the chosen matchpoint and the shibboleth attribute name.
321
322 =back
323
324 It should be as simple as that; you should now be able to login via shibboleth in the opac.
325
326 If you need more help configuring your B<S>ervice B<P>rovider to authenticate against a chosen B<Id>entity B<P>rovider then it might be worth taking a look at the community wiki L<page|http://wiki.koha-community.org/wiki/Shibboleth_Configuration>
327
328 =head1 FUNCTIONS
329
330 =head2 logout_shib
331
332 Sends a logout signal to the native shibboleth service provider and then logs out of koha.  Depending upon the native service provider configuration and identity provider capabilities this may or may not perform a single sign out action.
333
334   logout_shib($query);
335
336 =head2 login_shib_url
337
338 Given a query, this will return a shibboleth login url with return code to page with given given query.
339
340   my $shibLoginURL = login_shib_url($query);
341
342 =head2 get_login_shib
343
344 Returns the shibboleth login attribute should it be found present in the http session
345
346   my $shib_login = get_login_shib();
347
348 =head2 checkpw_shib
349
350 Given a shib_login attribute, this routine checks for a matching local user and if found returns true, their cardnumber and their userid.  If a match is not found, then this returns false.
351
352   my ( $retval, $retcard, $retuserid ) = C4::Auth_with_shibboleth::checkpw_shib( $shib_login );
353
354 =head2 _get_uri
355
356   _get_uri();
357
358 A sugar function to that simply returns the current page URI with appropriate protocol attached
359
360 This routine is NOT exported
361
362 =head2 _get_shib_config
363
364   my $config = _get_shib_config();
365
366 A sugar function that checks for a valid shibboleth configuration, and if found returns a hashref of it's contents
367
368 This routine is NOT exported
369
370 =head2 _autocreate
371
372   my ( $retval, $retcard, $retuserid ) = _autocreate( $config, $match );
373
374 Given a shibboleth attribute reference and a userid this internal routine will add the given user to Koha and return their user credentials.
375
376 This routine is NOT exported
377
378 =head1 SEE ALSO
379
380 =cut