-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathclass-wp-cli.php
More file actions
1743 lines (1573 loc) · 63.9 KB
/
class-wp-cli.php
File metadata and controls
1743 lines (1573 loc) · 63.9 KB
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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
defined( 'ABSPATH' ) or die();
require_once rsssl_path . 'lib/admin/class-encryption.php';
use RSSSL\lib\admin\Encryption;
use RSSSL\Pro\Security\WordPress\Firewall\Models\Rsssl_404_Block;
use RSSSL\Security\WordPress\Two_Fa\Rsssl_Two_Fa_Status;
use RSSSL\Security\WordPress\Two_Fa\Repositories\Rsssl_Two_Fa_User_Repository;
use RSSSL\Security\WordPress\Two_Fa\Services\Rsssl_Two_Fa_Reminder_Service;
use RSSSL\Security\WordPress\Two_Fa\Models\Rsssl_Two_FA_Data_Parameters;
/**
* WP-CLI integration for Really Simple Security
*
* For an overview of commands use wp help rsssl
*
* Usage examples:
* wp rsssl activate_ssl
* wp rsssl deactivate_ssl
* wp rsssl activate_recommended_features
* wp rsssl deactivate_recommended_features
* wp rsssl activate_security_headers
* wp rsssl deactivate_security_headers
* wp rsssl update_option --name=site_has_ssl --value=true
*
* Booleans should be passed to update_option as 0 or 1.
*
* To complete all standard dashboard notices (recommended features + .htaccess redirect + HSTS + e-mail verification):
*
* wp rsssl activate_recommended_features
* wp rsssl update_option --name=redirect --value=htaccess
* wp rsssl update_option --name=hsts --value=1
* wp rsssl update_option --name=hsts_preload --value=1
* wp rsssl update_option --name=hsts_subdomains --value=1
* wp rsssl update_option --name=hsts_max_age --value='63072000'
* wp rsssl update_option --name=notifications_email_address --value='you@example.com'
* wp option update rsssl_email_verification_status 'completed'
*/
class rsssl_wp_cli {
use Encryption;
public function __construct() {
if ( $this->wp_cli_active() ) {
add_action( 'init', [ $this, 'register_wp_cli_commands' ], 0 );
}
}
/**
* Checks if the conditions for running a Pro WP-CLI command are met.
* This is called *within* the command handler, ensuring plugin is loaded.
* Outputs an error and exits if conditions are not met.
*
* @return bool True if conditions are met, false otherwise (though it usually exits on false).
*/
private function check_pro_command_preconditions(bool $skip_license = false ): bool {
// Skip license check for free (non-pro) commands
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
$command = $backtrace[1]['function'] ?? '';
$command_list = $this->get_command_list();
if ( isset($command_list[$command]) && $command_list[$command]['pro'] === false ) {
return true;
}
// Check if Pro is active (redundant check, but safe)
if ( ! defined( 'rsssl_pro' ) ) {
WP_CLI::error(
__( 'This command is related to functionality available in Really Simple Security Pro, please consider upgrading to unlock all powerful security features. Read more: https://really-simple-ssl.com/pro', 'really-simple-ssl' ),
true // Exit after error
);
return false; // Should not be reached
}
if ( $skip_license ) {
return true; // Skip license check if explicitly requested
}
// Check if license is valid (now safe to call)
if ( ! RSSSL()->licensing->license_is_valid() ) {
$activate_command = 'wp rsssl activate_license <YOUR_LICENSE_KEY>';
// Check if the command exists in the list just to be safe
if (!isset($this->get_command_list()['activate_license'])) {
$activate_command = 'activate_license'; // Fallback text
}
WP_CLI::error(
sprintf(
__( 'It seems that no valid license key is activated for this domain. Activate your license key using the `%s` command, or purchase a valid license key via https://really-simple-ssl.com/pro', 'really-simple-ssl' ),
$activate_command
),
true // Exit after error
);
return false; // Should not be reached
}
// All checks passed
return true;
}
/**
* Check if WP-CLI is active.
*
* @return bool True if WP-CLI is active, false otherwise.
*/
public function wp_cli_active() {
return defined( 'WP_CLI' ) && WP_CLI;
}
/**
* Activate SSL through WP-CLI.
*
* Provides options for verbose output, forcing activation despite warnings,
* skipping confirmation, and performing a dry run.
*
* ## OPTIONS
*
* [--verbose]
* : Show detailed steps during activation.
*
* [--force]
* : Force activation even if pre-flight checks issue warnings and skip confirmation prompt.
*
* [--yes]
* : Skip the confirmation prompt before activating.
*
* [--dry-run]
* : Perform checks and report intended actions without making changes.
*
* ## EXAMPLES
*
* wp rsssl activate_ssl
* wp rsssl activate_ssl --verbose --yes
* wp rsssl activate_ssl --dry-run
*
* @param array $args Positional arguments (none used here).
* @param array $assoc_args Associative arguments (--verbose, --force, --yes, --dry-run).
* @return void
*/
public function activate_ssl( $args, $assoc_args ) {
if ( ! $this->check_pro_command_preconditions() ) return;
$is_verbose = WP_CLI\Utils\get_flag_value( $assoc_args, 'verbose', false );
$is_force = WP_CLI\Utils\get_flag_value( $assoc_args, 'force', false );
$skip_confirm = WP_CLI\Utils\get_flag_value( $assoc_args, 'yes', false );
$is_dry_run = WP_CLI\Utils\get_flag_value( $assoc_args, 'dry-run', false );
if ( $is_dry_run ) {
WP_CLI::line( "-- Dry Run Enabled: No changes will be made. --" );
}
try {
// --- Suggestion 3: Pre-flight Checks ---
if ( $is_verbose || $is_dry_run ) WP_CLI::debug( 'Running pre-activation checks...', 'rsssl-cli' );
// Assume this function now exists and returns ['success' => bool, 'message' => string, 'warnings' => array]
$checks = $this->perform_pre_flight_checks();
if ( ! empty( $checks['warnings'] ) ) {
foreach ( $checks['warnings'] as $warning ) {
WP_CLI::warning( $warning );
}
if ( ! $is_force && ! $is_dry_run ) {
WP_CLI::error( 'Pre-flight checks issued warnings. Use --force to proceed anyway.', false ); // Use false to allow dry-run continue
if (!$is_dry_run) return; // Stop if not dry run
}
}
if ( ! $checks['success'] ) {
// If checks outright fail (not just warnings)
WP_CLI::error( 'Pre-flight checks failed: ' . $checks['message'] );
return;
}
if ( $is_verbose || $is_dry_run ) WP_CLI::debug( 'Pre-flight checks passed.', 'rsssl-cli' );
// --- Report Intended Actions (Dry Run) ---
if ( $is_dry_run ) {
WP_CLI::line( "Intended actions:" );
WP_CLI::line( "- Update WordPress Site URL and Home URL to HTTPS." );
WP_CLI::line( "- Configure redirects (method depends on settings)." );
WP_CLI::line( "- Update internal links/content (if mixed content fixer enabled)." );
WP_CLI::line( "- Dismiss onboarding notice." );
WP_CLI::success( "Dry run complete. No changes were made." );
return; // End dry run here
}
// --- Suggestion 4: Confirmation Prompt ---
// Skip confirmation if --yes or --force is used
if ( ! $skip_confirm && ! $is_force ) {
WP_CLI::confirm( 'Are you sure you want to activate SSL for this site?' );
// WP_CLI::confirm exits script if user doesn't confirm
}
// --- Core Activation Logic ---
if ( $is_verbose ) WP_CLI::debug( 'Attempting SSL activation...', 'rsssl-cli' );
// --- Suggestion 5: Clarify Side Effects ---
// Move onboarding dismissal inside the main activation logic or make it explicit
// update_option( 'rsssl_onboarding_dismissed', true, false ); // Optionally moved inside activate_ssl or reported
// --- Suggestion 1: Granular Failure Reasons ---
// Assume RSSSL()->admin->activate_ssl() now returns an array or throws specific exceptions
// Passing $is_verbose allows the underlying function to potentially output debug info too
$result = RSSSL()->admin->activate_ssl( $is_verbose );
// Check if $result is structured like ['success' => bool, 'message' => string]
if ( is_array( $result ) && isset( $result['success'] ) ) {
if ( $result['success'] ) {
$success_message = 'SSL activated successfully.';
// Suggestion 5: Clarify Side Effects (Example)
if ( get_option('rsssl_onboarding_dismissed') ) {
$success_message .= ' Onboarding notice dismissed.';
}
WP_CLI::success( $success_message );
} else {
// Use the detailed message from the function
WP_CLI::error( 'SSL activation failed: ' . ( $result['message'] ?? 'Unknown reason.' ) );
}
} else if ( $result === true ) { // Handle simple boolean success
WP_CLI::success( 'SSL activated successfully. Onboarding notice dismissed.' );
} else { // Handle simple boolean failure or unexpected return
WP_CLI::error( 'SSL activation failed (unknown reason).' );
}
} catch ( Exception $e ) { // Catch specific exceptions if activate_ssl throws them
// Suggestion 1 & 2: More specific error based on exception type if possible
WP_CLI::error( 'Failed to activate SSL due to an unexpected error: ' . $e->getMessage() );
}
}
/**
* Deactivate SSL through WP-CLI.
*
* @return void
*/
public function deactivate_ssl() {
if ( ! $this->check_pro_command_preconditions() ) return;
try {
RSSSL()->admin->deactivate();
WP_CLI::success( 'SSL deactivated' );
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to deactivate SSL: ' . $e->getMessage() );
}
}
/**
* Update a Really Simple Security option via WP-CLI.
* Booleans should be passed as 0 or 1.
*
* @param array $args Command-line positional arguments.
* @param array $assoc_args Command-line associative arguments.
*
* @return void
*/
public function update_option( $args, $assoc_args ) {
if ( ! isset( $assoc_args['name'] ) || ! isset( $assoc_args['value'] ) ) {
WP_CLI::error( 'Both --name and --value parameters are required.' );
}
$name = sanitize_title( $assoc_args['name'] );
$value = $assoc_args['value'];
try {
rsssl_update_option( $name, $value );
WP_CLI::success( "Option $name updated to $value" );
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to update option: ' . $e->getMessage() );
}
}
/**
* Activate all recommended features via CLI
*
* @throws Exception
* return void
*/
public function activate_recommended_features() {
if ( ! $this->check_pro_command_preconditions() ) return;
try {
RSSSL()->admin->activate_recommended_features();
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to activate recommended features. ' . $e->getMessage() );
}
WP_CLI::success( 'Recommended features activated.' );
}
/**
* Deactivate all recommended features via CLI
*
* return void
*/
public function deactivate_recommended_features() {
if ( ! $this->check_pro_command_preconditions() ) return;
try {
// Deactivate Vulnerability Scanner
rsssl_update_option( 'enable_vulnerability_scanner', false );
// Deactivate essential WordPress hardening features
if (isset(RSSSL()->settingsConfigService)) {
$recommended_hardening_fields = RSSSL()->settingsConfigService->getRecommendedHardeningSettings();
foreach ( $recommended_hardening_fields as $field ) {
rsssl_update_option( $field, false );
}
}
// Disable Email login protection
rsssl_update_option( 'login_protection_enabled', false );
// Disable Mixed Content Fixer
rsssl_update_option( 'mixed_content_fixer', false );
// Disable firewall
rsssl_update_option( 'enable_firewall', false );
rsssl_update_option( 'event_log_enabled', false );
// Check if PRO version is active, then deactivate premium features
if ( defined( 'rsssl_pro' ) ) {
// Disable Two-Factor Authentication
rsssl_update_option( 'two_fa_enabled_roles_totp', [] );
// Disable Limit Login Attempts
rsssl_update_option( 'enable_limited_login_attempts', false );
// Disable advanced security headers
$security_headers = [
'upgrade_insecure_requests',
'x_content_type_options',
'hsts',
'x_xss_protection',
'x_frame_options',
'referrer_policy',
'csp_frame_ancestors',
];
foreach ( $security_headers as $header_key => $header_value ) {
if ( is_string( $header_key ) ) {
rsssl_update_option( $header_key, false );
} else {
rsssl_update_option( $header_value, false );
}
}
// Deactivate password security enforcement
rsssl_update_option( 'enforce_password_security_enabled', false );
rsssl_update_option( 'enable_hibp_check', false );
}
do_action('rsssl_update_rules');
WP_CLI::success( 'Recommended features deactivated.' );
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to deactivate recommended features: ' . $e->getMessage() );
}
}
/**
* Activate all recommended hardening features via CLI
*
* return void
*/
public function activate_recommended_hardening_features() {
if ( ! $this->check_pro_command_preconditions() ) return;
try {
if (isset(RSSSL()->settingsConfigService)) {
$recommended_hardening_fields = RSSSL()->settingsConfigService->getRecommendedHardeningSettings();
foreach ( $recommended_hardening_fields as $field ) {
rsssl_update_option( $field, true );
}
}
do_action('rsssl_update_rules');
WP_CLI::success( 'Recommended hardening features activated.' );
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to activate recommended hardening features: ' . $e->getMessage() );
}
}
/**
* Deactivate all recommended features via CLI
*
* return void
*/
public function deactivate_recommended_hardening_features() {
if ( ! $this->check_pro_command_preconditions() ) return;
try {
if (isset(RSSSL()->settingsConfigService)) {
$recommended_hardening_fields = RSSSL()->settingsConfigService->getRecommendedHardeningSettings();
foreach ( $recommended_hardening_fields as $field ) {
rsssl_update_option( $field, false );
}
}
do_action('rsssl_update_rules');
WP_CLI::success( 'Recommended hardening features deactivated.' );
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to deactivate recommended hardening features: ' . $e->getMessage() );
}
}
/**
* Activate recommended security headers via CLI
*/
public function activate_security_headers() {
if ( ! $this->check_pro_command_preconditions() ) return;
try {
foreach (RSSSL()->headers->get_recommended_security_headers() as $header ) {
if (isset($header['option_name'], $header['recommended_setting'])) {
rsssl_update_option( $header['option_name'], $header['recommended_setting'] );
}
}
WP_CLI::success( 'Recommended security header settings saved. Run "update_advanced_headers" command to activate them.' );
do_action('rsssl_update_rules');
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to activate security headers: ' . $e->getMessage() );
}
}
/**
* Deactivate recommended security headers via CLI
*/
public function deactivate_security_headers() {
if ( ! $this->check_pro_command_preconditions() ) return;
try {
$recommended_headers = RSSSL()->headers->get_recommended_security_headers();
foreach ( $recommended_headers as $header ) {
if ( isset( $header['option_name'] ) && isset( $header['disabled_setting'] ) ) {
rsssl_update_option($header['option_name'], $header['disabled_setting']);
}
}
do_action('rsssl_update_rules');
WP_CLI::success( 'Recommended security headers deactivated.' );
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to deactivate security headers: ' . $e->getMessage() );
}
}
/**
* Activate firewall via CLI
*
* return void
*/
public function activate_firewall() {
if ( ! $this->check_pro_command_preconditions() ) return;
try {
rsssl_update_option( 'enable_firewall', true );
rsssl_update_option( 'event_log_enabled', true );
do_action('rsssl_update_rules');
WP_CLI::success( 'Firewall activated.' );
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to activate firewall: ' . $e->getMessage() );
}
}
/**
* Deactivate firewall via CLI
*
* return void
*/
public function deactivate_firewall() {
if ( ! $this->check_pro_command_preconditions() ) return;
try {
rsssl_update_option( 'enable_firewall', false );
rsssl_update_option( 'event_log_enabled', false );
do_action('rsssl_update_rules');
WP_CLI::success( 'Firewall deactivated.' );
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to deactivate firewall: ' . $e->getMessage() );
}
}
/**
* Activate Two-Factor Authentication via CLI
*
* return void
*/
public function activate_2fa() {
if ( ! $this->check_pro_command_preconditions() ) return;
try {
rsssl_update_option( 'two_fa_enabled_roles_totp', [ 'administrator' ] );
rsssl_update_option( 'login_protection_enabled', true );
WP_CLI::success( 'Two-Factor Authentication activated.' );
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to activate Two-Factor Authentication: ' . $e->getMessage() );
}
}
/**
* Deactivate Two-Factor Authentication via CLI
*
* return void
*/
public function deactivate_2fa() {
if ( ! $this->check_pro_command_preconditions() ) return;
try {
rsssl_update_option( 'two_fa_enabled_roles_totp', [] );
rsssl_update_option( 'login_protection_enabled', false );
WP_CLI::success( 'Two-Factor Authentication deactivated.' );
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to deactivate Two-Factor Authentication: ' . $e->getMessage() );
}
}
/**
* Activate password security via CLI
*
* return void
*/
public function activate_password_security() {
if ( ! $this->check_pro_command_preconditions() ) return;
try {
rsssl_update_option( 'enforce_password_security_enabled', true );
rsssl_update_option( 'enforce_frequent_password_change', true );
rsssl_update_option( 'hide_rememberme', true );
rsssl_update_option( 'enable_hibp_check', true );
WP_CLI::success( 'Password security features activated.' );
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to activate password security: ' . $e->getMessage() );
}
}
/**
* Deactivate password security via CLI
*
* return void
*/
public function deactivate_password_security() {
if ( ! $this->check_pro_command_preconditions() ) return;
try {
rsssl_update_option( 'enforce_password_security_enabled', false );
rsssl_update_option( 'enforce_frequent_password_change', false );
rsssl_update_option( 'hide_rememberme', false );
rsssl_update_option( 'enable_hibp_check', false );
do_action('rsssl_update_rules');
WP_CLI::success( 'Password security features deactivated.' );
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to deactivate password security: ' . $e->getMessage() );
}
}
/**
* Activate login attempts limitation via CLI
*
* return void
*/
public function activate_lla() {
if ( ! $this->check_pro_command_preconditions() ) return;
try {
rsssl_update_option( 'enable_limited_login_attempts', true );
rsssl_update_option( 'event_log_enabled', true );
WP_CLI::success( 'Limit login attempts activated.' );
do_action('rsssl_update_rules');
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to activate limit login attempts: ' . $e->getMessage() );
}
}
/**
* Deactivate login attempts limitation via CLI
*
* return void
*/
public function deactivate_lla() {
if ( ! $this->check_pro_command_preconditions() ) return;
try {
rsssl_update_option( 'enable_limited_login_attempts', false );
rsssl_update_option( 'event_log_enabled', false );
do_action('rsssl_update_rules');
WP_CLI::success( 'Limit login attempts deactivated.' );
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to deactivate limit login attempts: ' . $e->getMessage() );
}
}
/**
* Activate vulnerability scanning via CLI
*
* return void
*/
public function activate_vulnerability_scanning() {
if ( ! $this->check_pro_command_preconditions() ) return;
try {
rsssl_update_option( 'enable_vulnerability_scanner', true );
WP_CLI::success( 'Vulnerability scanning activated.' );
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to activate vulnerability scanning: ' . $e->getMessage() );
}
}
/**
* Deactivate vulnerability scanning via CLI
*
* return void
*/
public function deactivate_vulnerability_scanning() {
if ( ! $this->check_pro_command_preconditions() ) return;
try {
rsssl_update_option( 'enable_vulnerability_scanner', false );
WP_CLI::success( 'Vulnerability scanning deactivated.' );
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to deactivate vulnerability scanning: ' . $e->getMessage() );
}
}
/**
* Activate license via CLI
*
* @param array $args Positional arguments. License should be passed as first and only argument
*
* @return void
*/
public function activate_license( $args ) {
if ( ! $this->check_pro_command_preconditions(true) ) return;
try {
// Check if license key is provided
if ( empty( $args[0] ) ) {
WP_CLI::error( 'Please provide a license key: wp rsssl activate_license YOUR_LICENSE_KEY' );
return;
}
$license_key = sanitize_text_field( $args[0] );
rsssl_update_option( 'license', $this->encrypt_with_prefix( $license_key, 'really_simple_ssl_' ) );
$status = RSSSL()->licensing->get_license_status( 'check_license', true );
update_option( 'rsssl_onboarding_dismissed', true, false );
if ( $status === 'valid' ) {
WP_CLI::success( 'License activated successfully.' );
} elseif ( $status === 'invalid' || $status === 'missing' ) {
WP_CLI::error( 'Invalid license key. You can find your license key on https://really-simple-ssl.com/account' );
} elseif ( $status === 'expired' ) {
WP_CLI::error( 'License has expired. Please renew via https://really-simple-ssl.com/account/subscriptions' );
} elseif ( $status === 'no_activations_left' ) {
WP_CLI::error( 'No activations left. Please upgrade your license via https://really-simple-ssl.com/account/subscriptions' );
} elseif ( $status === 'disabled' ) {
WP_CLI::error( 'This license is not valid. Find out why on your account page at https://really-simple-ssl.com/account' );
}
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to activate license: ' . $e->getMessage() );
}
}
/**
* Deactivate license via CLI
*
* @return void
*/
public function deactivate_license() {
if ( ! $this->check_pro_command_preconditions() ) return;
try {
rsssl_update_option( 'license', '' );
$status = RSSSL()->licensing->get_license_status( 'check_license', true );
update_option( 'rsssl_onboarding_dismissed', true, false );
// License key should now be empty
if ( $status === 'empty' ) {
WP_CLI::success( 'License deactivated successfully.' );
} else {
WP_CLI::error( 'Something went wrong when deactivating your license. Please try again.' );
}
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to deactivate license: ' . $e->getMessage() );
}
}
/**
* Add lock file for safe mode
*
* @return void
*/
public function add_lock_file() {
if ( ! $this->check_pro_command_preconditions() ) return;
try {
$lock_file = WP_CONTENT_DIR . '/rsssl-safe-mode.lock';
// Check if file already exists
if ( file_exists( $lock_file ) ) {
WP_CLI::warning( 'Lock file already exists.' );
return;
}
// Create lock file
$result = file_put_contents( $lock_file, time() );
if ( $result === false ) {
WP_CLI::error( 'Unable to create lock file.' );
}
// Set proper permissions
chmod( $lock_file, 0644 );
WP_CLI::success( 'Safe mode lock file created successfully.' );
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to create lock file: ' . $e->getMessage() );
}
}
/**
* Remove lock file for safe mode
*
* @return void
*/
public function remove_lock_file() {
if ( ! $this->check_pro_command_preconditions() ) return;
try {
$lock_file = WP_CONTENT_DIR . '/rsssl-safe-mode.lock';
// Check if file exists
if ( ! file_exists( $lock_file ) ) {
WP_CLI::warning( 'Lock file does not exist.' );
return;
}
// Remove lock file
if ( ! unlink( $lock_file ) ) {
WP_CLI::error( 'Unable to remove lock file.' );
}
WP_CLI::success( 'Safe mode lock file removed successfully.' );
} catch ( Exception $e ) {
WP_CLI::error( 'Failed to remove lock file: ' . $e->getMessage() );
}
}
/**
* Reset the 2FA status of a user to disabled
*
* Usage: wp rsssl reset_2fa 123
*
* @param array $args User ID should be the first element
*
* @throws \WP_CLI\ExitException
*/
public function reset_2fa( $args ): void
{
if ( ! $this->check_pro_command_preconditions() ) return;
// When empty array is passed, WP_CLI will return an error
if ( empty( $args ) ) {
WP_CLI::error( 'Please provide a user ID.', true );
}
$user_id = intval( $args[0] );
$user = get_user_by('id', $user_id);
if (empty($user)) {
WP_CLI::error('User not found.', true);
}
if (!class_exists('Rsssl_Two_Fa_Status')) {
require_once rsssl_path . '/security/wordpress/two-fa/class-rsssl-two-fa-status.php';
}
if ( $user ) {
// Delete all 2fa related user meta.
Rsssl_Two_Fa_Status::delete_two_fa_meta( $user->ID );
// Set the last login to now, so the user will be forced to use 2fa.
update_user_meta( $user->ID, 'rsssl_two_fa_last_login', gmdate( 'Y-m-d H:i:s' ) );
delete_user_meta( $user->ID, 'rsssl_passkey_configured'); // Remove passkey configuration if it exists
}
WP_CLI::success( 'Successfully reset 2FA for user id ' . $user_id );
}
/**
* Preview (dry-run) which users are in scope for 2FA reminders, optionally across subsites.
*
* Usage examples:
* wp rsssl twofa_preview
* wp rsssl twofa_preview --role=editor
* wp rsssl twofa_preview --include-subsites
* wp rsssl twofa_preview --site=7 --format=json
* wp rsssl twofa_preview --reset-meta
*/
public function twofa_preview( $args, $assoc_args ) {
if ( ! $this->check_pro_command_preconditions() ) return;
$role = $assoc_args['role'] ?? 'all';
$format = $assoc_args['format'] ?? 'table';
$includeNetwork = \WP_CLI\Utils\get_flag_value( $assoc_args, 'include-subsites', false );
$specificSiteId = $assoc_args['site'] ?? null;
$doResetMeta = \WP_CLI\Utils\get_flag_value( $assoc_args, 'reset-meta', false );
$rows = $this->collect_twofa_rows( $role, $includeNetwork, $specificSiteId, $doResetMeta );
if ( empty( $rows ) ) {
\WP_CLI::success( 'Geen gebruikers gevonden in de huidige 2FA scope.' );
return;
}
\WP_CLI\Utils\format_items( $format, $rows, [ 'blog_id','user_id','user_login','email','roles','reminder_sent' ] );
}
/**
* Send 2FA reminders for the current selection. Explicitly triggers the send flow per (sub)site.
*
* Usage examples:
* wp rsssl twofa_send
* wp rsssl twofa_send --role=author --site=3
* wp rsssl twofa_send --include-subsites --reset-meta
*/
public function twofa_send( $args, $assoc_args ) {
if ( ! $this->check_pro_command_preconditions() ) return;
$role = $assoc_args['role'] ?? 'all';
$includeNetwork = \WP_CLI\Utils\get_flag_value( $assoc_args, 'include-subsites', false );
$specificSiteId = $assoc_args['site'] ?? null;
$doResetMeta = \WP_CLI\Utils\get_flag_value( $assoc_args, 'reset-meta', false );
$service = new Rsssl_Two_Fa_Reminder_Service();
$siteIds = $this->determine_sites_for_twofa( $includeNetwork, $specificSiteId );
$total = 0;
foreach ( $siteIds as $blog_id ) {
$this->with_blog_for_twofa( (int) $blog_id, function() use ( $role, $service, $doResetMeta, &$total, $blog_id ) {
$repo = new Rsssl_Two_Fa_User_Repository();
$params = new Rsssl_Two_FA_Data_Parameters([
'filter_column' => 'user_role',
'filter_value' => $role,
]);
$collection = $repo->getForcedTwoFaUsersWithOpenStatus( $params );
if ( $doResetMeta ) {
foreach ( $collection->getUsers() as $u ) {
delete_user_meta( $u->getId(), 'rsssl_two_fa_reminder_sent' );
}
}
$countBefore = (int) $collection->getTotalRecords();
if ( $countBefore > 0 ) {
\WP_CLI::log( sprintf( 'Blog %d: verstuur reminders naar %d gebruiker(s)...', (int) $blog_id, $countBefore ) );
$service->processReminders( $collection );
$total += $countBefore;
} else {
\WP_CLI::log( sprintf( 'Blog %d: geen kandidaten.', (int) $blog_id ) );
}
} );
}
\WP_CLI::success( sprintf( 'Verzenden gereed. Totaal verstuurd: %d', (int) $total ) );
}
/** ----------------- Helpers (private) ----------------- */
/**
* Build preview rows for users in scope.
*/
private function collect_twofa_rows( string $role, bool $includeNetwork, $specificSiteId, bool $doResetMeta ): array {
$rows = [];
$siteIds = $this->determine_sites_for_twofa( $includeNetwork, $specificSiteId );
foreach ( $siteIds as $blog_id ) {
$this->with_blog_for_twofa( (int) $blog_id, function() use ( $role, $doResetMeta, $blog_id, &$rows ) {
$repo = new Rsssl_Two_Fa_User_Repository();
$params = new Rsssl_Two_FA_Data_Parameters([
'filter_column' => 'user_role',
'filter_value' => $role,
]);
foreach ( $repo->getForcedTwoFaUsersWithOpenStatus( $params )->getUsers() as $u ) {
$user_id = (int) $u->getId();
$wp_user = get_userdata( $user_id );
if ( ! $wp_user ) {
continue;
}
if ( $doResetMeta ) {
delete_user_meta( $user_id, 'rsssl_two_fa_reminder_sent' );
}
$rows[] = [
'blog_id' => (string) $blog_id,
'user_id' => (string) $user_id,
'user_login' => $wp_user->user_login,
'email' => $wp_user->user_email,
'roles' => implode( ',', $wp_user->roles ?? [] ),
'reminder_sent' => get_user_meta( $user_id, 'rsssl_two_fa_reminder_sent', true ) ? 'yes' : 'no',
];
}
} );
}
return $rows;
}
/**
* Decide which sites to traverse for multisite support.
*/
private function determine_sites_for_twofa( bool $includeNetwork, $specificSiteId ): array {
if ( is_multisite() ) {
if ( ! empty( $specificSiteId ) ) {
return [ (int) $specificSiteId ];
}
if ( $includeNetwork ) {
$ids = [];
foreach ( get_sites( [ 'fields' => 'ids', 'number' => 0 ] ) as $bid ) {
$ids[] = (int) $bid;
}
return $ids;
}
return [ get_current_blog_id() ];
}
return [ 0 ];
}
/**
* Execute a callback within the context of a (sub)site.
*/
private function with_blog_for_twofa( int $blog_id, callable $cb ): void {
if ( is_multisite() && $blog_id > 0 ) {
switch_to_blog( $blog_id );
try {
$cb();
} finally {
restore_current_blog();
}
} else {
$cb();
}
}
/**
* Update the advanced-headers.php with the latest rules
*
* @return void
*/
public function update_advanced_headers() {
if ( ! $this->check_pro_command_preconditions() ) return;
do_action('rsssl_update_rules');
WP_CLI::success( 'Successfully update advanced headers.' );
}
/**
* Add an IP to the firewall blocklist.
*
* @example wp rsssl add_firewall_ip_block 123.123.123.1 --note="This is a temporary block"
* @example wp rsssl add_firewall_ip_block 123.123.123.1 --permanent --note="This is a permanent block"
*
* @param array $args Should contain IP as the first element
* @param array $assoc_args Can contain a note with a 'note' key
*/
public function add_firewall_ip_block(array $args, array $assoc_args): void
{
if ( ! $this->check_pro_command_preconditions() ) return;
$this->handleFirewallTableEntry($args, $assoc_args, 'blocked', 'add');
}
/**
* Can be used to remove a (temporary) block from the firewall blocklist.
* @example wp rsssl remove_firewall_ip_block 123.123.123.1
*
* @param $args array Should contain the ip address
*/
public function remove_firewall_ip_block(array $args, array $assoc_args ): void
{
if ( ! $this->check_pro_command_preconditions() ) return;
$this->handleFirewallTableEntry($args, $assoc_args, 'blocked', 'remove');
}
/**
* Return a table of the current blocked IPs with the headers:
* IP Address, Note, Permanent
*/
public function show_blocked_ips() {
if ( ! $this->check_pro_command_preconditions() ) return;
$columns = [
'ip_address',
'note',
'permanent',
];
$blockedIps = ( new Rsssl_404_Block() )->get_blocked_ips($columns);
WP_CLI\Utils\format_items('table', $blockedIps, $columns);
}
/**
* Add an IP to the firewall's trusted list.
*
* Usage: wp rsssl add_firewall_trusted_ip 123.123.123.1
*
* @param array $args Should contain IP as the first element
* @param array $assoc_args Can contain a note with a 'note' key
* @uses handleFirewallTableEntry()
*/
public function add_firewall_trusted_ip(array $args, array $assoc_args) {
if ( ! $this->check_pro_command_preconditions() ) return;
$this->handleFirewallTableEntry($args, $assoc_args, 'trusted', 'add');
}
/**
* Remove an IP from the firewall's trusted list.
*
* Usage: wp rsssl remove_firewall_trusted_ip 123.123.123.1
*
* @param array $args Should contain IP as the first element