Advertisement
Guest User

Untitled

a guest
Mar 1st, 2017
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 18.56 KB | None | 0 0
  1. <?php
  2. /*
  3. Plugin Name: Very Simple Password for Wordpress
  4. Plugin URI:  https://developer.wordpress.org/plugins/very-simple-password-for-wordpress/
  5. Description: This adds a simple password protection for wordpress.
  6. Version:     1.6
  7. Author:      Lucas Bustamante
  8. Author URI:  https://www.lucasbustamante.com.br
  9. */
  10.  
  11. defined( 'ABSPATH' ) or die( 'No script kiddies please!' );
  12.  
  13.  
  14. if (is_admin()){
  15.  
  16.     // Create database
  17.     global $VSPFW_db_version;
  18.     $VSPFW_db_version = '1.6';
  19.  
  20.     function VSPFW_install() {
  21.         global $wpdb;
  22.         global $VSPFW_db_version;
  23.  
  24.         $table_name = $wpdb->prefix . 'vspfw';
  25.        
  26.         $charset_collate = $wpdb->get_charset_collate();
  27.  
  28.         $sql = "CREATE TABLE $table_name (
  29.             id mediumint(9) NOT NULL AUTO_INCREMENT,
  30.             time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
  31.             unique_key varchar(32) DEFAULT '' NOT NULL,
  32.             ip_address varchar(45) DEFAULT '' NOT NULL,
  33.             PRIMARY KEY  (id)
  34.         ) $charset_collate;";
  35.  
  36.         require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
  37.         dbDelta( $sql );
  38.  
  39.         add_option( 'VSPFW_db_version', $VSPFW_db_version );
  40.  
  41.         // In case we need to change database structure on future versions
  42.         $installed_ver = get_option( "VSPFW_db_version" );
  43.  
  44.         if ( $installed_ver != $VSPFW_db_version ) {
  45.  
  46.             $table_name = $wpdb->prefix . 'vspfw';
  47.  
  48.             $sql = "CREATE TABLE $table_name (
  49.                 id mediumint(9) NOT NULL AUTO_INCREMENT,
  50.                 time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
  51.                 unique_key varchar(32) DEFAULT '' NOT NULL,
  52.                 ip_address varchar(45) DEFAULT '' NOT NULL,
  53.                 PRIMARY KEY  (id)
  54.             ) $charset_collate;";
  55.  
  56.             require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
  57.             dbDelta( $sql );
  58.  
  59.             update_option( "VSPFW_db_version", $VSPFW_db_version );
  60.         }
  61.  
  62.     }
  63.     register_activation_hook( __FILE__, 'VSPFW_install' );
  64.  
  65.  
  66.     // Add Options page
  67.     require('VSPFW_options.php');
  68.  
  69.     // Add VSPW under Options menu on Admin panel
  70.     function VSPFW_add_menu() {
  71.         add_submenu_page('options-general.php','Very Simple Password for Wordpress','Very Simple Password for Wordpress','manage_options', 'very_simple_password_for_wordpress', 'very_simple_password_for_wordpress');
  72.     }
  73.     add_action('admin_menu', 'VSPFW_add_menu');
  74.  
  75.     // Add "Settings" link to plugins page
  76.     function VSPFW_add_action_links ( $links ) {
  77.      $mylinks = array(
  78.         '<a href="' . admin_url( 'options-general.php?page=very_simple_password_for_wordpress' ) . '">Settings</a>',
  79.      );
  80.     return array_merge( $links, $mylinks );
  81.     }
  82.     add_filter( 'plugin_action_links_' . plugin_basename(__FILE__), 'VSPFW_add_action_links' );
  83.  
  84.     // Register configurable options
  85.     function VSPFW_register_settings() {
  86.       register_setting( 'VSPFW-option-group', 'vspfw_background_image', 'strval');
  87.       register_setting( 'VSPFW-option-group', 'vspfw_days', 'intval');
  88.       register_setting( 'VSPFW-option-group', 'vspfw_enter_password_string', 'strval');
  89.       register_setting( 'VSPFW-option-group', 'vspfw_logo_url', 'strval');
  90.       register_setting( 'VSPFW-option-group', 'vspfw_submit', 'strval');
  91.       register_setting( 'VSPFW-option-group', 'vspfw_password', 'strval');
  92.       register_setting( 'VSPFW-option-group', 'vspfw_enabled', 'strval');
  93.       register_setting( 'VSPFW-option-group', 'vspfw_wrong_password', 'strval');
  94.       register_setting( 'VSPFW-option-group', 'vspfw_default_logo_changed_once', 'boolval');
  95.       register_setting( 'VSPFW-option-group', 'vspfw_default_background_changed_once', 'boolval');
  96.       register_setting( 'VSPFW-option-group', 'vspfw_show_contact_info', 'strval');
  97.       register_setting( 'VSPFW-option-group', 'vspfw_contact_email_changed_once', 'boolval');
  98.       register_setting( 'VSPFW-option-group', 'vspfw_contact_email', 'strval');
  99.       register_setting( 'VSPFW-option-group', 'vspfw_need_the_password_string', 'strval' );
  100.       register_setting( 'VSPFW-option-group', 'vspfw_allow_request_password', 'strval' );
  101.       register_setting( 'VSPFW-option-group', 'vspfw_website_domain', 'strval' );
  102.       register_setting( 'VSPFW-option-group', 'vspfw_force_reauth', 'strval' );
  103.       register_setting( 'VSPFW-option-group', 'vspfw_force_reauth_message', 'strval' );
  104.       register_setting( 'VSPFW-option-group', 'vspfw_brute_force_protection_message', 'strval' );
  105.       register_setting( 'VSPFW-option-group', 'vspfw_brute_force_protection_tries', 'intval' );
  106.       register_setting( 'VSPFW-option-group', 'vspfw_brute_force_protection_interval', 'intval' );
  107.     }
  108.     add_action('admin_init', 'VSPFW_register_settings' );
  109.  
  110.     // Sets default values
  111.    
  112.     if (get_option('vspfw_background_image') == "" && get_option('vspfw_default_background_changed_once') == false) {
  113.         update_option('vspfw_background_image', plugins_url('/images/bg-default.jpg', __FILE__));
  114.         update_option('vspfw_default_background_changed_once', true);
  115.     }
  116.     if (get_option('vspfw_default_background_changed_once') == "") {
  117.         update_option('vspfw_default_background_changed_once', false);
  118.     }
  119.     if (get_option('vspfw_default_logo_changed_once') == "") {
  120.         update_option('vspfw_default_logo_changed_once', false);
  121.     }
  122.     if (get_option('vspfw_logo_url') == "" && get_option('vspfw_default_logo_changed_once') == false) {
  123.         update_option('vspfw_logo_url', plugins_url('/images/lock.png', __FILE__));
  124.         update_option('vspfw_default_logo_changed_once', true);
  125.     }
  126.     if (get_option('vspfw_days') == "") {
  127.         update_option('vspfw_days', '3650');
  128.     }
  129.     if (get_option('vspfw_enter_password_string') == "") {
  130.         update_option('vspfw_enter_password_string', 'Please enter the password:');
  131.     }
  132.     if (get_option('vspfw_submit') == "") {
  133.         update_option('vspfw_submit', 'Enter');
  134.     }
  135.     if (get_option('vspfw_website_domain') == "") {
  136.         update_option('vspfw_website_domain', vspfw_filter_domain_to_use_on_cookie(get_bloginfo('url')));
  137.     }
  138.     if (get_option('vspfw_wrong_password') == "") {
  139.         update_option('vspfw_wrong_password', 'Wrong password...');
  140.     }
  141.     if (get_option('vspfw_show_contact_info') == "") {
  142.         update_option('vspfw_show_contact_info', 'false');
  143.     }
  144.     if (get_option('vspfw_contact_email_changed_once') == "") {
  145.         update_option('vspfw_contact_email_changed_once', false);
  146.     }
  147.     if (get_option('vspfw_contact_email') == "" && get_option('vspfw_contact_email_changed_once') == false) {
  148.         update_option('vspfw_contact_email', get_bloginfo('admin_email'));
  149.         get_option('vspfw_contact_email_changed_once') == true;
  150.     }
  151.     if (get_option('vspfw_need_the_password_string') == "" ) {
  152.         update_option('vspfw_need_the_password_string', 'Need the password?');
  153.     }
  154.     // Brute force config
  155.     if (get_option('vspfw_brute_force_protection_tries') == "" ) {
  156.         update_option('vspfw_brute_force_protection_tries', '5');
  157.     }
  158.     if (get_option('vspfw_brute_force_protection_interval') == "" ) {
  159.         update_option('vspfw_brute_force_protection_interval', '300');
  160.     }
  161.     if (get_option('vspfw_brute_force_protection_message') == "") {
  162.         update_option('vspfw_brute_force_protection_message', 'You have failed the password too many times. Please try again a few minutes...');
  163.     }
  164.     // Reset the reauth checkbox, so it doesn't reset all the time
  165.     if (get_option('vspfw_users_reauth') != "" ) {
  166.         update_option('vspfw_users_reauth', '');
  167.     }
  168.     // Reset the reauth message, so it doesn't appear all the time
  169.     if (get_option('vspfw_force_reauth_message') != "" ) {
  170.         update_option('vspfw_force_reauth_message', '');
  171.     }
  172.  
  173.     // Reauth all users
  174.     if (get_option('vspfw_force_reauth') == 'force_reauth') {
  175.         global $wpdb;
  176.         $table_name = $wpdb->prefix . 'vspfw';
  177.         $delete = $wpdb->query('TRUNCATE TABLE `'.$table_name.'`');
  178.         if ($delete) {
  179.             update_option('vspfw_force_reauth_message', 'Succesfully delleted all cookies from the '.$table_name.' table. Now all visitors have to enter the password again.');
  180.         } else {
  181.             update_option('vspfw_force_reauth_message', 'Couldn\'t delete cookies from '.$table_name.' - you might want to do it manually.');
  182.         }
  183.         update_option('vspfw_force_reauth', '');
  184.     }
  185.  
  186. }
  187.  
  188. // Enable media management on this plugin
  189. function enqueue_media_uploader() {
  190.     wp_enqueue_media();
  191. }
  192. add_action("admin_enqueue_scripts", "enqueue_media_uploader", 10);
  193.  
  194. // Custom function to determine if this is the login page http://stackoverflow.com/questions/5266945/wordpress-how-detect-if-current-page-is-the-login-page
  195. function VSPFW_is_login_page() {
  196.     return in_array($GLOBALS['pagenow'], array('wp-login.php'));
  197. }
  198.  
  199. // Check if a cookie is in database and is still valid
  200. function VSPFW_check_cookie_on_database($cookie) {
  201.     if (strlen($cookie) == 32) {
  202.  
  203.         global $wpdb;
  204.         $table_name = $wpdb->prefix . 'vspfw';
  205.  
  206.         $results = $wpdb->get_results( 'SELECT * FROM '.$table_name.' WHERE unique_key = "'.$cookie.'"', OBJECT );
  207.  
  208.         if ($results) {
  209.             return true;
  210.         }
  211.     }
  212.     return false;
  213. }
  214.  
  215. // Filter domain to use on cookie
  216. // Only called at the first time the plugin runs
  217. function vspfw_filter_domain_to_use_on_cookie($domain) {
  218.     // Removes http/s:// from domain
  219.     $domain = str_replace("https://", '', $domain);
  220.     $domain = str_replace("http://", '', $domain);
  221.  
  222.     // Replaces www. with . wich will work as a wilcard for cookies under that domain
  223.     $domain = str_replace('www.','.', $domain);
  224.  
  225.     // Check if domain starts with dot, if not, inserts one
  226.     if (substr($domain, 0, 1) != '.') {
  227.         $domain = '.'.$domain;
  228.     }
  229.  
  230.     return $domain;
  231. }
  232.  
  233. // Don't ask for password on login or admin panel
  234. function VSPFW_should_ask_password() {
  235.     // We have plugin enabled and password set
  236.     if ((get_option('vspfw_enabled') == "enabled") && (get_option('vspfw_password') != "")) {
  237.         // Disable password on admin panel, login page and for admin users
  238.         if (!is_admin() && !VSPFW_is_login_page() && !current_user_can('manage_options')) {
  239.             if (!VSPFW_check_cookie_on_database($_COOKIE['vspfw_password_entered'])) {
  240.                 return true;
  241.             }
  242.         }
  243.     }
  244. }
  245.  
  246. // Load CSS if needed
  247. function vspfw_css() {
  248.     if (VSPFW_should_ask_password()) {
  249.     ?>
  250.             <style>
  251.                 body {
  252.                     background:<?php echo (get_option('vspfw_background_image')==''?'#f1f1f1':'url('.esc_html(get_option('vspfw_background_image')).');') ?>;
  253.                 }
  254.                 #vspfw {
  255.                     top:25%;
  256.                     left: 50%;
  257.                     transform: translate3d(-50%,-25%, 0);
  258.                     position: absolute;
  259.                     background: #FFF;
  260.                     border: 1px solid #e3e3e3;
  261.                     border-radius: 5px;
  262.                     text-align: center;
  263.                     padding: 1em 3em;
  264.  
  265.                 }
  266.                 div#vspfw-request-password {
  267.                     color: #6b6b6b;
  268.                     position: absolute;
  269.                     bottom: -50px;
  270.                 }
  271.                 #vspfw input[type="submit"] {
  272.                     background: #3079ff;
  273.                     padding: 7px 15px;
  274.                     color: #FFF;
  275.                     border: 0;
  276.                     font-size: 17px;
  277.                     cursor: pointer;
  278.                 }
  279.                 #vspfw input[type="submit"]:hover {
  280.                     background:#6ca0ff;
  281.                 }
  282.                 #vspfw input[type="password"] {
  283.                     padding:5px 10px;
  284.                 }
  285.                 div#vspfw-enter-password-string {
  286.                     margin-bottom: 10px;
  287.                 }
  288.                 div#vspfw-request-password {
  289.                     color: #6b6b6b;
  290.                     bottom: -30px;
  291.                     position: relative;
  292.                     height: 0;
  293.                 }
  294.             </style>
  295.      <?php
  296.     }
  297. }
  298. add_action('init', 'vspfw_css', 50);
  299.  
  300. // Load admin CSS
  301. function vspfw_admin_css() {
  302.     if (is_admin()) {
  303.     ?>
  304.         <style>
  305.             .vspfw-option label {
  306.                 display: block;
  307.                 margin: 10px 0 2px 0;
  308.             }
  309.             .vspfw-option .image-preview img {
  310.                 max-width: 200px;
  311.                 max-height: 200px;
  312.                 margin: 10px 0;
  313.             }
  314.             div#vspfw-further-customization {
  315.                 display:none;
  316.             }
  317.             .vspfw-option-group {
  318.                 margin: 20px 0;
  319.             }
  320.             .vspfw-option-group h2 {
  321.                 margin: 30px 0 0 0;
  322.             }
  323.             .vspfw-instructions {
  324.                 display: inline-block;
  325.                 margin-left: 10px;
  326.                 max-width: 50%;
  327.                 vertical-align: middle;
  328.                 background: #ffffff;
  329.                 padding: 5px 10px;
  330.                 color: #000;
  331.                 border-radius: 5px;
  332.                 border: 1px solid #e3e3e3;
  333.                 border-left: 5px solid #ff9438;
  334.             }
  335.             div#vspfw_force_reauth_message {
  336.                 background: #FFF;
  337.                 font-weight: bold;
  338.                 padding: 10px;
  339.             }
  340.         </style>
  341.      <?php
  342.     }
  343. }
  344. add_action('admin_enqueue_scripts', 'vspfw_admin_css', 50);
  345.  
  346. // Load admin JS
  347. function vspfw_admin_js() {
  348.     if (is_admin()) {
  349.         wp_enqueue_script('jquery');
  350.     ?>
  351.         <script type="text/javascript">
  352.         jQuery(document).ready(function($){
  353.             $('.upload_media_button').click(function(e) {
  354.                 var botao = $(this);
  355.                 e.preventDefault();
  356.                 var image = wp.media({
  357.                     title: 'Upload Image',
  358.                     // mutiple: true if you want to upload multiple files at once
  359.                     multiple: false
  360.                 }).open()
  361.                 .on('select', function(e){
  362.                     // This will return the selected image from the Media Uploader, the result is an object
  363.                     var uploaded_image = image.state().get('selection').first();
  364.                     // We convert uploaded_image to a JSON object to make accessing it easier
  365.                     // Output to the console uploaded_image
  366.                     console.log(uploaded_image);
  367.                     var image_url = uploaded_image.toJSON().url;
  368.                     // Let's assign the url value to the input field
  369.                     console.log(botao);
  370.                     $(botao).siblings('.image-preview').find('img').attr('src', image_url);
  371.                     $(botao).siblings('.image_field').val(image_url);
  372.                 });
  373.             });
  374.         });
  375.         </script>
  376.      <?php
  377.     }
  378. }
  379. add_action('admin_footer', 'vspfw_admin_js', 20);
  380.  
  381. // Load Javascript if needed
  382. function vspfw_js() {
  383.     if (VSPFW_should_ask_password()) {
  384.     ?>
  385.             <script type="text/javascript"></script>
  386.      <?php
  387.     }
  388. }
  389. // No need for javascript on front-end now
  390. //add_action('init', 'vspfw_js', 6);
  391.  
  392. // Add md5 cookie to database
  393. function VSPFW_add_md5_cookie_do_database($unique_key, $ip_address) {
  394.     global $wpdb;
  395.    
  396.     $table_name = $wpdb->prefix . 'vspfw';
  397.    
  398.     $wpdb->insert(
  399.         $table_name,
  400.         array(
  401.             'time' => current_time( 'mysql' ),
  402.             'unique_key' => $unique_key,
  403.             'ip_address' => $ip_address,
  404.         )
  405.     );
  406.     if (is_int($wpdb->insert_id)) {
  407.         return true;
  408.     } else {
  409.         return false;
  410.     }
  411. }
  412.  
  413. // Add failed login attempt to database, to prevent brute force attacks
  414. function VSPFW_prevent_brute_force_add_try($ip_address) {
  415.     global $wpdb;
  416.    
  417.     $table_name = $wpdb->prefix . 'vspfw';
  418.    
  419.     $wpdb->insert(
  420.         $table_name,
  421.         array(
  422.             'time' => current_time( 'mysql' ),
  423.             'unique_key' => 'failed',
  424.             'ip_address' => $ip_address,
  425.         )
  426.     );
  427. }
  428.  
  429. // Check brute force attack
  430. function VSPFW_prevent_brute_force_check($ip_address) {
  431.         global $wpdb;
  432.  
  433.         $table_name = $wpdb->prefix . 'vspfw';
  434.         $results = $wpdb->get_results( 'SELECT * FROM '.$table_name.' WHERE ip_address = "'.$ip_address.'" AND unique_key = "failed"', OBJECT );
  435.  
  436.         $failed_login_attempts_between_time_frame = 0;
  437.  
  438.         foreach ($results as $result) {
  439.             // Add to counter every try in the last 120 seconds (or what the user configured)
  440.             if ((current_time(timestamp) - strtotime($result->time)) < get_option('vspfw_brute_force_protection_interval')) {
  441.                 $failed_login_attempts_between_time_frame++;
  442.             }
  443.         }
  444.         // If user failed the login more than 5 times in 120 seconds, it blocks him
  445.         if ($failed_login_attempts_between_time_frame > get_option('vspfw_brute_force_protection_tries')) {
  446.             // Brute force triggered
  447.             // Send email to administrator
  448.                 error_log('Very Simple Password for Wordpress - Brute force protection triggered on website '.get_bloginfo('site_name').' ('.get_bloginfo('url').') - More than '.get_option('vspfw_brute_force_protection_tries').' failed login attempts in an interval of '.get_option('vspfw_brute_force_protection_interval').' seconds by visitor with IP address '.$ip_address, 1, get_bloginfo('admin_email'));
  449.                 $vspfw_email_already_sent = true;
  450.  
  451.             // Stop function VSPFW_auth_frontend_user and display error message instead
  452.             return false;
  453.         } else {
  454.             // All good -  Brute force protection NOT triggered
  455.             return true;
  456.         }
  457. }
  458. add_action('init', 'VSPFW_prevent_brute_force_check');
  459.  
  460. // Check if user submitted password on the front-end
  461. function VSPFW_auth_frontend_user() {
  462.     $nonce=$_REQUEST['vspfw_user_entered_password_wpnonce'];
  463.     if (VSPFW_should_ask_password() && wp_verify_nonce($nonce, 'vspfw_user_entered_password_wpnonce')) {
  464.         if (isset($_POST['vspfw_password']) && !empty($_POST['vspfw_password'])) {
  465.             $ip_address = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
  466.             if (VSPFW_prevent_brute_force_check($ip_address)) {
  467.                 $pw = sanitize_text_field($_POST['vspfw_password']);
  468.                 if ($pw == get_option('vspfw_password')) {
  469.                         // Generate unique md5 to store as cookie
  470.                         $unique_key = md5(current_time(timestamp)+(rand(0,100)));
  471.                         if (!VSPFW_add_md5_cookie_do_database($unique_key, $ip_address)) {
  472.                             error_log('Warning from Very Simple Password for Wordpress: There was an error inserting the unique id to the database. You should review the plugin code or disable it.', 1, get_bloginfo('admin_email'));
  473.                             wp_die("Very Simple Password for Wordpress couldn't insert the UniqueID to the database. Please contact website owner.");
  474.                             exit;
  475.                         }
  476.                         // Set the cookie with the unique id for the period specified by the admin
  477.                         setcookie('vspfw_password_entered', esc_html($unique_key), strtotime( '+'.get_option('vspfw_days').' days'), '/', esc_html(get_option('vspfw_debug_domain')));
  478.                         $_COOKIE['vspfw_password_entered'] = esc_html($unique_key);
  479.                         // Refresh after setting cookie, because $_COOKIE is set on page load - http://stackoverflow.com/questions/3230133/accessing-cookie-immediately-after-setcookie
  480.                         //echo '<script type="text/javascript">window.location.reload(true);</script>';
  481.                         //header('Refresh:0');
  482.                 } else {
  483.                     // Add this failed login to database to prevent anti-brute force attacks
  484.                     VSPFW_prevent_brute_force_add_try($ip_address);
  485.                     // Display wrong password
  486.                     echo '<div style="text-align:center;color: #a94442;background-color: #f2dede;border-color: #ebccd1; padding:15px;margin:20px;">'.get_option('vspfw_wrong_password').'</div>';
  487.                 }
  488.             } else {
  489.                 // Display brute force protection
  490.                 echo '<div style="text-align:center;color: #a94442;background-color: #f2dede;border-color: #ebccd1; padding:15px;margin:20px;">'.get_option('vspfw_brute_force_protection_message').'</div>';
  491.             }
  492.         }
  493.     }
  494. }
  495. add_action('init', 'VSPFW_auth_frontend_user', 40);
  496.  
  497. // Check if $_COOKIE is set. I know this is simple and not safe, but the idea behind this plugin is to provide real-life solution to a site you need to hide while you develop it, not secure rocket science blueprints.
  498. function VSPFW_CheckPassword() {
  499.     // Check if password is enabled and set, and if we should ask for password
  500.     if (VSPFW_should_ask_password()) {
  501.             // If he doesn't, asks for password and stops Wordpress
  502.             require('VSPFW_view.php');
  503.             exit();
  504.         }
  505. }
  506. add_action('init', 'VSPFW_CheckPassword', 50);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement