/**
  * Populate global variables with information about the currently logged in user.
  *
  * Will set the current user, if the current user is not set. The current user
  * will be set to the logged in person. If no user is logged in, then it will
  * set the current user to 0, which is invalid and won't have any permissions.
  *
  * @since 0.71
  * @uses $current_user Checks if the current user is set
  * @uses wp_validate_auth_cookie() Retrieves current logged in user.
  *
  * @return bool|null False on XMLRPC Request and invalid auth cookie. Null when current user set
  */
 function get_currentuserinfo()
 {
     global $current_user;
     if (!empty($current_user)) {
         if ($current_user instanceof WP_User) {
             return;
         }
         // Upgrade stdClass to WP_User
         if (is_object($current_user) && isset($current_user->ID)) {
             $cur_id = $current_user->ID;
             $current_user = null;
             wp_set_current_user($cur_id);
             return;
         }
         // $current_user has a junk value. Force to WP_User with ID 0.
         $current_user = null;
         wp_set_current_user(0);
         return false;
     }
     if (defined('XMLRPC_REQUEST') && XMLRPC_REQUEST) {
         wp_set_current_user(0);
         return false;
     }
     if (!($user = wp_validate_auth_cookie())) {
         if (is_blog_admin() || is_network_admin() || empty($_COOKIE[LOGGED_IN_COOKIE]) || !($user = wp_validate_auth_cookie($_COOKIE[LOGGED_IN_COOKIE], 'logged_in'))) {
             wp_set_current_user(0);
             return false;
         }
     }
     wp_set_current_user($user);
 }
Esempio n. 2
1
 public static function verify_cookie($value)
 {
     if ($old_user_id = wp_validate_auth_cookie($value, 'logged_in')) {
         return user_can($old_user_id, 'view_query_monitor');
     }
     return false;
 }
Esempio n. 3
1
 public function create_post()
 {
     global $json_api;
     if (!$json_api->query->nonce) {
         $json_api->error("You must include a 'nonce' value to create posts. Use the `get_nonce` Core API method.");
     }
     if (!$json_api->query->cookie) {
         $json_api->error("You must include a 'cookie' authentication cookie. Use the `create_auth_cookie` Auth API method.");
     }
     $nonce_id = $json_api->get_nonce_id('posts', 'create_post');
     if (!wp_verify_nonce($json_api->query->nonce, $nonce_id)) {
         $json_api->error("Your 'nonce' value was incorrect. Use the 'get_nonce' API method.");
     }
     $user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
     if (!$user_id) {
         $json_api->error("Invalid authentication cookie. Use the `generate_auth_cookie` Auth API method.");
     }
     if (!user_can($user_id, 'edit_posts')) {
         $json_api->error("You need to login with a user capable of creating posts.");
     }
     nocache_headers();
     $post = new JSON_API_Post();
     $id = $post->create($_REQUEST);
     if (empty($id)) {
         $json_api->error("Could not create post.");
     }
     return array('post' => $post);
 }
Esempio n. 4
0
 function test_auth_cookie_scheme()
 {
     // arbitrary scheme name
     $cookie = wp_generate_auth_cookie(self::$user_id, time() + 3600, 'foo');
     $this->assertEquals(self::$user_id, wp_validate_auth_cookie($cookie, 'foo'));
     // wrong scheme name - should fail
     $cookie = wp_generate_auth_cookie(self::$user_id, time() + 3600, 'foo');
     $this->assertEquals(false, wp_validate_auth_cookie($cookie, 'bar'));
 }
Esempio n. 5
0
function wp_signon($credentials = '')
{
    if (empty($credentials)) {
        if (!empty($_POST['log'])) {
            $credentials['user_login'] = $_POST['log'];
        }
        if (!empty($_POST['pwd'])) {
            $credentials['user_password'] = $_POST['pwd'];
        }
        if (!empty($_POST['rememberme'])) {
            $credentials['remember'] = $_POST['rememberme'];
        }
    }
    if (!empty($credentials['user_login'])) {
        $credentials['user_login'] = sanitize_user($credentials['user_login']);
    }
    if (!empty($credentials['user_password'])) {
        $credentials['user_password'] = trim($credentials['user_password']);
    }
    if (!empty($credentials['remember'])) {
        $credentials['remember'] = true;
    } else {
        $credentials['remember'] = false;
    }
    do_action_ref_array('wp_authenticate', array(&$credentials['user_login'], &$credentials['user_password']));
    // If no credential info provided, check cookie.
    if (empty($credentials['user_login']) && empty($credentials['user_password'])) {
        $user = wp_validate_auth_cookie();
        if ($user) {
            return new WP_User($user);
        }
        if (!empty($_COOKIE[AUTH_COOKIE])) {
            return new WP_Error('expired_session', __('Please log in again.'));
        }
        // If the cookie is not set, be silent.
        return new WP_Error();
    }
    if (empty($credentials['user_login']) || empty($credentials['user_password'])) {
        $error = new WP_Error();
        if (empty($credentials['user_login'])) {
            $error->add('empty_username', __('<strong>ERROR</strong>: The username field is empty.'));
        }
        if (empty($credentials['user_password'])) {
            $error->add('empty_password', __('<strong>ERROR</strong>: The password field is empty.'));
        }
        return $error;
    }
    $user = wp_authenticate($credentials['user_login'], $credentials['user_password']);
    if (is_wp_error($user)) {
        return $user;
    }
    wp_set_auth_cookie($user->ID, $credentials['remember']);
    do_action('wp_login', $credentials['user_login']);
    return $user;
}
Esempio n. 6
0
function json_api_auth_checkAuthCookie($sDefaultPath)
{
    global $json_api;
    if ($json_api->query->cookie) {
        $user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
        if ($user_id) {
            $user = get_userdata($user_id);
            wp_set_current_user($user->ID, $user->user_login);
        }
    }
}
Esempio n. 7
0
 public function login(StatTracker $app)
 {
     $response = null;
     if (wp_validate_auth_cookie('', 'logged_in')) {
         if ($app['session']->get("agent") === null) {
             $user = wp_get_current_user();
             // Allow a plugin to grant/deny this user. See wiki for details
             $user = apply_filters(ST_USER_AUTH_FILTER, $user);
             if (!$user instanceof \WP_User) {
                 if (is_string($user)) {
                     $response = AuthResponse::registrationRequired($user);
                 } else {
                     $response = AuthResponse::registrationRequired("Access was denied. Please contact @" . ADMIN_AGENT);
                 }
                 $this->logger->info(sprintf("Registration required for %s", $email_address));
             } else {
                 $agent = Agent::lookupAgentName($user->user_email);
                 if (!$agent->isValid()) {
                     $name = apply_filters(ST_AGENT_NAME_FILTER, $user->user_login);
                     $this->logger->info(sprintf("Adding new agent %s", $name));
                     $agent->name = $name;
                     // Insert them into the DB
                     $stmt = $app->db()->prepare("INSERT INTO Agent (email, agent) VALUES (?, ?) ON DUPLICATE KEY UPDATE agent = ?;");
                     $stmt->execute(array($user->user_email, $name, $name));
                     $stmt->closeCursor();
                     // Generate an API token
                     $this->generateAPIToken($agent);
                     $agent = Agent::lookupAgentName($user->user_email);
                     if (!$agent->isValid()) {
                         $this->logger->error(sprintf("%s still not a valid agent", $agent->name));
                         return AuthResponse::error("An unrecoverable error has occured");
                     }
                 }
                 $app['session']->set("agent", $agent);
                 $response = AuthResponse::okay($agent);
                 $this->logger->info(sprintf("%s authenticated successfully", $agent->name));
             }
         } else {
             $agent = $app['session']->get("agent");
             if (Agent::lookupAgentByToken($agent->getToken())->isValid()) {
                 $response = AuthResponse::okay($agent);
             } else {
                 $this->logger->info(sprintf("Invalid token for %s. Logging out", $agent->name));
                 return $this->logout($app);
             }
         }
         return $response;
     } else {
         $app['session']->set("agent", null);
         $response = AuthResponse::authenticationRequired($this);
     }
     return $response;
 }
Esempio n. 8
0
 public function get_currentuserinfo()
 {
     global $json_api;
     if (!$json_api->query->cookie) {
         $json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` Auth API method.");
     }
     $user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
     if (!$user_id) {
         $json_api->error("Invalid authentication cookie. Use the `generate_auth_cookie` Auth API method.");
     }
     $user = get_userdata($user_id);
     return array("user" => array("id" => $user->ID, "username" => $user->user_login, "nicename" => $user->user_nicename, "email" => $user->user_email, "url" => $user->user_url, "registered" => $user->user_registered, "displayname" => $user->display_name, "firstname" => $user->user_firstname, "lastname" => $user->last_name, "nickname" => $user->nickname, "description" => $user->user_description, "capabilities" => $user->wp_capabilities));
 }
Esempio n. 9
0
 function auth_redirect()
 {
     // Checks if a user is logged in, if not redirects them to the login page
     if (is_ssl() || force_ssl_admin()) {
         $secure = true;
     } else {
         $secure = false;
     }
     // If https is required and request is http, redirect
     if ($secure && !is_ssl() && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin')) {
         if (0 === strpos($_SERVER['REQUEST_URI'], 'http')) {
             wp_redirect(preg_replace('|^http://|', 'https://', $_SERVER['REQUEST_URI']));
             exit;
         } else {
             wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
             exit;
         }
     }
     if ($user_id = wp_validate_auth_cookie()) {
         do_action('auth_redirect', $user_id);
         // If the user wants ssl but the session is not ssl, redirect.
         if (!$secure && get_user_option('use_ssl', $user_id) && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin')) {
             if (0 === strpos($_SERVER['REQUEST_URI'], 'http')) {
                 wp_redirect(preg_replace('|^http://|', 'https://', $_SERVER['REQUEST_URI']));
                 exit;
             } else {
                 wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
                 exit;
             }
         }
         return;
         // The cookie is good so we're done
     }
     // The cookie is no good so force login
     nocache_headers();
     if (OPENSSO_ENABLED) {
         // Redirect to OpenSSO login page then return here
         $login_url = OPENSSO_BASE_URL . '?goto=' . urlencode(opensso_full_url());
     } else {
         if (is_ssl()) {
             $proto = 'https://';
         } else {
             $proto = 'http://';
         }
         $redirect = strpos($_SERVER['REQUEST_URI'], '/options.php') && wp_get_referer() ? wp_get_referer() : $proto . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
         $login_url = wp_login_url($redirect);
     }
     wp_redirect($login_url);
     exit;
 }
Esempio n. 10
0
 function auth_redirect()
 {
     // Checks if a user is logged in, if not redirects them to the login page
     $secure = is_ssl() || force_ssl_admin();
     $secure = apply_filters('secure_auth_redirect', $secure);
     // If https is required and request is http, redirect
     if ($secure && !is_ssl() && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin')) {
         if (0 === strpos($_SERVER['REQUEST_URI'], 'http')) {
             wp_redirect(set_url_scheme($_SERVER['REQUEST_URI'], 'https'));
             exit;
         } else {
             wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
             exit;
         }
     }
     if (is_user_admin()) {
         $scheme = 'logged_in';
     } else {
         $scheme = apply_filters('auth_redirect_scheme', '');
     }
     if ($user_id = wp_validate_auth_cookie('', $scheme)) {
         do_action('auth_redirect', $user_id);
         // If the user wants ssl but the session is not ssl, redirect.
         if (!$secure && get_user_option('use_ssl', $user_id) && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin')) {
             if (0 === strpos($_SERVER['REQUEST_URI'], 'http')) {
                 wp_redirect(set_url_scheme($_SERVER['REQUEST_URI'], 'https'));
                 exit;
             } else {
                 wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
                 exit;
             }
         }
         return;
         // The cookie is good so we're done
     }
     // The cookie is no good so force login
     nocache_headers();
     $redirect = strpos($_SERVER['REQUEST_URI'], '/options.php') && wp_get_referer() ? wp_get_referer() : set_url_scheme('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
     // Change login url
     $login_url = Maestrano::sso()->getInitPath();
     wp_redirect($login_url);
     exit;
 }
Esempio n. 11
0
 public static function syncAttackData($exit = true)
 {
     global $wpdb;
     $waf = wfWAF::getInstance();
     $lastAttackMicroseconds = $wpdb->get_var("SELECT MAX(attackLogTime) FROM {$wpdb->base_prefix}wfHits");
     if ($waf->getStorageEngine()->hasNewerAttackData($lastAttackMicroseconds)) {
         $attackData = $waf->getStorageEngine()->getNewestAttackDataArray($lastAttackMicroseconds);
         if ($attackData) {
             foreach ($attackData as $request) {
                 if (count($request) !== 9) {
                     continue;
                 }
                 list($logTimeMicroseconds, $requestTime, $ip, $learningMode, $paramKey, $paramValue, $failedRules, $ssl, $requestString) = $request;
                 // Skip old entries and hits in learning mode, since they'll get picked up anyways.
                 if ($logTimeMicroseconds <= $lastAttackMicroseconds || $learningMode) {
                     continue;
                 }
                 $hit = new wfRequestModel();
                 $hit->attackLogTime = $logTimeMicroseconds;
                 $hit->statusCode = 403;
                 $hit->ctime = $requestTime;
                 $hit->IP = wfUtils::inet_pton($ip);
                 if (preg_match('/user\\-agent:(.*?)\\n/i', $requestString, $matches)) {
                     $hit->UA = trim($matches[1]);
                     $hit->isGoogle = wfCrawl::isGoogleCrawler($hit->UA);
                 }
                 if (preg_match('/Referer:(.*?)\\n/i', $requestString, $matches)) {
                     $hit->referer = trim($matches[1]);
                 }
                 if (preg_match('/^[a-z]+\\s+(.*?)\\s+/i', $requestString, $uriMatches) && preg_match('/Host:(.*?)\\n/i', $requestString, $hostMatches)) {
                     $hit->URL = 'http' . ($ssl ? 's' : '') . '://' . trim($hostMatches[1]) . trim($uriMatches[1]);
                 }
                 if (preg_match('/cookie:(.*?)\\n/i', $requestString, $matches)) {
                     $hit->newVisit = strpos($matches[1], 'wfvt_' . crc32(site_url())) !== false ? 1 : 0;
                     $hasVerifiedHumanCookie = strpos($matches[1], 'wordfence_verifiedHuman') !== false;
                     if ($hasVerifiedHumanCookie && preg_match('/wordfence_verifiedHuman=(.*?);/', $matches[1], $cookieMatches)) {
                         $hit->jsRun = (int) wp_verify_nonce($cookieMatches[1], 'wordfence_verifiedHuman' . $hit->UA . $ip);
                     }
                     $hasLoginCookie = strpos($matches[1], $ssl ? SECURE_AUTH_COOKIE : AUTH_COOKIE) !== false;
                     if ($hasLoginCookie && preg_match('/' . ($ssl ? SECURE_AUTH_COOKIE : AUTH_COOKIE) . '=(.*?);/', $matches[1], $cookieMatches)) {
                         $authCookie = rawurldecode($cookieMatches[1]);
                         $authID = $ssl ? wp_validate_auth_cookie($authCookie, 'secure_auth') : wp_validate_auth_cookie($authCookie, 'auth');
                         if ($authID) {
                             $hit->userID = $authID;
                         }
                     }
                 }
                 $path = '/';
                 if (preg_match('/^[A-Z]+ (.*?) HTTP\\/1\\.1/', $requestString, $matches)) {
                     if (($pos = strpos($matches[1], '?')) !== false) {
                         $path = substr($matches[1], 0, $pos);
                     } else {
                         $path = $matches[1];
                     }
                 }
                 $hit->action = 'blocked:waf';
                 /** @var wfWAFRule $rule */
                 $ruleIDs = explode('|', $failedRules);
                 $actionData = array('learningMode' => $learningMode, 'failedRules' => $failedRules, 'paramKey' => $paramKey, 'paramValue' => $paramValue, 'path' => $path);
                 if ($ruleIDs && $ruleIDs[0]) {
                     $rule = $waf->getRule($ruleIDs[0]);
                     if ($rule) {
                         $hit->actionDescription = $rule->getDescription();
                         $actionData['category'] = $rule->getCategory();
                         $actionData['ssl'] = $ssl;
                         $actionData['fullRequest'] = base64_encode($requestString);
                     }
                 }
                 $hit->actionData = wfRequestModel::serializeActionData($actionData);
                 $hit->save();
                 self::scheduleSendAttackData();
             }
         }
         $waf->getStorageEngine()->truncateAttackData();
     }
     update_site_option('wordfence_syncingAttackData', 0);
     update_site_option('wordfence_syncAttackDataAttempts', 0);
     if ($exit) {
         exit;
     }
 }
 /**
  * This happens only if allow_facebook_registration is true.
  */
 function handle_fb_session_state()
 {
     if (wp_validate_auth_cookie('')) {
         return $this->handle_fb_auth_tokens();
     }
     $fb_user = $this->model->fb->getUser();
     if ($fb_user) {
         $user_id = $this->model->get_wp_user_from_fb();
         if (!$user_id) {
             $user_id = $this->model->map_fb_to_current_wp_user();
         }
         if ($user_id) {
             $user = get_userdata($user_id);
             /*
             if (is_multisite() && function_exists('is_user_member_of_blog')) {
             	if (!is_user_member_of_blog($user_id)) return false; // Don't allow this
             }
             */
             wp_set_current_user($user->ID, $user->user_login);
             wp_set_auth_cookie($user->ID);
             // Logged in with Facebook, yay
             do_action('wp_login', $user->user_login);
             $this->handle_fb_auth_tokens();
             if (!(defined('DOING_AJAX') && isset($_REQUEST['action']) && 'wdfb_perhaps_create_wp_user' == $_REQUEST['action'])) {
                 wp_redirect(admin_url());
                 exit;
             }
         }
     }
 }
Esempio n. 13
0
if (!defined('WP_ADMIN')) {
    define('WP_ADMIN', true);
}
if (defined('ABSPATH')) {
    require_once ABSPATH . 'wp-load.php';
} else {
    require_once dirname(dirname(__FILE__)) . '/wp-load.php';
}
/** Allow for cross-domain requests (from the front end). */
send_origin_headers();
require_once ABSPATH . 'wp-admin/includes/admin.php';
nocache_headers();
/** This action is documented in wp-admin/admin.php */
do_action('admin_init');
$action = empty($_REQUEST['action']) ? '' : $_REQUEST['action'];
if (!wp_validate_auth_cookie()) {
    if (empty($action)) {
        /**
         * Fires on a non-authenticated admin post request where no action was supplied.
         *
         * @since 2.6.0
         */
        do_action('admin_post_nopriv');
    } else {
        /**
         * Fires on a non-authenticated admin post request for the given action.
         *
         * The dynamic portion of the hook name, `$action`, refers to the given
         * request action.
         *
         * @since 2.6.0
 /**
  * Checks if a user is logged in, if not it redirects them to the login page.
  *
  * @param none
  * @return void
  */
 function auth_redirect()
 {
     if ($this->is_ssl() || force_ssl_admin()) {
         $secure = true;
     } else {
         $secure = false;
     }
     // If https is required and request is http, redirect
     if ($secure && !$this->is_ssl() && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin')) {
         $this->redirect('https');
     }
     if ($user_id = wp_validate_auth_cookie('', apply_filters('auth_redirect_scheme', ''))) {
         do_action('auth_redirect', $user_id);
         // If the user wants ssl but the session is not ssl, redirect.
         if (!$secure && get_user_option('use_ssl', $user_id) && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin')) {
             $this->redirect('https');
         }
         return;
         // The cookie is good so we're done
     }
     // The cookie is no good so force login
     nocache_headers();
     if ($this->is_ssl()) {
         $proto = 'https://';
     } else {
         $proto = 'http://';
     }
     $redirect = strpos($_SERVER['REQUEST_URI'], '/admin.php') && wp_get_referer() ? wp_get_referer() : $proto . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
     // Rewrite URL to Shared SSL URL
     if ($this->shared_ssl && strpos($redirect, 'https://') !== false) {
         $redirect = $this->replace_http_url($redirect);
     }
     $login_url = wp_login_url($redirect);
     wp_redirect($login_url);
     exit;
 }
Esempio n. 15
0
 /**
  * Set headers and cookies.
  *
  * @since 1.1.0
  */
 protected function set_headers_cookies()
 {
     if (!$this->options_handler->is_enabled('enable_cache') || $this->is_url_blacklisted()) {
         header('X-Cache-Enabled: False');
         return;
     }
     header('X-Cache-Enabled: True');
     // Check if WP LOGGED_IN_COOKIE is set, validate it and define $userIsLoggedIn
     if (isset($_COOKIE[LOGGED_IN_COOKIE])) {
         $userIsLoggedIn = wp_validate_auth_cookie($_COOKIE[LOGGED_IN_COOKIE], 'logged_in');
     } else {
         $userIsLoggedIn = false;
     }
     // Logged In Users
     if ($userIsLoggedIn || !empty($_POST['wp-submit']) && 'Log In' === $_POST['wp-submit']) {
         // Enable the cache bypass for logged users by setting a cache bypass cookie
         setcookie('wpSGCacheBypass', 1, time() + 100 * MINUTE_IN_SECONDS, '/');
     } elseif (!$userIsLoggedIn || 'logout' === $_GET['action']) {
         setcookie('wpSGCacheBypass', 0, time() - HOUR_IN_SECONDS, '/');
     }
 }
 /**
  * Register a form
  * 
  * @param unknown_type $newforms
  * @return array
  */
 function bum_register_form($newforms = null)
 {
     static $forms;
     if (!isset($forms)) {
         $forms = array();
     }
     if (is_null($newforms)) {
         return $forms;
     }
     //initializing variables
     $defaults = array('action' => 'example-form', 'redirect_to' => false, 'current_user_can' => 'edit_posts', 'is_user_logged_in' => true, 'validate' => false, 'delete' => false, 'user_ip' => $_SERVER['REMOTE_ADDR'], 'send_email' => false, 'ID' => false, 'post_title' => "", 'post_parent' => 0, 'post_status' => 'pending', 'post_category' => '', 'comment_status' => 'open', 'tags_input' => "", 'post_type' => 'post', 'post_name' => "", 'post_content' => '', 'post_excerpt' => "", 'post_author' => wp_validate_auth_cookie(), 'ping_status' => get_option('default_ping_status'), 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'post_date' => date('Y-m-d H:i:s', time()), 'post_date_gmt' => date('Y-m-d H:i:s', time()));
     $newforms = wp_parse_args($newforms, $defaults);
     $forms[$newforms['action']] = $newforms;
     return true;
 }
/**
 * Checks if a user is logged in, if not it redirects them to the login page.
 *
 * @since 1.5
 */
function auth_redirect() {
	// Checks if a user is logged in, if not redirects them to the login page

	if ( is_ssl() || force_ssl_admin() )
		$secure = true;
	else
		$secure = false;

	// If https is required and request is http, redirect
	if ( $secure && !is_ssl() && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
		if ( 0 === strpos($_SERVER['REQUEST_URI'], 'http') ) {
			wp_redirect(preg_replace('|^http://|', 'https://', $_SERVER['REQUEST_URI']));
			exit();
		} else {
			wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
			exit();
		}
	}

	if ( $user_id = wp_validate_auth_cookie() ) {
		// If the user wants ssl but the session is not ssl, redirect.
		if ( !$secure && get_user_option('use_ssl', $user_id) && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
			if ( 0 === strpos($_SERVER['REQUEST_URI'], 'http') ) {
				wp_redirect(preg_replace('|^http://|', 'https://', $_SERVER['REQUEST_URI']));
				exit();
			} else {
				wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
				exit();
			}
		}

		return;  // The cookie is good so we're done
	}

	// The cookie is no good so force login
	nocache_headers();

	if ( is_ssl() )
		$proto = 'https://';
	else
		$proto = 'http://';

	$redirect = ( strpos($_SERVER['REQUEST_URI'], '/options.php') && wp_get_referer() ) ? wp_get_referer() : $proto . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

	$login_url = site_url( 'wp-login.php?redirect_to=' . urlencode( $redirect ), 'login' );

	wp_redirect($login_url);
	exit();
}
 /**
  * Is it a good time to check for updates?
  *
  * @return bool
  */
 private function can_update()
 {
     // Don't check for updates on wp-login.php, this happens when you request
     // an admin page but are not logged in and then redirected to wp-login.php
     if (false === wp_validate_auth_cookie()) {
         return false;
     }
     // Don't run on plugin activation/deactivation, request will seem slow
     foreach (array('activate', 'deactivate', 'activate-multi', 'deactivate-multi') as $key) {
         if (array_key_exists($key, $_REQUEST)) {
             return false;
         }
     }
     // Don't check for updates on the following actions
     $actions = array('hmwp_ms_upgrade_diff', 'hmwp_ms_upgrade', 'hmwp_ms_upgrade_run', 'activate', 'deactivate', 'activate-selected', 'deactivate-selected');
     if (in_array(HMWP_MS_Utils::get('action'), $actions)) {
         return false;
     }
     return true;
 }
Esempio n. 19
0
function get_currentuserinfo() {
	global $current_user;
	global $xoopsModule,$xoopsUser,$xoopsUserIsAdmin;


	if ($xoopsModule){
		if ( defined('XMLRPC_REQUEST') && XMLRPC_REQUEST )
			return false;

		if (is_object($xoopsUser)){			// When the user is logging in xoops
			if ( ! empty($current_user) ){
				$xoops_user = $xoopsUser->getVar("uname");
				if ($current_user->user_login == $xoops_user){	// If xoops login user and wordpress current user are the same
					return;
				}
			}
			if (check_xpress_auth_cookie()){	//The cookie is login user's or it checks it
				if (function_exists('wp_validate_auth_cookie')){
					if ( $user = wp_validate_auth_cookie() ) {
						// When the user meta prefix is different according to the change in the xoops data base prefix, it restores it. 
						if (!check_user_meta_prefix($user)){
							repair_user_meta_prefix();
						}
						wp_set_current_user($user);
						return ;
					}
				} else { // for WP2.0					
					if ( !empty($_COOKIE[USER_COOKIE]) && !empty($_COOKIE[PASS_COOKIE])){
						if(wp_login($_COOKIE[USER_COOKIE], $_COOKIE[PASS_COOKIE], true) ) {
							$user_login = $_COOKIE[USER_COOKIE];
							wp_set_current_user(0, $user_login);
							return;
						}
					}
				}
			}				
			return xpress_login();	
		} else {							// For the xoops guest
			if ( ! empty($current_user) ){	// When a current user of wordpress is set, a current user is cleared. 
				wp_set_current_user(0);
				wp_logout();
				wp_clear_auth_cookie();
			}
			return false;
		}
	} else {
		// WP original
		if ( defined('XMLRPC_REQUEST') && XMLRPC_REQUEST )
			return false;

		if ( ! empty($current_user) )
			return;

		if (function_exists('wp_validate_auth_cookie')){
			if ( ! $user = wp_validate_auth_cookie() ) {
				 if ( empty($_COOKIE[LOGGED_IN_COOKIE]) || !$user = wp_validate_auth_cookie($_COOKIE[LOGGED_IN_COOKIE], 'logged_in') ) {
				 	wp_set_current_user(0);
				 	return false;
				 }
			}
			wp_set_current_user($user);
		} else { // for WP2.0
			if ( empty($_COOKIE[USER_COOKIE]) || empty($_COOKIE[PASS_COOKIE]) || 
				!wp_login($_COOKIE[USER_COOKIE], $_COOKIE[PASS_COOKIE], true) ) {
				wp_set_current_user(0);
				return false;
			}
			$user_login = $_COOKIE[USER_COOKIE];
			wp_set_current_user(0, $user_login);
		}
	}
}
Esempio n. 20
0
 /**
  * Validate the old_user cookie and return its user data.
  *
  * @return bool|object False if there's no old_user cookie or it's invalid, WP_User object if it's present and valid.
  */
 function get_old_user()
 {
     if (isset($_COOKIE[OLDUSER_COOKIE])) {
         if ($old_user_id = wp_validate_auth_cookie($_COOKIE[OLDUSER_COOKIE], 'old_user')) {
             return get_userdata($old_user_id);
         }
     }
     return false;
 }
Esempio n. 21
0
 /**
  * Checks if a user is logged in, if not it redirects them to the login page.
  *
  * @since 1.5
  */
 function auth_redirect()
 {
     // Checks if a user is logged in, if not redirects them to the login page
     if (is_ssl() || force_ssl_admin()) {
         $secure = true;
     } else {
         $secure = false;
     }
     // If https is required and request is http, redirect
     if ($secure && !is_ssl()) {
         if (0 === strpos($_SERVER['REQUEST_URI'], 'http')) {
             wp_redirect(preg_replace('|^http://|', 'https://', $_SERVER['REQUEST_URI']));
             exit;
         } else {
             wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
             exit;
         }
     }
     if (wp_validate_auth_cookie()) {
         return;
     }
     // The cookie is good so we're done
     // The cookie is no good so force login
     nocache_headers();
     if (is_ssl()) {
         $proto = 'https://';
     } else {
         $proto = 'http://';
     }
     $login_url = site_url('wp-login.php?redirect_to=' . urlencode($proto . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']), 'login');
     wp_redirect($login_url);
     exit;
 }
Esempio n. 22
0
 /**
  * @see UGD_Login_Module_Interface::isAuthenticated()
  *
  */
 public function isAuthenticated()
 {
     return wp_validate_auth_cookie();
 }
/**
 * Get the current user
 * 
 * Function is responsible for creating and returning the user object
 * 
 * @since 1.0
 * @param $userid
 * @return global object reference
 */
function &get_user($userid = null)
{
    //initializing variables
    static $users;
    if (is_null($users)) {
        $users = array();
    }
    //loading library
    require_once ABSPATH . WPINC . DS . 'pluggable.php';
    //if we want the logged in user
    if (is_null($userid)) {
        if (!($user = wp_validate_auth_cookie())) {
            if (is_admin() || empty($_COOKIE[LOGGED_IN_COOKIE]) || !($user = wp_validate_auth_cookie($_COOKIE[LOGGED_IN_COOKIE], 'logged_in'))) {
                $userid = 0;
            }
        }
        $userid = $user;
    }
    //if we're wanting to standardize the userid
    if (is_object($userid) && isset($userid->ID)) {
        $userid = $userid->ID;
    }
    if (!isset($users[$userid])) {
        $user = new WP_User($userid);
        $users[$userid] =& $user;
    }
    return $users[$userid];
}
Esempio n. 24
0
/**
 * Validate the logged-in cookie.
 *
 * Checks the logged-in cookie if the previous auth cookie could not be
 * validated and parsed.
 *
 * This is a callback for the determine_current_user filter, rather than API.
 *
 * @since 3.9.0
 *
 * @param int|bool $user_id The user ID (or false) as received from the
 *                       determine_current_user filter.
 * @return int|false User ID if validated, false otherwise. If a user ID from
 *                   an earlier filter callback is received, that value is returned.
 */
function wp_validate_logged_in_cookie($user_id)
{
    if ($user_id) {
        return $user_id;
    }
    if (is_blog_admin() || is_network_admin() || empty($_COOKIE[LOGGED_IN_COOKIE])) {
        return false;
    }
    return wp_validate_auth_cookie($_COOKIE[LOGGED_IN_COOKIE], 'logged_in');
}
Esempio n. 25
0
 /**
  * Checks if a user is logged in, if not it redirects them to the login page.
  *
  * @since 1.5.0
  */
 function auth_redirect()
 {
     // Checks if a user is logged in, if not redirects them to the login page
     $secure = is_ssl() || force_ssl_admin();
     /**
      * Filter whether to use a secure authentication redirect.
      *
      * @since 3.1.0
      *
      * @param bool $secure Whether to use a secure authentication redirect. Default false.
      */
     $secure = apply_filters('secure_auth_redirect', $secure);
     // If https is required and request is http, redirect
     if ($secure && !is_ssl() && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin')) {
         if (0 === strpos($_SERVER['REQUEST_URI'], 'http')) {
             wp_redirect(set_url_scheme($_SERVER['REQUEST_URI'], 'https'));
             exit;
         } else {
             wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
             exit;
         }
     }
     if (is_user_admin()) {
         $scheme = 'logged_in';
     } else {
         /**
          * Filter the authentication redirect scheme.
          *
          * @since 2.9.0
          *
          * @param string $scheme Authentication redirect scheme. Default empty.
          */
         $scheme = apply_filters('auth_redirect_scheme', '');
     }
     if ($user_id = wp_validate_auth_cookie('', $scheme)) {
         /**
          * Fires before the authentication redirect.
          *
          * @since 2.8.0
          *
          * @param int $user_id User ID.
          */
         do_action('auth_redirect', $user_id);
         // If the user wants ssl but the session is not ssl, redirect.
         if (!$secure && get_user_option('use_ssl', $user_id) && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin')) {
             if (0 === strpos($_SERVER['REQUEST_URI'], 'http')) {
                 wp_redirect(set_url_scheme($_SERVER['REQUEST_URI'], 'https'));
                 exit;
             } else {
                 wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
                 exit;
             }
         }
         return;
         // The cookie is good so we're done
     }
     // The cookie is no good so force login
     nocache_headers();
     $redirect = strpos($_SERVER['REQUEST_URI'], '/options.php') && wp_get_referer() ? wp_get_referer() : set_url_scheme('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
     $login_url = wp_login_url($redirect, true);
     wp_redirect($login_url);
     exit;
 }
Esempio n. 26
0
 /**
  * Produces a token based on the current user.
  *
  * @since 140422 First documented version.
  *
  * @return string Produces a token based on the current user;
  *    else an empty string if that's not possible to do.
  *
  * @note The return value of this function is cached to reduce overhead on repeat calls.
  *
  * @note This routine may trigger a flag which indicates that the current user was logged-in at some point,
  *    but now the login cookie can no longer be validated by WordPress; i.e. they are NOT actually logged in any longer.
  *    See {@link $user_login_cookie_expired_or_invalid}
  *
  * @warning Do NOT call upon this method until WordPress reaches it's cache postload phase.
  */
 public function user_token()
 {
     if (isset(static::$static[__FUNCTION__])) {
         return static::$static[__FUNCTION__];
     }
     $wp_validate_auth_cookie_possible = $this->function_is_possible('wp_validate_auth_cookie');
     if ($wp_validate_auth_cookie_possible && ($user_id = (int) wp_validate_auth_cookie('', 'logged_in'))) {
         return static::$static[__FUNCTION__] = $user_id;
     } else {
         if (!empty($_COOKIE['comment_author_email_' . COOKIEHASH]) && is_string($_COOKIE['comment_author_email_' . COOKIEHASH])) {
             return static::$static[__FUNCTION__] = md5(strtolower(stripslashes($_COOKIE['comment_author_email_' . COOKIEHASH])));
         } else {
             if (!empty($_COOKIE['wp-postpass_' . COOKIEHASH]) && is_string($_COOKIE['wp-postpass_' . COOKIEHASH])) {
                 return static::$static[__FUNCTION__] = md5(stripslashes($_COOKIE['wp-postpass_' . COOKIEHASH]));
             } else {
                 if (defined('SID') && SID) {
                     return static::$static[__FUNCTION__] = preg_replace('/[^a-z0-9]/i', '', SID);
                 }
             }
         }
     }
     if ($wp_validate_auth_cookie_possible && !empty($_COOKIE['wordpress_logged_in_' . COOKIEHASH]) && is_string($_COOKIE['wordpress_logged_in_' . COOKIEHASH])) {
         $this->user_login_cookie_expired_or_invalid = TRUE;
     }
     // Flag as `TRUE`.
     return static::$static[__FUNCTION__] = '';
 }
Esempio n. 27
0
 public function post_comment()
 {
     global $json_api;
     if (!$json_api->query->cookie) {
         $json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` method.");
     }
     $user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
     if (!$user_id) {
         $json_api->error("Invalid cookie. Use the `generate_auth_cookie` method.");
     }
     if (!$json_api->query->post_id) {
         $json_api->error("No post specified. Include 'post_id' var in your request.");
     } elseif (!$json_api->query->content) {
         $json_api->error("Please include 'content' var in your request.");
     }
     if (!$json_api->query->comment_status) {
         $json_api->error("Please include 'comment_status' var in your request. Possible values are '1' (approved) or '0' (not-approved)");
     } else {
         $comment_approved = $json_api->query->comment_status;
     }
     $user_info = get_userdata($user_id);
     $time = current_time('mysql');
     $agent = $_SERVER['HTTP_USER_AGENT'];
     $ip = $_SERVER['REMOTE_ADDR'];
     $data = array('comment_post_ID' => $json_api->query->post_id, 'comment_author' => $user_info->user_login, 'comment_author_email' => $user_info->user_email, 'comment_author_url' => $user_info->user_url, 'comment_content' => $json_api->query->content, 'comment_type' => '', 'comment_parent' => 0, 'user_id' => $user_info->ID, 'comment_author_IP' => $ip, 'comment_agent' => $agent, 'comment_date' => $time, 'comment_approved' => $comment_approved);
     //print_r($data);
     $comment_id = wp_insert_comment($data);
     return array("comment_id" => $comment_id);
 }
Esempio n. 28
0
 /**
  * Authenticate an old user by verifying the latest entry in the auth cookie.
  *
  * @param  WP_User $user A WP_User object (usually from the logged_in cookie).
  * @return bool Whether verification with the auth cookie passed.
  */
 public static function authenticate_old_user(WP_User $user)
 {
     $cookie = user_switching_get_auth_cookie();
     if (!empty($cookie)) {
         if (user_switching::secure_auth_cookie()) {
             $scheme = 'secure_auth';
         } else {
             $scheme = 'auth';
         }
         if ($old_user_id = wp_validate_auth_cookie(end($cookie), $scheme)) {
             return $user->ID === $old_user_id;
         }
     }
     return false;
 }
Esempio n. 29
0
/**
 * Authenticate the user using the WordPress auth cookie.
 */
function wp_authenticate_cookie($user, $username, $password)
{
    if (is_a($user, 'WP_User')) {
        return $user;
    }
    if (empty($username) && empty($password)) {
        $user_id = wp_validate_auth_cookie();
        if ($user_id) {
            return new WP_User($user_id);
        }
        global $auth_secure_cookie;
        if ($auth_secure_cookie) {
            $auth_cookie = SECURE_AUTH_COOKIE;
        } else {
            $auth_cookie = AUTH_COOKIE;
        }
        if (!empty($_COOKIE[$auth_cookie])) {
            return new WP_Error('expired_session', __('Please log in again.'));
        }
        // If the cookie is not set, be silent.
    }
    return $user;
}
 public static function syncAttackData($exit = true)
 {
     global $wpdb;
     $waf = wfWAF::getInstance();
     $lastAttackMicroseconds = $wpdb->get_var("SELECT MAX(attackLogTime) FROM {$wpdb->base_prefix}wfHits");
     if ($waf->getStorageEngine()->hasNewerAttackData($lastAttackMicroseconds)) {
         $attackData = $waf->getStorageEngine()->getNewestAttackDataArray($lastAttackMicroseconds);
         if ($attackData) {
             foreach ($attackData as $request) {
                 if (count($request) !== 9 && count($request) !== 10) {
                     continue;
                 }
                 list($logTimeMicroseconds, $requestTime, $ip, $learningMode, $paramKey, $paramValue, $failedRules, $ssl, $requestString, $metadata) = $request;
                 // Skip old entries and hits in learning mode, since they'll get picked up anyways.
                 if ($logTimeMicroseconds <= $lastAttackMicroseconds || $learningMode) {
                     continue;
                 }
                 $hit = new wfRequestModel();
                 $hit->attackLogTime = $logTimeMicroseconds;
                 $hit->statusCode = 403;
                 $hit->ctime = $requestTime;
                 $hit->IP = wfUtils::inet_pton($ip);
                 if (preg_match('/user\\-agent:(.*?)\\n/i', $requestString, $matches)) {
                     $hit->UA = trim($matches[1]);
                     $hit->isGoogle = wfCrawl::isGoogleCrawler($hit->UA);
                 }
                 if (preg_match('/Referer:(.*?)\\n/i', $requestString, $matches)) {
                     $hit->referer = trim($matches[1]);
                 }
                 if (preg_match('/^[a-z]+\\s+(.*?)\\s+/i', $requestString, $uriMatches) && preg_match('/Host:(.*?)\\n/i', $requestString, $hostMatches)) {
                     $hit->URL = 'http' . ($ssl ? 's' : '') . '://' . trim($hostMatches[1]) . trim($uriMatches[1]);
                 }
                 if (preg_match('/cookie:(.*?)\\n/i', $requestString, $matches)) {
                     $hit->newVisit = strpos($matches[1], 'wfvt_' . crc32(site_url())) !== false ? 1 : 0;
                     $hasVerifiedHumanCookie = strpos($matches[1], 'wordfence_verifiedHuman') !== false;
                     if ($hasVerifiedHumanCookie && preg_match('/wordfence_verifiedHuman=(.*?);/', $matches[1], $cookieMatches)) {
                         $hit->jsRun = (int) wp_verify_nonce($cookieMatches[1], 'wordfence_verifiedHuman' . $hit->UA . $ip);
                     }
                     $hasLoginCookie = strpos($matches[1], $ssl ? SECURE_AUTH_COOKIE : AUTH_COOKIE) !== false;
                     if ($hasLoginCookie && preg_match('/' . ($ssl ? SECURE_AUTH_COOKIE : AUTH_COOKIE) . '=(.*?);/', $matches[1], $cookieMatches)) {
                         $authCookie = rawurldecode($cookieMatches[1]);
                         $authID = $ssl ? wp_validate_auth_cookie($authCookie, 'secure_auth') : wp_validate_auth_cookie($authCookie, 'auth');
                         if ($authID) {
                             $hit->userID = $authID;
                         }
                     }
                 }
                 $path = '/';
                 if (preg_match('/^[A-Z]+ (.*?) HTTP\\/1\\.1/', $requestString, $matches)) {
                     if (($pos = strpos($matches[1], '?')) !== false) {
                         $path = substr($matches[1], 0, $pos);
                     } else {
                         $path = $matches[1];
                     }
                 }
                 $metadata = $metadata != null ? (array) $metadata : array();
                 if (isset($metadata['finalAction']) && $metadata['finalAction']) {
                     // The request was blocked/redirected because of its IP based on the plugin's blocking settings. WAF blocks should be reported but not shown in live traffic with that as a reason.
                     $action = $metadata['finalAction']['action'];
                     $actionDescription = $action;
                     if (class_exists('wfWAFIPBlocksController')) {
                         if ($action == wfWAFIPBlocksController::WFWAF_BLOCK_UAREFIPRANGE) {
                             $id = $metadata['finalAction']['id'];
                             $wpdb->query($wpdb->prepare("UPDATE {$wpdb->base_prefix}wfBlocksAdv SET totalBlocked = totalBlocked + 1, lastBlocked = %d WHERE id = %d", $requestTime, $id));
                             wfActivityReport::logBlockedIP($ip);
                         } else {
                             if ($action == wfWAFIPBlocksController::WFWAF_BLOCK_COUNTRY_REDIR) {
                                 $actionDescription .= ' (' . wfConfig::get('cbl_redirURL') . ')';
                                 wfConfig::inc('totalCountryBlocked');
                                 wfActivityReport::logBlockedIP($ip);
                             } else {
                                 if ($action == wfWAFIPBlocksController::WFWAF_BLOCK_COUNTRY) {
                                     wfConfig::inc('totalCountryBlocked');
                                     wfActivityReport::logBlockedIP($ip);
                                 } else {
                                     if ($action == wfWAFIPBlocksController::WFWAF_BLOCK_WFSN) {
                                         wordfence::wfsnReportBlockedAttempt($ip, 'login');
                                     }
                                 }
                             }
                         }
                     }
                     if (strlen($actionDescription) == 0) {
                         $actionDescription = 'Blocked by Wordfence';
                     }
                     if (empty($failedRules)) {
                         // Just a plugin block
                         $hit->action = 'blocked:wordfence';
                         if (class_exists('wfWAFIPBlocksController')) {
                             if ($action == wfWAFIPBlocksController::WFWAF_BLOCK_WFSN) {
                                 $hit->action = 'blocked:wfsnrepeat';
                             }
                         }
                         $hit->actionDescription = $actionDescription;
                     } else {
                         if ($failedRules == 'logged') {
                             $hit->action = 'logged:waf';
                         } else {
                             // Blocked by the WAF but would've been blocked anyway by the plugin settings so that message takes priority
                             $hit->action = 'blocked:waf-always';
                             $hit->actionDescription = $actionDescription;
                         }
                     }
                 } else {
                     if ($failedRules == 'logged') {
                         $hit->action = 'logged:waf';
                     } else {
                         $hit->action = 'blocked:waf';
                     }
                 }
                 /** @var wfWAFRule $rule */
                 $ruleIDs = explode('|', $failedRules);
                 $actionData = array('learningMode' => $learningMode, 'failedRules' => $failedRules, 'paramKey' => $paramKey, 'paramValue' => $paramValue, 'path' => $path);
                 if ($ruleIDs && $ruleIDs[0]) {
                     $rule = $waf->getRule($ruleIDs[0]);
                     if ($rule) {
                         if ($hit->action == 'logged:waf' || $hit->action == 'blocked:waf') {
                             $hit->actionDescription = $rule->getDescription();
                         }
                         $actionData['category'] = $rule->getCategory();
                         $actionData['ssl'] = $ssl;
                         $actionData['fullRequest'] = base64_encode($requestString);
                     } else {
                         if ($ruleIDs[0] == 'logged') {
                             if ($hit->action == 'logged:waf' || $hit->action == 'blocked:waf') {
                                 $hit->actionDescription = 'Watched IP Traffic: ' . $ip;
                             }
                             $actionData['category'] = 'logged';
                             $actionData['ssl'] = $ssl;
                             $actionData['fullRequest'] = base64_encode($requestString);
                         }
                     }
                 }
                 $hit->actionData = wfRequestModel::serializeActionData($actionData);
                 $hit->save();
                 self::scheduleSendAttackData();
             }
         }
         $waf->getStorageEngine()->truncateAttackData();
     }
     update_site_option('wordfence_syncingAttackData', 0);
     update_site_option('wordfence_syncAttackDataAttempts', 0);
     update_site_option('wordfence_lastSyncAttackData', time());
     if ($exit) {
         exit;
     }
 }