Exemple #1
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;
 }
Exemple #2
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');
     }
 }
Exemple #3
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>';
     }
 }
Exemple #4
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 
    }
	/**
	 * Sanitize and validate input
	 *
	 * @param  Array $input array of input fields
	 *
	 * @return Array         Sanitized array
	 */
	public function sanitize_module_input( $input ) {

		global $itsec_globals;

		$input['protect_files']               = ( isset( $input['protect_files'] ) && intval( $input['protect_files'] == 1 ) ? true : false );
		$input['directory_browsing']          = ( isset( $input['directory_browsing'] ) && intval( $input['directory_browsing'] == 1 ) ? true : false );
		$input['request_methods']             = ( isset( $input['request_methods'] ) && intval( $input['request_methods'] == 1 ) ? true : false );
		$input['suspicious_query_strings']    = ( isset( $input['suspicious_query_strings'] ) && intval( $input['suspicious_query_strings'] == 1 ) ? true : false );
		$input['non_english_characters']      = ( isset( $input['non_english_characters'] ) && intval( $input['non_english_characters'] == 1 ) ? true : false );
		$input['long_url_strings']            = ( isset( $input['long_url_strings'] ) && intval( $input['long_url_strings'] == 1 ) ? true : false );
		$input['write_permissions']           = ( isset( $input['write_permissions'] ) && intval( $input['write_permissions'] == 1 ) ? true : false );
		$input['wlwmanifest_header']          = ( isset( $input['wlwmanifest_header'] ) && intval( $input['wlwmanifest_header'] == 1 ) ? true : false );
		$input['edituri_header']              = ( isset( $input['edituri_header'] ) && intval( $input['edituri_header'] == 1 ) ? true : false );
		$input['theme_updates']               = ( isset( $input['theme_updates'] ) && intval( $input['theme_updates'] == 1 ) ? true : false );
		$input['plugin_updates']              = ( isset( $input['plugin_updates'] ) && intval( $input['plugin_updates'] == 1 ) ? true : false );
		$input['core_updates']                = ( isset( $input['core_updates'] ) && intval( $input['core_updates'] == 1 ) ? true : false );
		$input['comment_spam']                = ( isset( $input['comment_spam'] ) && intval( $input['comment_spam'] == 1 ) ? true : false );
		$input['file_editor']                 = ( isset( $input['file_editor'] ) && intval( $input['file_editor'] == 1 ) ? true : false );
		$input['disable_xmlrpc']              = isset( $input['disable_xmlrpc'] ) ? intval( $input['disable_xmlrpc'] ) : 0;
		$input['allow_xmlrpc_multiauth']      = isset( $input['allow_xmlrpc_multiauth'] ) ? (bool) $input['allow_xmlrpc_multiauth'] : true;
		$input['uploads_php']                 = ( isset( $input['uploads_php'] ) && intval( $input['uploads_php'] == 1 ) ? true : false );
		$input['safe_jquery']                 = ( isset( $input['safe_jquery'] ) && intval( $input['safe_jquery'] == 1 ) ? true : false );
		$input['login_errors']                = ( isset( $input['login_errors'] ) && intval( $input['login_errors'] == 1 ) ? true : false );
		$input['force_unique_nicename']       = ( isset( $input['force_unique_nicename'] ) && intval( $input['force_unique_nicename'] == 1 ) ? true : false );
		$input['disable_unused_author_pages'] = ( isset( $input['disable_unused_author_pages'] ) && intval( $input['disable_unused_author_pages'] == 1 ) ? true : false );

		if ( ! isset( $this->settings['allow_xmlrpc_multiauth'] ) ) {
			$this->settings['allow_xmlrpc_multiauth'] = null;
		}

		if (
			( $input['protect_files'] !== $this->settings['protect_files'] ||
			  $input['directory_browsing'] !== $this->settings['directory_browsing'] ||
			  $input['request_methods'] !== $this->settings['request_methods'] ||
			  $input['suspicious_query_strings'] !== $this->settings['suspicious_query_strings'] ||
			  $input['non_english_characters'] !== $this->settings['non_english_characters'] ||
			  $input['comment_spam'] !== $this->settings['comment_spam'] ||
			  $input['disable_xmlrpc'] !== $this->settings['disable_xmlrpc'] ||
			  $input['allow_xmlrpc_multiauth'] !== $this->settings['allow_xmlrpc_multiauth'] ||
			  $input['uploads_php'] !== $this->settings['uploads_php']
			) ||
			isset( $itsec_globals['settings']['write_files'] ) && $itsec_globals['settings']['write_files'] === true
		) {

			add_site_option( 'itsec_rewrites_changed', true );

		}

		if ( $input['file_editor'] !== $this->settings['file_editor'] ) {

			add_site_option( 'itsec_config_changed', true );

		}


		if ( $input['write_permissions'] === true ) {
			// 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 ( $input['write_permissions'] !== $this->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( trailingslashit( $GLOBALS['itsec_globals']['plugin_dir'] ) . 'core/lib/class-itsec-lib-config-file.php' );
			require_once( trailingslashit( $GLOBALS['itsec_globals']['plugin_dir'] ) . 'core/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 );
		}


		if ( is_multisite() ) {

			$this->settings = $input;

		}

		return $input;

	}
 /**
  * Saves all wpconfig rules to wp-config.php.
  *
  * Gets a file lock for wp-config.php and calls the writing function if successful.
  *
  * @since  4.0.0
  *
  * @return mixed array or false if writing disabled or error message
  */
 public function save_wpconfig()
 {
     require_once trailingslashit($GLOBALS['itsec_globals']['plugin_dir']) . 'core/lib/class-itsec-lib-config-file.php';
     $result = ITSEC_Lib_Config_File::update_wp_config();
     if (is_wp_error($result)) {
         $retval = array('success' => false, 'text' => $result->get_error_message());
     } else {
         $retval = array('success' => true, 'text' => true);
     }
     return $retval;
 }
 /**
  * Sanitize and validate input
  *
  */
 public function process_database_prefix()
 {
     global $wpdb, $itsec_files;
     //suppress error messages due to timing
     error_reporting(0);
     @ini_set('display_errors', 0);
     $check_prefix = true;
     //Assume the first prefix we generate is unique
     //generate a new table prefix that doesn't conflict with any other in use in the database
     while ($check_prefix) {
         $avail = 'abcdefghijklmnopqrstuvwxyz0123456789';
         //first character should be alpha
         $new_prefix = $avail[mt_rand(0, 25)];
         //length of new prefix
         $prelength = mt_rand(4, 9);
         //generate remaning characters
         for ($i = 0; $i < $prelength; $i++) {
             $new_prefix .= $avail[mt_rand(0, 35)];
         }
         //complete with underscore
         $new_prefix .= '_';
         $new_prefix = esc_sql($new_prefix);
         //just be safe
         $check_prefix = $wpdb->get_results('SHOW TABLES LIKE "' . $new_prefix . '%";', ARRAY_N);
         //if there are no tables with that prefix in the database set checkPrefix to false
     }
     //assume this will work
     $type = 'updated';
     $message = __('Settings Updated', 'better-wp-security');
     $tables = $wpdb->get_results('SHOW TABLES LIKE "' . $wpdb->base_prefix . '%"', ARRAY_N);
     //retrieve a list of all tables in the DB
     //Rename each table
     foreach ($tables as $table) {
         $table = substr($table[0], strlen($wpdb->base_prefix), strlen($table[0]));
         //Get the table name without the old prefix
         //rename the table and generate an error if there is a problem
         if ($wpdb->query('RENAME TABLE `' . $wpdb->base_prefix . $table . '` TO `' . $new_prefix . $table . '`;') === false) {
             $type = 'error';
             $message = sprintf('%s %s%s. %s', __('Error: Could not rename table', 'better-wp-security'), $wpdb->base_prefix, $table, __('You may have to rename the table manually.', 'better-wp-security'));
             add_settings_error('itsec', esc_attr('settings_updated'), $message, $type);
         }
     }
     if (is_multisite()) {
         //multisite requires us to rename each blogs' options
         $blogs = $wpdb->get_col("SELECT blog_id FROM `" . $new_prefix . "blogs` WHERE public = '1' AND archived = '0' AND mature = '0' AND spam = '0' ORDER BY blog_id DESC");
         //get list of blog id's
         if (is_array($blogs)) {
             //make sure there are other blogs to update
             //update each blog's user_roles option
             foreach ($blogs as $blog) {
                 $wpdb->query('UPDATE `' . $new_prefix . $blog . '_options` SET option_name = "' . $new_prefix . $blog . '_user_roles" WHERE option_name = "' . $wpdb->base_prefix . $blog . '_user_roles" LIMIT 1;');
             }
         }
     }
     $upOpts = $wpdb->query('UPDATE `' . $new_prefix . 'options` SET option_name = "' . $new_prefix . 'user_roles" WHERE option_name = "' . $wpdb->base_prefix . 'user_roles" LIMIT 1;');
     //update options table and set flag to false if there's an error
     if ($upOpts === false) {
         //set an error
         $type = 'error';
         $message = __('Could not update prefix references in options table.', 'better-wp-security');
         add_settings_error('itsec', esc_attr('settings_updated'), $message, $type);
     }
     $rows = $wpdb->get_results('SELECT * FROM `' . $new_prefix . 'usermeta`');
     //get all rows in usermeta
     //update all prefixes in usermeta
     foreach ($rows as $row) {
         if (substr($row->meta_key, 0, strlen($wpdb->base_prefix)) == $wpdb->base_prefix) {
             $pos = $new_prefix . substr($row->meta_key, strlen($wpdb->base_prefix), strlen($row->meta_key));
             $result = $wpdb->query('UPDATE `' . $new_prefix . 'usermeta` SET meta_key="' . $pos . '" WHERE meta_key= "' . $row->meta_key . '" LIMIT 1;');
             if ($result == false) {
                 $type = 'error';
                 $message = __('Could not update prefix references in usermeta table.', 'better-wp-security');
                 add_settings_error('itsec', esc_attr('settings_updated'), $message, $type);
             }
         }
     }
     require_once trailingslashit($GLOBALS['itsec_globals']['plugin_dir']) . 'core/lib/class-itsec-lib-config-file.php';
     require_once trailingslashit($GLOBALS['itsec_globals']['plugin_dir']) . 'core/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);
     $error = '';
     if (is_wp_error($config)) {
         $error = sprintf(__('Unable to read the <code>wp-config.php</code> file in order to update the Database Prefix. Error details as follows: %1$s (%2$s)', 'better-wp-security'), $config->get_error_message(), $config->get_error_code());
     } else {
         $regex = '/(\\$table_prefix\\s*=\\s*)([\'"]).+?\\2(\\s*;)/';
         $config = preg_replace($regex, "\${1}'{$new_prefix}'\${3}", $config);
         $write_result = ITSEC_Lib_File::write($config_file_path, $config);
         if (is_wp_error($write_result)) {
             $error = sprintf(__('Unable to update the <code>wp-config.php</code> file in order to update the Database Prefix. Error details as follows: %1$s (%2$s)', 'better-wp-security'), $config->get_error_message(), $config->get_error_code());
         }
     }
     if (!empty($error)) {
         add_settings_error('itsec', esc_attr('settings_updated'), $error, 'error');
         add_site_option('itsec_manual_update', true);
     }
     $this->settings = $new_prefix;
     //this tells the form field that all went well.
     if (is_multisite()) {
         if (!empty($error)) {
             $error_handler = new WP_Error();
             $error_handler->add('error', $error);
             $this->core->show_network_admin_notice($error_handler);
         } else {
             $this->core->show_network_admin_notice(false);
         }
         $this->settings = false;
     }
 }
	/**
	 * Sanitize and validate input
	 *
	 * @since 4.6.0
	 */
	public function process_salts() {
		global $itsec_globals;
		
		
		require_once( trailingslashit( $GLOBALS['itsec_globals']['plugin_dir'] ) . 'core/lib/class-itsec-lib-config-file.php' );
		require_once( trailingslashit( $GLOBALS['itsec_globals']['plugin_dir'] ) . 'core/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 );
		$error = '';
		
		if ( is_wp_error( $config ) ) {
			$error = sprintf( __( 'Unable to read the <code>wp-config.php</code> file in order to update the salts. Error details as follows: %1$s (%2$s)', 'it-l10n-ithemes-security-pro' ), $config->get_error_message(), $config->get_error_code() );
		} else {
			$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 ) {
				$new_salt = $this->get_salt();
				$new_salt = str_replace( '$', '\\$', $new_salt );
				
				$regex = "/(define\s*\(\s*(['\"])$define\\2\s*,\s*)(['\"]).+?\\3(\s*\)\s*;)/";
				$config = preg_replace( $regex, "\${1}'$new_salt'\${4}", $config );
			}
			
			$write_result = ITSEC_Lib_File::write( $config_file_path, $config );
			
			if ( is_wp_error( $write_result ) ) {
				$error = sprintf( __( 'Unable to update the <code>wp-config.php</code> file in order to update the salts. Error details as follows: %1$s (%2$s)', 'it-l10n-ithemes-security-pro' ), $config->get_error_message(), $config->get_error_code() );
			}
		}
		
		if ( ! empty( $error ) ) {
			add_settings_error( 'itsec', esc_attr( 'settings_updated' ), $error, 'error' );
			add_site_option( 'itsec_manual_update', true );
		}


		$this->settings = true; //this tells the form field that all went well.

		if ( is_multisite() ) {

			if ( ! empty( $error ) ) {

				$error_handler = new WP_Error();

				$error_handler->add( 'error', $error );

				$this->core->show_network_admin_notice( $error_handler );

			} else {

				$this->core->show_network_admin_notice( false );

			}

			$this->settings = true;

		}

		if ( $this->settings === true ) {

			update_site_option( 'itsec_salts', $itsec_globals['current_time_gmt'] );

			wp_clear_auth_cookie();
			$redirect_to = ! empty( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : ITSEC_Lib::get_home_root() . 'wp-login.php?loggedout=true';
			wp_safe_redirect( $redirect_to );

		}

	}
 /**
  * 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>';
     }
 }
 public function process_directory()
 {
     if ($this->is_custom_directory()) {
         $this->show_error(__('The <code>wp-content</code> directory has already been renamed. No Directory Name changes have been made.', 'it-l10n-better-wp-security'));
         $this->show_network_admin_notice();
         return;
     }
     $dir_name = sanitize_file_name($_POST['name']);
     if (empty($dir_name)) {
         $this->show_error(__('The Directory Name cannot be empty.', 'it-l10n-better-wp-security'));
         $this->show_network_admin_notice();
         return;
     }
     if ('wp-content' === $dir_name) {
         $this->show_error(__('You have not chosen a new name for wp-content. Nothing was saved.', 'it-l10n-better-wp-security'));
         $this->show_network_admin_notice();
         return;
     }
     if (preg_match('{^(?:/|\\|[a-z]:)}i', $dir_name)) {
         $this->show_error(sprintf(__('The Directory Name cannot be an absolute path. Please supply a path that is relative to <code>ABSPATH</code> (<code>%s</code>).', 'it-l10n-better-wp-security'), ABSPATH));
         $this->show_network_admin_notice();
         return;
     }
     $dir = ABSPATH . $dir_name;
     if (file_exists($dir)) {
         $this->show_error(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.', 'it-l10n-better-wp-security'), $dir));
         $this->show_network_admin_notice();
         return;
     }
     require_once trailingslashit($GLOBALS['itsec_globals']['plugin_dir']) . 'core/lib/class-itsec-lib-config-file.php';
     $old_permissions = ITSEC_Lib_Directory::get_permissions(WP_CONTENT_DIR);
     $result = rename(WP_CONTENT_DIR, $dir);
     if (!$result) {
         $this->show_error(sprintf(__('Unable to rename the <code>wp-content</code> directory to <code>%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.', 'it-l10n-better-wp-security'), $dir_name));
         $this->show_network_admin_notice();
         return;
     }
     $new_permissions = ITSEC_Lib_Directory::get_permissions($dir);
     if (is_int($old_permissions) && is_int($new_permissions) && $old_permissions != $new_permissions) {
         $result = ITSEC_Lib_Directory::chmod($dir, $old_permissions);
         if (is_wp_error($result)) {
             $this->show_error(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.', 'it-l10n-better-wp-security'), $dir_name, $old_permissions));
         }
     }
     $php_content_dir = str_replace("'", "\\'", $dir);
     $php_content_url = str_replace("'", "\\'", get_option('siteurl') . "/{$dir_name}");
     $modification = "define( 'WP_CONTENT_DIR', '{$php_content_dir}' ); // " . __('Do not remove. Removing this line could break your site. Added by Security > Settings > Change Content Directory.', 'it-l10n-better-wp-security') . "\n";
     $modification .= "define( 'WP_CONTENT_URL', '{$php_content_url}' ); // " . __('Do not remove. Removing this line could break your site. Added by Security > Settings > Change Content Directory.', 'it-l10n-better-wp-security') . "\n";
     $append_result = ITSEC_Lib_Config_File::append_wp_config($modification, true);
     if (is_wp_error($append_result)) {
         $rename_result = rename($dir, WP_CONTENT_DIR);
         if ($rename_result) {
             ITSEC_Lib_Directory::chmod(WP_CONTENT_DIR, $old_permissions);
             $this->show_error(sprintf(__('Unable to update the <code>wp-config.php</code> file. No directory or config file changes have been made. %1$s (%2$s)', 'it-l10n-better-wp-security'), $append_result->get_error_message(), $append_result->get_error_code()));
             $this->show_error(sprintf(__('In order to change the content directory on your server, you will have to manually change the configuration and rename the directory. Details can be found <a href="%s">here</a>.', 'it-l10n-better-wp-security'), 'https://codex.wordpress.org/Editing_wp-config.php#Moving_wp-content_folder'));
         } else {
             $this->show_error(sprintf(__('CRITICAL ERROR: The <code>wp-content</code> directory was successfully renamed to the new name (<code>%1$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 rename the <code>%1$s</code> directory back to <code>wp-content</code> or manually update the <code>wp-config.php</code> file with the necessary modifications. Instructions for making this modification can be found <a href="%2$s">here</a>.', 'it-l10n-better-wp-security'), $dir_name, 'https://codex.wordpress.org/Editing_wp-config.php#Moving_wp-content_folder'));
             $this->show_error(sprintf(__('Details on the error that prevented the <code>wp-config.php</code> file from updating is as follows: %1$s (%2$s)', 'it-l10n-better-wp-security'), $append_result->get_error_message(), $append_result->get_error_code()));
         }
         return;
     }
     $backup = get_site_option('itsec_backup');
     if ($backup !== false && isset($backup['location'])) {
         $backup['location'] = str_replace(WP_CONTENT_DIR, $dir, $backup['location']);
         update_site_option('itsec_backup', $backup);
     }
     $global = get_site_option('itsec_global');
     if ($global !== false && (isset($global['log_location']) || isset($global['nginx_file']))) {
         if (isset($global['log_location'])) {
             $global['log_location'] = str_replace(WP_CONTENT_DIR, $dir, $global['log_location']);
         }
         if (isset($global['nginx_file'])) {
             $global['nginx_file'] = str_replace(WP_CONTENT_DIR, $dir, $global['nginx_file']);
         }
         update_site_option('itsec_global', $global);
     }
     $this->show_network_admin_notice();
 }
 protected function is_modified_by_it_security()
 {
     if (!$this->is_custom_directory()) {
         return false;
     }
     if (isset($this->is_modified_by_it_security)) {
         return $this->is_modified_by_it_security;
     }
     $this->is_modified_by_it_security = false;
     require_once trailingslashit($GLOBALS['itsec_globals']['plugin_dir']) . 'core/lib/class-itsec-lib-config-file.php';
     $wp_config_file = ITSEC_Lib_Config_File::get_wp_config_file_path();
     if (empty($wp_config_file)) {
         return false;
     }
     require_once trailingslashit($GLOBALS['itsec_globals']['plugin_dir']) . 'core/lib/class-itsec-lib-file.php';
     $wp_config = ITSEC_Lib_File::read($wp_config_file);
     if (is_wp_error($wp_config)) {
         return false;
     }
     $define_expression = $this->get_wp_config_define_expression();
     if (!preg_match($define_expression, $wp_config)) {
         return false;
     }
     require_once trailingslashit($GLOBALS['itsec_globals']['plugin_dir']) . 'core/lib/class-itsec-lib-utility.php';
     $wp_config_without_comments = ITSEC_Lib_Utility::strip_php_comments($wp_config);
     if (is_wp_error($wp_config_without_comments)) {
         return false;
     }
     $define_expression_without_comment = $this->get_wp_config_define_expression(false);
     if (!preg_match($define_expression_without_comment, $wp_config_without_comments)) {
         return false;
     }
     $this->is_modified_by_it_security = true;
     return true;
 }
Exemple #12
0
 /**
  * Gets location of .htaccess
  *
  * Finds and returns path to .htaccess or nginx.conf if appropriate
  *
  * @since 4.0.0
  *
  * @return string path to .htaccess
  */
 public static function get_htaccess()
 {
     require_once ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-config-file.php';
     return ITSEC_Lib_Config_File::get_server_config_file_path();
 }
Exemple #13
0
 public static function is_modified_by_it_security()
 {
     if (isset($GLOBALS['__itsec_content_directory_is_modified_by_it_security'])) {
         return $GLOBALS['__itsec_content_directory_is_modified_by_it_security'];
     }
     $GLOBALS['__itsec_content_directory_is_modified_by_it_security'] = false;
     if (!self::is_custom_directory()) {
         return false;
     }
     require_once $GLOBALS['itsec_globals']['plugin_dir'] . 'core/lib/class-itsec-lib-config-file.php';
     $wp_config_file = ITSEC_Lib_Config_File::get_wp_config_file_path();
     if (empty($wp_config_file)) {
         return false;
     }
     require_once $GLOBALS['itsec_globals']['plugin_dir'] . 'core/lib/class-itsec-lib-file.php';
     $wp_config = ITSEC_Lib_File::read($wp_config_file);
     if (is_wp_error($wp_config)) {
         return false;
     }
     $define_expression = self::get_wp_config_define_expression();
     if (!preg_match($define_expression, $wp_config)) {
         return false;
     }
     require_once $GLOBALS['itsec_globals']['plugin_dir'] . 'core/lib/class-itsec-lib-utility.php';
     $wp_config_without_comments = ITSEC_Lib_Utility::strip_php_comments($wp_config);
     if (is_wp_error($wp_config_without_comments)) {
         return false;
     }
     $define_expression_without_comment = self::get_wp_config_define_expression(false);
     if (!preg_match($define_expression_without_comment, $wp_config_without_comments)) {
         return false;
     }
     $GLOBALS['__itsec_content_directory_is_modified_by_it_security'] = true;
     return true;
 }
Exemple #14
0
 /**
  * Process quick ban of host.
  *
  * Immediately adds the supplied host to the .htaccess file for banning.
  *
  * @since 4.0.0
  *
  * @param string $host the host to ban
  *
  * @return bool true on success or false on failure
  */
 public function quick_ban($host)
 {
     $host = trim($host);
     require_once ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-ip-tools.php';
     if (!ITSEC_Lib_IP_Tools::validate($host)) {
         return false;
     }
     $host_rule = '# ' . __('Quick ban IP. Will be updated on next formal rules save.', 'better-wp-security') . "\n";
     if ('nginx' === ITSEC_Lib::get_server()) {
         $host_rule .= "\tdeny {$host};\n";
     } else {
         if ('apache' === ITSEC_Lib::get_server()) {
             $dhost = str_replace('.', '\\.', $host);
             //re-define $dhost to match required output for SetEnvIf-RegEX
             $host_rule .= "SetEnvIF REMOTE_ADDR \"^{$dhost}\$\" DenyAccess\n";
             //Ban IP
             $host_rule .= "SetEnvIF X-FORWARDED-FOR \"^{$dhost}\$\" DenyAccess\n";
             //Ban IP from Proxy-User
             $host_rule .= "SetEnvIF X-CLUSTER-CLIENT-IP \"^{$dhost}\$\" DenyAccess\n";
             //Ban IP for Cluster/Cloud-hosted WP-Installs
             $host_rule .= "<IfModule mod_authz_core.c>\n";
             $host_rule .= "\t<RequireAll>\n";
             $host_rule .= "\t\tRequire all granted\n";
             $host_rule .= "\t\tRequire not env DenyAccess\n";
             $host_rule .= "\t\tRequire not ip {$host}\n";
             $host_rule .= "\t</RequireAll>\n";
             $host_rule .= "</IfModule>\n";
             $host_rule .= "<IfModule !mod_authz_core.c>\n";
             $host_rule .= "\tOrder allow,deny\n";
             $host_rule .= "\tDeny from env=DenyAccess\n";
             $host_rule .= "\tDeny from {$host}\n";
             $host_rule .= "\tAllow from all\n";
             $host_rule .= "</IfModule>\n";
         }
     }
     require_once ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-config-file.php';
     $result = ITSEC_Lib_Config_File::append_server_config($host_rule);
     if (is_wp_error($result)) {
         return false;
     }
     return true;
 }
Exemple #15
0
 public static function change_database_prefix()
 {
     global $wpdb;
     require_once $GLOBALS['itsec_globals']['plugin_dir'] . 'core/lib/class-itsec-lib-config-file.php';
     require_once $GLOBALS['itsec_globals']['plugin_dir'] . 'core/lib/class-itsec-lib-file.php';
     $response = array('errors' => array(), 'new_prefix' => false);
     //suppress error messages due to timing
     //		error_reporting( 0 );
     //		@ini_set( 'display_errors', 0 );
     $check_prefix = true;
     //Assume the first prefix we generate is unique
     //generate a new table prefix that doesn't conflict with any other in use in the database
     while ($check_prefix) {
         $avail = 'abcdefghijklmnopqrstuvwxyz0123456789';
         //first character should be alpha
         $new_prefix = $avail[mt_rand(0, 25)];
         //length of new prefix
         $prelength = mt_rand(4, 9);
         //generate remaning characters
         for ($i = 0; $i < $prelength; $i++) {
             $new_prefix .= $avail[mt_rand(0, 35)];
         }
         //complete with underscore
         $new_prefix .= '_';
         $new_prefix = esc_sql($new_prefix);
         //just be safe
         $check_prefix = $wpdb->get_results('SHOW TABLES LIKE "' . $new_prefix . '%";', ARRAY_N);
         //if there are no tables with that prefix in the database set checkPrefix to false
     }
     $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)) {
         /* translators: 1: Specific error details */
         $response['errors'][] = new WP_Error($confix->get_error_code(), sprintf(__('Unable to read the <code>wp-config.php</code> file in order to update the Database Prefix. Error details as follows: %1$s', 'better-wp-security'), $config->get_error_message()));
         return $response;
     }
     $regex = '/(\\$table_prefix\\s*=\\s*)([\'"]).+?\\2(\\s*;)/';
     $config = preg_replace($regex, "\${1}'{$new_prefix}'\${3}", $config);
     $write_result = ITSEC_Lib_File::write($config_file_path, $config);
     if (is_wp_error($write_result)) {
         /* translators: 1: Specific error details */
         $response['errors'][] = new WP_Error($confix->get_error_code(), sprintf(__('Unable to update the <code>wp-config.php</code> file in order to update the Database Prefix. Error details as follows: %1$s', 'better-wp-security'), $config->get_error_message()));
         return $response;
     }
     $response['new_prefix'] = $new_prefix;
     $tables = $wpdb->get_results('SHOW TABLES LIKE "' . $wpdb->base_prefix . '%"', ARRAY_N);
     //retrieve a list of all tables in the DB
     //Rename each table
     foreach ($tables as $table) {
         $table = substr($table[0], strlen($wpdb->base_prefix), strlen($table[0]));
         //Get the table name without the old prefix
         //rename the table and generate an error if there is a problem
         if ($wpdb->query('RENAME TABLE `' . $wpdb->base_prefix . $table . '` TO `' . $new_prefix . $table . '`;') === false) {
             $response['errors'][] = new WP_Error('itsec-database-prefix-utility-change-database-prefix-failed-table-rename', sprintf(__('Could not rename table %1$s. You may have to rename the table manually.', 'better-wp-security'), $wpdb->base_prefix . $table));
         }
     }
     if (is_multisite()) {
         //multisite requires us to rename each blogs' options
         $blogs = $wpdb->get_col("SELECT blog_id FROM `" . $new_prefix . "blogs` WHERE public = '1' AND archived = '0' AND mature = '0' AND spam = '0' ORDER BY blog_id DESC");
         //get list of blog id's
         if (is_array($blogs)) {
             //make sure there are other blogs to update
             //update each blog's user_roles option
             foreach ($blogs as $blog) {
                 $wpdb->query('UPDATE `' . $new_prefix . $blog . '_options` SET option_name = "' . $new_prefix . $blog . '_user_roles" WHERE option_name = "' . $wpdb->base_prefix . $blog . '_user_roles" LIMIT 1;');
             }
         }
     }
     $upOpts = $wpdb->query('UPDATE `' . $new_prefix . 'options` SET option_name = "' . $new_prefix . 'user_roles" WHERE option_name = "' . $wpdb->base_prefix . 'user_roles" LIMIT 1;');
     //update options table and set flag to false if there's an error
     if ($upOpts === false) {
         //set an error
         $response['errors'][] = new WP_Error('itsec-database-prefix-utility-change-database-prefix-failed-options-update', __('Could not update prefix references in options table.', 'better-wp-security'));
     }
     $rows = $wpdb->get_results('SELECT * FROM `' . $new_prefix . 'usermeta`');
     //get all rows in usermeta
     //update all prefixes in usermeta
     foreach ($rows as $row) {
         if (substr($row->meta_key, 0, strlen($wpdb->base_prefix)) == $wpdb->base_prefix) {
             $pos = $new_prefix . substr($row->meta_key, strlen($wpdb->base_prefix), strlen($row->meta_key));
             $result = $wpdb->query('UPDATE `' . $new_prefix . 'usermeta` SET meta_key="' . $pos . '" WHERE meta_key= "' . $row->meta_key . '" LIMIT 1;');
             if ($result == false) {
                 $response['errors'][] = new WP_Error('itsec-database-prefix-utility-change-database-prefix-failed-usermeta-update', __('Could not update prefix references in usermeta table.', 'better-wp-security'));
             }
         }
     }
     return $response;
 }