LDAP.pm 26.2 KB
Newer Older
1
2
3
4
5
package Ravada::Auth::LDAP;

use strict;
use warnings;

6
7
8
9
10
11
=head1 NAME

Ravada::Auth::LDAP - LDAP library for Ravada

=cut

12
13
use Authen::Passphrase;
use Authen::Passphrase::SaltedDigest;
14
use Carp qw(carp croak);
15
use Data::Dumper;
Francesc Guasch's avatar
Francesc Guasch committed
16
17
18
19
use Digest::SHA qw(sha1_hex sha256_hex);
use Encode;
use PBKDF2::Tiny qw/derive/;
use MIME::Base64;
20
21
22
23
use Moose;
use Net::LDAP;
use Net::LDAPS;
use Net::LDAP::Entry;
24
use Net::LDAP::Util qw(escape_filter_value);
25
26
use Net::Domain qw(hostdomain);

27
28
29
no warnings "experimental::signatures";
use feature qw(signatures);

30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
use Ravada::Auth::SQL;

with 'Ravada::Auth::User';

our $CONFIG = \$Ravada::CONFIG;

our $LDAP;
our $LDAP_ADMIN;
our $BASE;
our @OBJECT_CLASS = ('top'
                    ,'organizationalPerson'
                    ,'person'
                    ,'inetOrgPerson'
                   );

45
46
our @OBJECT_CLASS_POSIX = (@OBJECT_CLASS,'posixAccount');

47
48
49
50
our $STATUS_EOF = 1;
our $STATUS_DISCONNECTED = 81;
our $STATUS_BAD_FILTER = 89;

Francesc Guasch's avatar
Francesc Guasch committed
51
52
53
54
55
our $PBKDF2_SALT_LENGTH = 64;
our $PBKDF2_ITERATIONS_LENGTH = 4;
our $PBKDF2_HASH_LENGTH = 256;
our $PBKDF2_LENGTH = $PBKDF2_SALT_LENGTH + $PBKDF2_ITERATIONS_LENGTH + $PBKDF2_HASH_LENGTH;

56
57
58
59
60
61
62
63
=head2 BUILD

Internal OO build

=cut

sub BUILD {
    my $self = shift;
64
    die "ERROR: Login failed '".$self->name."'"
65
66
67
68
69
70
71
72
73
74
75
76
        if !$self->login;
    return $self;
}

=head2 add_user

Adds a new user in the LDAP directory

    Ravada::Auth::LDAP::add_user($name, $password, $is_admin);

=cut

Francesc Guasch's avatar
Francesc Guasch committed
77
sub add_user($name, $password, $storage='rfc2307', $algorithm=undef ) {
78
79

    _init_ldap_admin();
80

81
82
83
    $name = escape_filter_value($name);
    $password = escape_filter_value($password);

84
85
    confess "No dc base in config ".Dumper($$CONFIG->{ldap})
        if !_dc_base();
86
87
88
89
90
91
92
93
94
95
96
    my ($givenName, $sn) = $name =~ m{(\w+)\.(.*)};

    my %entry = (
        cn => $name
        , uid => $name
#        , uidNumber => _new_uid()
#        , gidNumber => $GID
        , objectClass => [@OBJECT_CLASS]
        , givenName => ($givenName or $name)
        , sn => ($sn or $name)
#        , homeDirectory => "/home/$name"
Francesc Guasch's avatar
Francesc Guasch committed
97
        ,userPassword => _password_store($password, $storage, $algorithm)
98
99
100
101
102
    );
    my $dn = "cn=$name,"._dc_base();

    my $mesg = $LDAP_ADMIN->add($dn, attr => [%entry]);
    if ($mesg->code) {
103
        die "Error afegint $name to $dn ".$mesg->error;
104
105
106
    }
}

107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
=head2 add_user_posix

Adds a new user in the LDAP directory

    Ravada::Auth::LDAP::add_user_posix($name, $password);

=cut

sub add_user_posix(%args) {
    my $name = delete $args{name} or croak "Error: missing name";
    my $password = delete $args{password} or croak "Error: missing password";
    my $gid = (delete $args{gid} or _get_gid());
    my $storage = ( delete $args{storage} or 'rfc2307');
    my $algorithm = delete $args{algorithm};
    confess "Error : unknown args ".dumper(\%args) if keys %args;

    _init_ldap_admin();

    $name = escape_filter_value($name);
    $password = escape_filter_value($password);

    confess "No dc base in config ".Dumper($$CONFIG->{ldap})
        if !_dc_base();
    my ($givenName, $sn) = $name =~ m{(\w+)\.(.*)};

    my %entry = (
        cn => $name
        , uid => $name
        , uidNumber => _new_uid()
        , gidNumber => $gid
        , objectClass => \@OBJECT_CLASS_POSIX
        , givenName => ($givenName or $name)
        , sn => ($sn or $name)
        ,homeDirectory => "/home/$name"
        ,userPassword => _password_store($password, $storage, $algorithm)
    );
    my $dn = "cn=$name,"._dc_base();

    my $mesg = $LDAP_ADMIN->add($dn, attr => [%entry]);
    if ($mesg->code) {
        die "Error afegint $name to $dn ".$mesg->error;
    }
}

sub _get_gid() {
    my @group = search_group(name => "*");
    my ($group_users) = grep { $_->get_value('cn') eq 'users' } @group;
    $group_users = $group[0] if !$group_users;
    if (!$group_users) {
156
        add_group('users');
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
        ($group_users) = search_group(name => 'users');
        confess "Error: I can create nor find LDAP group 'users'" if !$group_users;
    }
    return $group_users->get_value('gidNumber');
}

sub _new_uid($ldap=_init_ldap_admin(), $base=_dc_base()) {

    my $id = 1000;
    for (;;) {
        my $mesg = $ldap->search(      # Search for the user
            base   => $base,
            scope  => 'sub',
            filter => "uidNumber=$id",
            typesonly => 0,
            attrs  => ['*']
        );

        confess "LDAP error ".$mesg->code." ".$mesg->error if $mesg->code;

        my @entries = $mesg->entries;
        return $id if !scalar @entries;
        $id++;
        $id+= int(rand(10))+1;
    }
}

184
sub _password_store($password, $storage, $algorithm=undef) {
Francesc Guasch's avatar
Francesc Guasch committed
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
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
    return _password_rfc2307($password, $algorithm) if lc($storage) eq 'rfc2307';
    return _password_pbkdf2($password, $algorithm)  if lc($storage) eq 'pbkdf2';

    confess "Error: Unknown storage '$storage'";

}

sub _password_pbkdf2($password, $algorithm='SHA-256') {
    $algorithm = 'SHA-256' if ! defined $algorithm;

    my $salt = encode('ascii',Ravada::Utils::random_name($PBKDF2_SALT_LENGTH));

    die "wrong salt length ".length($salt)." != $PBKDF2_SALT_LENGTH"
    if length($salt) != $PBKDF2_SALT_LENGTH;

    my $iterations = 1024;
    my $derive = derive($algorithm
        , encode('ascii',$password)
        , $salt
        , $iterations
        , $PBKDF2_HASH_LENGTH);

    my $iterations_n = pack('N', $iterations);

    die "wrong iterations length ".length($iterations_n)." != $PBKDF2_ITERATIONS_LENGTH"
    if length($iterations_n) != $PBKDF2_ITERATIONS_LENGTH;

    my $pbkdf2 = $iterations_n.$salt.$derive;

    die "wrong pass length ".length($pbkdf2)." != $PBKDF2_LENGTH"
    if length($pbkdf2) != $PBKDF2_LENGTH;

    $algorithm =~ s/-//;
    return "\{PBKDF2_$algorithm}"
        .encode_base64($pbkdf2,"");
}

sub _password_rfc2307($password, $algorithm='MD5') {

    my $apr=Authen::Passphrase::SaltedDigest->new(passphrase => $password
        , algorithm => ($algorithm or 'MD5'));
    return $apr->as_rfc2307();
}

229
230
231
232
233
234
235
236
237
238
239
=head2 remove_user

Removes the user

    Ravada::Auth::LDAP::remove_user($name);

=cut

sub remove_user {
    my $name = shift;
    _init_ldap_admin();
240
    my ($entry) = search_user(name => $name);
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
    die "ERROR: Entry for user $name not found\n" if !$entry;

#    $LDAP->delete($entry);
#    warn Dumper($entry);
    my $mesg = $LDAP_ADMIN->delete($entry);
    die "ERROR: ".$mesg->code." : ".$mesg->error
        if $mesg->code;

#    $entry->delete->update($LDAP);
}

=head2 search_user

Search user by uid

  my $entry = Ravada::Auth::LDAP::search_user($uid);

=cut

sub search_user {
261
    my %args;
262

263
264
265
266
267
    if ( scalar @_>1 ) {
        %args = @_;
    } else {
        $args{name} = $_[0];
    }
268

269
270
    my $username = delete $args{name} or confess "Missing user name";
    my $retry = (delete $args{retry} or 0);
Francesc Guasch's avatar
Francesc Guasch committed
271
    my $field = (delete $args{field} or $$CONFIG->{ldap}->{field} or 'uid');
272
    my $ldap = (delete $args{ldap} or _init_ldap_admin());
273
    my $base = (delete $args{base} or _dc_base());
274
    my $typesonly= (delete $args{typesonly} or 0);
Francesc Guasch's avatar
Francesc Guasch committed
275
276
    my $escape_username = 1;
    $escape_username = delete $args{escape_username} if exists $args{escape_username};
277
    my $filter_orig = delete $args{filter};
278
279
    my $sizelimit = (delete $args{sizelimit} or 100);
    my $timelimit = (delete $args{timelimit} or 60);
280

281
282
283
    confess "ERROR: Unknown fields ".Dumper(\%args) if keys %args;
    confess "ERROR: I can't connect to LDAP " if!$ldap;

Francesc Guasch's avatar
Francesc Guasch committed
284
    $username = escape_filter_value($username) if $escape_username;
285
    $username =~ s/ /\\ /g;
286

287
    my $filter = "($field=$username)";
288
    if (!defined $filter_orig && exists $$CONFIG->{ldap}->{filter} ) {
289
290
        my $filter_config = $$CONFIG->{ldap}->{filter};
        $filter = "(&($field=$username) ($filter_config))";
291
292
    } else {
        $filter = "(&($field=$username) ($filter_orig))" if $filter_orig;
293
294
    }

295
296
297
    my $mesg = $ldap->search(      # Search for the user
    base   => $base,
    scope  => 'sub',
298
    filter => $filter,
299
    typesonly => $typesonly,
300
301
302
    attrs  => ['*'],
    sizelimit => $sizelimit,
    timelimit => $timelimit
303

304
    );
305

306
    if ( $retry <= 3 && $mesg->code && $mesg->code != 4 ) {
307
         warn "LDAP error ".$mesg->code." ".$mesg->error."."
308
            ."Retrying ! [$retry]"  if $retry;
309
310
311
         $LDAP_ADMIN = undef;
         sleep ($retry + 1);
         _init_ldap_admin();
312
313
         return search_user(
                name => $username
314
               ,base => $base
315
316
              ,field => $field
              ,retry => ++$retry
317
              ,typesonly => $typesonly
318
              ,filter => $filter_orig
319
              ,sizelimit => $sizelimit
320
         );
321
322
323
324
325
326
327
    }

    die "ERROR: ".$mesg->code." : ".$mesg->error
        if $mesg->code;

    return if !$mesg->count();

328
329
330
    my @entries = $mesg->entries;
    return $entries[0] if !wantarray;
    return @entries;
331
332
333
334
335
336
337
338
}

=head2 add_group

Add a group to the LDAP

=cut

339
340
sub add_group($name, $base=_dc_base(), $class=['groupOfUniqueNames','nsMemberOf','posixGroup','top' ]) {
    $base = _dc_base() if !defined $base;
341
    $name = escape_filter_value($name);
342
343
    my $oc_posix_group;
    $oc_posix_group = grep { /^posixGroup$/ } @$class;
344

345
    my @attrs =( cn=>$name
Francesc Guasch's avatar
Francesc Guasch committed
346
                    ,objectClass => $class
347
348
349
                    ,ou => 'Groups'
                    ,description => "Group for $name"
    );
350
351
352
353
354
355
356
357
    push @attrs, (gidNumber => _search_new_gid()) if $oc_posix_group;

    my @data = (
        dn => "cn=$name,ou=groups,$base"
        , cn => $name
        , attrs => \@attrs
      );
    my $mesg = $LDAP_ADMIN->add(@data);
358
    if ($mesg->code) {
359
        die "Error creating group $name : ".$mesg->error."\n".Dumper(\@data);
360
361
362
363
    }

}

Francesc Guasch's avatar
Francesc Guasch committed
364
365
366
367
368
369
370
371
372
373
374
375
376
377
sub _search_new_gid() {
    my %gid;
    for my $group (  search_group( name => '*' ) ) {
        my $gid_number = $group->get_value('gidNumber');
        next if !$gid_number;
        $gid{$gid_number}++;
    }
    my $new_gid = 100;
    for (;;) {
        return $new_gid if !$gid{$new_gid};
        $new_gid++;
    }
}

378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
=head2 remove_group

Removes the group from the LDAP directory. Use with caution

    Ravada::Auth::LDAP::remove_group($name, $base);

=cut


sub remove_group {
    my $name = shift;
    my $base = shift;

    $base = "ou=groups,"._dc_base() if !$base;

    my $entry = search_group(name => $name, base => $base);
    if (!$entry) {
        die "I can't find cn=$name at base: ".($base or _dc_base());
    }
    my $mesg = $LDAP_ADMIN->delete($entry);
    die "ERROR: ".$mesg->code." : ".$mesg->error
        if $mesg->code;
}

=head2 search_group

    Search group by name

=cut

sub search_group {
    my %args = @_;

411
    my $name = delete $args{name} or confess "Error: missing name";
412
413
414
415
416
417
    my $base = ( delete $args{base} or "ou=groups,"._dc_base() );
    my $ldap = ( delete $args{ldap} or _init_ldap_admin());
    my $retry =( delete $args{retry} or 0);

    confess "ERROR: Unknown fields ".Dumper(\%args) if keys %args;
    confess "ERROR: I can't connect to LDAP " if!$ldap;
418
    my $filter = "cn=$name";
419
    my $mesg = $ldap ->search (
420
        filter => $filter
421
         ,base => $base
422
         ,sizelimit => 100
423
    );
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
    warn "LDAP retry ".$mesg->code." ".$mesg->error." [filter: $filter , base: $base]" if $retry > 1;
    if ($mesg->code == 4 ) {
        if ( $name eq '*' ) {
            $name = 'a*';
        } elsif ($name eq 'a*' ) {
            $name = 'a*a*';
        } else {
            die "LDAP error: ".$mesg->code." ".$mesg->error;
        }
        return search_group(
            name => $name
            ,base => $base
            ,ldap => $ldap
            ,retry => $retry+1
        );
    }
440
441

    if ( $retry <= 3 && $mesg->code){
442
        warn "LDAP error ".$mesg->code." ".$mesg->error.". [cn=$name] "
443
444
445
446
447
448
449
450
451
            ."Retrying ! [$retry]"  if $retry;
         $LDAP_ADMIN = undef;
         sleep ($retry + 1);
         _init_ldap_admin();
         return search_group (
                name => $name
               ,base => $base
              ,retry => ++$retry
         );
452
453
    }
    my @entries = $mesg->entries;
454
    return @entries if wantarray;
455

Francesc Guasch's avatar
Francesc Guasch committed
456
    return $entries[0];
457
458
}

459
460
461
462
463
=head2 search_group_members

=cut

sub search_group_members($cn, $retry = 0) {
464
465
466
467
468
469
470
    my $base = "ou=groups,"._dc_base();
    my $ldap = _init_ldap_admin();
    my $mesg = $ldap ->search (
        filter => "memberuid=$cn"
         ,base => $base
         ,sizelimit => 100
    );
471
472
    if ( ($mesg->code == 1 || $mesg->code == 81) && $retry <3 ) {
        $LDAP_ADMIN = undef;
473
        return search_group_members($cn, $retry+1);
474
    }
475
476
477
478
479
480
481
482
483
484
485
486
487
488
    warn $mesg->code." ".$mesg->error." [base: $base]" if $mesg->code;

    my @entries = map { $_->get_value('cn') } $mesg->entries();

    $mesg = $ldap ->search (
        filter => "member=cn=$cn,"._dc_base()
         ,base => $base
         ,sizelimit => 100
    );
    my @entries2 = map { $_->get_value('cn') } $mesg->entries();

    return (sort (@entries,@entries2));
}

489
490
491
492
=head2 add_to_group

Adds user to group

493
    add_to_group($dn, $group_name);
494
495
496
497

=cut

sub add_to_group {
498
499
    my ($dn, $group_name) = @_;
    if ( $dn !~ /=.*,/ ) {
500
501
502
503
        my $user = search_user(name => $dn, field => 'uid');
        $user = search_user(name => $dn, field => 'cn') if !$user;

        confess "Error: user '$dn' not found" if !$user;
504
505
        $dn = $user->dn;
    }
506
507
508
509

    my $group = search_group(name => $group_name, ldap => $LDAP_ADMIN)   
        or die "No such group $group_name";

510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
    if ( grep {/^groupOfNames$/} $group->get_value('objectClass') ) {
        $group->add(member => $dn)
    } elsif ( grep {/^posixGroup$/} $group->get_value('objectClass') ) {
        my ($cn) = $dn =~ /^cn=(.*?),/;
        ($cn) = $dn =~ /^uid=(.*?),/ if !$cn;
        die "Error: I can't find cn in $dn" if !$cn;
        my @attributes = $group->attributes;
        my $attribute;
        for (qw(uniqueMember memberUid)) {
            $attribute = $_ if grep /^$_$/,@attributes;
        }
        ($attribute) = grep /member/i,@attributes if !$attribute;
        if ($attribute eq 'memberUid') {
            $group->add($attribute => $cn);
        } else {
            $group->add($attribute => $dn);
        }
    } else {
        die "Error: group $group_name class unknown ".Dumper($group->get_value('objectClass'));
    }
530
    my $mesg = $group->update($LDAP_ADMIN);
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
    die "Error: adding member ".$dn." ".$mesg->error if $mesg->code;

}

=head2 remove_from_group

Removes user from group

    add_to_group($dn, $group_name);

=cut

sub remove_from_group {
    my ($dn, $group_name) = @_;

    my $group = search_group(name => $group_name, ldap => $LDAP_ADMIN)
        or die "No such group $group_name";

    my $found = 0;
    for my $attribute ( $group->attributes() ) {
        next if $attribute !~ /member/i;
        my $uid = $dn;
        $uid =~s/.*?=(.*?),.*/$1/ if $attribute eq 'memberUid';
        my $mesg  = $group->delete($attribute => $uid )->update(_init_ldap_admin());

        die "Error: [".$mesg->code."] removing $uid from $group_name - $attribute ".$mesg->error
        if $mesg->code;

        $found++;

    }
    die "Error: group $group_name class unknown ".Dumper($group->get_value('objectClass'))
    if !$found;
564
565
566

}

567

568
569
570
571
572
573
=head2 login

    $user->login($name, $password);

=cut

574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
sub _search_posix_group($self, $name) {
    my $base = 'ou=groups,'._dc_base();
    my $field = 'cn';
    if ($name =~ /(.*?)=(.*)/) {
        $field = $1;
        $name = $2;
        if ($name =~ /(.*?),(.*)/) {
            $name = $1;
            $base = $2;
        }
    }
    my @posix_group = search_user (
        name => $name
        ,base => $base
        ,field => $field
    );
    warn "WARNING: found too many entries for posix_group $name"
    .Dumper([map {$_->dn } @posix_group])
        if (scalar @posix_group > 1);
    return $posix_group[0];
}

596
597
598
599
600
601
=head2 group_members

Returns a list of the group members

=cut

602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
sub group_members {
    return _group_members(@_);
}

sub _group_members($group_name = $$CONFIG->{ldap}->{group}) {
    my $group = $group_name;
    if (!ref($group)) {
        $group = search_group(name => $group_name);
        if (!$group) {
            confess "Warning: group $group_name not found";
            return;
        }
    }
    confess "Error: invalid object ".ref($group) if ref($group)!~ /^Net::LDAP/;
    my @oc = $group->get_value('objectClass');

    my @members;
    for my $attribute ($group->attributes) {
        next if $attribute !~ /member/i;
        push @members, $group->get_value($attribute);
    }
    my %members = map { $_ => 1 } @members;
    @members = sort keys %members;
    return @members;
}

sub _check_posix_group($self) {
629
    my $posix_group_name = $$CONFIG->{ldap}->{ravada_posix_group};
630
    return 1 if !$posix_group_name;
631
632

    if ($posix_group_name) {
633
        my $posix_group = $self->_search_posix_group($posix_group_name);
634
635
636
637
638
639
640
641
642
643
644
645
646
        if (!$posix_group) {
            warn "Warning: posix group $posix_group_name not found";
            return;
        }
        my @member = $posix_group->get_value('memberUid');
        my $user_name = $self->name;
        my ($found) = grep /^$user_name$/,@member;
        if (!$found) {
            warn "Error: $user_name is not a member of posix group $posix_group_name\n";
            warn Dumper(\@member) if $Ravada::DEBUG;
            return;
        }
        $self->{_ldap_entry} = $posix_group;
647
    }
648
649
650
651
652
653
654
}

sub login($self) {
    my $user_ok;
    my $allowed;

    return if !$self->_check_posix_group();
655
656

        $user_ok = $self->_login_bind()
Francesc Guasch's avatar
Francesc Guasch committed
657
658
659
660
661
        if !exists $$CONFIG->{ldap}->{auth} || $$CONFIG->{ldap}->{auth} =~ /bind|all/i;

        $user_ok = $self->_login_match()
            if !$user_ok && exists $$CONFIG->{ldap}->{auth}
            && $$CONFIG->{ldap}->{auth} =~ /match|all/i;
662
663
664
665

        $self->_check_user_profile($self->name)   if $user_ok;
        $LDAP_ADMIN->unbind if $LDAP_ADMIN && exists $self->{_auth} && $self->{_auth} eq 'bind';
        return $user_ok;
666
667
668
669
670
671
672
}

sub _login_bind {
    my $self = shift;

    my ($username, $password) = ($self->name , $self->password);

673
    my $found = 0;
Francesc Guasch's avatar
Francesc Guasch committed
674
675
676
677
678
679
680
681

    my @user;
    if (exists $$CONFIG->{ldap}->{field} && defined $$CONFIG->{ldap}->{field} ) {
        @user = search_user( name => $self->name );
    } else {
        @user = (search_user(name => $self->name, field => 'uid')
                ,search_user(name => $self->name, field => 'cn'));
    }
682
683
684
685
686
687
688
689
    my %user = map { $_->dn => $_ } @user;

    my @error;
    for my $dn ( sort keys %user ) {
        if ($$CONFIG->{ldap}->{group} && !is_member($dn,$$CONFIG->{ldap}->{group})) {
            push @error, ("Warning: $dn does not belong to group $$CONFIG->{ldap}->{group}");
            next;
        }
690
        $found++;
691
692
        my $ldap;
        eval { $ldap = _connect_ldap($dn, $password) };
693
694
        warn "ERROR: Bad credentials for $dn"
            if $Ravada::DEBUG && $@;
695
        if ( $ldap ) {
696
            $self->{_auth} = 'bind';
697
            $self->{_ldap_entry} = $user{$dn} if $user{$dn};
698
699
            return 1;
        }
700
        push @error,("ERROR: Bad credentials for $dn");
701
    }
702
703
    warn Dumper(\@error)
            if $Ravada::DEBUG && scalar (@error);
704
705
706
    return 0;
}

707
708
709
710
711
712
713
714
715
716
717
=head2 ldap_entry

Returns the ldap entry as a Net::LDAP::Entry of the user if it has
LDAP external authentication

=cut

sub ldap_entry($self) {
    return $self->{_ldap_entry};
}

718
sub _login_match {
719
720
721
    my $self = shift;
    my ($username, $password) = ($self->name , $self->password);

722
    $LDAP_ADMIN = undef;
723
724
725
726
727
    _init_ldap_admin();
    my $user_ok;

    my @entries = search_user($username);

728
    my @error;
729
730
    for my $entry (@entries) {

731
732
733
734
        if ($$CONFIG->{ldap}->{group} && !is_member($entry->dn,$$CONFIG->{ldap}->{group})) {
            push @error, ("Warning: ".$entry->dn.." does not belong to group $$CONFIG->{ldap}->{group}");
            next;
        }
735
736
737
738
739
#       my $mesg;
#       eval { $mesg = $LDAP->bind( $user_dn, password => $password )};
#       return 1 if $mesg && !$mesg->code;

#       warn "ERROR: ".$mesg->code." : ".$mesg->error. " : Bad credentials for $username";
740
741
742
        eval { $user_ok = $self->_match_password($entry, $password) };
        warn $@ if $@;

743
744
745
746
        if ( $user_ok ) {
            $self->{_ldap_entry} = $entry;
            last;
        }
747
748
    }

749
750
751
    if ($user_ok) {
        $self->{_auth} = 'match';
    }
752

753
754
    warn Dumper(\@error)
            if $Ravada::DEBUG && scalar (@error);
755
756
757
758
759
760
    return $user_ok;
}

sub _check_user_profile {
    my $self = shift;
    my $user_sql = Ravada::Auth::SQL->new(name => $self->name);
761
762
763
764
765
766
    if ( $user_sql->id ) {
        if ($user_sql->external_auth ne 'ldap') {
            $user_sql->external_auth('ldap');
        }
        return;
    }
767

768
769
    Ravada::Auth::SQL::add_user(name => $self->name, is_external => 1, is_temporary => 0
        , external_auth => 'ldap');
770
771
772
773
774
775
}

sub _match_password {
    my $self = shift;
    my $user = shift;
    my $password = shift or die "ERROR: Missing password for ".$user->get_value('cn'); # We won't allow empty passwords
776
777
    confess "ERROR: Wrong entry ".$user->dump
        if !scalar($user->attributes);
778

779
780
    die "ERROR: No userPassword for ".$user->get_value('uid')
            .Dumper($user)
781
782
783
784
785
786
787
        if !$user->get_value('userPassword');
    my $password_ldap = $user->get_value('userPassword');

#    warn $user->get_value('uid')."\n".$user->get_value('userPassword')
#        ."\n"
#        .sha1_hex($password);

Francesc Guasch's avatar
Francesc Guasch committed
788
789
790
791
792
    my ($storage) = $password_ldap =~ /^{([a-z0-9]+)[_}]/i;
    my ($password_ldap_hex) = $password_ldap =~ /.*?}(.*)/;
    return Authen::Passphrase->from_rfc2307($password_ldap)->match($password)
        if $storage =~ /rfc2307|md5/i;

793
794
    return _match_pbkdf2($password_ldap,$password) if $storage eq 'PBKDF2';
    return _match_ssha($password_ldap,$password) if $storage eq 'SSHA';
Francesc Guasch's avatar
Francesc Guasch committed
795
796
797
798
799
800
801
802
803
804
805

    confess "Error: storage $storage can't do match. Use bind.";
}

sub _ntohl {
    return unless defined wantarray;
    confess "Wrong number of arguments ($#_) to " . __PACKAGE__ . "::ntohl, called"
    if @_ != 1 and !wantarray;
    unpack('L*', pack('N*', @_));
}

806
807
808
809
sub _match_ssha($password_ldap, $password) {
    return Authen::Passphrase->from_rfc2307($password_ldap)->match($password);
}

Francesc Guasch's avatar
Francesc Guasch committed
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
sub _match_pbkdf2($password_db_64, $password) {

    my ($sign,$password_db) = $password_db_64 =~ /(\{.*?})(.*)/;
    $password_db=decode_base64($password_db);

    my ($algorithm,$n) = $sign =~ /_(.*?)(\d+)}/;

    die "password_db length wrong: ".length($password_db)
    ." != $PBKDF2_LENGTH"
        if length($password_db) != $PBKDF2_LENGTH;

    my ($iterations_db) = substr($password_db, 0, $PBKDF2_ITERATIONS_LENGTH);
    my $iterations = unpack 'V', $iterations_db;
    ($iterations) = _ntohl($iterations);

    my ($salt)
    = substr($password_db, $PBKDF2_ITERATIONS_LENGTH, $PBKDF2_SALT_LENGTH);
    my $derive = derive("$algorithm-$n", encode('ascii',$password), $salt
        , $iterations, $PBKDF2_HASH_LENGTH);

    my $match = $sign.encode_base64($iterations_db.$salt.$derive,"");

    return $password_db_64 eq $match;

834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
}

sub _dc_base {
    
    return $$CONFIG->{ldap}->{base}
        if $$CONFIG->{ldap}->{base};

    my $base = '';
    for my $part (split /\./,hostdomain()) {
        $base .= "," if $base;
        $base .= "dc=$part";
    }
    return $base;
}

sub _connect_ldap {
    my ($dn, $pass) = @_;
    $pass = '' if !defined $pass;

    my $host = ($$CONFIG->{ldap}->{server} or 'localhost');
    my $port = ($$CONFIG->{ldap}->{port} or 389);
855
856
857
858
859
860
861
    my $secure = 0;
    if (exists $$CONFIG->{ldap}->{secure} && defined $$CONFIG->{ldap}->{secure}) {
        $secure = $$CONFIG->{ldap}->{secure};
        $secure = 0 if $secure =~ /false|no/i;
    } else {
        $secure = 1 if $port == 636;
    }
862
863
864
    my $ldap;
    
    for my $retry ( 1 .. 3 ) {
865
        if ($secure ) {
Francesc Guasch's avatar
Francesc Guasch committed
866
            $ldap = _connect_ldaps($host, $port);
867
868
869
870
871
872
873
874
875
876
877
878
879
880
        } else {
            $ldap = Net::LDAP->new($host, port => $port, verify => 'none') 
        }
        last if $ldap;
        warn "WARNING: I can't connect to LDAP server at $host / $port : $@ [ retry $retry ]";
        sleep 1 + $retry;
    }
    die "I can't connect to LDAP server at $host / $port : $@"  if !$ldap;

    if ($dn) {
        my $mesg = $ldap->bind($dn, password => $pass);
        die "ERROR: ".$mesg->code." : ".$mesg->error. " : Bad credentials for $dn\n"
            if $mesg->code;

881
882
    } else {
        return;
883
884
885
886
887
    }

    return $ldap;
}

Francesc Guasch's avatar
Francesc Guasch committed
888
889
890
891
892
893
894
895
896
897
898
sub _connect_ldaps($host, $port) {
    my @args;
    push @args,(sslversion => $$CONFIG->{ldap}->{sslversion})
    if exists $$CONFIG->{ldap}->{sslversion};

    return Net::LDAPS->new($host, port => $port, verify => 'none'
        ,@args
    )

}

899
900
901
902
903
904
905
906
907
908
sub _init_ldap_admin {
    return $LDAP_ADMIN if $LDAP_ADMIN;

    my ($dn, $pass);
    if ($$CONFIG->{ldap} ) {
        ($dn, $pass) = ( $$CONFIG->{ldap}->{admin_user}->{dn} 
            , $$CONFIG->{ldap}->{admin_user}->{password});
    } else {
        confess "ERROR: Missing ldap section in config file ".Dumper($$CONFIG)."\n"
    }
909
    return if !$dn;
910
911
912
913
914
    $LDAP_ADMIN = _connect_ldap($dn, $pass) ;
    return $LDAP_ADMIN;
}

sub _init_ldap {
915
    return $LDAP if $LDAP;
916
917

    $LDAP = _connect_ldap();
918
    return $LDAP;
919
920
921
922
923
924
925
926
927
928
929
930
}

=head2 is_admin

Returns wether an user is admin

=cut

sub is_admin {
    my $self = shift;
    my $verbose = shift;

931
    my $admin_group =  $$CONFIG->{ldap}->{admin_group} or return;
932
933
934
935
936
937
938
939
    my $group = search_group(name => $admin_group)
        or do {
            warn "WARNING: I can't find group $admin_group in the LDAP directory\n"
                if $verbose;
            return 0;
        };


940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
    return is_member($self->name, $admin_group);

}

=head2 is_member

Returns if an user is member of a group

    if (is_member($group, $cn)) {
    }

=cut

sub is_member($cn, $group) {
    my $user;
    my $dn;
    if (ref($cn) && ref($cn) =~ /Net::LDAP::Entry/) {
        $user = $cn;
        $cn = $user->get_value('cn');
        $dn = $user->dn;
    } elsif($cn=~/=.*,/) {
        $dn = $cn;
        $cn =~ s/.*?=(.*?),.*/$1/;
    }
964

965
966
967
    my @members = _group_members($group);
    return 1 if grep /^$cn$/, @members;

968
969
970
971
972
973
974
975
976
977
    if (!$dn) {
        if (!$user) {
            for my $field ( 'uid','cn') {
                $user = search_user(name => $cn, field => $field);
                last if $user;
            }
            confess "Error: unknown user '$cn'" if !$user;
        }
        $dn = $user->dn if !$dn;
    }
978
979
980
981
982
983
984

    return 1 if grep /^$dn$/, @members;

    my $group_name = $group;
    $group_name = $group->dn if ref($group);

    return 0;
985
986
}

987
988
989
990
991
992
993
994
=head2 is_external

Returns true if the user authentication is external to SQL, so true for LDAP users always

=cut

sub is_external { return 1 }

995
996
997
998
999
1000
1001
=head2 init

LDAP init, don't call, does nothing

=cut

sub init {
1002
1003
    $LDAP = undef;
    $LDAP_ADMIN = undef;
1004
1005
1006
}

1;