Auth.pm 18.3 KB
Newer Older
1
2
3
4
# -*- indent-tabs-mode: nil; -*-
# vim:ft=perl:et:sw=4
# $Id$

salaun's avatar
salaun committed
5
# Sympa - SYsteme de Multi-Postage Automatique
6
7
8
9
10
#
# Copyright (c) 1997, 1998, 1999 Institut Pasteur & Christophe Wolfhugel
# Copyright (c) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
# 2006, 2007, 2008, 2009, 2010, 2011 Comite Reseau des Universites
# Copyright (c) 2011, 2012, 2013, 2014 GIP RENATER
salaun's avatar
salaun committed
11
12
13
14
15
16
17
18
19
20
21
22
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
23
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
salaun's avatar
salaun committed
24
25
26

package Auth;

27
28
use strict;
use warnings;
29
use POSIX qw();
salaun's avatar
salaun committed
30
31

use Conf;
32
use LDAPSource;
salaun's avatar
salaun committed
33
use List;
34
use Log;
35
use report;
36
use SDM;
salaun's avatar
salaun committed
37

38
39
40
## return the password finger print (this proc allow futur replacement of md5
## by sha1 or ....)
sub password_fingerprint {
41

sikeda's avatar
sikeda committed
42
    Log::do_log('debug', 'Auth::password_fingerprint');
43
44

    my $pwd = shift;
45
46
47
48
49
    if (Conf::get_robot_conf('*', 'password_case') eq 'insensitive') {
        return tools::md5_fingerprint(lc($pwd));
    } else {
        return tools::md5_fingerprint($pwd);
    }
50
51
}

52
## authentication : via email or uid
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
sub check_auth {
    my $robot = shift;
    my $auth  = shift;    ## User email or UID
    my $pwd   = shift;    ## Password
    Log::do_log('debug', 'Auth::check_auth(%s)', $auth);

    my ($canonic, $user);

    if (tools::valid_email($auth)) {
        return authentication($robot, $auth, $pwd);
    } else {
        ## This is an UID
        foreach my $ldap (@{$Conf::Conf{'auth_services'}{$robot}}) {
            # only ldap service are to be applied here
            next unless ($ldap->{'auth_type'} eq 'ldap');

            $canonic =
                ldap_authentication($robot, $ldap, $auth, $pwd, 'uid_filter');
            last if ($canonic);    ## Stop at first match
        }
        if ($canonic) {

            unless ($user = Sympa::User::get_global_user($canonic)) {
                $user = {'email' => $canonic};
            }
            return {
                'user'       => $user,
                'auth'       => 'ldap',
                'alt_emails' => {$canonic => 'ldap'}
            };

        } else {
            report::reject_report_web('user', 'incorrect_passwd', {})
                unless ($ENV{'SYMPA_SOAP'});
            Log::do_log('err', "Incorrect LDAP password");
            return undef;
        }
    }
}
salaun's avatar
salaun committed
92

93
## This subroutine if Sympa may use its native authentication for a given user
94
95
## It might not if no user_table paragraph is found in auth.conf or if the
## regexp or
96
97
98
99
100
101
102
103
## negative_regexp exclude this user
## IN : robot, user email
## OUT : boolean
sub may_use_sympa_native_auth {
    my ($robot, $user_email) = @_;

    my $ok = 0;
    ## check each auth.conf paragrpah
104
105
106
107
108
109
110
111
112
113
114
115
    foreach my $auth_service (@{$Conf::Conf{'auth_services'}{$robot}}) {
        next unless ($auth_service->{'auth_type'} eq 'user_table');

        next
            if ($auth_service->{'regexp'}
            && ($user_email !~ /$auth_service->{'regexp'}/i));
        next
            if ($auth_service->{'negative_regexp'}
            && ($user_email =~ /$auth_service->{'negative_regexp'}/i));

        $ok = 1;
        last;
116
    }
117

118
119
    return $ok;
}
salaun's avatar
salaun committed
120
121

sub authentication {
122
123
    my ($robot, $email, $pwd) = @_;
    my ($user, $canonic);
sikeda's avatar
sikeda committed
124
    Log::do_log('debug', 'Auth::authentication(%s)', $email);
salaun's avatar
salaun committed
125

126
    unless ($user = Sympa::User::get_global_user($email)) {
127
128
        $user = {'email' => $email};
    }
salaun's avatar
salaun committed
129
    unless ($user->{'password'}) {
130
        $user->{'password'} = '';
salaun's avatar
salaun committed
131
    }
132
133
134
135
136
137
138
139
140
141
142
143

    if ($user->{'wrong_login_count'} >
        Conf::get_robot_conf($robot, 'max_wrong_password')) {
        # too many wrong login attemp
        Sympa::User::update_global_user($email,
            {wrong_login_count => $user->{'wrong_login_count'} + 1});
        report::reject_report_web('user', 'too_many_wrong_login', {})
            unless ($ENV{'SYMPA_SOAP'});
        Log::do_log('err',
            'login is blocked : too many wrong password submission for %s',
            $email);
        return undef;
144
    }
145
146
147
148
    foreach my $auth_service (@{$Conf::Conf{'auth_services'}{$robot}}) {
        next if ($auth_service->{'auth_type'} eq 'authentication_info_url');
        next if ($email !~ /$auth_service->{'regexp'}/i);
        next
149
150
            if $auth_service->{'negative_regexp'}
                and $email =~ /$auth_service->{'negative_regexp'}/i;
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183

        ## Only 'user_table' and 'ldap' backends will need that Sympa collects
        ## the user passwords
        ## Other backends are Single Sign-On solutions
        if ($auth_service->{'auth_type'} eq 'user_table') {
            my $fingerprint = password_fingerprint($pwd);

            if ($fingerprint eq $user->{'password'}) {
                Sympa::User::update_global_user($email,
                    {wrong_login_count => 0});
                return {
                    'user'       => $user,
                    'auth'       => 'classic',
                    'alt_emails' => {$email => 'classic'}
                };
            }
        } elsif ($auth_service->{'auth_type'} eq 'ldap') {
            if ($canonic = ldap_authentication(
                    $robot, $auth_service, $email, $pwd, 'email_filter'
                )
                ) {
                unless ($user = Sympa::User::get_global_user($canonic)) {
                    $user = {'email' => $canonic};
                }
                Sympa::User::update_global_user($canonic,
                    {wrong_login_count => 0});
                return {
                    'user'       => $user,
                    'auth'       => 'ldap',
                    'alt_emails' => {$email => 'ldap'}
                };
            }
        }
salaun's avatar
salaun committed
184
    }
salaun's avatar
salaun committed
185

186
    # increment wrong login count.
187
188
    Sympa::User::update_global_user($email,
        {wrong_login_count => $user->{'wrong_login_count'} + 1});
189

190
191
192
193
    report::reject_report_web('user', 'incorrect_passwd', {})
        unless ($ENV{'SYMPA_SOAP'});
    Log::do_log('err', 'authentication: incorrect password for user %s',
        $email);
salaun's avatar
salaun committed
194

195
196
    my $param;    #FIXME FIXME: not used.
    $param->{'init_email'}         = $email;
sikeda's avatar
sikeda committed
197
    $param->{'escaped_init_email'} = tools::escape_chars($email);
salaun's avatar
salaun committed
198
199
200
201
    return undef;
}

sub ldap_authentication {
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
    my ($robot, $ldap, $auth, $pwd, $whichfilter) = @_;
    my ($mesg, $host, $ldap_passwd, $ldap_anonymous);
    Log::do_log('debug2', 'Auth::ldap_authentication(%s,%s,%s)',
        $auth, '****', $whichfilter);
    Log::do_log('debug3', 'Password used: %s', $pwd);

    unless (tools::search_fullpath($robot, 'auth.conf')) {
        return undef;
    }

    ## No LDAP entry is defined in auth.conf
    if ($#{$Conf::Conf{'auth_services'}{$robot}} < 0) {
        Log::do_log('notice', 'Skipping empty auth.conf');
        return undef;
    }

    # only ldap service are to be applied here
    return undef unless ($ldap->{'auth_type'} eq 'ldap');

    # skip ldap auth service if the an email address was provided
    # and this email address does not match the corresponding regexp
    return undef if ($auth =~ /@/ && $auth !~ /$ldap->{'regexp'}/i);

    my @alternative_conf = split(/,/, $ldap->{'alternative_email_attribute'});
    my $attrs            = $ldap->{'email_attribute'};
    my $filter           = $ldap->{'get_dn_by_uid_filter'}
        if ($whichfilter eq 'uid_filter');
    $filter = $ldap->{'get_dn_by_email_filter'}
        if ($whichfilter eq 'email_filter');
    $filter =~ s/\[sender\]/$auth/ig;

    ## bind in order to have the user's DN
    my $param = tools::dup_var($ldap);
    my $ds    = LDAPSource->new($param);

    unless (defined $ds && ($ldap_anonymous = $ds->connect())) {
        Log::do_log('err', "Unable to connect to the LDAP server '%s'",
            $ldap->{'host'});
        return undef;
    }

    $mesg = $ldap_anonymous->search(
        base    => $ldap->{'suffix'},
        filter  => "$filter",
        scope   => $ldap->{'scope'},
        timeout => $ldap->{'timeout'}
    );

    if ($mesg->count() == 0) {
        Log::do_log('notice',
            'No entry in the LDAP Directory Tree of %s for %s',
            $ldap->{'host'}, $auth);
        $ds->disconnect();
        return undef;
    }

    my $refhash = $mesg->as_struct();
    my (@DN) = keys(%$refhash);
    $ds->disconnect();

    ##  bind with the DN and the pwd

    ## Duplicate structure first
    ## Then set the bind_dn and password according to the current user
    $param                         = tools::dup_var($ldap);
    $param->{'ldap_bind_dn'}       = $DN[0];
    $param->{'ldap_bind_password'} = $pwd;

    $ds = LDAPSource->new($param);
salaun's avatar
salaun committed
271

272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
    unless (defined $ds && ($ldap_passwd = $ds->connect())) {
        Log::do_log('err', "Unable to connect to the LDAP server '%s'",
            $param->{'host'});
        return undef;
    }

    $mesg = $ldap_passwd->search(
        base    => $ldap->{'suffix'},
        filter  => "$filter",
        scope   => $ldap->{'scope'},
        timeout => $ldap->{'timeout'}
    );

    if ($mesg->count() == 0 || $mesg->code() != 0) {
        Log::do_log('notice', "No entry in the LDAP Directory Tree of %s",
            $ldap->{'host'});
        $ds->disconnect();
        return undef;
    }

    ## To get the value of the canonic email and the alternative email
    my (@canonic_email, @alternative);

    ## Keep previous alt emails not from LDAP source
    my $previous = {};
    foreach my $alt (keys %{$param->{'alt_emails'}}) {
        $previous->{$alt} = $param->{'alt_emails'}{$alt}
            if ($param->{'alt_emails'}{$alt} ne 'ldap');
    }
    $param->{'alt_emails'} = {};

    my $entry = $mesg->entry(0);
    @canonic_email = $entry->get_value($attrs, 'alloptions' => 1);
    foreach my $email (@canonic_email) {
        my $e = lc($email);
        $param->{'alt_emails'}{$e} = 'ldap' if ($e);
    }

    foreach my $attribute_value (@alternative_conf) {
        @alternative = $entry->get_value($attribute_value, 'alloptions' => 1);
        foreach my $alter (@alternative) {
            my $a = lc($alter);
            $param->{'alt_emails'}{$a} = 'ldap' if ($a);
        }
    }

    ## Restore previous emails
    foreach my $alt (keys %{$previous}) {
        $param->{'alt_emails'}{$alt} = $previous->{$alt};
    }

    $ds->disconnect() or Log::do_log('notice', "unable to unbind");
    Log::do_log('debug3', "canonic: $canonic_email[0]");
    ## If the identifier provided was a valid email, return the provided
    ## email.
    ## Otherwise, return the canonical email guessed after the login.
    if (tools::valid_email($auth)
        && !Conf::get_robot_conf($robot, 'ldap_force_canonical_email')) {
        return ($auth);
    } else {
        return lc($canonic_email[0]);
    }
}
salaun's avatar
salaun committed
335
336

# fetch user email using his cas net_id and the paragrapah number in auth.conf
337
sub get_email_by_net_id {
338
339
340

    my $robot      = shift;
    my $auth_id    = shift;
341
    my $attributes = shift;
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357

    Log::do_log('debug',
        "Auth::get_email_by_net_id($auth_id,$attributes->{'uid'})");

    if (defined $Conf::Conf{'auth_services'}{$robot}[$auth_id]
        {'internal_email_by_netid'}) {
        my $sso_config   = @{$Conf::Conf{'auth_services'}{$robot}}[$auth_id];
        my $netid_cookie = $sso_config->{'netid_http_header'};

        $netid_cookie =~ s/(\w+)/$attributes->{$1}/ig;

        my $email =
            List::get_netidtoemail_db($robot, $netid_cookie,
            $Conf::Conf{'auth_services'}{$robot}[$auth_id]{'service_id'});

        return $email;
358
    }
359

sikeda's avatar
sikeda committed
360
    my $ldap = @{$Conf::Conf{'auth_services'}{$robot}}[$auth_id];
361

sikeda's avatar
sikeda committed
362
    my $param = tools::dup_var($ldap);
363
    my $ds    = LDAPSource->new($param);
364
    my $ldap_anonymous;
365

366
    unless (defined $ds && ($ldap_anonymous = $ds->connect())) {
367
368
369
        Log::do_log('err', "Unable to connect to the LDAP server '%s'",
            $ldap->{'ldap_host'});
        return undef;
salaun's avatar
salaun committed
370
371
    }

372
    my $filter = $ldap->{'ldap_get_email_by_uid_filter'};
373
    $filter =~ s/\[([\w-]+)\]/$attributes->{$1}/ig;
salaun's avatar
salaun committed
374
375

#	my @alternative_conf = split(/,/,$ldap->{'alternative_email_attribute'});
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391

    my $emails = $ldap_anonymous->search(
        base    => $ldap->{'ldap_suffix'},
        filter  => $filter,
        scope   => $ldap->{'ldap_scope'},
        timeout => $ldap->{'ldap_timeout'},
        attrs   => [$ldap->{'ldap_email_attribute'}],
    );
    my $count = $emails->count();

    if ($emails->count() == 0) {
        Log::do_log('notice', "No entry in the LDAP Directory Tree of %s",
            $ldap->{'ldap_host'});
        $ds->disconnect();
        return undef;
    }
salaun's avatar
salaun committed
392

393
    $ds->disconnect();
394

395
    ## return only the first attribute
396
397
398
399
    my @results = $emails->entries;
    foreach my $result (@results) {
        return (lc($result->get_value($ldap->{'ldap_email_attribute'})));
    }
salaun's avatar
salaun committed
400

401
}
salaun's avatar
salaun committed
402

403
404
# check trusted_application_name et trusted_application_password : return 1 or
# undef;
405
sub remote_app_check_password {
406
407
408
409
410

    my ($trusted_application_name, $password, $robot) = @_;
    Log::do_log('debug', 'Auth::remote_app_check_password (%s,%s)',
        $trusted_application_name, $robot);

sikeda's avatar
sikeda committed
411
    my $md5 = tools::md5_fingerprint($password);
412

413
414
    my $vars;
    # seach entry for trusted_application in Conf
415
416
    my @trusted_apps;

417
    # select trusted_apps from robot context or sympa context
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
    @trusted_apps = @{Conf::get_robot_conf($robot, 'trusted_applications')};

    foreach my $application (@trusted_apps) {

        if (lc($application->{'name'}) eq lc($trusted_application_name)) {
            if ($md5 eq $application->{'md5password'}) {
                # Log::do_log('debug', 'Auth::remote_app_check_password : authentication succeed for %s',$application->{'name'});
                my %proxy_for_vars;
                foreach my $varname (@{$application->{'proxy_for_variables'}})
                {
                    $proxy_for_vars{$varname} = 1;
                }
                return (\%proxy_for_vars);
            } else {
                Log::do_log('info',
                    'Auth::remote_app_check_password: bad password from %s',
                    $trusted_application_name);
                return undef;
            }
        }
    }
439
    # no matching application found
440
441
442
    Log::do_log('info',
        'Auth::remote_app-check_password: unknown application name %s',
        $trusted_application_name);
443
444
    return undef;
}
445
446
447

# create new entry in one_time_ticket table using a rand as id so later access
# is authenticated
448
449
450
#

sub create_one_time_ticket {
451
452
    my $email       = shift;
    my $robot       = shift;
453
    my $data_string = shift;
454
455
    my $remote_addr =
        shift;    ## Value may be 'mail' if the IP address is not known
456

sikeda's avatar
sikeda committed
457
    my $ticket = SympaSession::get_random();
458
459
460
    Log::do_log('info',
        'Auth::create_one_time_ticket(%s,%s,%s,%s) value = %s',
        $email, $robot, $data_string, $remote_addr, $ticket);
461
462
463

    my $date = time;
    my $sth;
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484

    unless (
        SDM::do_query(
            "INSERT INTO one_time_ticket_table (ticket_one_time_ticket, robot_one_time_ticket, email_one_time_ticket, date_one_time_ticket, data_one_time_ticket, remote_addr_one_time_ticket, status_one_time_ticket) VALUES (%s, %s, %s, %d, %s, %s, %s)",
            SDM::quote($ticket),
            SDM::quote($robot),
            SDM::quote($email),
            time,
            SDM::quote($data_string),
            SDM::quote($remote_addr),
            SDM::quote('open')
        )
        ) {
        Log::do_log(
            'err',
            'Unable to insert new one time ticket for user %s, robot %s in the database',
            $email,
            $robot
        );
        return undef;
    }
485
486
487
488
489
490
491
    return $ticket;
}

# read one_time_ticket from table and remove it
#
sub get_one_time_ticket {
    my $ticket_number = shift;
492
493
494
495
    my $addr          = shift;

    Log::do_log('debug2', '(%s)', $ticket_number);

496
    my $sth;
497
498
499
500
501
502
503
504
505
506
507

    unless (
        $sth = SDM::do_query(
            "SELECT ticket_one_time_ticket AS ticket, robot_one_time_ticket AS robot, email_one_time_ticket AS email, date_one_time_ticket AS \"date\", data_one_time_ticket AS data, remote_addr_one_time_ticket AS remote_addr, status_one_time_ticket as status FROM one_time_ticket_table WHERE ticket_one_time_ticket = %s ",
            SDM::quote($ticket_number)
        )
        ) {
        Log::do_log('err',
            'Unable to retrieve one time ticket %s from database',
            $ticket_number);
        return {'result' => 'error'};
508
    }
509

510
    my $ticket = $sth->fetchrow_hashref('NAME_lc');
511
512
513
514
515
516

    unless ($ticket) {
        Log::do_log('info',
            'Auth::get_one_time_ticket: Unable to find one time ticket %s',
            $ticket);
        return {'result' => 'not_found'};
517
    }
518

519
    my $result;
520
521
    my $printable_date =
        POSIX::strftime("%d %b %Y at %H:%M:%S", localtime($ticket->{'date'}));
522
523

    if ($ticket->{'status'} ne 'open') {
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
        $result = 'closed';
        Log::do_log(
            'info',
            'Auth::get_one_time_ticket: ticket %s from %s has been used before (%s)',
            $ticket_number,
            $ticket->{'email'},
            $printable_date
        );
    } elsif (time - $ticket->{'date'} > 48 * 60 * 60) {
        Log::do_log(
            'info',
            'Auth::get_one_time_ticket: ticket %s from %s refused because expired (%s)',
            $ticket_number,
            $ticket->{'email'},
            $printable_date
        );
        $result = 'expired';
    } else {
        $result = 'success';
543
    }
544
545
546
547
548
549
550
551
552
    unless (
        SDM::do_query(
            "UPDATE one_time_ticket_table SET status_one_time_ticket = %s WHERE (ticket_one_time_ticket=%s)",
            SDM::quote($addr),
            SDM::quote($ticket_number)
        )
        ) {
        Log::do_log('err', 'Unable to set one time ticket %s status to %s',
            $ticket_number, $addr);
553
554
    }

555
556
557
558
559
560
561
562
563
564
565
    Log::do_log('info', 'Auth::get_one_time_ticket(%s) : result : %s',
        $ticket_number, $result);
    return {
        'result'      => $result,
        'date'        => $ticket->{'date'},
        'email'       => $ticket->{'email'},
        'remote_addr' => $ticket->{'remote_addr'},
        'robot'       => $ticket->{'robot'},
        'data'        => $ticket->{'data'},
        'status'      => $ticket->{'status'}
    };
566
}
567

salaun's avatar
salaun committed
568
1;