4af6f4f3cfcb0d0da6146d9e34aaa103e3247336
[virtual-ldap] / bin / ldap-roundcube.pl
1 #!/usr/bin/perl
2 # Copyright (c) 2006 Hans Klunder <hans.klunder@bigfoot.com>. All rights reserved.
3 # This program is free software; you can redistribute it and/or
4 # modify it under the same terms as Perl itself.
5
6 # It's modified by Dobrica Pavlinusic <dpavlin@rot13.org> to include following:
7 #
8 # * rewrite LDAP bind request cn: username@domain.com -> uid=username,dc=domain,dc=com
9 # * rewrite search responses:
10 # ** expand key:value pairs from hrEduPersonUniqueNumber into hrEduPersonUniqueNumber_key
11 # ** augment response with yaml/dn.yaml data (for external data import)
12
13 use strict;
14 use warnings;
15
16 use IO::Select;
17 use IO::Socket;
18 use IO::Socket::SSL;
19 use warnings;
20 use Data::Dump qw/dump/;
21 use Convert::ASN1 qw(asn_read);
22 use Net::LDAP::ASN qw(LDAPRequest LDAPResponse);
23 our $VERSION = '0.3';
24 use fields qw(socket target);
25 use YAML qw/LoadFile/;
26
27 my $debug = $ENV{DEBUG} || 0;
28 $|=1; # flush STDOUT
29
30 my $config = {
31         yaml_dir => './yaml/',
32         listen => shift @ARGV || 'localhost:1389',
33         upstream_ldap => 'ldap.ffzg.hr',
34         upstream_ssl => 1,
35         overlay_prefix => 'ffzg-',
36 #       log_file => 'log/ldap-rewrite.log',
37
38 };
39
40 my $log_fh;
41
42 sub log {
43         my $level = $1 if $_[0] =~ m/^(#+)/;
44         return if defined($level) && length($level) > $debug;
45
46         warn join("\n", @_);
47
48         return unless $config->{log_file};
49
50         if ( ! $log_fh ) {
51                 open($log_fh, '>>', $config->{log_file}) || die "can't open ", $config->{log_file},": $!";
52                 print $log_fh "# " . time;
53         }
54         $log_fh->autoflush(1);
55         print $log_fh join("\n", @_),"\n";
56 }
57
58 BEGIN {
59         $SIG{'__WARN__'} = sub { main::log(@_); }
60 }
61
62
63 if ( ! -d $config->{yaml_dir} ) {
64         warn "DISABLE ", $config->{yaml_dir}," data overlay";
65 }
66
67 warn "# config = ",dump( $config );
68
69 sub handle {
70         my $clientsocket=shift;
71         my $serversocket=shift;
72
73         # read from client
74         asn_read($clientsocket, my $reqpdu);
75         if ( ! $reqpdu ) {
76                 warn "# client closed connection\n";
77                 return 0;
78         }
79         $reqpdu = log_request($reqpdu);
80
81         # send to server
82         print $serversocket $reqpdu or die "Could not send PDU to server\n ";
83         
84         # read from server
85         my $ready;
86         my $sel = IO::Select->new($serversocket);
87         for( $ready = 1 ; $ready ; $ready = $sel->can_read(0)) {
88                 asn_read($serversocket, my $respdu);
89                 if ( ! $respdu ) {
90                         warn "server closed connection\n";
91                         return 0;
92                 }
93                 $respdu = log_response($respdu, $reqpdu);
94                 # and send the result to the client
95                 print $clientsocket $respdu || return 0;
96         }
97
98         return 1;
99 }
100
101
102 sub log_request {
103         my $pdu=shift;
104
105         die "empty pdu" unless $pdu;
106
107 #       print '-' x 80,"\n";
108 #       print "Request ASN 1:\n";
109 #       Convert::ASN1::asn_hexdump(\*STDOUT,$pdu);
110 #       print "Request Perl:\n";
111         my $request = $LDAPRequest->decode($pdu);
112         warn "## request = ",dump($request);
113
114         if ( defined $request->{bindRequest} ) {
115                 if ( $request->{bindRequest}->{name} =~ m{@} ) {
116                         my $old = $request->{bindRequest}->{name};
117                         $request->{bindRequest}->{name} =~ s/[@\.]/,dc=/g;
118                         $request->{bindRequest}->{name} =~ s/^/uid=/;
119                         print "rewrite bind cn $old -> ", $request->{bindRequest}->{name}, "\n";
120                         Convert::ASN1::asn_hexdump(\*STDOUT,$pdu) if $debug;
121                         $pdu = $LDAPRequest->encode($request);
122                         Convert::ASN1::asn_hexdump(\*STDOUT,$pdu) if $debug;
123                 }
124         }
125
126         return $pdu;
127 }
128
129 sub log_response {
130         my ($pdu,$reqpdu)=@_;
131         die "empty pdu" unless $pdu;
132
133         my $search_uid = 0;
134         my $request = $LDAPRequest->decode($reqpdu);
135         if ( exists $request->{searchRequest}->{filter} ) {
136                 my $filter = dump($request->{searchRequest}->{filter});
137 warn "XXX $filter";
138                 if ( $filter =~ m/attributeDesc => "uid"/ ) {
139                         warn "got uid search";
140                         $search_uid = 1;
141                 }
142         }
143
144 #       print '-' x 80,"\n";
145 #       print "Response ASN 1:\n";
146 #       Convert::ASN1::asn_hexdump(\*STDOUT,$pdu);
147 #       print "Response Perl:\n";
148         my $response = $LDAPResponse->decode($pdu);
149
150         if ( defined $response->{protocolOp}->{searchResEntry} ) {
151                 my $uid = $response->{protocolOp}->{searchResEntry}->{objectName};
152                 warn "# rewrite objectName $uid\n";
153
154                 my @attrs;
155
156                 foreach my $attr ( @{ $response->{protocolOp}->{searchResEntry}->{attributes} } ) {
157                         if ( $attr->{type} =~ m/date/i ) {
158                                 foreach my $i ( 0 .. $#{ $attr->{vals} } ) {
159                                         $attr->{vals}->[$i] = "$1-$2-$3" if $attr->{vals}->[$i] =~ m/^([12]\d\d\d)([01]\d+)([0123]\d+)$/;
160                                 }
161 =for disable
162                         } elsif ( $attr->{type} eq 'hrEduPersonUniqueNumber' ) {
163                                 foreach my $val ( @{ $attr->{vals} } ) {
164                                         next if $val !~ m{.+:.+};
165                                         my ( $n, $v ) = split(/\s*:\s*/, $val );
166                                         push @attrs, { type => $attr->{type} . '_' . $n, vals => [ $v ] };
167                                 }
168                         } elsif ( $attr->{type} eq 'hrEduPersonGroupMember' ) {
169                                 foreach my $i ( 0 .. $#{ $attr->{vals} } ) {
170                                         $attr->{vals}->[$i] =~ s/^u2010/p2010/gs && warn "FIXME group";
171                                 }
172                         } elsif ( $attr->{type} eq 'homePostalAddress' ) {
173                                 foreach my $val ( @{ $attr->{vals} } ) {
174                                         next if $val !~ m{^(.+)\s*,\s*(\d+)\s+(.+)};
175                                         push @attrs,
176                                                 { type => 'homePostalAddress_address', vals => [ $1 ] },
177                                                 { type => 'homePostalAddress_zipcode', vals => [ $2 ] },
178                                                 { type => 'homePostalAddress_city', vals => [ $3 ] };
179                                 }
180                         } elsif ( $attr->{type} eq 'mail' ) {
181                                 my @emails;
182                                 foreach my $i ( 0 .. $#{ $attr->{vals} } ) {
183                                         my $e = $attr->{vals}->[$i];
184                                         if ( $e =~ m/\s+/ ) {
185                                                 push @emails, split(/\s+/, $e);
186                                         } else {
187                                                 push @emails, $e;
188                                         }
189                                 }
190                                 $attr->{vals} = [ shift @emails ];
191                                 foreach my $i ( 0 .. $#emails ) {
192                                         push @attrs, { type => $attr->{type} . '_' . ( $i + 1 ) , vals => [ $emails[$i] ] };
193                                 }
194 =cut
195                         } elsif ( $attr->{type} eq 'mail' ) {
196                                 my @emails;
197                                 foreach my $i ( 0 .. $#{ $attr->{vals} } ) {
198                                         my $e = $attr->{vals}->[$i];
199                                         if ( $e =~ m/\s+/ ) {
200                                                 push @emails, split(/\s+/, $e);
201                                         } else {
202                                                 push @emails, $e;
203                                         }
204                                 }
205                                 if ( $search_uid ) {    # only for new_user_identity plugin which does uid search
206                                         $attr->{vals} = [ grep { m/\@ffzg/ } @emails ]; # remote all emails not @ffzg.hr @ffzg.unizg.hr
207                                 }
208                         } elsif ( $attr->{type} eq 'facsimileTelephoneNumber' ) {
209                                 my @fax;
210                                 foreach my $i ( 0 .. $#{ $attr->{vals} } ) {
211                                         my $e = $attr->{vals}->[$i];
212                                         push @fax, $e;
213                                 }
214                                 $attr->{vals} = [ grep { ! m/\Q+385 xx xxxx xxx\E/ } @fax ];
215                         }
216                 }
217
218                 warn "# ++ attrs ",dump( @attrs );
219
220                 push @{ $response->{protocolOp}->{searchResEntry}->{attributes} }, $_ foreach @attrs;
221
222 =for removed
223                 my @additional_yamls = ( $uid );
224                 foreach my $attr ( @{ $response->{protocolOp}->{searchResEntry}->{attributes} } ) {
225                         foreach my $v ( @{ $attr->{vals} } ) {
226                                 push @additional_yamls, $attr->{type} . '/' . $v;
227                         }
228                 }
229
230                 #warn "# additional_yamls ",dump( @additional_yamls );
231
232                 foreach my $path ( @additional_yamls ) {
233                         my $full_path = $config->{yaml_dir} . '/' . $path . '.yaml';
234                         next unless -e $full_path;
235
236                         my $data = LoadFile( $full_path );
237                         warn "# $full_path yaml = ",dump($data);
238
239                         foreach my $type ( keys %$data ) {
240
241                                 my $vals = $data->{$type};
242
243                                 push @{ $response->{protocolOp}->{searchResEntry}->{attributes} }, {
244                                         type => $config->{overlay_prefix} . $type,
245                                         vals => ref($vals) eq 'ARRAY' ? $vals : [ $vals ],
246                                 };
247                         }
248                 }
249 =cut
250
251                 $pdu = $LDAPResponse->encode($response);
252         }
253
254         warn "## response = ", dump($response);
255
256         return $pdu;
257 }
258
259
260 my $listenersock = IO::Socket::INET->new(
261         Listen => 5,
262         Proto => 'tcp',
263         Reuse => 1,
264         LocalAddr => $config->{listen},
265 ) || die "can't open listen socket: $!";
266
267 our $server_sock;
268
269 sub connect_to_server {
270         my $sock;
271         if ( $config->{upstream_ssl} ) {
272                 $sock = IO::Socket::SSL->new( $config->{upstream_ldap} . ':ldaps' );
273         } else {
274                 $sock = IO::Socket::INET->new(
275                         Proto => 'tcp',
276                         PeerAddr => $config->{upstream_ldap},
277                         PeerPort => 389,
278                 );
279         }
280         die "can't open ", $config->{upstream_ldap}, " $!\n" unless $sock;
281         warn "## connected to ", $sock->peerhost, ":", $sock->peerport, "\n";
282         return $sock;
283 }
284
285 my $sel = IO::Select->new($listenersock);
286 while (my @ready = $sel->can_read) {
287         foreach my $fh (@ready) {
288                 if ($fh == $listenersock) {
289                         # let's create a new socket
290                         my $psock = $listenersock->accept;
291                         $sel->add($psock);
292                         warn "## add $psock " . time;
293                 } else {
294                         $server_sock->{$fh} ||= connect_to_server;
295                         if ( ! handle($fh,$server_sock->{$fh}) ) {
296                                 warn "## remove $fh " . time;
297                                 $sel->remove($server_sock->{$fh});
298                                 $server_sock->{$fh}->close;
299                                 delete $server_sock->{$fh};
300                                 # we have finished with the socket
301                                 $sel->remove($fh);
302                                 $fh->close;
303                         }
304                 }
305         }
306 }
307
308 1;