Exemplo n.º 1
0
 protected function sanitize_settings()
 {
     $this->sanitize_setting('bool', 'default', __('Default Blacklist', 'better-wp-security'));
     $this->sanitize_setting('bool', 'enable_ban_lists', __('Ban Lists', 'better-wp-security'));
     $this->sanitize_setting('newline-separated-ips', 'host_list', __('Ban Hosts', 'better-wp-security'));
     if (is_array($this->settings['host_list'])) {
         require_once ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-ip-tools.php';
         $whitelisted_hosts = array();
         $current_ip = ITSEC_Lib::get_ip();
         foreach ($this->settings['host_list'] as $host) {
             if (is_user_logged_in() && ITSEC_Lib_IP_Tools::intersect($current_ip, ITSEC_Lib_IP_Tools::ip_wild_to_ip_cidr($host))) {
                 $this->set_can_save(false);
                 /* translators: 1: input name, 2: invalid host */
                 $this->add_error(sprintf(__('The following host in %1$s matches your current IP and cannot be banned: %2$s', 'better-wp-security'), __('Ban Hosts', 'better-wp-security'), $host));
                 continue;
             }
             if (ITSEC_Lib::is_ip_whitelisted($host)) {
                 $whitelisted_hosts[] = $host;
             }
         }
         if (!empty($whitelisted_hosts)) {
             $this->set_can_save(false);
             /* translators: 1: input name, 2: invalid host list */
             $this->add_error(wp_sprintf(_n('The following IP in %1$s is whitelisted and cannot be banned: %2$l', 'The following IPs in %1$s are whitelisted and cannot be banned: %2$l', count($whitelisted_hosts), 'better-wp-security'), __('Ban Hosts', 'better-wp-security'), $whitelisted_hosts));
         }
     }
     $this->sanitize_setting(array($this, 'sanitize_agent_list_entry'), 'agent_list', __('Ban User Agents', 'better-wp-security'));
 }
Exemplo n.º 2
0
 private static function add_network_brute_force_signup()
 {
     if (!in_array('network-brute-force', self::$available_modules)) {
         return;
     }
     $settings = ITSEC_Modules::get_settings('network-brute-force');
     if (!empty($settings['api_key']) && !empty($settings['api_secret'])) {
         self::enforce_activation('network-brute-force', __('Network Brute Force Protection', 'better-wp-security'));
         return;
     }
     require_once ITSEC_Core::get_core_dir() . '/lib/form.php';
     $form = new ITSEC_Form();
     $form->add_input_group('security-check');
     ob_start();
     self::open_container('incomplete', 'itsec-security-check-network-brute-force-container');
     echo '<p>' . __('With Network Brute Force Protection, your site is protected against attackers found by other sites running iThemes Security. If your site identifies a new attacker, it automatically notifies the network so that other sites are protected as well. To join this site to the network and enable the protection, click the button below.', 'better-wp-security') . '</p>';
     ob_start();
     $form->add_text('email', array('class' => 'regular-text', 'value' => get_option('admin_email')));
     $email_input = ob_get_clean();
     /* translators: 1: email text input */
     echo '<p><label for="itsec-security-check-email">' . sprintf(__('Email Address: %1$s', 'better-wp-security'), $email_input) . '</p>';
     ob_start();
     $form->add_select('updates_optin', array('true' => __('Yes', 'better-wp-security'), 'false' => __('No', 'better-wp-security')));
     $optin_input = ob_get_clean();
     /* translators: 1: opt-in input */
     echo '<p><label for="itsec-security-check-updates_optin">' . sprintf(__('Receive email updates about WordPress Security from iThemes: %1$s', 'better-wp-security'), $optin_input) . '</p>';
     ob_start();
     $form->add_button('enable_network_brute_force', array('class' => 'button-primary', 'value' => __('Activate Network Brute Force Protection', 'better-wp-security')));
     echo '<p>' . ob_get_clean() . '</p>';
     echo '<div id="itsec-security-check-network-brute-force-errors"></div>';
     echo '</div>';
     self::$calls_to_action[] = ob_get_clean();
 }
Exemplo n.º 3
0
 public function generate_new_salts()
 {
     if (!ITSEC_Modules::get_setting('global', 'write_files')) {
         return new WP_Error('itsec-wordpress-salts-utilities-write-files-disabled', __('The "Write to Files" setting is disabled in Global Settings. In order to use this feature, you must enable the "Write to Files" setting.', 'better-wp-security'));
     }
     require_once ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-config-file.php';
     require_once ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-file.php';
     $config_file_path = ITSEC_Lib_Config_File::get_wp_config_file_path();
     $config = ITSEC_Lib_File::read($config_file_path);
     if (is_wp_error($config)) {
         return new WP_Error('itsec-wordpress-salts-utilities-cannot-read-wp-config.php', sprintf(__('Unable to read the <code>wp-config.php</code> file in order to update the salts. You will need to manually update the file. Error details as follows: %1$s (%2$s)', 'better-wp-security'), $config->get_error_message(), $config->get_error_code()));
     }
     $defines = array('AUTH_KEY', 'SECURE_AUTH_KEY', 'LOGGED_IN_KEY', 'NONCE_KEY', 'AUTH_SALT', 'SECURE_AUTH_SALT', 'LOGGED_IN_SALT', 'NONCE_SALT');
     foreach ($defines as $define) {
         if (empty($salts)) {
             $salts = self::get_new_salts();
         }
         $salt = array_pop($salts);
         if (empty($salt)) {
             $salt = wp_generate_password(64, true, true);
         }
         $salt = str_replace('$', '\\$', $salt);
         $regex = "/(define\\s*\\(\\s*(['\"]){$define}\\2\\s*,\\s*)(['\"]).+?\\3(\\s*\\)\\s*;)/";
         $config = preg_replace($regex, "\${1}'{$salt}'\${4}", $config);
     }
     $write_result = ITSEC_Lib_File::write($config_file_path, $config);
     if (is_wp_error($write_result)) {
         return new WP_Error('itsec-wordpress-salts-utilities-cannot-save-wp-config.php', sprintf(__('Unable to update the <code>wp-config.php</code> file in order to update the salts. You will need to manually update the file. Error details as follows: %1$s (%2$s)', 'better-wp-security'), $config->get_error_message(), $config->get_error_code()));
     }
     return true;
 }
Exemplo n.º 4
0
 protected function validate_settings()
 {
     if (!$this->can_save()) {
         return;
     }
     $previous_settings = ITSEC_Modules::get_settings($this->get_id());
     $diff = array_diff_assoc($this->settings, $previous_settings);
     if (!empty($diff)) {
         ITSEC_Response::regenerate_server_config();
     }
     if ($this->settings['write_permissions']) {
         // Always set permissions to 0444 when saving the settings.
         // This ensures that the file permissions are fixed each time the settings are saved.
         $new_permissions = 0444;
     } else {
         if ($this->settings['write_permissions'] !== $previous_settings['write_permissions']) {
             // Only revert the settings to the defaults when disabling the setting.
             // This avoids changing the file permissions when the setting has yet to be enabled and disabled.
             $new_permissions = 0664;
         }
     }
     if (isset($new_permissions)) {
         // Only change the permissions when needed.
         require_once ITSEC_Core::get_core_dir() . 'lib/class-itsec-lib-config-file.php';
         require_once ITSEC_Core::get_core_dir() . 'lib/class-itsec-lib-file.php';
         $server_config_file = ITSEC_Lib_Config_File::get_server_config_file_path();
         $wp_config_file = ITSEC_Lib_Config_File::get_wp_config_file_path();
         ITSEC_Lib_File::chmod($server_config_file, $new_permissions);
         ITSEC_Lib_File::chmod($wp_config_file, $new_permissions);
         ITSEC_Response::reload_module('file-permissions');
     }
 }
Exemplo n.º 5
0
 protected function render_description($form)
 {
     require_once ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-config-file.php';
     $config = ITSEC_Lib_Config_File::get_wp_config();
     if (empty($config)) {
         _e('There is nothing that needs to be written to your <code>wp-config.php</code> file.', 'better-wp-security');
     } else {
         echo '<p>' . __("The following rules need to be written to your <code>wp-config.php</code> file. Please make sure to keep the comments in place.") . '</p>';
         echo '<div class="itsec_rewrite_rules"><pre>' . esc_html($config) . '</pre></div>';
     }
 }
 /**
  * Define host column
  *
  * @param array $item array of row data
  *
  * @return string formatted output
  *
  **/
 function column_host($item)
 {
     require_once ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-ip-tools.php';
     $r = array();
     if (!is_array($item['host'])) {
         $item['host'] = array($item['host']);
     }
     foreach ($item['host'] as $host) {
         if (ITSEC_Lib_IP_Tools::validate($host)) {
             $r[] = '<a href="http://www.traceip.net/?query=' . urlencode($host) . '" target="_blank">' . esc_html($host) . '</a>';
         }
     }
     $return = implode('<br />', $r);
     return $return;
 }
 public function __construct()
 {
     add_action('itsec-settings-page-register-module', array($this, 'register_module'));
     add_action('itsec-settings-page-register-widget', array($this, 'register_widget'));
     add_action('itsec-page-show', array($this, 'handle_page_load'));
     add_action('itsec-page-ajax', array($this, 'handle_ajax_request'));
     add_action('admin_print_scripts', array($this, 'add_scripts'));
     add_action('admin_print_styles', array($this, 'add_styles'));
     add_filter('admin_body_class', array($this, 'add_settings_classes'));
     $this->set_translation_strings();
     if (!empty($_GET['enable']) && !empty($_GET['itsec-enable-nonce']) && wp_verify_nonce($_GET['itsec-enable-nonce'], 'itsec-enable-' . $_GET['enable'])) {
         ITSEC_Modules::activate($_GET['enable']);
     }
     require dirname(__FILE__) . '/module-settings.php';
     require dirname(__FILE__) . '/sidebar-widget.php';
     require_once ITSEC_Core::get_core_dir() . '/lib/form.php';
     do_action('itsec-settings-page-init');
     do_action('itsec-settings-page-register-modules');
     do_action('itsec-settings-page-register-widgets');
     if (!empty($_POST) && (!defined('DOING_AJAX') || !DOING_AJAX)) {
         $this->handle_post();
     }
 }
 /**
  * Echos rewrite metabox content.
  *
  * Echos the rewrite rules in the dashboard.
  *
  * @since 4.0.0
  *
  * @return void
  */
 public function rewrite_metabox_contents()
 {
     require_once ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-config-file.php';
     $config = ITSEC_Lib_Config_File::get_server_config();
     if (empty($config)) {
         _e('There are no rules to write.', 'better-wp-security');
     } else {
         echo '<div class="itsec_rewrite_rules">' . highlight_string($config, true) . '</div>';
     }
 }
Exemplo n.º 9
0
 /**
  * Execute module upgrade
  *
  * @return void
  */
 public function execute_upgrade($itsec_old_version)
 {
     if ($itsec_old_version < 4000) {
         global $itsec_bwps_options;
         $current_options = get_site_option('itsec_ban_users');
         // Don't do anything if settings haven't already been set, defaults exist in the module system and we prefer to use those
         if (false !== $current_options) {
             $current_options['enabled'] = isset($itsec_bwps_options['bu_enabled']) && $itsec_bwps_options['bu_enabled'] == 1 ? true : false;
             $current_options['default'] = isset($itsec_bwps_options['bu_blacklist']) && $itsec_bwps_options['bu_blacklist'] == 1 ? true : false;
             if (isset($itsec_bwps_options['bu_banlist']) && !is_array($itsec_bwps_options['bu_banlist']) && strlen($itsec_bwps_options['bu_banlist']) > 1) {
                 $raw_hosts = explode(PHP_EOL, $itsec_bwps_options['bu_banlist']);
                 foreach ($raw_hosts as $host) {
                     if (strlen($host) > 1) {
                         $current_options['host_list'][] = $host;
                     }
                 }
             }
             if (isset($itsec_bwps_options['bu_banagent']) && !is_array($itsec_bwps_options['bu_banagent']) && strlen($itsec_bwps_options['bu_banagent']) > 1) {
                 $current_options['agent_list'] = explode(PHP_EOL, $itsec_bwps_options['bu_banagent']);
                 $raw_agents = explode(PHP_EOL, $itsec_bwps_options['bu_banagent']);
                 foreach ($raw_agents as $agent) {
                     if (strlen($agent) > 1) {
                         $current_options['agent_list'][] = $agent;
                     }
                 }
             }
             update_site_option('itsec_ban_users', $current_options);
             ITSEC_Response::regenerate_server_config();
         }
     }
     if ($itsec_old_version < 4027) {
         ITSEC_Response::regenerate_server_config();
     }
     if ($itsec_old_version < 4041) {
         $current_options = get_site_option('itsec_ban_users');
         // If there are no current options, go with the new defaults by not saving anything
         if (is_array($current_options)) {
             $itsec_modules = ITSEC_Modules::get_instance();
             // 'enable_ban_lists' was previously just 'enabled'
             // Make sure the new module is properly activated or deactivated
             if ($current_options['enabled']) {
                 ITSEC_Modules::activate('backup');
                 $current_options['enable_ban_lists'] = true;
             } else {
                 ITSEC_Modules::deactivate('backup');
                 $current_options['enable_ban_lists'] = false;
             }
             unset($current_options['enabled']);
             // Filter out invalid IPs
             $current_options['host_list'] = array_map('trim', $current_options['host_list']);
             if (!class_exists('ITSEC_Lib_IP_Tools')) {
                 require_once ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-ip-tools.php';
             }
             foreach ($current_options['host_list'] as $index => $ip) {
                 if ('' === $ip || false === ITSEC_Lib_IP_Tools::ip_wild_to_ip_cidr($ip)) {
                     unset($current_options['host_list'][$index]);
                 }
             }
             $itsec_modules->set_settings('ban-users', $current_options);
         }
     }
 }
Exemplo n.º 10
0
 /**
  * Executes backup function.
  *
  * Handles the execution of database backups.
  *
  * @since 4.0.0
  *
  * @param bool $one_time whether this is a one-time backup
  *
  * @return void
  */
 private function execute_backup($one_time = false)
 {
     global $wpdb, $itsec_globals, $itsec_logger;
     //get all of the tables
     if (isset($this->settings['all_sites']) && true === $this->settings['all_sites']) {
         $tables = $wpdb->get_results('SHOW TABLES', ARRAY_N);
         //retrieve a list of all tables in the DB
     } else {
         $tables = $wpdb->get_results('SHOW TABLES LIKE "' . $wpdb->base_prefix . '%"', ARRAY_N);
         //retrieve a list of all tables for this WordPress installation
     }
     $return = '';
     //cycle through each table
     foreach ($tables as $table) {
         $num_fields = sizeof($wpdb->get_results('DESCRIBE `' . $table[0] . '`;'));
         $return .= 'DROP TABLE IF EXISTS `' . $table[0] . '`;';
         $row2 = $wpdb->get_row('SHOW CREATE TABLE `' . $table[0] . '`;', ARRAY_N);
         $return .= PHP_EOL . PHP_EOL . $row2[1] . ";" . PHP_EOL . PHP_EOL;
         if (!in_array(substr($table[0], strlen($wpdb->prefix)), $this->settings['exclude'])) {
             $result = $wpdb->get_results('SELECT * FROM `' . $table[0] . '`;', ARRAY_N);
             foreach ($result as $row) {
                 $return .= 'INSERT INTO `' . $table[0] . '` VALUES(';
                 for ($j = 0; $j < $num_fields; $j++) {
                     $row[$j] = addslashes($row[$j]);
                     $row[$j] = preg_replace('#' . PHP_EOL . '#', "\n", $row[$j]);
                     if (isset($row[$j])) {
                         $return .= '"' . $row[$j] . '"';
                     } else {
                         $return .= '""';
                     }
                     if ($j < $num_fields - 1) {
                         $return .= ',';
                     }
                 }
                 $return .= ");" . PHP_EOL;
             }
         }
         $return .= PHP_EOL . PHP_EOL;
     }
     $return .= PHP_EOL . PHP_EOL;
     //save file
     $file = 'backup-' . substr(sanitize_title(get_bloginfo('name')), 0, 20) . '-' . current_time('Ymd-His') . '-' . wp_generate_password(30, false);
     require_once ITSEC_Core::get_core_dir() . 'lib/class-itsec-lib-directory.php';
     $dir = $this->settings['location'];
     ITSEC_Lib_Directory::create($dir);
     $fileext = '.sql';
     $handle = @fopen($dir . '/' . $file . '.sql', 'w+');
     @fwrite($handle, $return);
     @fclose($handle);
     //zip the file
     if (true === $this->settings['zip']) {
         if (!class_exists('PclZip')) {
             require ABSPATH . 'wp-admin/includes/class-pclzip.php';
         }
         $zip = new PclZip($dir . '/' . $file . '.zip');
         if (0 != $zip->create($dir . '/' . $file . '.sql', PCLZIP_OPT_REMOVE_PATH, $dir)) {
             //delete .sql and keep zip
             @unlink($dir . '/' . $file . '.sql');
             $fileext = '.zip';
         }
     }
     if (2 !== $this->settings['method'] || true === $one_time) {
         require_once ITSEC_Core::get_core_dir() . 'lib/class-itsec-mailer.php';
         $mail = new ITSEC_Mail();
         $mail->add_header(esc_html__('Database Backup', 'better-wp-security'), sprintf(wp_kses(__('Site Database Backup for <b>%s</b>', 'better-wp-security'), array('b' => array())), date_i18n(get_option('date_format'))));
         $mail->add_info_box(esc_html__('Attached is the database backup file for your site.', 'better-wp-security'), 'attachment');
         $mail->add_section_heading(esc_html__('Website', 'better-wp-security'));
         $mail->add_text(esc_html(network_home_url()));
         $mail->add_section_heading(esc_html__('Date', 'better-wp-security'));
         $mail->add_text(esc_html(date_i18n(get_option('date_format'))));
         $mail->add_footer();
         $raw_recipients = ITSEC_Modules::get_setting('global', 'backup_email');
         $recipients = array();
         foreach ($raw_recipients as $recipient) {
             $recipient = trim($recipient);
             if (is_email($recipient)) {
                 $recipients[] = $recipient;
             }
         }
         $subject = sprintf(esc_html__('[%s] Database Backup', 'better-wp-security'), esc_url(network_home_url()));
         $subject = apply_filters('itsec_backup_email_subject', $subject);
         $attachment = array("{$dir}/{$file}{$fileext}");
         $mail_success = $mail->send($recipients, $subject, $attachment);
     }
     if (1 === $this->settings['method']) {
         @unlink($dir . '/' . $file . $fileext);
     } else {
         $retain = isset($this->settings['retain']) ? absint($this->settings['retain']) : 0;
         //delete extra files
         if (0 < $retain) {
             $files = scandir($dir, 1);
             $count = 0;
             if (is_array($files) && 0 < count($files)) {
                 foreach ($files as $file) {
                     if (strstr($file, 'backup')) {
                         if ($count >= $retain) {
                             @unlink(trailingslashit($dir) . $file);
                         }
                         $count++;
                     }
                 }
             }
         }
     }
     if (false === $one_time) {
         ITSEC_Modules::set_setting('backup', 'last_run', ITSEC_Core::get_current_time_gmt());
     }
     switch ($this->settings['method']) {
         case 0:
             if (false === $mail_success) {
                 $status = array('status' => __('Error', 'better-wp-security'), 'details' => __('saved locally but email to backup recipients could not be sent.', 'better-wp-security'));
             } else {
                 $status = array('status' => __('Success', 'better-wp-security'), 'details' => __('emailed to backup recipients and saved locally', 'better-wp-security'));
             }
             break;
         case 1:
             if (false === $mail_success) {
                 $status = array('status' => __('Error', 'better-wp-security'), 'details' => __('email to backup recipients could not be sent.', 'better-wp-security'));
             } else {
                 $status = array('status' => __('Success', 'better-wp-security'), 'details' => __('emailed to backup recipients', 'better-wp-security'));
             }
             break;
         default:
             $status = array('status' => __('Success', 'better-wp-security'), 'details' => __('saved locally', 'better-wp-security'));
             break;
     }
     $itsec_logger->log_event('backup', 3, array($status));
 }
 public static function add_notice($callback)
 {
     $self = self::get_instance();
     if (!$self->notices_loaded) {
         wp_enqueue_style('itsec-notice', plugins_url('core/css/itsec_notice.css', ITSEC_Core::get_core_dir()), array(), '20160609');
         wp_enqueue_script('itsec-notice', plugins_url('core/js/itsec-notice.js', ITSEC_Core::get_core_dir()), array(), '20160512');
         $self->notices_loaded = true;
     }
     if (is_multisite()) {
         add_action('network_admin_notices', $callback);
     } else {
         add_action('admin_notices', $callback);
     }
 }
Exemplo n.º 12
0
    /**
     * Displays all logs content
     *
     * @since 4.3
     *
     * @return void
     */
    public function all_logs_content()
    {
        global $wpdb;
        require_once ITSEC_Core::get_core_dir() . '/class-itsec-logger-all-logs.php';
        $log_display = new ITSEC_Logger_All_Logs();
        $log_display->prepare_items();
        $log_display->display();
        $log_count = $wpdb->get_var("SELECT COUNT(*) FROM `" . $wpdb->base_prefix . "itsec_log`;");
        ?>
		<form method="post" action="">
			<?php 
        wp_nonce_field('itsec_clear_logs', 'wp_nonce');
        ?>
			<input type="hidden" name="itsec_clear_logs" value="clear_logs"/>
			<table class="form-table">
				<tr valign="top">
					<th scope="row" class="settinglabel">
						<?php 
        _e('Log Summary', 'better-wp-security');
        ?>
					</th>
					<td class="settingfield">

						<p><?php 
        _e('Your database contains', 'better-wp-security');
        ?>
							<strong><?php 
        echo $log_count;
        ?>
</strong> <?php 
        _e('log entries.', 'better-wp-security');
        ?>
						</p>

						<p><?php 
        _e('Use the button below to purge the log table in your database. Please note this will purge all log entries in the database including 404s.', 'better-wp-security');
        ?>
</p>

						<p class="submit"><input type="submit" class="button-primary"
						                         value="<?php 
        _e('Clear Logs', 'better-wp-security');
        ?>
"/></p>
					</td>
				</tr>
			</table>
		</form>
	<?php 
    }
Exemplo n.º 13
0
 public static function add_notice($callback, $all_pages = false)
 {
     global $pagenow, $plugin_page;
     if (!$all_pages && !in_array($pagenow, array('plugins.php', 'update-core.php')) && (!isset($plugin_page) || !in_array($plugin_page, array('itsec', 'itsec-logs')))) {
         return;
     }
     $self = self::get_instance();
     if (!$self->notices_loaded) {
         wp_enqueue_style('itsec-notice', plugins_url('core/css/itsec_notice.css', ITSEC_Core::get_core_dir()), array(), '20160609');
         wp_enqueue_script('itsec-notice', plugins_url('core/js/itsec-notice.js', ITSEC_Core::get_core_dir()), array(), '20160512');
         $self->notices_loaded = true;
     }
     if (is_multisite()) {
         add_action('network_admin_notices', $callback);
     } else {
         add_action('admin_notices', $callback);
     }
 }
Exemplo n.º 14
0
 /**
  * Executes backup function.
  *
  * Handles the execution of database backups.
  *
  * @since 4.0.0
  *
  * @param bool $one_time whether this is a one-time backup
  *
  * @return void
  */
 private function execute_backup($one_time = false)
 {
     global $wpdb, $itsec_globals, $itsec_logger;
     //get all of the tables
     if (isset($this->settings['all_sites']) && true === $this->settings['all_sites']) {
         $tables = $wpdb->get_results('SHOW TABLES', ARRAY_N);
         //retrieve a list of all tables in the DB
     } else {
         $tables = $wpdb->get_results('SHOW TABLES LIKE "' . $wpdb->base_prefix . '%"', ARRAY_N);
         //retrieve a list of all tables for this WordPress installation
     }
     $return = '';
     //cycle through each table
     foreach ($tables as $table) {
         $num_fields = sizeof($wpdb->get_results('DESCRIBE `' . $table[0] . '`;'));
         $return .= 'DROP TABLE IF EXISTS `' . $table[0] . '`;';
         $row2 = $wpdb->get_row('SHOW CREATE TABLE `' . $table[0] . '`;', ARRAY_N);
         $return .= PHP_EOL . PHP_EOL . $row2[1] . ";" . PHP_EOL . PHP_EOL;
         if (!in_array(substr($table[0], strlen($wpdb->prefix)), $this->settings['exclude'])) {
             $result = $wpdb->get_results('SELECT * FROM `' . $table[0] . '`;', ARRAY_N);
             foreach ($result as $row) {
                 $return .= 'INSERT INTO `' . $table[0] . '` VALUES(';
                 for ($j = 0; $j < $num_fields; $j++) {
                     $row[$j] = addslashes($row[$j]);
                     $row[$j] = preg_replace('#' . PHP_EOL . '#', "\n", $row[$j]);
                     if (isset($row[$j])) {
                         $return .= '"' . $row[$j] . '"';
                     } else {
                         $return .= '""';
                     }
                     if ($j < $num_fields - 1) {
                         $return .= ',';
                     }
                 }
                 $return .= ");" . PHP_EOL;
             }
         }
         $return .= PHP_EOL . PHP_EOL;
     }
     $return .= PHP_EOL . PHP_EOL;
     //save file
     $file = 'backup-' . substr(sanitize_title(get_bloginfo('name')), 0, 20) . '-' . current_time('Ymd-His') . '-' . wp_generate_password(30, false);
     require_once ITSEC_Core::get_core_dir() . 'lib/class-itsec-lib-directory.php';
     $dir = $this->settings['location'];
     ITSEC_Lib_Directory::create($dir);
     $fileext = '.sql';
     $handle = @fopen($dir . '/' . $file . '.sql', 'w+');
     @fwrite($handle, $return);
     @fclose($handle);
     //zip the file
     if (true === $this->settings['zip']) {
         if (!class_exists('PclZip')) {
             require ABSPATH . 'wp-admin/includes/class-pclzip.php';
         }
         $zip = new PclZip($dir . '/' . $file . '.zip');
         if (0 != $zip->create($dir . '/' . $file . '.sql', PCLZIP_OPT_REMOVE_PATH, $dir)) {
             //delete .sql and keep zip
             @unlink($dir . '/' . $file . '.sql');
             $fileext = '.zip';
         }
     }
     if (2 !== $this->settings['method'] || true === $one_time) {
         $attachment = array($dir . '/' . $file . $fileext);
         $body = __('Attached is the backup file for the database powering', 'better-wp-security') . ' ' . get_option('siteurl') . __(' taken', 'better-wp-security') . ' ' . date('l, F jS, Y \\a\\t g:i a', $itsec_globals['current_time']);
         //Setup the remainder of the email
         $recipients = ITSEC_Modules::get_setting('global', 'backup_email');
         $subject = __('Site Database Backup', 'better-wp-security') . ' ' . date('l, F jS, Y \\a\\t g:i a', $itsec_globals['current_time']);
         $subject = apply_filters('itsec_backup_email_subject', $subject);
         $headers = 'From: ' . get_bloginfo('name') . ' <' . get_option('admin_email') . '>' . "\r\n";
         $mail_success = false;
         //Use HTML Content type
         add_filter('wp_mail_content_type', array($this, 'set_html_content_type'));
         //Send emails to all recipients
         foreach ($recipients as $recipient) {
             if (is_email(trim($recipient))) {
                 if (defined('ITSEC_DEBUG') && true === ITSEC_DEBUG) {
                     $body .= '<p>' . __('Debug info (source page): ' . esc_url($_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"])) . '</p>';
                 }
                 $mail_success = wp_mail(trim($recipient), $subject, '<html>' . $body . '</html>', $headers, $attachment);
             }
         }
         //Remove HTML Content type
         remove_filter('wp_mail_content_type', array($this, 'set_html_content_type'));
     }
     if (1 === $this->settings['method']) {
         @unlink($dir . '/' . $file . $fileext);
     } else {
         $retain = isset($this->settings['retain']) ? absint($this->settings['retain']) : 0;
         //delete extra files
         if (0 < $retain) {
             $files = scandir($dir, 1);
             $count = 0;
             if (is_array($files) && 0 < count($files)) {
                 foreach ($files as $file) {
                     if (strstr($file, 'backup')) {
                         if ($count >= $retain) {
                             @unlink(trailingslashit($dir) . $file);
                         }
                         $count++;
                     }
                 }
             }
         }
     }
     if (false === $one_time) {
         ITSEC_Modules::set_setting('backup', 'last_run', ITSEC_Core::get_current_time_gmt());
     }
     switch ($this->settings['method']) {
         case 0:
             if (false === $mail_success) {
                 $status = array('status' => __('Error', 'better-wp-security'), 'details' => __('saved locally but email to backup recipients could not be sent.', 'better-wp-security'));
             } else {
                 $status = array('status' => __('Success', 'better-wp-security'), 'details' => __('emailed to backup recipients and saved locally', 'better-wp-security'));
             }
             break;
         case 1:
             if (false === $mail_success) {
                 $status = array('status' => __('Error', 'better-wp-security'), 'details' => __('email to backup recipients could not be sent.', 'better-wp-security'));
             } else {
                 $status = array('status' => __('Success', 'better-wp-security'), 'details' => __('emailed to backup recipients', 'better-wp-security'));
             }
             break;
         default:
             $status = array('status' => __('Success', 'better-wp-security'), 'details' => __('saved locally', 'better-wp-security'));
             break;
     }
     $itsec_logger->log_event('backup', 3, array($status));
 }
Exemplo n.º 15
0
 protected final function sanitize_setting($type, $var, $name, $prevent_save_on_error = true, $trim_value = true)
 {
     $id = $this->get_id();
     if (!isset($this->settings[$var])) {
         $this->add_error(new WP_Error("itsec-validator-missing-var-{$id}-{$var}", sprintf(__('A validation check for %1$s failed. The %2$s value is missing. This could be due to a problem with the iThemes Security installation or an invalid modification. Please reinstall iThemes Security and try again.', 'better-wp-security'), $id, $name)));
         return false;
     }
     if ($trim_value && is_string($this->settings[$var])) {
         $this->settings[$var] = trim($this->settings[$var]);
     }
     $error = false;
     if ('string' === $type) {
         $this->settings[$var] = (string) $this->settings[$var];
     } else {
         if ('non-empty-string' === $type) {
             $this->settings[$var] = (string) $this->settings[$var];
             if (empty($this->settings[$var])) {
                 $error = sprintf(__('The %1$s value cannot be empty.', 'better-wp-security'), $name);
             }
         } else {
             if ('title' === $type) {
                 $this->settings[$var] = sanitize_title($this->settings[$var]);
             } else {
                 if ('non-empty-title' === $type) {
                     $this->settings[$var] = sanitize_title($this->settings[$var]);
                     if (empty($this->settings[$var])) {
                         $error = sprintf(__('The %1$s value cannot be empty.', 'better-wp-security'), $name);
                     }
                 } else {
                     if ('array' === $type) {
                         if (!is_array($this->settings[$var])) {
                             if (empty($this->settings[$var])) {
                                 $this->settings[$var] = array();
                             } else {
                                 $this->settings[$var] = array($this->settings[$var]);
                             }
                         }
                     } else {
                         if ('bool' === $type) {
                             if ('false' === $this->settings[$var]) {
                                 $this->settings[$var] = false;
                             } else {
                                 if ('true' === $this->settings[$var]) {
                                     $this->settings[$var] = true;
                                 } else {
                                     $this->settings[$var] = (bool) $this->settings[$var];
                                 }
                             }
                         } else {
                             if ('int' === $type) {
                                 $test_val = intval($this->settings[$var]);
                                 if ((string) $test_val === (string) $this->settings[$var]) {
                                     $this->settings[$var] = $test_val;
                                 } else {
                                     $error = sprintf(__('The %1$s value must be an integer.', 'better-wp-security'), $name);
                                 }
                             } else {
                                 if ('positive-int' === $type) {
                                     $test_val = intval($this->settings[$var]);
                                     if ((string) $test_val === (string) $this->settings[$var] && $test_val >= 0) {
                                         $this->settings[$var] = $test_val;
                                     } else {
                                         $error = sprintf(__('The %1$s value must be a positive integer.', 'better-wp-security'), $name);
                                     }
                                 } else {
                                     if ('email' === $type) {
                                         $this->settings[$var] = sanitize_text_field($this->settings[$var]);
                                         if (empty($this->settings[$var]) || !is_email($this->settings[$var])) {
                                             $error = sprintf(__('The %1$s value must be a valid email address.', 'better-wp-security'), $name);
                                         }
                                     } else {
                                         if ('valid-username' === $type) {
                                             $this->settings[$var] = sanitize_text_field($this->settings[$var]);
                                             if (!empty($this->settings[$var]) && !validate_username($this->settings[$var])) {
                                                 $error = sprintf(__('The %1$s value is not a valid username.', 'better-wp-security'), $name);
                                             }
                                         } else {
                                             if ('date' === $type) {
                                                 $val = $this->settings[$var];
                                                 $separator = '[\\-/\\. ]';
                                                 if (preg_match("|^(\\d\\d\\d\\d){$separator}(\\d\\d?){$separator}(\\d\\d?)\$|", $val, $match)) {
                                                     $year = intval($match[1]);
                                                     $month = intval($match[2]);
                                                     $day = intval($match[3]);
                                                     if (!checkdate($month, $day, $year)) {
                                                         $error = sprintf(__('The %1$s value must be a valid date.', 'better-wp-security'), $name);
                                                     }
                                                 } else {
                                                     $error = sprintf(__('The %1$s value must be a valid date in the format of YYYY-MM-DD.', 'better-wp-security'), $name);
                                                 }
                                             } else {
                                                 if ('writable-directory' === $type) {
                                                     if (!is_string($this->settings[$var])) {
                                                         $error = sprintf(__('The %1$s value must be a string.', 'better-wp-security'), $name);
                                                     } else {
                                                         require_once ITSEC_Core::get_core_dir() . 'lib/class-itsec-lib-directory.php';
                                                         $this->settings[$var] = rtrim($this->settings[$var], DIRECTORY_SEPARATOR);
                                                         if (!ITSEC_Lib_Directory::is_dir($this->settings[$var])) {
                                                             $result = ITSEC_Lib_Directory::create($this->settings[$var]);
                                                             if (is_wp_error($result)) {
                                                                 $error = sprintf(_x('The directory supplied in %1$s cannot be used as a valid directory. %2$s', '%1$s is the input name. %2$s is the error message.', 'better-wp-security'), $name, $result->get_error_message());
                                                             }
                                                         }
                                                         if (empty($error) && !ITSEC_Lib_Directory::is_writable($this->settings[$var])) {
                                                             $error = sprintf(__('The directory supplied in %1$s is not writable. Please select a directory that can be written to.', 'better-wp-security'), $name);
                                                         }
                                                         if (empty($error)) {
                                                             ITSEC_Lib_Directory::add_file_listing_protection($this->settings[$var]);
                                                         }
                                                     }
                                                 } else {
                                                     if ('writable-file' === $type) {
                                                         if (!is_string($this->settings[$var])) {
                                                             $error = sprintf(__('The %1$s value must be a string.', 'better-wp-security'), $name);
                                                         } else {
                                                             require_once ITSEC_Core::get_core_dir() . 'lib/class-itsec-lib-directory.php';
                                                             if (!ITSEC_Lib_File::is_file($this->settings[$var]) && ITSEC_Lib_File::exists($this->settings[$var])) {
                                                                 $error = sprintf(__('The file path supplied in %1$s cannot be used as it already exists but is not a file. Please supply a valid file path.', 'better-wp-security'), $name);
                                                             } else {
                                                                 $result = ITSEC_Lib_Directory::create(dirname($this->settings[$var]));
                                                                 if (is_wp_error($result)) {
                                                                     $error = sprintf(_x('The file path supplied in %1$s cannot be used as the parent directory cannot be created. %2$s', '%1$s is the input name. %2$s is the error message.', 'better-wp-security'), $name, $result->get_error_message());
                                                                 } else {
                                                                     if (!ITSEC_Lib_File::exists($this->settings[$var])) {
                                                                         $result = ITSEC_Lib_File::write($this->settings[$var], '');
                                                                         if (is_wp_error($result)) {
                                                                             $error = sprintf(__('The file path supplied in %1$s could not be created. Please supply a file path that can be written to.', 'better-wp-security'), $name);
                                                                         } else {
                                                                             if (!is_writable($this->settings[$var])) {
                                                                                 $error = sprintf(__('The file path supplied in %1$s was successfully created, but it cannot be updated. Please supply a file path that can be written to.', 'better-wp-security'), $name);
                                                                             }
                                                                         }
                                                                     } else {
                                                                         if (!is_writable($this->settings[$var])) {
                                                                             $error = sprintf(__('The file path supplied in %1$s is not writable. Please supply a file path that can be written to.', 'better-wp-security'), $name);
                                                                         }
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     } else {
                                                         if (is_array($type) && 2 === count($type) && $this === $type[0]) {
                                                             $this->settings[$var] = $this->convert_string_to_array($this->settings[$var]);
                                                             if (!is_array($this->settings[$var])) {
                                                                 $error = sprintf(__('The %1$s value must be a string with each entry separated by a new line.', 'better-wp-security'), $name);
                                                             } else {
                                                                 $invalid_entries = array();
                                                                 foreach ($this->settings[$var] as $index => $entry) {
                                                                     $entry = sanitize_text_field(trim($entry));
                                                                     $this->settings[$var][$index] = $entry;
                                                                     if (empty($entry)) {
                                                                         unset($this->settings[$var][$index]);
                                                                     } else {
                                                                         $result = call_user_func($type, $entry);
                                                                         if (false === $result) {
                                                                             $invalid_entries[] = $entry;
                                                                         } else {
                                                                             $this->settings[$var][$index] = $result;
                                                                         }
                                                                     }
                                                                 }
                                                                 $this->settings[$var] = array_unique($this->settings[$var]);
                                                                 if (!empty($invalid_entries)) {
                                                                     $error = wp_sprintf(_n('The following entry in %1$s is invalid: %2$l', 'The following entries in %1$s are invalid: %2$l', count($invalid_entries), 'better-wp-security'), $name, $invalid_entries);
                                                                 }
                                                             }
                                                         } else {
                                                             if (is_array($type)) {
                                                                 if (is_array($this->settings[$var])) {
                                                                     $invalid_entries = array();
                                                                     foreach ($this->settings[$var] as $index => $entry) {
                                                                         $entry = sanitize_text_field(trim($entry));
                                                                         $this->settings[$var][$index] = $entry;
                                                                         if (empty($entry)) {
                                                                             unset($this->settings[$var][$index]);
                                                                         } else {
                                                                             if (!in_array($entry, $type, true)) {
                                                                                 $invalid_entries[] = $entry;
                                                                             }
                                                                         }
                                                                     }
                                                                     $this->settings[$var] = array_unique($this->settings[$var]);
                                                                     if (!empty($invalid_entries)) {
                                                                         $error = wp_sprintf(_n('The following entry in %1$s is invalid: %2$l', 'The following entries in %1$s are invalid: %2$l', count($invalid_entries), 'better-wp-security'), $name, $invalid_entries);
                                                                     }
                                                                 } else {
                                                                     if (!in_array($this->settings[$var], $type, true)) {
                                                                         $error = wp_sprintf(_n('The valid value for %1$s is: %2$l.', 'The valid values for %1$s are: %2$l.', count($type), 'better-wp-security'), $name, $type);
                                                                         $type = 'array';
                                                                     }
                                                                 }
                                                             } else {
                                                                 if ('newline-separated-array' === $type) {
                                                                     $this->settings[$var] = $this->convert_string_to_array($this->settings[$var]);
                                                                     if (!is_array($this->settings[$var])) {
                                                                         $error = sprintf(__('The %1$s value must be a string with each entry separated by a new line.', 'better-wp-security'), $name);
                                                                     }
                                                                 } else {
                                                                     if ('newline-separated-emails' === $type) {
                                                                         $this->settings[$var] = $this->convert_string_to_array($this->settings[$var]);
                                                                         if (!is_array($this->settings[$var])) {
                                                                             $error = sprintf(__('The %1$s value must be a string with each entry separated by a new line.', 'better-wp-security'), $name);
                                                                         } else {
                                                                             $invalid_emails = array();
                                                                             foreach ($this->settings[$var] as $index => $email) {
                                                                                 $email = sanitize_text_field(trim($email));
                                                                                 $this->settings[$var][$index] = $email;
                                                                                 if (empty($email)) {
                                                                                     unset($this->settings[$var][$index]);
                                                                                 } else {
                                                                                     if (!is_email($email)) {
                                                                                         $invalid_emails[] = $email;
                                                                                     }
                                                                                 }
                                                                             }
                                                                             $this->settings[$var] = array_unique($this->settings[$var]);
                                                                             if (!empty($invalid_emails)) {
                                                                                 $error = wp_sprintf(_n('The following email in %1$s is invalid: %2$l', 'The following emails in %1$s are invalid: %2$l', count($invalid_emails), 'better-wp-security'), $name, $invalid_emails);
                                                                             }
                                                                         }
                                                                     } else {
                                                                         if ('newline-separated-ips' === $type) {
                                                                             $this->settings[$var] = $this->convert_string_to_array($this->settings[$var]);
                                                                             if (!is_array($this->settings[$var])) {
                                                                                 $error = sprintf(__('The %1$s value must be a string with each entry separated by a new line.', 'better-wp-security'), $name);
                                                                             } else {
                                                                                 require_once ITSEC_Core::get_core_dir() . 'lib/class-itsec-lib-ip-tools.php';
                                                                                 $invalid_ips = array();
                                                                                 foreach ($this->settings[$var] as $index => $ip) {
                                                                                     $ip = trim($ip);
                                                                                     if ('' === $ip) {
                                                                                         unset($this->settings[$var][$index]);
                                                                                     } else {
                                                                                         $validated_ip = ITSEC_Lib_IP_Tools::ip_wild_to_ip_cidr($ip);
                                                                                         if (false === $validated_ip) {
                                                                                             $invalid_ips[] = $ip;
                                                                                         } else {
                                                                                             $this->settings[$var][$index] = $validated_ip;
                                                                                         }
                                                                                     }
                                                                                 }
                                                                                 $this->settings[$var] = array_unique($this->settings[$var]);
                                                                                 if (!empty($invalid_ips)) {
                                                                                     $error = wp_sprintf(_n('The following IP in %1$s is invalid: %2$l', 'The following IPs in %1$s are invalid: %2$l', count($invalid_ips), 'better-wp-security'), $name, $invalid_ips);
                                                                                 }
                                                                             }
                                                                         } else {
                                                                             if ('newline-separated-extensions' === $type) {
                                                                                 $this->settings[$var] = $this->convert_string_to_array($this->settings[$var]);
                                                                                 if (!is_array($this->settings[$var])) {
                                                                                     $error = sprintf(__('The %1$s value must be a string with each entry separated by a new line.', 'better-wp-security'), $name);
                                                                                 } else {
                                                                                     $invalid_extensions = array();
                                                                                     foreach ($this->settings[$var] as $index => $extension) {
                                                                                         if (!preg_match('/^(\\.[^.]+)+$/', $extension)) {
                                                                                             $invalid_extensions[] = $extension;
                                                                                         }
                                                                                     }
                                                                                     $this->settings[$var] = array_unique($this->settings[$var]);
                                                                                     if (!empty($invalid_extensions)) {
                                                                                         $error = wp_sprintf(_n('The following extension in %1$s is invalid: %2$l', 'The following extensions in %1$s are invalid: %2$l', count($invalid_extensions), 'better-wp-security'), $name, $invalid_extensions);
                                                                                     }
                                                                                 }
                                                                             } else {
                                                                                 /* translators: 1: sanitize type, 2: input name */
                                                                                 $error = sprintf(__('An invalid sanitize type of "%1$s" was received for the %2$s input.', 'better-wp-security'), $type, $name);
                                                                             }
                                                                         }
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     if (false !== $error) {
         $this->add_error(new WP_Error("itsec-validator-{$id}-invalid-type-{$var}-{$type}", $error));
         $this->vars_to_skip_validate_matching_types[] = $var;
         if ($prevent_save_on_error) {
             $this->set_can_save(false);
         }
         return false;
     }
     return true;
 }
Exemplo n.º 16
0
 /**
  * Determines whether a given IP address is blacklisted
  *
  * @param string $ip              ip to check (can be in CIDR notation)
  * @param array  $blacklisted_ips ip list to compare to if not yet saved to options
  *
  * @return boolean true if blacklisted or false
  */
 public static function is_ip_blacklisted($ip = null, $blacklisted_ips = null)
 {
     $ip = sanitize_text_field($ip);
     if (empty($ip)) {
         $ip = ITSEC_Lib::get_ip();
     }
     if (!class_exists('ITSEC_Lib_IP_Tools')) {
         require_once ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-ip-tools.php';
     }
     if (is_null($blacklisted_ips)) {
         $blacklisted_ips = self::get_blacklisted_ips();
     }
     foreach ($blacklisted_ips as $blacklisted_ip) {
         if (ITSEC_Lib_IP_Tools::intersect($ip, ITSEC_Lib_IP_Tools::ip_wild_to_ip_cidr($blacklisted_ip))) {
             return true;
         }
     }
     return false;
 }
Exemplo n.º 17
0
 public static function change_content_directory($dir_name)
 {
     $dir_name = sanitize_file_name($dir_name);
     if (empty($dir_name)) {
         return new WP_Error('itsec-content-directory-utility-change-content-directory-empty-directory-name', __('The content directory cannot be changed to a blank directory name.', 'better-wp-security'));
     }
     if (preg_match('{^(?:/|\\|[a-z]:)}i', $dir_name)) {
         return new WP_Error('itsec-content-diraectory-utility-change-content-directory-received-absolute-path', sprintf(__('The new directory name cannot be an absolute path. Please supply a path that is relative to <code>ABSPATH</code> (<code>%s</code>).', 'better-wp-security'), esc_html(ABSPATH)));
     }
     if (0 === strpos(WP_CONTENT_DIR, ABSPATH)) {
         $old_name = substr(WP_CONTENT_DIR, strlen(ABSPATH));
         $new_name = $dir_name;
     } else {
         $old_name = WP_CONTENT_DIR;
         $new_name = ABSPATH . $dir_name;
     }
     $old_dir = WP_CONTENT_DIR;
     $new_dir = ABSPATH . $dir_name;
     if ($old_dir === $new_dir) {
         return new WP_Error('itsec-content-directory-utility-change-content-directory-received-same-directory', __('The new directory name cannot be the same as the current directory name. Please supply a new directory name.', 'better-wp-security'));
     }
     if (file_exists($new_dir)) {
         return new WP_Error('itsec-content-directory-utility-change-content-directory-path-already-exists', sprintf(__('A file or directory already exists at <code>%s</code>. No Directory Name changes have been made. Please choose a new Directory Name or remove the existing file or directory and try again.', 'better-wp-security'), esc_html($new_dir)));
     }
     require_once ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-config-file.php';
     $old_permissions = ITSEC_Lib_Directory::get_permissions($old_dir);
     $result = rename($old_dir, $new_dir);
     if (!$result) {
         /* translators: 1: Old directory path, 2: New directory path */
         return new WP_Error('itsec-content-directory-utility-change-content-directory-cannot-rename-directory', sprintf(__('Unable to rename the <code>%1$s</code> directory to <code>%2$s</code>. This could indicate a file permission issue or that your server does not support the supplied name as a valid directory name. No config file or directory changes have been made.', 'better-wp-security'), esc_html($old_name), esc_html($new_name)));
     }
     // Make sure ITSEC_Core knows it's in a different place
     $plugin_file = str_replace($old_dir, $new_dir, ITSEC_Core::get_plugin_file());
     ITSEC_Core::set_plugin_file($plugin_file);
     ITSEC_Core::update_wp_upload_dir($old_dir, $new_dir);
     ITSEC_Modules::update_module_paths($old_dir, $new_dir);
     $new_permissions = ITSEC_Lib_Directory::get_permissions($new_dir);
     if (is_int($old_permissions) && is_int($new_permissions) && $old_permissions != $new_permissions) {
         $result = ITSEC_Lib_Directory::chmod($new_dir, $old_permissions);
         if (is_wp_error($result)) {
             /* translators: 1: Directory path, 2: Directory permissions */
             return new WP_Error('itsec-content-directory-utility-change-content-directory-unable-to-change-permissions', sprintf(__('Unable to set the permissions of the new Directory Name (<code>%1$s</code>) to match the permissions of the old Directory Name. You may have to manually change the permissions of the directory to <code>%2$s</code> in order for your site to function properly.', 'better-wp-security'), esc_html($new_name), esc_html($old_permissions)));
         }
     }
     if ('wp-content' === $dir_name) {
         // We're undoing the change.
         $expression = self::get_wp_config_define_expression();
         $expression = substr($expression, 0, -1);
         $expression .= "[\r\n]*|";
         $modification_result = ITSEC_Lib_Config_File::remove_from_wp_config($expression);
     } else {
         $modification = self::get_wp_config_modification($new_dir, get_option('siteurl') . "/{$dir_name}");
         $modification_result = ITSEC_Lib_Config_File::append_wp_config($modification, true);
     }
     if (is_wp_error($modification_result)) {
         $rename_result = rename($new_dir, $old_dir);
         if ($rename_result) {
             // Reset the ITSEC_Core plugin file back to its old setting.
             $plugin_file = str_replace($new_dir, $old_dir, ITSEC_Core::get_plugin_file());
             ITSEC_Core::set_plugin_file($plugin_file);
             ITSEC_Core::update_wp_upload_dir($new_dir, $old_dir);
             ITSEC_Modules::update_module_paths($new_dir, $old_dir);
             ITSEC_Lib_Directory::chmod($old_dir, $old_permissions);
             /* translators: 1: Specific error details */
             return new WP_Error($modification_result->get_error_code(), sprintf(__('Unable to update the <code>wp-config.php</code> file. No directory or config file changes have been made. The error that prevented the file from updating is as follows: %1$s', 'better-wp-security'), $modification_result->get_error_message()));
         } else {
             /* translators: 1: Old directory path, 2: New directory path, 3: Specific error details */
             return new WP_Error($modification_result->get_error_code(), sprintf(__('CRITICAL ERROR: The <code>%1$s</code> directory was successfully renamed to the new name (<code>%2$s</code>). However, an error occurred when updating the <code>wp-config.php</code> file to configure WordPress to use the new content directory. iThemes Security attempted to rename the directory back to its original name, but an unknown error prevented the rename from working as expected. In order for your site to function properly, you will either need to manually rename the <code>%2$s</code> directory back to <code>%1$s</code> or manually update the <code>wp-config.php</code> file with the necessary modifications. The error that prevented the file from updating is as follows: %3$s', 'better-wp-security'), $old_name, $new_name, $modification_result->get_error_message()));
         }
     }
     $backups_location = ITSEC_Modules::get_setting('backup', 'location');
     $backups_location = str_replace($old_dir, $new_dir, $backups_location);
     ITSEC_Modules::set_setting('backup', 'location', $backups_location);
     $log_location = ITSEC_Modules::get_setting('global', 'log_location');
     $log_location = str_replace($old_dir, $new_dir, $log_location);
     ITSEC_Modules::set_setting('global', 'log_location', $log_location);
     $nginx_file = ITSEC_Modules::get_setting('global', 'nginx_file');
     $nginx_file = str_replace($old_dir, $new_dir, $nginx_file);
     ITSEC_Modules::set_setting('global', 'nginx_file', $nginx_file);
     return $dir_name;
 }
Exemplo n.º 18
0
 public static function get_server_config_ban_hosts_rules($server_type)
 {
     $host_list = ITSEC_Modules::get_setting('ban-users', 'host_list', array());
     if (!is_array($host_list) || empty($host_list)) {
         return '';
     }
     if (!class_exists('ITSEC_Lib_IP_Tools')) {
         require_once ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-ip-tools.php';
     }
     $host_rules = '';
     $set_env_rules = '';
     $deny_rules = '';
     $require_rules = '';
     // process hosts list
     foreach ($host_list as $host) {
         $host = ITSEC_Lib_IP_Tools::ip_wild_to_ip_cidr(trim($host));
         if (empty($host)) {
             continue;
         }
         if (ITSEC_Lib::is_ip_whitelisted($host)) {
             /**
              * @todo warn the user the ip to be banned is whitelisted
              */
             continue;
         }
         if (in_array($server_type, array('apache', 'litespeed'))) {
             $converted_host = ITSEC_Lib_IP_Tools::ip_cidr_to_ip_regex($host);
             if (empty($converted_host)) {
                 continue;
             }
             $set_env_rules .= "\tSetEnvIF REMOTE_ADDR \"^{$converted_host}\$\" DenyAccess\n";
             // Ban IP
             $set_env_rules .= "\tSetEnvIF X-FORWARDED-FOR \"^{$converted_host}\$\" DenyAccess\n";
             // Ban IP from a proxy
             $set_env_rules .= "\tSetEnvIF X-CLUSTER-CLIENT-IP \"^{$converted_host}\$\" DenyAccess\n";
             // Ban IP from a load balancer
             $set_env_rules .= "\n";
             $require_rules .= "\t\t\tRequire not ip {$host}\n";
             $deny_rules .= "\t\tDeny from {$host}\n";
         } else {
             if ('nginx' === $server_type) {
                 $host_rules .= "\tdeny {$host};\n";
             }
         }
     }
     $rules = '';
     if ('apache' === $server_type) {
         if (!empty($set_env_rules)) {
             $rules .= "\n";
             $rules .= "\t# " . __('Ban Hosts - Security > Settings > Banned Users', 'better-wp-security') . "\n";
             $rules .= $set_env_rules;
             $rules .= "\t<IfModule mod_authz_core.c>\n";
             $rules .= "\t\t<RequireAll>\n";
             $rules .= "\t\t\tRequire all granted\n";
             $rules .= "\t\t\tRequire not env DenyAccess\n";
             $rules .= $require_rules;
             $rules .= "\t\t</RequireAll>\n";
             $rules .= "\t</IfModule>\n";
             $rules .= "\t<IfModule !mod_authz_core.c>\n";
             $rules .= "\t\tOrder allow,deny\n";
             $rules .= "\t\tAllow from all\n";
             $rules .= "\t\tDeny from env=DenyAccess\n";
             $rules .= $deny_rules;
             $rules .= "\t</IfModule>\n";
         }
     } else {
         if ('litespeed' === $server_type) {
             if (!empty($set_env_rules)) {
                 $rules .= "\n";
                 $rules .= "\t# " . __('Ban Hosts - Security > Settings > Banned Users', 'better-wp-security') . "\n";
                 $rules .= $set_env_rules;
                 $rules .= "\t<IfModule mod_litespeed.c>\n";
                 $rules .= "\t\tOrder allow,deny\n";
                 $rules .= "\t\tAllow from all\n";
                 $rules .= "\t\tDeny from env=DenyAccess\n";
                 $rules .= $deny_rules;
                 $rules .= "\t</IfModule>\n";
             }
         } else {
             if ('nginx' === $server_type) {
                 if (!empty($host_rules)) {
                     $rules .= "\n";
                     $rules .= "\t# " . __('Ban Hosts - Security > Settings > Banned Users', 'better-wp-security') . "\n";
                     $rules .= $host_rules;
                 }
             }
         }
     }
     return $rules;
 }
Exemplo n.º 19
0
 public static function get_validator($slug)
 {
     $self = self::get_instance();
     if (!isset($self->_module_validators[$slug])) {
         require_once ITSEC_Core::get_core_dir() . '/lib/validator.php';
         self::load_module_file('validator.php', $slug);
     }
     if (!isset($self->_module_validators[$slug])) {
         return null;
     }
     return $self->_module_validators[$slug];
 }
Exemplo n.º 20
0
 /**
  * Uninstall execution
  *
  * @since 4.0
  *
  * @return void
  * */
 private function uninstall_execute()
 {
     global $itsec_globals, $wpdb;
     $this->deactivate_execute();
     require_once $itsec_globals['plugin_dir'] . 'core/class-itsec-modules.php';
     ITSEC_Modules::run_uninstall();
     $itsec_files = ITSEC_Core::get_itsec_files();
     $itsec_files->do_deactivate();
     delete_site_option('itsec-storage');
     delete_site_option('itsec_global');
     delete_site_option('itsec_data');
     delete_site_option('itsec_initials');
     delete_site_option('itsec_jquery_version');
     delete_site_option('itsec_message_queue');
     $wpdb->query("DROP TABLE IF EXISTS " . $wpdb->base_prefix . "itsec_log;");
     $wpdb->query("DROP TABLE IF EXISTS " . $wpdb->base_prefix . "itsec_lockouts;");
     $wpdb->query("DROP TABLE IF EXISTS " . $wpdb->base_prefix . "itsec_temp;");
     if (is_dir(ITSEC_Core::get_storage_dir())) {
         require_once ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-directory.php';
         ITSEC_Lib_Directory::remove(ITSEC_Core::get_storage_dir());
     }
     ITSEC_Lib::clear_caches();
 }
Exemplo n.º 21
0
 /**
  * Release the lock.
  *
  * Releases a file lock to allow others to use it.
  *
  * @since  4.0.0
  *
  * @param string $lock_file file name of lock
  *
  * @return bool true if released, false otherwise
  */
 public function release_file_lock($lock_file)
 {
     if (ITSEC_Modules::get_setting('global', 'lock_file')) {
         return true;
     }
     require_once ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-directory.php';
     $lock_file = ITSEC_Core::get_storage_dir() . '/' . sanitize_text_field($lock_file) . '.lock';
     $result = ITSEC_Lib_Directory::remove($lock_file);
     if (is_wp_error($result)) {
         return false;
     }
     return true;
 }
Exemplo n.º 22
0
    protected function render_settings($form)
    {
        if (!defined('DOING_AJAX') || !DOING_AJAX) {
            echo '<p>' . __('Click the button to load the current file permissions.', 'better-wp-security') . '</p>';
            echo '<p>' . $form->add_button('load_file_permissions', array('value' => __('Load File Permissions Details', 'better-wp-security'), 'class' => 'button-primary itsec-reload-module')) . '</p>';
            return;
        }
        require_once ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-config-file.php';
        $wp_upload_dir = ITSEC_Core::get_wp_upload_dir();
        $path_data = array(array(ABSPATH, 0755), array(ABSPATH . WPINC, 0755), array(ABSPATH . 'wp-admin', 0755), array(ABSPATH . 'wp-admin/js', 0755), array(WP_CONTENT_DIR, 0755), array(get_theme_root(), 0755), array(WP_PLUGIN_DIR, 0755), array($wp_upload_dir['basedir'], 0755), array(ITSEC_Lib_Config_File::get_wp_config_file_path(), 0444), array(ITSEC_Lib_Config_File::get_server_config_file_path(), 0444));
        $rows = array();
        foreach ($path_data as $path) {
            $row = array();
            list($path, $suggested_permissions) = $path;
            $display_path = preg_replace('/^' . preg_quote(ABSPATH, '/') . '/', '', $path);
            $display_path = ltrim($display_path, '/');
            if (empty($display_path)) {
                $display_path = '/';
            }
            $row[] = $display_path;
            $row[] = sprintf('%o', $suggested_permissions);
            $permissions = fileperms($path) & 0777;
            $row[] = sprintf('%o', $permissions);
            if (!$permissions || $permissions != $suggested_permissions) {
                $row[] = __('WARNING', 'better-wp-security');
                $row[] = '<div style="background-color: #FEFF7F; border: 1px solid #E2E2E2;">&nbsp;&nbsp;&nbsp;</div>';
            } else {
                $row[] = __('OK', 'better-wp-security');
                $row[] = '<div style="background-color: #22EE5B; border: 1px solid #E2E2E2;">&nbsp;&nbsp;&nbsp;</div>';
            }
            $rows[] = $row;
        }
        $class = 'entry-row';
        ?>
	<p><?php 
        $form->add_button('reload_file_permissions', array('value' => __('Reload File Permissions Details', 'better-wp-security'), 'class' => 'button-primary itsec-reload-module'));
        ?>
</p>
	<table class="widefat">
		<thead>
			<tr>
				<th><?php 
        _e('Relative Path', 'better-wp-security');
        ?>
</th>
				<th><?php 
        _e('Suggestion', 'better-wp-security');
        ?>
</th>
				<th><?php 
        _e('Value', 'better-wp-security');
        ?>
</th>
				<th><?php 
        _e('Result', 'better-wp-security');
        ?>
</th>
				<th><?php 
        _e('Status', 'better-wp-security');
        ?>
</th>
			</tr>
		</thead>
		<tfoot>
			<tr>
				<th><?php 
        _e('Relative Path', 'better-wp-security');
        ?>
</th>
				<th><?php 
        _e('Suggestion', 'better-wp-security');
        ?>
</th>
				<th><?php 
        _e('Value', 'better-wp-security');
        ?>
</th>
				<th><?php 
        _e('Result', 'better-wp-security');
        ?>
</th>
				<th><?php 
        _e('Status', 'better-wp-security');
        ?>
</th>
			</tr>
		</tfoot>
		<tbody>
			<?php 
        foreach ($rows as $row) {
            ?>
				<tr class="<?php 
            echo $class;
            ?>
">
					<?php 
            foreach ($row as $column) {
                ?>
						<td><?php 
                echo $column;
                ?>
</td>
					<?php 
            }
            ?>
				</tr>
				<?php 
            $class = 'entry-row' === $class ? 'entry-row alternate' : 'entry-row';
            ?>
			<?php 
        }
        ?>
		</tbody>
	</table>
	<br />
<?php 
    }
Exemplo n.º 23
0
 /**
  * Send the daily digest email.
  *
  * @since 2.6.0
  *
  * @return
  */
 public function send_daily_digest()
 {
     global $itsec_lockout;
     $send_email = false;
     require_once ITSEC_Core::get_core_dir() . 'lib/class-itsec-mailer.php';
     $mail = new ITSEC_Mail();
     $mail->add_header(esc_html__('Daily Security Digest', 'better-wp-security'), sprintf(wp_kses(__('Your Daily Security Digest for <b>%s</b>', 'better-wp-security'), array('b' => array())), date_i18n(get_option('date_format'))));
     $mail->add_info_box(sprintf(wp_kses(__('The following is a summary of security related activity on your site: <b>%s</b>', 'better-wp-security'), array('b' => array())), get_option('siteurl')));
     $mail->add_section_heading(esc_html__('Lockouts', 'better-wp-security'), 'lock');
     $user_count = sizeof($itsec_lockout->get_lockouts('user', true));
     $host_count = sizeof($itsec_lockout->get_lockouts('host', true));
     if ($host_count > 0 || $user_count > 0) {
         $mail->add_lockouts_summary($user_count, $host_count);
         $send_email = true;
     } else {
         $mail->add_text(esc_html__('No lockouts since the last email check.', 'better-wp-security'));
     }
     if (is_array($this->queue) && !empty($this->queue['messages']) && is_array($this->queue['messages'])) {
         if (in_array('file-change', $this->queue['messages'])) {
             $mail->add_section_heading(esc_html__('File Changes', 'better-wp-security'), 'folder');
             $mail->add_text(esc_html__('File changes detected on the site.', 'better-wp-security'));
             $send_email = true;
         }
         $messages = array();
         foreach ($this->queue['messages'] as $message) {
             if ('file-change' === $message) {
                 continue;
             }
             $messages[] = $message;
         }
         if (!empty($messages)) {
             $mail->add_section_heading(esc_html__('Messages', 'better-wp-security'), 'message');
             foreach ($messages as $message) {
                 $mail->add_text($message);
             }
             $send_email = true;
         }
     }
     if (!$send_email) {
         return;
     }
     $mail->add_details_box(sprintf(wp_kses(__('For more details, <a href="%s"><b>visit your security logs</b></a>', 'better-wp-security'), array('a' => array('href' => array()), 'b' => array())), ITSEC_Core::get_logs_page_url()));
     $mail->add_divider();
     $mail->add_large_text(esc_html__('Is your site as secure as it could be?', 'better-wp-security'));
     $mail->add_text(esc_html__('Ensure your site is using recommended settings and features with a security check.', 'better-wp-security'));
     $mail->add_button(esc_html__('Run a Security Check ✓', 'better-wp-security'), ITSEC_Core::get_security_check_page_url());
     if (defined('ITSEC_DEBUG') && true === ITSEC_DEBUG) {
         $mail->add_text(sprintf(esc_html__('Debug info (source page): %s', 'better-wp-security'), esc_url($_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"])));
     }
     $mail->add_footer();
     $raw_recipients = ITSEC_Modules::get_setting('global', 'notification_email');
     $recipients = array();
     foreach ($raw_recipients as $recipient) {
         $recipient = trim($recipient);
         if (is_email($recipient)) {
             $recipients[] = $recipient;
         }
     }
     $this->queue = array('last_sent' => ITSEC_Core::get_current_time_gmt(), 'messages' => array());
     update_site_option('itsec_message_queue', $this->queue);
     $subject = sprintf(esc_html__('[%s] Daily Security Digest', 'better-wp-security'), esc_url(get_option('siteurl')));
     return $mail->send($recipients, $subject);
 }