Debian Codegraph @

lemonldap-ng-manager/lib/Lemonldap/NG/Manager/Conf.pm

raw
1 # This module implements all the methods that responds to '/confs/*' requests
2 # It contains 2 sections:
3 # - initialization methods
4 # - upload method
5 #
6 # Read methods are inherited from Lemonldap::NG::Common::Conf::RESTServer
7 package Lemonldap::NG::Manager::Conf;
8
9 use strict;
10 use utf8;
11 use Mouse;
12 use Lemonldap::NG::Common::Conf::Constants;
13 use Lemonldap::NG::Common::UserAgent;
14 use Lemonldap::NG::Common::EmailTransport;
15 use Lemonldap::NG::Common::Util::Crypto;
16 use URI::URL;
17
18 extends qw(
19 Lemonldap::NG::Manager::Plugin
20 Lemonldap::NG::Common::Conf::RESTServer
21 );
22
23 our $VERSION = '2.23.0';
24
25 #############################
26 # I. INITIALIZATION METHODS #
27 #############################
28
29 use constant defaultRoute => 'manager.html';
30 use constant icon => 'cog';
31
32 has defaultNewKeySize => ( is => 'rw', default => 2048, );
33 has defaultCurve => ( is => 'rw', default => 'prime256v1', );
34
35 sub init {
36 my ( $self, $conf ) = @_;
37
38 $self->defaultNewKeySize( $conf->{defaultNewKeySize} )
39 if $conf->{defaultNewKeySize};
40
41 $self->ua( Lemonldap::NG::Common::UserAgent->new($conf) );
42
43 # HTML template
44 $self->addRoute( 'manager.html', undef, ['GET'] )
45
46 # READ
47 # Special keys
48 ->addRoute(
49 confs => {
50 ':cfgNum' => [
51 qw(virtualHosts samlIDPMetaDataNodes samlSPMetaDataNodes
52 applicationList oidcOPMetaDataNodes oidcRPMetaDataNodes
53 casSrvMetaDataNodes casAppMetaDataNodes
54 authChoiceModules grantSessionRules combModules sfExtra
55 openIdIDPList keyNodes)
56 ]
57 },
58 ['GET']
59 )
60
61 # Other keys
62 ->addRoute( confs => { ':cfgNum' => { '*' => 'getKey' } }, ['GET'] )
63
64 # New key and conf save
65 ->addRoute(
66 confs => {
67 newRSAKey => 'newRSAKey',
68 newCertificate => 'newCertificate',
69 newEcCertificate => 'newEcCertificate',
70 newEcKeys => 'newEcKeys',
71 sendTestMail => 'sendTestMail',
72 raw => 'newRawConf',
73 '*' => 'newConf'
74 },
75 ['POST']
76 )
77
78 # Difference between confs
79 ->addRoute( diff => { ':conf1' => { ':conf2' => 'diff' } } )
80 ->addRoute( 'diff.html', undef, ['GET'] )
81
82 # Url loader
83 ->addRoute( 'prx', undef, ['POST'] );
84 return 1;
85 }
86
87 # 35 - New Certificate on demand
88 # --------------------------
89
90 ##@method public PSGI-JSON-response newRSAKey($req)
91 # Return a hashref containing private and public keys
92 # The posted data must contain a JSON object containing
93 # {"password":"newpassword"}
94 #
95 #@param $req Lemonldap::NG::Common::PSGI::Request object
96 #@return PSGI JSON response
97 sub newCertificate {
98 my ( $self, $req, @others ) = @_;
99 return $self->sendError( $req, 'There is no subkey for "newCertificate"',
100 400 )
101 if (@others);
102 my $query = $req->jsonBodyToObj;
103
104 my $keys = $self->_generateX509( $query->{password}, "RSA" );
105 return $self->sendJSONresponse( $req, $keys );
106 }
107
108 sub newEcCertificate {
109 my ( $self, $req, @others ) = @_;
110 return $self->sendError( $req, 'There is no subkey for "newEcCertificate"',
111 400 )
112 if (@others);
113 my $query = $req->jsonBodyToObj;
114
115 my $keys = $self->_generateX509( $query->{password}, "EC" );
116 return $self->sendJSONresponse( $req, $keys );
117 }
118
119 # 35 - New RSA key pair on demand
120 # --------------------------
121
122 ##@method public PSGI-JSON-response newRSAKey($req)
123 # Return a hashref containing private and public keys
124 # The posted data must contain a JSON object containing
125 # {"password":"newpassword"}
126 #
127 #@param $req Lemonldap::NG::Common::PSGI::Request object
128 #@return PSGI JSON response
129 sub newRSAKey {
130 my ( $self, $req, @others ) = @_;
131 return $self->sendError( $req, 'There is no subkey for "newRSAKey"', 400 )
132 if (@others);
133
134 my $key_size = $self->defaultNewKeySize;
135 my $query = $req->jsonBodyToObj;
136 my $password = $query->{password};
137
138 my $keys =
139 Lemonldap::NG::Common::Util::Crypto::genRsaKey( $key_size, $password );
140
141 return $self->sendJSONresponse( $req, $keys );
142 }
143
144 # 35 - New EC key pair on demand
145 # --------------------------
146
147 ##@method public PSGI-JSON-response newEcKeys($req)
148 # Return a hashref containing private and public keys
149 #
150 #@param $req Lemonldap::NG::Common::PSGI::Request object
151 #@return PSGI JSON response
152 sub newEcKeys {
153 my ( $self, $req, @others ) = @_;
154
155 my $keys = Lemonldap::NG::Common::Util::Crypto::genEcKey('prime256v1');
156 return $self->sendJSONresponse( $req, $keys );
157 }
158
159 # This function does the dirty X509 work,
160 # mostly copied from IO::Socket::SSL::Utils
161 # and adapter to work on old platforms (CentOS7)
162
163 sub _generateX509 {
164 my ( $self, $password, $type ) = @_;
165 my $conf = $self->confAcc->getConf();
166 my $portal_uri = new URI::URL( $conf->{portal} || "http://localhost" );
167 my $portal_host = $portal_uri->host;
168
169 if ( $type eq "EC" ) {
170 my $curve = $self->defaultCurve;
171 return Lemonldap::NG::Common::Util::Crypto::genEcCertKey( $curve,
172 $password, $portal_host );
173 }
174 else {
175 my $key_size = $self->defaultNewKeySize;
176 return Lemonldap::NG::Common::Util::Crypto::genCertKey( $key_size,
177 $password, $portal_host );
178 }
179 }
180
181 # Sending a test Email
182 # --------------------
183
184 ##@method public PSGI-JSON-response sendTestMail($req)
185 # Sends a test email to the provided address
186 # The posted data must contain a JSON object containing
187 # {"dest":"[email protected]"}
188 #
189 #@param $req Lemonldap::NG::Common::PSGI::Request object
190 #@return PSGI JSON response
191 sub sendTestMail {
192 my ( $self, $req, @others ) = @_;
193 return $self->sendError( $req, 'There is no subkey for "sendTestMail"',
194 400 )
195 if (@others);
196 my $dest = $req->jsonBodyToObj->{dest};
197 unless ($dest) {
198 $self->logger->debug("Missing dest parameter for sending test mail");
199 return $self->sendJSONresponse(
200 $req,
201 {
202 success => \0,
203 error => "You must provide an email address"
204 }
205 );
206 }
207 my $conf = $self->confAcc->getConf();
208
209 # Try to send test Email
210 $self->logger->info("Sending test email to $dest");
211 eval {
212 Lemonldap::NG::Common::EmailTransport::sendTestMail( $conf, $dest );
213 };
214 my $error = $@;
215 my $success = ( $error ? 0 : 1 );
216
217 $self->logger->debug("Email was sent") unless $error;
218 return $self->sendJSONresponse(
219 $req,
220 {
221 success => \$success,
222 ( $error ? ( error => $error ) : () )
223 }
224 );
225 }
226
227 # 36 - URL File loader
228 # ---------------
229
230 ##@method public PSGI-JSON-response prx()
231 # Load file using posted URL and return its content
232 #
233 #@return PSGI JSON response
234 sub prx {
235 my ( $self, $req, @others ) = @_;
236 return $self->sendError( $req, 'There is no subkey for "prx"', 400 )
237 if (@others);
238 my $query = $req->jsonBodyToObj;
239 return $self->sendError( $req, 'Missing parameter', 400 )
240 unless ( $query->{url} );
241 return $self->sendError( $req, 'Bad parameter', 400 )
242 unless ( $query->{url} =~ m#^(?:f|ht)tps?://\w# );
243 $self->ua->timeout(10);
244
245 my $response = $self->ua->get( $query->{url} );
246 unless ( $response->code == 200 ) {
247 return $self->sendError(
248 $req,
249 "Received unexpected HTTP status code "
250 . $response->code . " ("
251 . $response->message
252 . ") when trying to load content from "
253 . $query->{url},
254 400
255 );
256 }
257 unless ( $response->header('Content-Type') =~
258 m#^(?:application/json|(?:application|text)/.*xml).*$# )
259 {
260 return $self->sendError( $req,
261 'Content refused for security reason (neither XML or JSON)', 400 );
262 }
263 return $self->sendJSONresponse( $req, { content => $response->content } );
264 }
265
266 ######################
267 # IV. Upload methods #
268 ######################
269
270 # In this section, 3 methods:
271 # - getConfByNum: override SUPER method to be able to use Zero
272 # - newConf(), load a new configuration and invokes reloadUrls
273 # - newRawConf(): restore a saved conf
274
275 sub getConfByNum {
276 my ( $self, $cfgNum, @args ) = @_;
277 unless ( $self->currentConf
278 and %{ $self->currentConf }
279 and $cfgNum == $self->currentConf->{cfgNum} )
280 {
281 my $tmp;
282 if ( $cfgNum == 0 ) {
283 require Lemonldap::NG::Manager::Conf::Zero;
284 $tmp = Lemonldap::NG::Manager::Conf::Zero::zeroConf();
285 $self->currentConf($tmp);
286 }
287 else {
288 $tmp = $self->SUPER::getConfByNum( $cfgNum, @args );
289 return undef unless ( defined $tmp );
290 }
291 }
292 return $cfgNum;
293 }
294
295 ## @method PSGI-JSON-response newConf($req)
296 # Call Lemonldap::NG::Manager::Conf::Parser to parse new configuration and store
297 # it
298 #
299 #@param $req Lemonldap::NG::Common::PSGI::Request
300 #@return PSGI JSON response
301 sub newConf {
302 my ( $self, $req, @other ) = @_;
303 return $self->sendError( $req, 'There is no subkey for "newConf"', 400 )
304 if (@other);
305
306 # Body must be json
307 my $new = $req->jsonBodyToObj;
308 return $self->sendError( $req, undef, 400 ) unless ( defined $new );
309
310 # Verify that cfgNum has been sent
311 return $self->sendError( $req, "Missing configuration number", 400 )
312 unless ( defined $req->params('cfgNum') );
313
314 # # Verify that cfgDate has been sent
315 # return $self->sendError( $req, "Missing configuration date", 400 )
316 # unless ( defined $req->params('cfgDate') );
317
318 # Set current conf to cfgNum
319 return $self->sendError(
320 $req,
321 "Configuration "
322 . $req->params('cfgNum')
323 . " not available "
324 . $Lemonldap::NG::Common::Conf::msg,
325 400
326 ) unless ( defined $self->getConfByNum( $req->params('cfgNum') ) );
327
328 # Parse new conf
329 require Lemonldap::NG::Manager::Conf::Parser;
330 my $parser = Lemonldap::NG::Manager::Conf::Parser->new(
331 { tree => $new, refConf => $self->currentConf, req => $req } );
332
333 # If ref conf isn't last conf, consider conf changed
334 my $currentCfgNum = $self->confAcc->lastCfg;
335 $req->error($Lemonldap::NG::Common::Conf::msg)
336 unless ( defined $currentCfgNum );
337 return $self->sendError( $req, undef, 400 ) if ( $req->error );
338 my $currentConf =
339 $self->confAcc->getConf(
340 { CfgNum => $currentCfgNum, raw => 1, noCache => 1 } );
341 my $currentCfgDate = $currentConf->{cfgDate};
342 $self->logger->debug(
343 "Current CfgNum/cfgDate: $currentCfgNum/$currentCfgDate");
344 $parser->confChanged(1)
345 if ( $currentCfgNum ne $req->params('cfgNum')
346 || $req->params('cfgDate')
347 && $req->params('cfgDate') ne $currentCfgDate );
348
349 my $res = { result => $parser->check( $self->p ) };
350
351 # "message" fields: note that words enclosed by "__" (__word__) will be
352 # translated
353 $res->{details}->{'__errors__'} = $parser->{errors}
354 if ( @{ $parser->{errors} } );
355 unless ( @{ $parser->{errors} } ) {
356 if ( @{ $parser->{needConfirmation} } && !$req->params('force') ) {
357 $res->{needConfirm} = 1;
358 $res->{details}->{'__needConfirmation__'} =
359 $parser->{needConfirmation};
360 }
361 $res->{message} = $parser->{message};
362 foreach my $t (qw(warnings changes)) {
363 $res->{details}->{ '__' . $t . '__' } = $parser->$t
364 if ( @{ $parser->$t } );
365 }
366 }
367 if ( $res->{result} ) {
368 my %args;
369 $args{force} = 1 if ( $req->params('force') );
370 if ( $req->params('cfgDate') ) {
371 $args{cfgDate} = $req->params('cfgDate');
372 $args{currentCfgDate} = $currentCfgDate;
373 }
374 my $s = UNKNOWN_ERROR;
375 $s = $self->confAcc->saveConf( $parser->newConf, %args )
376 unless ( @{ $parser->{needConfirmation} } && !$args{force} );
377 if ( $s > 0 ) {
378 $self->auditLog(
379 $req,
380 message => (
381 'User ' . $self->p->userId($req) . " has stored conf $s"
382 ),
383 code => "CONF_STORED",
384 user => $self->p->userId($req),
385 cfgNum => $s,
386 );
387
388 $res->{result} = 1;
389 $res->{cfgNum} = $s;
390 if ( my $status = $self->applyConf( $parser->newConf ) ) {
391 push @{ $res->{details}->{__applyResult__} },
392 { message => "$_: $status->{$_}" }
393 foreach ( keys %$status );
394 }
395 }
396 else {
397 $self->auditLog(
398 $req,
399 message => (
400 'Saving attempt rejected, asking for confirmation to '
401 . $self->p->userId($req)
402 ),
403 code => "CONF_REJECTED",
404 user => $self->p->userId($req),
405 );
406
407 $res->{result} = 0;
408 if ( $s == CONFIG_WAS_CHANGED ) {
409 $res->{needConfirm} = 1;
410 $res->{details}->{'__needConfirmation__'} ||= [];
411 push @{ $res->{details}->{'__needConfirmation__'} },
412 { message => '__newCfgAvailableWarning__' };
413 }
414 else {
415 $res->{message} = $Lemonldap::NG::Common::Conf::msg;
416 }
417 }
418 }
419 return $self->sendJSONresponse( $req, $res );
420 }
421
422 ## @method PSGI-JSON-response newRawConf($req)
423 # Store directly raw configuration
424 #
425 #@param $req Lemonldap::NG::Common::PSGI::Request
426 #@return PSGI JSON response
427 sub newRawConf {
428 my ( $self, $req, @other ) = @_;
429 return $self->sendError( $req, 'There is no subkey for "newConf"', 400 )
430 if (@other);
431
432 # Body must be json
433 my $new = $req->jsonBodyToObj;
434 unless ( defined($new) ) {
435 return $self->sendError( $req, undef, 400 );
436 }
437
438 require Lemonldap::NG::Manager::Conf::Parser;
439 my $parser = Lemonldap::NG::Manager::Conf::Parser->new( {
440 refConf => $self->currentConf,
441 newConf => $new,
442 req => $req,
443 }
444 );
445
446 $parser->confChanged(1);
447
448 my $res = { result => $parser->check( $self->p ) };
449
450 # "message" fields: note that words enclosed by "__" (__word__) will be
451 # translated
452 $res->{details}->{'__errors__'} = $parser->{errors}
453 if ( @{ $parser->{errors} } );
454 unless ( @{ $parser->{errors} } ) {
455 if ( @{ $parser->{needConfirmation} } && !$req->params('force') ) {
456 $res->{needConfirm} = 1;
457 $res->{details}->{'__needConfirmation__'} =
458 $parser->{needConfirmation};
459 }
460 $res->{message} = $parser->{message};
461 foreach my $t (qw(warnings changes)) {
462 $res->{details}->{ '__' . $t . '__' } = $parser->$t
463 if ( @{ $parser->$t } );
464 }
465 }
466 if ( $res->{result} ) {
467
468 # When uploading a new conf, always force it since cfgNum has a few
469 # chances to be equal to last config cfgNum
470 my $s = $self->confAcc->saveConf( $new, force => 1 );
471 if ( $s > 0 ) {
472 $self->auditLog(
473 $req,
474 message => (
475 'User '
476 . $self->p->userId($req)
477 . " has stored (raw) conf $s"
478 ),
479 code => "CONF_STORED_RAW",
480 user => $self->p->userId($req),
481 cfgNum => $s,
482 );
483 $res->{result} = 1;
484 $res->{cfgNum} = $s;
485 }
486 else {
487 $self->auditLog(
488 $req,
489 message => (
490 'Raw saving attempt rejected, asking for confirmation to '
491 . $self->p->userId($req)
492 ),
493 code => "CONF_REJECTED_RAW",
494 user => $self->p->userId($req),
495 );
496 $res->{result} = 0;
497 $res->{needConfirm} = 1 if ( $s == CONFIG_WAS_CHANGED );
498 $res->{message} .= '__needConfirmation__';
499 }
500 }
501 return $self->sendJSONresponse( $req, $res );
502 }
503
504 sub diff {
505 my ( $self, $req, @path ) = @_;
506 return $self->sendError( $req, 'to many arguments in path info', 400 )
507 if (@path);
508 my @cfgNum =
509 ( scalar( $req->param('conf1') ), scalar( $req->param('conf2') ) );
510 my @conf;
511 $self->logger->debug(" Loading confs");
512
513 # Load the 2 configurations
514 for ( my $i = 0 ; $i < 2 ; $i++ ) {
515 if ( %{ $self->currentConf }
516 and $cfgNum[$i] == $self->currentConf->{cfgNum} )
517 {
518 $conf[$i] = $self->currentConf;
519 }
520 else {
521 $conf[$i] = $self->confAcc->getConf(
522 { cfgNum => $cfgNum[$i], raw => 1, noCache => 1 } );
523 return $self->sendError(
524 $req,
525 "Configuration $cfgNum[$i] not available $Lemonldap::NG::Common::Conf::msg",
526 400
527 ) unless ( $conf[$i] );
528 }
529 }
530 require Lemonldap::NG::Manager::Conf::Diff;
531 return $self->sendJSONresponse(
532 $req,
533 [
534 $self->Lemonldap::NG::Manager::Conf::Diff::diff(
535 $conf[0], $conf[1]
536 )
537 ]
538 );
539 }
540
541 1;