]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/AuthProxy.pm
LP#1468422 Use auth_internal.validate to shore up AuthProxy
[Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / AuthProxy.pm
1 #!/usr/bin/perl
2
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
16
17 =head1 NAME
18
19 OpenILS::Application::AuthProxy - Negotiator for proxy-style authentication
20
21 =head1 AUTHOR
22
23 Dan Wells, dbw2@calvin.edu
24
25 =cut
26
27 package OpenILS::Application::AuthProxy;
28
29 use strict;
30 use warnings;
31 use OpenILS::Application;
32 use base qw/OpenILS::Application/;
33 use OpenSRF::Utils::Cache;
34 use OpenSRF::Utils::Logger qw(:logger);
35 use OpenSRF::Utils::SettingsClient;
36 use OpenILS::Application::AppUtils;
37 use OpenILS::Utils::Fieldmapper;
38 use OpenILS::Utils::CStoreEditor qw/:funcs/;
39 use OpenILS::Event;
40 use UNIVERSAL::require;
41 use Digest::MD5 qw/md5_hex/;
42 my $U = 'OpenILS::Application::AppUtils';
43
44 # NOTE: code assumes throughout that '0' is never a valid username, barcode,
45 # or password; some logic will need to be tweaked to support it if needed.
46
47 my @authenticators;
48 my %authenticators_by_name;
49 my $enabled = 'false';
50 my $cache;
51 my $seed_timeout;
52 my $block_timeout;
53 my $block_count;
54
55 sub initialize {
56     my $conf = OpenSRF::Utils::SettingsClient->new;
57     $cache = OpenSRF::Utils::Cache->new();
58
59     my @pfx = ( "apps", "open-ils.auth", "app_settings", "auth_limits" );
60
61     # read in (or set defaults) for brute force blocking settings
62     $seed_timeout = $conf->config_value( @pfx, "seed" );
63     $seed_timeout = 30 if (!$seed_timeout or $seed_timeout < 0);
64     $block_timeout = $conf->config_value( @pfx, "block_time" );
65     $block_timeout = $seed_timeout * 3 if (!$block_timeout or $block_timeout < 0);
66     $block_count = $conf->config_value( @pfx, "block_count" );
67     $block_count = 10 if (!$block_count or $block_count < 0);
68
69     @pfx = ( "apps", "open-ils.auth_proxy", "app_settings" );
70
71     $enabled = $conf->config_value( @pfx, 'enabled' );
72
73     my $auth_configs = $conf->config_value( @pfx, 'authenticators', 'authenticator' );
74     $auth_configs = [$auth_configs] if ref($auth_configs) eq 'HASH';
75
76     if ( !@$auth_configs ) {
77         $logger->error("AuthProxy: authenticators list not found!");
78     } else {
79         foreach my $auth_config (@$auth_configs) {
80             my $auth_handler;
81             if ($auth_config->{'name'} eq 'native') {
82                 $auth_handler = 'OpenILS::Application::AuthProxy::Native';
83             } else {
84                 $auth_handler = $auth_config->{module};
85                 next unless $auth_handler;
86
87                 $logger->debug("Attempting to load AuthProxy handler: $auth_handler");
88                 $auth_handler->use;
89                 if($@) {
90                     $logger->error("Unable to load AuthProxy handler [$auth_handler]: $@");
91                     next;
92                 }
93             }
94
95             &_make_option_array($auth_config, 'login_types', 'type');
96             &_make_option_array($auth_config, 'org_units', 'unit');
97
98             my $authenticator = $auth_handler->new($auth_config);
99             push @authenticators, $authenticator;
100             $authenticators_by_name{$authenticator->name} = $authenticator;
101             $logger->debug("Successfully loaded AuthProxy handler: $auth_handler");
102         }
103         $logger->debug("AuthProxy: authenticators loaded");
104     }
105 }
106
107 # helper function to simplify the config structure
108 sub _make_option_array {
109     my ($auth_config, $container_name, $node_name) = @_;
110
111     if (exists $auth_config->{$container_name}
112         and ref $auth_config->{$container_name} eq 'HASH') {
113         my $nodes = $auth_config->{$container_name}{$node_name};
114         if ($nodes) {
115             if (ref $nodes ne 'ARRAY') {
116                 $auth_config->{$container_name} = [$nodes];
117             } else {
118                 $auth_config->{$container_name} = $nodes;
119             }
120         } else {
121             delete $auth_config->{$container_name};
122         }
123     } else {
124         delete $auth_config->{$container_name};
125     }
126 }
127
128
129
130 __PACKAGE__->register_method(
131     method    => "enabled",
132     api_name  => "open-ils.auth_proxy.enabled",
133     api_level => 1,
134     stream    => 1,
135     argc      => 0,
136     signature => {
137         desc => q/Check if AuthProxy is enabled/,
138         return => {
139             desc => "True if enabled, false if not",
140             type => "bool"
141         }
142     }
143 );
144 sub enabled {
145     return (!$enabled or $enabled eq 'false') ? 0 : 1;
146 }
147
148 __PACKAGE__->register_method(
149     method    => "login",
150     api_name  => "open-ils.auth_proxy.login",
151     api_level => 1,
152     stream    => 1,
153     argc      => 1,
154     signature => {
155         desc => q/Basic single-factor login method/,
156         params => [
157             {name=> "args", desc => q/A hash of arguments.  Valid keys and their meanings:
158     username := Username to authenticate.
159     barcode  := Barcode of user to authenticate 
160     password := Password for verifying the user.
161     type     := Type of login being attempted (Staff Client, OPAC, etc.).
162     org      := Org unit id
163 /,
164                 type => "hash"}
165         ],
166         return => {
167             desc => "Authentication seed or failure event",
168             type => "mixed"
169         }
170     }
171 );
172 sub login {
173     my ( $self, $conn, $args ) = @_;
174     $args ||= {};
175
176     return OpenILS::Event->new( 'LOGIN_FAILED' )
177       unless (&enabled() and ($args->{'username'} or $args->{'barcode'}));
178
179     if ($args->{barcode} and !$args->{username}) {
180         # translate barcode logins into username logins by locating
181         # the matching card/user and collecting the username.
182
183         my $card = new_editor()->search_actor_card([
184             {barcode => $args->{barcode}, active => 't'},
185             {flesh => 1, flesh_fields => {ac => ['usr']}}
186         ])->[0];
187
188         if ($card) {
189             $args->{username} = $card->usr->usrname;
190         } else { # must have or resolve to a username
191             return OpenILS::Event->new( 'LOGIN_FAILED' );
192         }
193     }
194
195     # check for possibility of brute-force attack
196     my $fail_count = $cache->get_cache('oils_auth_' . $args->{'username'} . '_count') || 0;
197     if ($fail_count >= $block_count) {
198         $logger->debug("AuthProxy found too many recent failures for '" . $args->{'username'} . "' : $fail_count, forcing failure state.");
199         $cache->put_cache('oils_auth_' . $args->{'username'} . '_count', ++$fail_count, $block_timeout);
200         return OpenILS::Event->new( 'LOGIN_FAILED' );
201     }
202
203     my @error_events;
204     my $authenticated = 0;
205     my $auths;
206
207     # if they specify an authenticator by name, only try that one
208     if ($args->{'name'}) {
209         $auths = [$authenticators_by_name{$args->{'name'}}];
210     } else {
211         $auths = \@authenticators;
212     }
213
214     foreach my $authenticator (@$auths) {
215         # skip authenticators specified for a different login type
216         # or org unit id
217         if ($authenticator->login_types and $args->{'type'}) {
218             next unless grep(/^(all|$args->{'type'})$/, @{$authenticator->{'login_types'}});
219         }
220         if ($authenticator->org_units and $args->{'org'}) {
221             next unless grep(/^(all|$args->{'org'})$/, @{$authenticator->{'org_units'}});
222         }
223
224         my $event;
225         # treat native specially
226         if ($authenticator->name eq 'native') {
227             $event = &_do_login($args);
228         } else {
229             $event = $authenticator->authenticate($args);
230         }
231         my $code = $U->event_code($event);
232         if ($code) {
233             push @error_events, $event;
234         } elsif (defined $code) { # code is '0', i.e. SUCCESS
235             if (exists $event->{'payload'}) { # we have a complete native login
236                 return $event;
237             } else { # create an EG session for the successful external login
238                 #
239                 # before we actually create the session, let's first check if
240                 # Evergreen thinks this user is allowed to login
241                 #
242                 # (we do this *after* authentication to avoid any personal data
243                 # leakage)
244
245                 # get the user id
246                 my $user = $U->cstorereq(
247                     "open-ils.cstore.direct.actor.user.search.atomic",
248                     { usrname => $args->{'username'} }
249                 );
250                 if (!$user->[0]) {
251                     $logger->debug("Authenticated username '" . $args->{'username'} . "' has no Evergreen account, aborting");
252                     return OpenILS::Event->new( 'LOGIN_FAILED' );
253                 } else {
254                     $args->{user_id} = $user->[0]->id;
255                 }
256
257                 # validate the account
258                 my $trimmed_args = {
259                     user_id => $args->{user_id},
260                     login_type => $args->{type},
261                     org_unit => $args->{org}
262                 };
263                 $event = &_auth_internal('user.validate', $trimmed_args);
264                 if ($U->event_code($event)) { # non-zero = we didn't succeed
265                     # can't recover from invalid user, return right away
266                     return $event;
267                 } else { # it's all good
268                     return &_auth_internal('session.create', $trimmed_args);
269                 }
270             }
271         }
272     }
273
274     # if we got this far, we failed
275     # increment the brute force counter if 'native' didn't already
276     if (!exists $authenticators_by_name{'native'}) {
277         $cache->put_cache('oils_auth_' . $args->{'username'} . '_count', ++$fail_count, $block_timeout);
278     }
279     # TODO: send back some form of collected error events
280     return OpenILS::Event->new( 'LOGIN_FAILED' );
281 }
282
283 sub _auth_internal {
284     my ($method, $args) = @_;
285
286     my $response = OpenSRF::AppSession->create("open-ils.auth_internal")->request(
287         'open-ils.auth_internal.'.$method,
288         $args
289     )->gather(1);
290
291     return OpenILS::Event->new( 'LOGIN_FAILED' )
292       unless $response;
293
294     return $response;
295 }
296
297 sub _do_login {
298     my $args = shift;
299     my $authenticated = shift;
300
301     my $seeder = $args->{'username'} ? $args->{'username'} : $args->{'barcode'};
302     my $seed =
303       OpenSRF::AppSession->create("open-ils.auth")
304       ->request( 'open-ils.auth.authenticate.init', $seeder )->gather(1);
305
306     return OpenILS::Event->new( 'LOGIN_FAILED' )
307       unless $seed;
308
309     my $real_password = $args->{'password'};
310     $args->{'password'} = md5_hex( $seed . md5_hex($real_password) );
311     my $response = OpenSRF::AppSession->create("open-ils.auth")->request(
312         'open-ils.auth.authenticate.complete',
313         $args
314     )->gather(1);
315     $args->{'password'} = $real_password;
316
317     return OpenILS::Event->new( 'LOGIN_FAILED' )
318       unless $response;
319
320     return $response;
321 }
322
323 __PACKAGE__->register_method(
324     method    => "authenticators",
325     api_name  => "open-ils.auth_proxy.authenticators",
326     api_level => 1,
327     stream    => 1,
328     argc      => 1,
329     signature => {
330         desc => q/Get a list of viable authenticators/,
331         params => [
332             {name=> "args", desc => q/A hash of arguments.  Valid keys and their meanings:
333     type     := Type of login being attempted (Staff Client, OPAC, etc.).
334     org      := Org unit id
335 /,
336                 type => "hash"}
337         ],
338         return => {
339             desc => "List of viable authenticators",
340             type => "array"
341         }
342     }
343 );
344 sub authenticators {
345     my ( $self, $conn, $args ) = @_;
346
347     my @viable_auths;
348
349     foreach my $authenticator (@authenticators) {
350         # skip authenticators specified for a different login type
351         # or org unit id
352         if ($authenticator->login_types and $args->{'type'}) {
353             next unless grep(/^(all|$args->{'type'})$/, @{$authenticator->login_types});
354         }
355         if ($authenticator->org_units and $args->{'org'}) {
356             next unless grep(/^(all|$args->{'org'})$/, @{$authenticator->org_units});
357         }
358
359         push @viable_auths, $authenticator->name;
360     }
361
362     return \@viable_auths;
363 }
364
365
366 # --------------------------------------------------------------------------
367 # Stub package for 'native' authenticator
368 # --------------------------------------------------------------------------
369 package OpenILS::Application::AuthProxy::Native;
370 use strict; use warnings;
371 use base 'OpenILS::Application::AuthProxy::AuthBase';
372
373 1;