Debian Codegraph @

lemonldap-ng-common/lib/Lemonldap/NG/Common/Safelib.pm

raw
1 ##@file
2 # Functions shared in Safe jail
3
4 ##@class
5 # Functions shared in Safe jail
6 package Lemonldap::NG::Common::Safelib;
7
8 use strict;
9 use Encode;
10 use MIME::Base64;
11 use Lemonldap::NG::Common::IPv6;
12 use JSON::XS;
13 use Net::CIDR;
14 use Digest::SHA;
15 use Date::Parse;
16
17 our $VERSION = '2.23.0';
18
19 # Set here all the names of functions that must be available in Safe objects.
20 # Note that only functions, not methods, can be written here
21 our $functions =
22 [
23 qw(&checkLogonHours &date &dateToTime &checkDate &basic &unicode2iso &unicode2isoSafe &iso2unicode &iso2unicodeSafe &groupMatch &isInNet6 &varIsInUri &has2f_internal &ipInSubnet &subjectid &inDomain_internal)
24 ];
25
26 ## @function boolean ipInSubnet(string ip, string network, ... )
27 # Function to check if an IP is part of a network
28 # @param $ip IP address to test
29 # @param $network Network in CIDR notation
30 # You can call the function with multiple networks
31 # @return 1 true, 0 else
32 sub ipInSubnet {
33 my ( $ip, @networks ) = @_;
34 return Net::CIDR::cidrlookup( $ip, @networks );
35 }
36
37 ## @function boolean subjectid(string alg, string value, string scope, string salt)
38 # Function to compute an opaque identifier from a value and optional salt
39 # @param $value ID to encrypt
40 # @param $scope Domain used for restricting scope
41 # @param $salt Salt appended to generate hash
42 # @return encrypted ID
43 sub subjectid {
44 my ( $value, $scope, $salt ) = @_;
45 $salt //= "";
46 $scope = $scope ? "\@$scope" : "";
47 return (
48 lc( encode_base32( Digest::SHA::sha256( $value . $salt ) ) ) . $scope );
49 }
50
51 # This function is copied from MIME::Base32 under GPL/Artistic license
52 # by Daniel Peder <[email protected]>
53 sub encode_base32 {
54 my $arg = shift;
55 return '' unless defined($arg); # mimic MIME::Base64
56
57 $arg = unpack( 'B*', $arg );
58 $arg =~ s/(.....)/000$1/g;
59 my $l = length($arg);
60 if ( $l & 7 ) {
61 my $e = substr( $arg, $l & ~7 );
62 $arg = substr( $arg, 0, $l & ~7 );
63 $arg .= "000$e" . '0' x ( 5 - length $e );
64 }
65 $arg = pack( 'B*', $arg );
66 $arg =~ tr|\0-\37|A-Z2-7|;
67 return $arg;
68 }
69
70 ## @function boolean checkLogonHours(string logon_hours, string syntax, string time_correction, boolean default_access)
71 # Function to check logon hours
72 # @param $logon_hours string representing allowed logon hours (GMT)
73 # @param $syntax optional hexadecimal (default) or octetstring
74 # @param $time_correction optional hours to add or to subtract
75 # @param $default_access optional what result to return for users without logons hours
76 # @return 1 if access allowed, 0 else
77 sub checkLogonHours {
78 my ( $logon_hours, $syntax, $time_correction, $default_access ) = @_;
79
80 # Active Directory - logonHours: $attr_src_syntax = octetstring
81 # Samba - sambaLogonHours: ???
82 # LL::NG - ssoLogonHours: $attr_src_syntax = hexadecimal
83 $syntax ||= "hexadecimal";
84
85 # Default access if no value
86 $default_access ||= "0";
87 return $default_access unless $logon_hours;
88
89 # Get the base2 value of logon_hours
90 # Each byte represent an hour of the week
91 # Begin with sunday at 0h00
92 my $base2_logon_hours;
93 if ( $syntax eq "octetstring" ) {
94 $base2_logon_hours = unpack( "B*", $logon_hours );
95 }
96 if ( $syntax eq "hexadecimal" ) {
97
98 # Remove white spaces
99 $logon_hours =~ s/ //g;
100 $base2_logon_hours = unpack( "B*", pack( "H*", $logon_hours ) );
101 }
102
103 # Get the present day and hour
104 my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
105 gmtime(time);
106
107 # Get the hour position
108 my $hourpos = $wday * 24 + $hour;
109
110 # Use time_correction
111 if ($time_correction) {
112 my ( $sign, $time ) = ( $time_correction =~ /([+|-]?)(\d+)/ );
113 if ( $sign =~ /-/ ) { $hourpos -= $time; }
114 else { $hourpos += $time; }
115 }
116
117 # Get the corresponding byte
118 return substr( $base2_logon_hours, $hourpos, 1 );
119 }
120
121 ## @function integer listMatch
122 # Test if a value is found in a collection
123 # @param $list Can be a hash, array or string including the separator
124 # @param $values string The values to search for
125 # @param $ignorecase boolean Be case insensitive
126 # @return 1 if the value was found, 0 else
127 # NOTE: this function is not exported directly in this module because we don't
128 # want the user to have to worry about separator. Is is wrapped in a closure in
129 # Jail.pm
130 sub listMatch {
131 my ( $sep, $list, @values ) = @_;
132 my $flags = '';
133 my @a;
134
135 if ( $values[-1] eq '1' || $values[-1] eq '0' ) {
136 $flags = pop @values ? 'i' : '';
137 }
138
139 if ( ref($list) eq "ARRAY" ) {
140 @a = @{$list};
141 }
142 elsif ( ref($list) eq "HASH" ) {
143 @a = keys %{$list};
144 }
145 else {
146 @a = split $sep, $list;
147 }
148
149 foreach my $value (@values) {
150 return 1 if grep /(?$flags)^\Q$value\E$/, @a;
151 }
152
153 return 0;
154 }
155
156 ## @function integer date
157 # Get current local date
158 # @param $gmt optional boolean To return GMT date (default is local date)
159 # @return current date on format YYYYMMDDHHMMSS
160 sub date {
161 my $gmt = shift;
162 my ( $sec, $min, $hour, $mday, $mon, $year ) = $gmt ? gmtime : localtime;
163
164 $year += 1900;
165 $mon += 1;
166 $mon = "0" . $mon if ( $mon < 10 );
167 $mday = "0" . $mday if ( $mday < 10 );
168 $hour = "0" . $hour if ( $hour < 10 );
169 $min = "0" . $min if ( $min < 10 );
170 $sec = "0" . $sec if ( $sec < 10 );
171
172 return $year . $mon . $mday . $hour . $min . $sec;
173 }
174
175 ## @function integer dateToTime(string date)
176 # Converts a LDAP date into epoch time or returns undef upon failure.
177 # @param $date string Date in YYYYMMDDHHMMSS[+/-0000] format. It may contain a differential timezone, otherwise default TZ is GMT
178 # @return Date converted to time
179 sub dateToTime {
180 my $date = shift;
181 return undef unless ($date);
182
183 # Parse date
184 my ( $year, $month, $day, $hour, $min, $sec, $zone ) =
185 ( $date =~ /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})([-+\w]*)/ );
186
187 # Convert date to epoch time with GMT as default timezone if date contains none
188 return str2time(
189 $year . "-"
190 . $month . "-"
191 . $day . "T"
192 . $hour . ":"
193 . $min . ":"
194 . $sec
195 . $zone,
196 "GMT"
197 );
198 }
199
200 ## @function boolean checkDate(string start, string end, boolean default_access)
201 # Function to check a date
202 # @param $start string Start date in YYYYMMDDHHMMSS[+/-0000] format. It may contain a differential timezone, otherwise default TZ is GMT
203 # @param $end string End date in YYYYMMDDHHMMSS[+/-0000] format. It may contain a differential timezone, otherwise default TZ is GMT
204 # @param $default_access optional what result to return for users without start and end dates
205 # @return 1 if access allowed, 0 else
206 sub checkDate {
207 my ( $start, $end, $default_access ) = @_;
208
209 # Default access if no value
210 $default_access ||= "0";
211 return $default_access unless ( $start or $end );
212
213 # If no start, set start to 01 01 1970
214 $start ||= "19700101000000";
215
216 # If no end, set end to the end of the world
217 $end ||= "99991231235959";
218
219 # Convert dates to epoch time
220 my $starttime = &dateToTime($start);
221 my $endtime = &dateToTime($end);
222
223 # Convert current GMT date to epoch time
224 my $datetime = &dateToTime( &date(1) );
225
226 return 1 if ( ( $datetime >= $starttime ) and ( $datetime <= $endtime ) );
227 return 0;
228
229 }
230
231 ## @function string basic(string login, string password)
232 # Return string that can be used for HTTP-BASIC authentication
233 # @param login User login
234 # @param password User password
235 # @return Authorization header content
236 sub basic {
237 my ( $login, $password ) = @_;
238
239 # UTF-8 strings should be ISO encoded
240 $login = &unicode2iso($login);
241 $password = &unicode2iso($password);
242
243 return "Basic " . encode_base64( $login . ":" . $password, '' );
244 }
245
246 ## @function string unicode2iso(string string)
247 # Convert UTF-8 in ISO-8859-1
248 # @param string UTF-8 string
249 # @return ISO string
250 sub unicode2iso {
251 my ($string) = @_;
252
253 return encode( "iso-8859-1", decode( "utf-8", $string ) );
254 }
255
256 ## @function string unicode2isoSafe(string string)
257 ## This function is compliant with the Safe jail
258 ## but not as portable as the original one
259 # Convert UTF-8 in ISO-8859-1
260 # @param string UTF-8 string
261 # @return ISO string
262 sub unicode2isoSafe {
263 my ($string) = @_;
264
265 my $res = $string;
266 utf8::decode($res);
267 utf8::downgrade($res);
268 return $res;
269 }
270
271 ## @function string iso2unicode(string string)
272 # Convert ISO-8859-1 in UTF-8
273 # @param string ISO string
274 # @return UTF-8 string
275 sub iso2unicode {
276 my ($string) = @_;
277
278 return encode( "utf-8", decode( "iso-8859-1", $string ) );
279 }
280
281 ## @function string iso2unicodeSafe(string string)
282 ## This function is compliant with the Safe jail
283 ## but not as portable as the original one
284 # Convert ISO-8859-1 in UTF-8
285 # @param string ISO string
286 # @return UTF-8 string
287 sub iso2unicodeSafe {
288 my ($string) = @_;
289
290 my $res = $string;
291 utf8::encode($res);
292 return $res;
293 }
294
295 ## @function int groupMatch(hashref groups, string attribute, string value)
296 # Check in hGroups structure if a group attribute contains a value
297 # @param groups The $hGroups variable
298 # @param attribute Name of the attribute
299 # @param value Value to check
300 # @return int Number of values that match
301 sub groupMatch {
302 my ( $groups, $attribute, $value ) = @_;
303 my $match = 0;
304
305 foreach my $group ( keys %$groups ) {
306 if ( ref( $groups->{$group}->{$attribute} ) eq "ARRAY" ) {
307 foreach ( @{ $groups->{$group}->{$attribute} } ) {
308 $match++ if ( $_ =~ /$value/ );
309 }
310 }
311 else {
312 $match++ if ( $groups->{$group}->{$attribute} =~ /$value/ );
313 }
314 }
315
316 return $match;
317 }
318
319 sub isInNet6 {
320 my ( $ip, $net ) = @_;
321 my ($bits) = $net =~ s#/(\d+)##;
322 return net6( $ip, $bits ) eq net6( $net, $bits ) ? 1 : 0;
323 }
324
325 sub varIsInUri {
326 my ( $uri, $wanteduri, $attribute, $restricted ) = @_;
327 return $restricted
328 ? $uri =~ /$wanteduri$attribute$/
329 : $uri =~ /$wanteduri$attribute/;
330 }
331
332 my $json = JSON::XS->new;
333
334 sub has2f_internal {
335 my ( $session, $type ) = @_;
336 return 0 unless $session->{_2fDevices};
337
338 my $_2fDevices = eval { $json->decode( $session->{_2fDevices} ); };
339 return 0 if ( $@ or ref($_2fDevices) ne "ARRAY" );
340
341 # Empty array
342 return 0 unless scalar @{$_2fDevices};
343
344 # Array has one value and we did not specify a type, succeed
345 if ($type) {
346 my @found = grep { lc( $_->{type} ) eq lc($type) } @{$_2fDevices};
347 return @found ? 1 : 0;
348 }
349
350 return 1;
351 }
352
353 sub inDomain_internal {
354 my ( $host, $domain ) = @_;
355 my $res = $host =~ /(?:^|\.)\Q$domain\E$/i;
356 return $res;
357 }
358
359 1;