Welcome to mirror list, hosted at ThFree Co, Russian Federation.

LDAP.pm « ExternalAuth « Authen « RT « lib - github.com/bestpractical/rt.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e6b22206c79747521b634f55e0083fb0979ad83b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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
92
93
94
95
96
97
98
99
100
101
102
103
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
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
184
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
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
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
# BEGIN BPS TAGGED BLOCK {{{
#
# COPYRIGHT:
#
# This software is Copyright (c) 1996-2022 Best Practical Solutions, LLC
#                                          <sales@bestpractical.com>
#
# (Except where explicitly superseded by other copyright notices)
#
#
# LICENSE:
#
# This work is made available to you under the terms of Version 2 of
# the GNU General Public License. A copy of that license should have
# been provided with this software, but in any event can be snarfed
# from www.gnu.org.
#
# This work 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
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 or visit their web page on the internet at
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
#
#
# CONTRIBUTION SUBMISSION POLICY:
#
# (The following paragraph is not intended to limit the rights granted
# to you to modify and distribute this software under the terms of
# the GNU General Public License and is only of importance to you if
# you choose to contribute your changes and enhancements to the
# community by submitting them to Best Practical Solutions, LLC.)
#
# By intentionally submitting any modifications, corrections or
# derivatives to this work, or any other work intended for use with
# Request Tracker, to Best Practical Solutions, LLC, you confirm that
# you are the copyright holder for those contributions and you grant
# Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
# royalty-free, perpetual, license to use, copy, create derivative
# works based on those contributions, and sublicense and distribute
# those contributions and any derivatives thereof.
#
# END BPS TAGGED BLOCK }}}

package RT::Authen::ExternalAuth::LDAP;

use Net::LDAP qw(LDAP_SUCCESS LDAP_PARTIAL_RESULTS);
use Net::LDAP::Util qw(ldap_error_name escape_filter_value);
use Net::LDAP::Filter;

use warnings;
use strict;

=head1 NAME

RT::Authen::ExternalAuth::LDAP - LDAP source for RT authentication

=head1 DESCRIPTION

Provides the LDAP implementation for L<RT::Authen::ExternalAuth>.

=head1 SYNOPSIS

    Set($ExternalSettings, {
        # AN EXAMPLE LDAP SERVICE
        'My_LDAP'       =>  {
            'type'                      =>  'ldap',

            'server'                    =>  'server.domain.tld',
            'user'                      =>  'rt_ldap_username',
            'pass'                      =>  'rt_ldap_password',

            'base'                      =>  'ou=Organisational Unit,dc=domain,dc=TLD',
            'filter'                    =>  '(FILTER_STRING)',
            'd_filter'                  =>  '(FILTER_STRING)',

            'group'                     =>  'GROUP_NAME',
            'group_attr'                =>  'GROUP_ATTR',

            'tls'                       =>  { verify => "require", cafile => "/path/to/ca.pem" },

            'net_ldap_args'             => [    version =>  3   ],

            'attr_match_list' => [
                'Name',
                'EmailAddress',
            ],
            'attr_map' => {
                'Name' => 'sAMAccountName',
                'EmailAddress' => 'mail',
                'Organization' => 'physicalDeliveryOfficeName',
                'RealName' => 'cn',
                'Gecos' => 'sAMAccountName',
                'WorkPhone' => 'telephoneNumber',
                'Address1' => 'streetAddress',
                'City' => 'l',
                'State' => 'st',
                'Zip' => 'postalCode',
                'Country' => 'co'
            },
        },
    } );

=head1 CONFIGURATION

LDAP-specific options are described here. Shared options
are described in L<RT::Authen::ExternalAuth>.

The example in the L</SYNOPSIS> lists all available options
and they are described below. Note that many of these values
are specific to LDAP, so you should consult your LDAP
documentation for details.

=over 4

=item server

The server hosting the LDAP or AD service.

=item user, pass

The username and password RT should use to connect to the LDAP
server.

If you can bind to your LDAP server anonymously you may be able to omit these
options.  Many servers do not allow anonymous binds, or restrict what information
they can see or how much information they can retrieve.  If your server does not
allow anonymous binds then you must have a service account created for this
component to function.

=item base

The LDAP search base.

=item filter

The filter to use to match RT users. You B<must> specify it
and it B<must> be a valid LDAP filter encased in parentheses.

For example:

    filter => '(objectClass=*)',

=item d_filter

The filter that will only match disabled users. Optional.
B<Must> be a valid LDAP filter encased in parentheses.

For example with Active Directory the following can be used:

    d_filter => '(userAccountControl:1.2.840.113556.1.4.803:=2)'

=item group

Does authentication depend on group membership? What group name?

=item group_attr

What is the attribute for the group object that determines membership?

=item group_scope

What is the scope of the group search? C<base>, C<one> or C<sub>.
Optional; defaults to C<base>, which is good enough for most cases.
C<sub> is appropriate when you have nested groups.

=item group_attr_value

What is the attribute of the user entry that should be matched against
group_attr above? Optional; defaults to C<dn>.

=item tls

Should we try to use TLS to encrypt connections?  Either a scalar, for
simple enabling, or a hash of values to pass to L<Net::LDAP/start_tls>.
By default, L<Net::LDAP> does B<no> certificate validation!  To validate
certificates, you must pass a hash with the C<verify> option set, along
with either C<capath> or C<cafile>.

C<capath> is a directory that contains certificates named using the hash
value of the certificates' subject names. On Debian-based distributions, the
C<ca-certificates> package manages a directory C</etc/ssl/certs>
suitable for this purpose (see L<Debian documentation|https://sources.debian.org/src/ca-certificates/latest/debian/README.Debian/>).
You can validate against public certificate authorities by passing:

    tls => { verify => 'require', capath => "/etc/ssl/certs" },

On Red Hat-based distributions, the C<ca-certificates> package manages a
directory C</etc/pki/tls/certs> suitable for this purpose
(see L<RedHat documentation|https://www.redhat.com/sysadmin/ca-certificates-cli>).
You can validate against public certificate authorities by passing:

    tls => { verify => 'require', capath => "/etc/pki/tls/certs" },

If you don't have this directory set up, or if you want to validate the
LDAP server certificate against a specific certificate authority, you can
pass the path to one public certificate in the C<cafile> option:

    tls => { verify => 'require', cafile => "/etc/YourCACertPath.pem" },

=item net_ldap_args

What other args should be passed to Net::LDAP->new($host,@args)?

=back

=cut

sub GetAuth {

    my ($service, $username, $password) = @_;

    my $config = RT->Config->Get('ExternalSettings')->{$service};
    $RT::Logger->debug( "Trying external auth service:",$service);

    my $base            = $config->{'base'};
    my $filter          = $config->{'filter'};
    my $group           = $config->{'group'};
    my $group_attr      = $config->{'group_attr'};
    my $group_attr_val  = $config->{'group_attr_value'} || 'dn';
    my $group_scope     = $config->{'group_scope'} || 'base';
    my $attr_map        = $config->{'attr_map'};
    my @attrs           = ('dn');
    my $attr_match_list = $config->{'attr_match_list'};

    # Make sure we fetch the user attribute we'll need for the group check
    push @attrs, $group_attr_val
        unless lc $group_attr_val eq 'dn';

    # Empty parentheses as filters cause Net::LDAP to barf.
    # We take care of this by using Net::LDAP::Filter, but
    # there's no harm in fixing this right now.
    undef $filter if defined $filter and $filter eq "()";

    # Now let's get connected
    my $ldap = _GetBoundLdapObj($config);
    return 0 unless ($ldap);

    # loop over each of the attr_match_list members for LDAP search
    my $ldap_msg;
    foreach my $attr_match ( @{$attr_match_list} ) {
        unless ( defined $attr_map->{$attr_match} ) {
            $RT::Logger->error( "Invalid LDAP mapping for $attr_match, no defined fields in attr_map" );
            next;
        }

        my $search_filter = Net::LDAP::Filter->new(
            '(&' .
            $filter .
            '(' .
            $attr_map->{$attr_match} .
            '=' .
            escape_filter_value($username) .
            '))'
        );

        $RT::Logger->debug( "LDAP Search === ",
                            "Base:",
                            $base,
                            "== Filter:",
                            $search_filter->as_string,
                            "== Attrs:",
                            join(',',@attrs) );

        $ldap_msg = $ldap->search( base   => $base,
                                   filter => $search_filter,
                                   attrs  => \@attrs );

        unless ( $ldap_msg->code == LDAP_SUCCESS || $ldap_msg->code == LDAP_PARTIAL_RESULTS ) {
            $RT::Logger->critical( "search for",
                                   $search_filter->as_string,
                                   "failed:",
                                   ldap_error_name($ldap_msg->code),
                                   $ldap_msg->code );
            # Didn't even get a partial result - jump straight to the next external auth service
            return 0;
        }

        if ( $ldap_msg->count != 1 ) {
            $RT::Logger->info( $service,
                               "AUTH FAILED:",
                               $username,
                               "User not found or more than one user found" );
            # We got no user, or too many users.. try the next attr_match_list field.
            next;
        }
        else {
            # User was found
            last;
        }
    }

    # if we didn't match anything, go to the next external auth service
    return 0 unless $ldap_msg->first_entry;

    my $ldap_entry = $ldap_msg->first_entry;
    my $ldap_dn    = $ldap_entry->dn;

    $RT::Logger->debug( "Found LDAP DN:",
                        $ldap_dn);

    # THIS bind determines success or failure on the password.
    $ldap_msg = $ldap->bind($ldap_dn, password => $password);

    unless ($ldap_msg->code == LDAP_SUCCESS) {
        $RT::Logger->info(  $service,
                            "AUTH FAILED",
                            $username,
                            "(can't bind:",
                            ldap_error_name($ldap_msg->code),
                            $ldap_msg->code,
                            ")");
        # Could not bind to the LDAP server as the user we found with the password
        # we were given, therefore the password must be wrong so we fail and
        # jump straight to the next external auth service
        return 0;
    }

    # The user is authenticated ok, but is there an LDAP Group to check?
    if ($group) {
        my $group_val = lc $group_attr_val eq 'dn'
                            ? $ldap_dn
                            : $ldap_entry->get_value($group_attr_val);

        # Fallback to the DN if the user record doesn't have a value
        unless (defined $group_val) {
            $group_val = $ldap_dn;
            $RT::Logger->debug("Attribute '$group_attr_val' has no value; falling back to '$group_val'");
        }

        # We only need the dn for the actual group since all we care about is existence
        @attrs  = qw(dn);
        my $search_filter = Net::LDAP::Filter->new("(${group_attr}=" . escape_filter_value($group_val) . ")");

        $RT::Logger->debug( "LDAP Search === ",
                            "Base:",
                            $group,
                            "== Scope:",
                            $group_scope,
                            "== Filter:",
                            $search_filter->as_string,
                            "== Attrs:",
                            join(',',@attrs));

        $ldap_msg = $ldap->search(  base   => $group,
                                    filter => $search_filter,
                                    attrs  => \@attrs,
                                    scope  => $group_scope);

        # And the user isn't a member:
        unless ($ldap_msg->code == LDAP_SUCCESS ||
                $ldap_msg->code == LDAP_PARTIAL_RESULTS) {
            $RT::Logger->critical(  "Search for",
                                    $search_filter->as_string,
                                    "failed:",
                                    ldap_error_name($ldap_msg->code),
                                    $ldap_msg->code);

            # Fail auth - jump to next external auth service
            return 0;
        }

        unless ($ldap_msg->count == 1) {
            $RT::Logger->debug(
                "LDAP group membership check returned",
                $ldap_msg->count, "results"
            );
            $RT::Logger->info(  $service,
                                "AUTH FAILED:",
                                $username);

            # Fail auth - jump to next external auth service
            return 0;
        }
    }

    # Any other checks you want to add? Add them here.

    # If we've survived to this point, we're good.
    $RT::Logger->info(  (caller(0))[3],
                        "External Auth OK (",
                        $service,
                        "):",
                        $username);
    return 1;

}


sub CanonicalizeUserInfo {

    my ($service, $key, $value) = @_;

    my $found = 0;
    my %params = (Name         => undef,
                  EmailAddress => undef,
                  RealName     => undef);

    # Load the config
    my $config = RT->Config->Get('ExternalSettings')->{$service};

    # Figure out what's what
    my $base            = $config->{'base'};
    my $filter          = $config->{'filter'};

    # Get the list of unique attrs we need
    my @attrs;
    for my $field ( values %{ $config->{'attr_map'} } ) {
        if ( ref $field eq 'CODE' ) {
            push @attrs, $field->();
        }
        elsif ( ref $field eq 'ARRAY' ) {
            push @attrs, @$field;
        }
        else {
            push @attrs, $field;
        }
    }

    # This is a bit confusing and probably broken. Something to revisit..
    my $filter_addition = ($key && $value) ? "(". $key . "=". escape_filter_value($value) .")" : "";
    if(defined($filter) && ($filter ne "()")) {
        $filter = Net::LDAP::Filter->new(   "(&" .
                                            $filter .
                                            $filter_addition .
                                            ")"
                                        );
    } else {
        $RT::Logger->debug( "LDAP Filter invalid or not present.");
    }

    unless (defined($base)) {
        $RT::Logger->critical(  (caller(0))[3],
                                "LDAP baseDN not defined");
        # Drop out to the next external information service
        return ($found, %params);
    }

    # Get a Net::LDAP object based on the config we provide
    my $ldap = _GetBoundLdapObj($config);

    # Jump to the next external information service if we can't get one,
    # errors should be logged by _GetBoundLdapObj so we don't have to.
    return ($found, %params) unless ($ldap);

    # Do a search for them in LDAP
    $RT::Logger->debug( "LDAP Search === ",
                        "Base:",
                        $base,
                        "== Filter:",
                        $filter->as_string,
                        "== Attrs:",
                        join(',',@attrs));

    my $ldap_msg = $ldap->search(base   => $base,
                                 filter => $filter,
                                 attrs  => \@attrs);

    # If we didn't get at LEAST a partial result, just die now.
    if ($ldap_msg->code != LDAP_SUCCESS and
        $ldap_msg->code != LDAP_PARTIAL_RESULTS) {
        $RT::Logger->critical(  (caller(0))[3],
                                ": Search for ",
                                $filter->as_string,
                                " failed: ",
                                ldap_error_name($ldap_msg->code),
                                $ldap_msg->code);
        # $found remains as 0

        # Drop out to the next external information service
        $ldap_msg = $ldap->unbind();
        if ($ldap_msg->code != LDAP_SUCCESS) {
            $RT::Logger->critical(  (caller(0))[3],
                                    ": Could not unbind: ",
                                    ldap_error_name($ldap_msg->code),
                                    $ldap_msg->code);
        }
        undef $ldap;
        undef $ldap_msg;
        return ($found, %params);

    } else {
        # If there's only one match, we're good; more than one and
        # we don't know which is the right one so we skip it.
        if ($ldap_msg->count == 1) {
            RT->Logger->debug("Found one matching record");
            my $entry = $ldap_msg->first_entry();
            foreach my $key (keys(%{$config->{'attr_map'}})) {
                # XXX TODO: This legacy code wants to be removed since modern
                # configs will always fall through to the else and the logic is
                # weird even if you do have the old config.
                if ($RT::LdapAttrMap and $RT::LdapAttrMap->{$key} eq 'dn') {
                    $params{$key} = $entry->dn();
                }
                else {

                    my $external_field = $config->{'attr_map'}{$key};
                    my @list = grep defined && length, ref $external_field eq 'ARRAY' ? @$external_field : ($external_field);
                    unless (@list) {
                        $RT::Logger->error("Invalid LDAP mapping for $key, no defined fields");
                        next;
                    }

                    my @values;
                    foreach my $e (@list) {
                        if ( ref $e eq 'CODE' ) {
                            push @values,
                              $e->(
                                external_entry => $entry,
                                mapping        => $config->{'attr_map'},
                                rt_field       => $key,
                                external_field => $external_field,
                              );
                        }
                        elsif ( ref $e ) {
                            $RT::Logger->error("Invalid type of LDAP mapping for $key, value is $e");
                            next;
                        }
                        else {
                            push @values, $entry->get_value( $e, asref => 1 );
                        }
                    }

                    # Use the first value if multiple values are set in ldap
                    @values = map { ref $_ eq 'ARRAY' ? $_->[0] : $_ } grep defined, @values;
                    $params{$key} = join ' ', grep defined && length, @values;
                }
            }
            $found = 1;
        } else {
            # Drop out to the next external information service
            RT->Logger->debug("Found " . $ldap_msg->count . " records. Need a single matching record"
                . " to populate user data, so continuing with other configured auth services.");
            $ldap_msg = $ldap->unbind();
            if ($ldap_msg->code != LDAP_SUCCESS) {
                $RT::Logger->critical(  (caller(0))[3],
                                        ": Could not unbind: ",
                                        ldap_error_name($ldap_msg->code),
                                        $ldap_msg->code);
            }
            undef $ldap;
            undef $ldap_msg;
            return ($found, %params);
        }
    }
    $ldap_msg = $ldap->unbind();
    if ($ldap_msg->code != LDAP_SUCCESS) {
        $RT::Logger->critical(  (caller(0))[3],
                                ": Could not unbind: ",
                                ldap_error_name($ldap_msg->code),
                                $ldap_msg->code);
    }

    undef $ldap;
    undef $ldap_msg;

    return ($found, %params);
}

sub UserExists {
    my ($username,$service) = @_;
   $RT::Logger->debug("UserExists params:\nusername: $username , service: $service");
    my $config              = RT->Config->Get('ExternalSettings')->{$service};

    my $base                = $config->{'base'};
    my $filter              = $config->{'filter'};

    # While LDAP filters must be surrounded by parentheses, an empty set
    # of parentheses is an invalid filter and will cause failure
    # This shouldn't matter since we are now using Net::LDAP::Filter below,
    # but there's no harm in doing this to be sure
    undef $filter if defined $filter and $filter eq "()";

    my $attr_map        = $config->{'attr_map'};
    my $attr_match_list = $config->{'attr_match_list'};

    my @attrs;
    foreach my $attr_match (@{$attr_match_list}) {
        push @attrs, $attr_map->{$attr_match}
            if defined $attr_map->{$attr_match};
    }

    # Ensure we try to get back a Name value from LDAP on the initial LDAP search.
    push @attrs, $attr_map->{'Name'};

    my $ldap = _GetBoundLdapObj($config);
    return unless $ldap;

    # loop over each of the attr_match_list members for the initial lookup
    foreach my $attr_match ( @{$attr_match_list} ) {
        unless ( defined $attr_map->{$attr_match} ) {
            $RT::Logger->error( "Invalid LDAP mapping for $attr_match, no defined fields in attr_map" );
            next;
        }

        my $search_filter = Net::LDAP::Filter->new(
            '(&' .
            $filter .
            '(' .
            $attr_map->{$attr_match} .
            '=' .
            escape_filter_value($username) .
            '))'
        );

        # Check that the user exists in the LDAP service
        $RT::Logger->debug( "LDAP Search === ",
                            "Base:",
                            $base,
                            "== Filter:",
                            ($search_filter ? $search_filter->as_string : ''),
                            "== Attrs:",
                            join(',',@attrs) );

        my $user_found = $ldap->search( base   => $base,
                                        filter => $search_filter,
                                        attrs  => \@attrs );

        unless ( $user_found->code == LDAP_SUCCESS || $user_found->code == LDAP_PARTIAL_RESULTS ) {
            $RT::Logger->debug( "search for",
                                $filter->as_string,
                                "failed:",
                                ldap_error_name($user_found->code),
                                $user_found->code );
            # Didn't even get a partial result - jump straight to the next external auth service
            return 0;
        }

        if ( $user_found->count < 1 ) {
            # If 0 or negative integer, no user found or major failure
            $RT::Logger->debug( "User Check Failed :: (",
                                $service,
                                ")",
                                $username,
                                "User not found" );
            next;
        }
        elsif ( $user_found->count > 1 ) {
            # If more than one result returned, jump to the next attr because the username field should be unique!
            $RT::Logger->debug( "User Check Failed :: (",
                                $service,
                                ")",
                                $username,
                                "More than one user with that username!" );
            next;
        }
        else {
            # User was found in LDAP
            return $attr_match;
        }
    }

    # No valid user was found using each of the search filters.
    # go to the next external auth service.
    return 0;
}

sub UserDisabled {

    my ($username,$service) = @_;

    # FIRST, check that the user exists in the LDAP service
    my $field = UserExists( $username, $service );

    unless($field) {
        $RT::Logger->debug("User (",$username,") doesn't exist! - Assuming not disabled for the purposes of disable checking");
        return 0;
    }

    my $config          = RT->Config->Get('ExternalSettings')->{$service};
    my $base            = $config->{'base'};
    my $filter          = $config->{'filter'};
    my $d_filter        = $config->{'d_filter'};
    my $search_filter;

    # While LDAP filters must be surrounded by parentheses, an empty set
    # of parentheses is an invalid filter and will cause failure
    # This shouldn't matter since we are now using Net::LDAP::Filter below,
    # but there's no harm in doing this to be sure
    undef $filter   if defined $filter   and $filter eq "()";
    undef $d_filter if defined $d_filter and $d_filter eq "()";

    unless ($d_filter) {
        # If we don't know how to check for disabled users, consider them all enabled.
        $RT::Logger->debug("No d_filter specified for this LDAP service (",
                            $service,
                            "), so considering all users enabled");
        return 0;
    }

    if (defined($config->{'attr_map'}->{$field})) {
        # Construct the complex filter
        $search_filter = Net::LDAP::Filter->new(   '(&' .
                                                    $filter .
                                                    $d_filter .
                                                    '(' .
                                                    $config->{'attr_map'}->{$field} .
                                                    '=' .
                                                    escape_filter_value($username) .
                                                    '))'
                                                );
    } else {
        $RT::Logger->debug("You haven't specified an LDAP attribute to match the RT \"$field\" attribute for this service (",
                            $service,
                            "), so it's impossible look up the disabled status of this user (",
                            $username,
                            ") so I'm just going to assume the user is not disabled");
        return 0;

    }

    my $ldap = _GetBoundLdapObj($config);
    next unless $ldap;

    # We only need the UID for confirmation now,
    # the other information would waste time and bandwidth
    my @attrs = ('uid');

    $RT::Logger->debug( "LDAP Search === ",
                        "Base:",
                        $base,
                        "== Filter:",
                        ($search_filter ? $search_filter->as_string : ''),
                        "== Attrs:",
                        join(',',@attrs));

    my $disabled_users = $ldap->search(base   => $base,
                                       filter => $search_filter,
                                       attrs  => \@attrs);
    # If ANY results are returned,
    # we are going to assume the user should be disabled
    if ($disabled_users->count) {
        undef $disabled_users;
        return 1;
    } else {
        undef $disabled_users;
        return 0;
    }
}
# {{{ sub _GetBoundLdapObj

sub _GetBoundLdapObj {

    # Config as hashref
    my $config = shift;

    # Figure out what's what
    my $ldap_server     = $config->{'server'};
    my $ldap_user       = $config->{'user'};
    my $ldap_pass       = $config->{'pass'};
    my $ldap_tls        = $config->{'tls'};
    $ldap_tls = $ldap_tls ? {} : undef unless ref $ldap_tls;
    my $ldap_args       = $config->{'net_ldap_args'};

    my $ldap = new Net::LDAP($ldap_server, @$ldap_args);

    unless ($ldap) {
        $RT::Logger->critical(  (caller(0))[3],
                                ": Cannot connect to",
                                $ldap_server);
        return undef;
    }

    if ($ldap_tls) {
        # Thanks to David Narayan for the fault tolerance bits
        eval { $ldap->start_tls( %{$ldap_tls} ); };
        if ($@) {
            $RT::Logger->critical(  (caller(0))[3],
                                    "Can't start TLS: ",
                                    $@);
            return;
        }

    }

    my $msg = undef;

    if (($ldap_user) and ($ldap_pass)) {
        $msg = $ldap->bind($ldap_user, password => $ldap_pass);
    } elsif (($ldap_user) and ( ! $ldap_pass)) {
        $msg = $ldap->bind($ldap_user);
    } else {
        $msg = $ldap->bind;
    }

    unless ($msg->code == LDAP_SUCCESS) {
        $RT::Logger->critical(  (caller(0))[3],
                                "Can't bind:",
                                ldap_error_name($msg->code),
                                $msg->code);
        return undef;
    } else {
        return $ldap;
    }
}

# }}}

RT::Base->_ImportOverlays();

1;