public function verify($password, $hash) { $key = hash(self::HASH_PRIMITIVE, $password, true); $hash = base64_decode($hash); $header = substr($hash, 0, self::HEADER_SIZE); $iv = substr($hash, self::HEADER_SIZE, self::IV_LENGTH); $ciphertext = substr($hash, self::HEADER_SIZE + self::IV_LENGTH); $decrypted = openssl_decrypt($ciphertext, self::CIPHER_PRIMITIVE, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv); list(, $version, $rounds, $pointerSize, $dataSize) = unpack('C*', $header); $iterationCount = pow(2, $rounds); $dataSizeDecoded = pow(2, $dataSize); if ($version !== 1) { throw new \RuntimeException("Unknown version encountered"); } if (strlen($decrypted) !== self::HASH_LENGTH + $iterationCount * $pointerSize) { throw new \RuntimeException("Invalid data payload, was it truncated?"); } $h = hash_init(self::HASH_PRIMITIVE); for ($i = 0; $i < $iterationCount; $i++) { $pointer = substr($decrypted, $i * $pointerSize, $pointerSize); hash_update($h, $this->read($pointer, $dataSizeDecoded)); } $test = hash_final($h, true); return hash_equals($test, substr($decrypted, $iterationCount * $pointerSize)); }
/** * Compares two strings. * * This method implements a constant-time algorithm to compare strings. * Regardless of the used implementation, it will leak length information. * * @param string $knownString The string of known length to compare against * @param string $userInput The string that the user can control * * @return bool true if the two strings are the same, false otherwise */ public static function equals($knownString, $userInput) { static $exists = null; if (null === $exists) { $exists = function_exists('hash_equals'); } $knownString = (string) $knownString; $userInput = (string) $userInput; if ($exists) { return hash_equals($knownString, $userInput); } $knownLen = strlen($knownString); $userLen = strlen($userInput); // Extend the known string to avoid uninitialized string offsets $knownString .= $userInput; // Set the result to the difference between the lengths $result = $knownLen - $userLen; // Note that we ALWAYS iterate over the user-supplied length // This is to mitigate leaking length information for ($i = 0; $i < $userLen; ++$i) { $result |= ord($knownString[$i]) ^ ord($userInput[$i]); } // They are only identical strings if $result is exactly 0... return 0 === $result; }
/** * To prevent timing attacks we are using PHP 5.6 native function hash_equals, * in case of PHP < 5.6 a timing safe equals comparison function * * more info here: * http://blog.ircmaxell.com/2014/11/its-all-about-time. * http://blog.ircmaxell.com/2014/11/its-all-about-time.html * * * @inheritdoc */ public function verify($key, $signature, $input) { $signedInput = $this->sign($input, $key); if (version_compare(PHP_VERSION, '5.6.0', '>=')) { return hash_equals($signature, $signedInput); } return $this->timingSafeEquals($signature, $signedInput); }
public function validateToken() { switch ($this->source) { case self::TYPE_STRIPE: if ('tok_' == substr($this->token, 0, 4)) { return TRUE; } break; case self::TYPE_COMP: $secret = $_ENV['TOK_SECRET_COMP']; goto join_COMPCASH; case self::TYPE_CASH: $secret = $_ENV['TOK_SECRET_CASH']; join_COMPCASH: if (FALSE === ($sepPos = strpos($this->token, ':'))) { break; } $inputSecret = substr($this->token, 0, $sepPos); if (hash_equals($secret, $inputSecret)) { return TRUE; } break; default: break; } throw new BookingTokenException("Invalid token"); }
/** * Validate valid CSRF token * * @param string $token * @return bool */ public function validate($token) { if ($token !== null && $this->getToken() !== null) { return hash_equals($token, $this->getToken()); } return false; }
/** * Decrypt a string. * * @access public * @static static method * @param string $ciphertext * @return string * @throws Exception If $ciphertext is empty, or If functions don't exists */ public static function decrypt($ciphertext) { if (empty($ciphertext)) { throw new Exception("the string to decrypt can't be empty"); } if (!function_exists('openssl_cipher_iv_length') || !function_exists('openssl_decrypt')) { throw new Exception("Encryption function don't exists"); } // generate key used for authentication using ENCRYPTION_KEY & HMAC_SALT $key = mb_substr(hash(self::HASH_FUNCTION, Config::get('ENCRYPTION_KEY') . Config::get('HMAC_SALT')), 0, 32, '8bit'); // split cipher into: hmac, cipher & iv $macSize = 64; $hmac = mb_substr($ciphertext, 0, $macSize, '8bit'); $iv_cipher = mb_substr($ciphertext, $macSize, null, '8bit'); // generate original hmac & compare it with the one in $ciphertext $originalHmac = hash_hmac('sha256', $iv_cipher, $key); if (!function_exists("hash_equals")) { throw new Exception("Function hash_equals() doesn't exist!"); } if (!hash_equals($hmac, $originalHmac)) { return false; } // split out the initialization vector and cipher $iv_size = openssl_cipher_iv_length(self::CIPHER); $iv = mb_substr($iv_cipher, 0, $iv_size, '8bit'); $cipher = mb_substr($iv_cipher, $iv_size, null, '8bit'); return openssl_decrypt($cipher, self::CIPHER, $key, OPENSSL_RAW_DATA, $iv); }
public static function checkPasswordForUser($password, UserEntity $user) { if (hash_equals($user->getPassword(), crypt($password, $user->getPassword()))) { return true; } return false; }
public function validateHash($hash, $password) { if (hash_equals($hash, crypt($password, $hash))) { return true; } return false; }
public function hashCheck($known, $user) { if (function_exists('hash_equals')) { return hash_equals($known, $user); } return $this->hash_equals($known, $user); }
public static function check($userToken) { if ($sessionToken = Session::get('csrf_token')) { return hash_equals($sessionToken, $userToken); } return false; }
/** * Prepare a single user output for response * * @param object $user User object. * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response data. */ public function prepare_item_for_response($user, $request) { $roles = $user->roles; if (empty($roles)) { $isadmin = false; } else { $isadmin = hash_equals($roles[0], 'administrator'); } $user_id = $user->ID; $user_blogs = get_blogs_of_user($user_id); $site = urldecode($request['site']); $data = array('id' => $user->ID, 'username' => $user->user_login, 'name' => $user->display_name, 'email' => $user->user_email, 'admin' => $isadmin, 'role' => $roles[0], 'site' => $_SERVER['SERVER_NAME'], 'host' => $_SERVER['HTTP_HOST'], 'blogs' => $user_blogs); $context = !empty($request['context']) ? $request['context'] : 'embed'; $data = $this->filter_response_by_context($data, $context); $data = $this->add_additional_fields_to_object($data, $request); // Wrap the data in a response object $response = rest_ensure_response($data); //$response->add_links( $this->prepare_links( $user ) ); /** * Filter user data returned from the REST API. * * @param WP_REST_Response $response The response object. * @param object $user User object used to create response. * @param WP_REST_Request $request Request object. */ return apply_filters('rest_prepare_user', $response, $user, $request); }
/** * Install constructor. * * @param \Twig_Environment $twig * @param array $data */ public function __construct(\Twig_Environment $twig, array $data = []) { if (!Halite::isLibsodiumSetupCorrectly()) { echo \file_get_contents(\dirname(__DIR__) . '/error_pages/old-libsodium.html'); exit(255); } $this->twig = $twig; $this->data = $data; $this->data['airship_version'] = \AIRSHIP_VERSION; $this->csrf = new CSRF(); // We do this to prevent someone from coming along and reading your // half-finished configuration settings (e.g. database passwords): if (empty($this->data['step'])) { $this->data['step'] = 1; } if (empty($this->data['token'])) { $this->data['token'] = Base64::encode(\random_bytes(33)); \setcookie('installer', $this->data['token'], \time() + 8640000, '/'); \Airship\redirect('/'); } elseif (empty($_COOKIE['installer'])) { echo 'No installer authorization token found.', "\n"; exit(255); } elseif (!\hash_equals($this->data['token'], $_COOKIE['installer'])) { // This effectively locks unauthorized users out of the system while installing echo 'Invalid installer authorization token.', "\n"; exit(255); } $dirs = ['comments', 'csp_hash', 'csp_static', 'hash', 'markdown', 'static', 'twig']; foreach ($dirs as $d) { if (!\is_dir(\dirname(__DIR__) . '/tmp/cache/' . $d)) { \mkdir(\dirname(__DIR__) . '/tmp/cache/' . $d, 0775, true); } } }
/** * Decodes JSON Web Token and set data in payload attribute. * * @return bool Indicate if token is valid */ public function decode() { $elements = explode('.', $this->value); if (count($elements) !== 3) { //invalid token format return false; } list($b64Header, $b64Payload, $b64Signature) = $elements; $headers = json_decode(base64_decode($b64Header)); $payload = json_decode(base64_decode($b64Payload)); $signature = base64_decode($b64Signature); //check header if (!$headers || !property_exists($headers, 'alg') || $headers->alg !== 'HS256' || !property_exists($headers, 'typ') || $headers->typ !== 'JWT') { //invalid header return false; } //check signature if (!$signature || !hash_equals($signature, hash_hmac('sha256', $b64Header . '.' . $b64Payload, $this->key, true))) { //invalid signature return false; } if (!$payload || !property_exists($payload, 'exp') || $payload->exp < time()) { //token expired return false; } $this->payload = $payload; //raw data is set, returns true return true; }
/** * {@inheritDoc} */ public function authenticate(RequestInterface $request) { $authHeader = AuthorizationHeader::createFromRequest($request); $signature = $authHeader->getSignature(); // Check whether the timestamp is valid. $comparison = $this->compareTimestamp($request, $this->expiry); if (-1 == $comparison) { throw new TimestampOutOfRangeException('Request is too old'); } elseif (1 == $comparison) { throw new TimestampOutOfRangeException('Request is too far in the future'); } // Load the API Key and sign the request. if (!($key = $this->keyLoader->load($authHeader->getId()))) { throw new KeyNotFoundException('API key not found'); } // Generate the signature from the passed authorization header. // If it matches the request signature, the request is authenticated. $compareRequest = $request->withoutHeader('Authorization'); $authHeaderBuilder = new AuthorizationHeaderBuilder($compareRequest, $key); $authHeaderBuilder->setRealm($authHeader->getRealm()); $authHeaderBuilder->setId($authHeader->getId()); $authHeaderBuilder->setNonce($authHeader->getNonce()); $authHeaderBuilder->setVersion($authHeader->getVersion()); $authHeaderBuilder->setCustomHeaders($authHeader->getCustomHeaders()); $compareAuthHeader = $authHeaderBuilder->getAuthorizationHeader(); $compareSignature = $compareAuthHeader->getSignature(); if (!hash_equals($compareSignature, $signature)) { throw new InvalidSignatureException('Signature not valid'); } return $key; }
/** * @Route("/album/{id}/download", requirements={ * "id": "\d+" * }) * @Method({"GET", "OPTIONS"}) */ public function downloadAlbumAction(Request $request, Album $album) { // Verify token $secret = $uploadDir = $this->getParameter('secret') . '54 90df2!!fh++ gGZ)='; $date = new \DateTime(); $time = $date->format('d-m-Y H:i'); $correct = hash('sha256', $secret . $time . $album->getId()); $token = $request->query->get('token'); if ($token === null) { $token = ''; } if (!hash_equals($correct, $token)) { return new JsonResponse(array('message' => 'Invalid token.'), 403); } $uploadDir = $this->getParameter('photo_upload_dir'); $filename = $uploadDir . '/' . $album->getId() . '-' . $album->getTitle() . '.zip'; $zip = new \ZipArchive(); if ($zip->open($filename, \ZipArchive::CREATE) !== true) { throw new Exception('Cannot open or create ZIP archive for file ' . $filename); } foreach ($album->getPhotos() as $photo) { if ($zip->locateName($photo->getFilename()) === false) { $zip->addFile($uploadDir . '/' . $photo->getFilename(), $photo->getFilename()); } } $zip->close(); $response = new BinaryFileResponse($filename); $response->headers->set('Content-disposition', 'attachment;filename="' . $album->getTitle() . '.zip"'); return $response; }
/** * @param Registry $registry * @param callable|null $secretValidator */ public function __construct(Registry $registry, callable $secretValidator = null) { $this->registry = $registry; $this->secretValidator = $secretValidator ?: function ($expected, $actual) { return hash_equals($expected, $actual); }; }
/** * {@inheritdoc} */ public function verify(JWKInterface $key, $input, $signature) { if (function_exists('hash_equals')) { return hash_equals($signature, $this->sign($key, $input)); } return $this->timingSafeEquals($signature, $this->sign($key, $input)); }
/** * Actives user by using a key * * @param string $key * Key to use for activation */ public function activateUser($key) { // Get tokendate from db $tokenhandler = new ActivationToken($this->db); $tokenhandler->setSelectorTokenString($key); // Store the current to extracted from selector:token string ($key) $token_from_key = $tokenhandler->getToken(); // Load the tokendata by using the selector from selector:token string ($key) $tokenhandler->loadTokenData(); // Get user id $id_user = $tokenhandler->getUserId(); // No user id means the activation must fail if (empty($id_user)) { return false; } // Get the token loaded from db via selector from selector:token string ($key) $token_from_db = $tokenhandler->getToken(); // Matching hashes? if (!hash_equals($token_from_key, $token_from_db)) { return false; } // Activate user $this->db->qb(['table' => 'core_users', 'method' => 'UPDATE', 'fields' => 'state', 'filter' => 'id_user=:id_user', 'params' => [':state' => 0, ':id_user' => $id_user]], true); // and delete the token of this user $tokenhandler->deleteActivationTokenByUserId($id_user); // And finally return user id return $id_user; }
/** * {@inheritdoc} */ public function isTokenValid(CsrfToken $token) { if (!$this->storage->hasToken($token->getId())) { return false; } return hash_equals($this->storage->getToken($token->getId()), $token->getValue()); }
function login($email, $pass) { if (($entry = $this->get($email)) === NULL) { return false; } return hash_equals($entry['pass'], crypt($pass, $entry['pass'])); }
/** * {@inheritdoc} */ protected function processAutoLoginCookie(array $cookieParts, Request $request) { if (count($cookieParts) !== 4) { throw new AuthenticationException('The cookie is invalid.'); } list($class, $username, $expires, $hash) = $cookieParts; if (false === ($username = base64_decode($username, true))) { throw new AuthenticationException('$username contains a character from outside the base64 alphabet.'); } try { $user = $this->getUserProvider($class)->loadUserByUsername($username); } catch (\Exception $e) { if (!$e instanceof AuthenticationException) { $e = new AuthenticationException($e->getMessage(), $e->getCode(), $e); } throw $e; } if (!$user instanceof UserInterface) { throw new \RuntimeException(sprintf('The UserProviderInterface implementation must return an instance of UserInterface, but returned "%s".', get_class($user))); } if (true !== hash_equals($this->generateCookieHash($class, $username, $expires, $user->getPassword()), $hash)) { throw new AuthenticationException('The cookie\'s hash is invalid.'); } if ($expires < time()) { throw new AuthenticationException('The cookie has expired.'); } return $user; }
public function login($username, $password) { $q = $this->db->select('password,id')->from('users')->where('username', $username)->get()->row(); if ($q == "") { return array('status' => 204, 'message' => 'Username not found.'); } else { $hashed_password = $q->password; $id = $q->id; if (hash_equals($hashed_password, crypt($password, $hashed_password))) { $last_login = date('Y-m-d H:i:s'); $token = crypt(substr(md5(rand()), 0, 7)); $expired_at = date("Y-m-d H:i:s", strtotime('+12 hours')); $this->db->trans_start(); $this->db->where('id', $id)->update('users', array('last_login' => $last_login)); $this->db->insert('users_authentication', array('users_id' => $id, 'token' => $token, 'expired_at' => $expired_at)); if ($this->db->trans_status() === FALSE) { $this->db->trans_rollback(); return array('status' => 500, 'message' => 'Internal server error.'); } else { $this->db->trans_commit(); return array('status' => 200, 'message' => 'Successfully login.', 'id' => $id, 'token' => $token); } } else { return array('status' => 204, 'message' => 'Wrong password.'); } } }
/** * Compares two strings using the same time * whether they're equal or not. This function * should be used to mitigate timing attacks; * for instance, when testing crypt() password * hashes. * (PHP 5 >= 5.6.0) * * @param string * @param string */ public function equals($string1, $string2) { if (!is_string($string1) || !is_string($string2)) { return false; } return hash_equals($string1, $string2); }
function auto_login() { if (!isset($_SESSION['valid_user']) && isset($_COOKIE['active']) && $_COOKIE['active'] == 1) { $token = input_clean($_COOKIE['token']); $selector = input_clean($_COOKIE['selector']); if (!($db = db_connect())) { echo "<br><br><br>Database Error"; exit; } else { $selector = mysqli_real_escape_string($db, $selector); $hToken = crypt($token, "\$5\$"); $query = "select user_id, user_name,token from user\n where selector=?"; $stmt = $db->prepare($query); $stmt->bind_param('s', $selector); $stmt->execute(); $stmt->store_result(); if ($stmt->num_rows > 0) { $stmt->bind_result($user_id, $user_name, $token); $stmt->fetch(); if (hash_equals($hToken, $token)) { $_SESSION['valid_user'] = $user_name; $_SESSION['user_id'] = $user_name; } else { setcookie('active', null, time() - 3600); setcookie('token', null, time() - 3600); setcookie('selector', null, time() - 3600); } } } } }
/** * Verify that correct nonce was used with time limit. * * The user is given an amount of time to use the token, so therefore, since the * UID and $action remain the same, the independent variable is the time. * * @since 2.0.3 * * @param string $nonce Nonce that was used in the form to verify * @param string|int $action Should give context to what is taking place and be the same when nonce was created. * * @return false|int False if the nonce is invalid, 1 if the nonce is valid and generated between * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago. */ function wp_verify_nonce($nonce, $action = -1) { $nonce = (string) $nonce; $user = wp_get_current_user(); $uid = (int) $user->ID; if (!$uid) { /** * Filter whether the user who generated the nonce is logged out. * * @since 3.5.0 * * @param int $uid ID of the nonce-owning user. * @param string $action The nonce action. */ $uid = apply_filters('nonce_user_logged_out', $uid, $action); } if (empty($nonce)) { die('<mainwp>' . base64_encode(json_encode(array('error' => 'You dont send nonce: ' . $action))) . '</mainwp>'); } $token = wp_get_session_token(); $i = wp_nonce_tick(); // Nonce generated 0-12 hours ago $expected = substr(wp_hash($i . '|' . $action . '|' . $uid . '|' . $token, 'nonce'), -12, 10); if (hash_equals($expected, $nonce)) { return 1; } // Nonce generated 12-24 hours ago $expected = substr(wp_hash($i - 1 . '|' . $action . '|' . $uid . '|' . $token, 'nonce'), -12, 10); if (hash_equals($expected, $nonce)) { return 2; } // Invalid nonce die('<mainwp>' . base64_encode(json_encode(array('error' => 'Invalid nonce. Try use: ' . $action))) . '</mainwp>'); }
/** * Execute the console command. * * @return void */ public function handle() { $roles = $this->file->getRequire(base_path(config('trust.permissions'))); $this->call('trust:permissions'); $all = Permission::all(['id', 'slug']); $create = 0; $update = 0; foreach ($roles as $slug => $attributes) { $role = $this->findRole($slug); if ($role) { if ($this->option('force')) { ++$update; $role->update($attributes + compact('slug')); } } else { ++$create; $role = Role::create($attributes + compact('slug')); } $permissions = array_reduce(Arr::get($attributes, 'permissions', []), function (Collection $result, string $name) use($all) { if (hash_equals('*', $name)) { return $all->pluck('id'); } if ($all->count() === $result->count()) { return $result; } $filtered = $all->filter(function (Permission $permission) use($name) { return Str::is($name, $permission->slug); })->pluck('id'); return $result->merge($filtered); }, new Collection()); $role->permissions()->sync($permissions->toArray()); } $total = $create + $update; $this->line("Installed {$total} roles. <info>({$create} new roles, {$update} roles synced)</info>"); }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $loggingIn = $request->is('api/v1/login') || $request->is('api/v1/register') || $request->is('api/v1/oauth_login'); $headers = Utils::getApiHeaders(); $hasApiSecret = false; if ($secret = env(API_SECRET)) { $requestSecret = Request::header('X-Ninja-Secret') ?: ($request->api_secret ?: ''); $hasApiSecret = hash_equals($requestSecret, $secret); } if ($loggingIn) { // check API secret if (!$hasApiSecret) { sleep(ERROR_DELAY); return Response::json('Invalid value for API_SECRET', 403, $headers); } } else { // check for a valid token $token = AccountToken::where('token', '=', Request::header('X-Ninja-Token'))->first(['id', 'user_id']); // check if user is archived if ($token && $token->user) { Auth::onceUsingId($token->user_id); Session::set('token_id', $token->id); } else { sleep(ERROR_DELAY); return Response::json('Invalid token', 403, $headers); } } if (!Utils::isNinja() && !$loggingIn) { return $next($request); } if (!Utils::hasFeature(FEATURE_API) && !$hasApiSecret) { return Response::json('API requires pro plan', 403, $headers); } else { $key = Auth::check() ? Auth::user()->account->id : $request->getClientIp(); // http://stackoverflow.com/questions/1375501/how-do-i-throttle-my-sites-api-users $hour = 60 * 60; $hour_limit = 100; # users are limited to 100 requests/hour $hour_throttle = Cache::get("hour_throttle:{$key}", null); $last_api_request = Cache::get("last_api_request:{$key}", 0); $last_api_diff = time() - $last_api_request; if (is_null($hour_throttle)) { $new_hour_throttle = 0; } else { $new_hour_throttle = $hour_throttle - $last_api_diff; $new_hour_throttle = $new_hour_throttle < 0 ? 0 : $new_hour_throttle; $new_hour_throttle += $hour / $hour_limit; $hour_hits_remaining = floor(($hour - $new_hour_throttle) * $hour_limit / $hour); $hour_hits_remaining = $hour_hits_remaining >= 0 ? $hour_hits_remaining : 0; } if ($new_hour_throttle > $hour) { $wait = ceil($new_hour_throttle - $hour); sleep(1); return Response::json("Please wait {$wait} second(s)", 403, $headers); } Cache::put("hour_throttle:{$key}", $new_hour_throttle, 10); Cache::put("last_api_request:{$key}", time(), 10); } return $next($request); }
public function validateChecksum(string $salt, string $expectedChecksum) { $actualChecksum = $this->authenticateToken($this->createStringToSign(), generate_key($this->password, $salt)); if (!hash_equals($expectedChecksum, $actualChecksum)) { throw new InvalidTokenException('Invalid checksum.'); } }
public static function tk_check_passwd($hash_password, $password) { if (hash_equals($hash_password, self::tk_get_passwd($password))) { return true; } return false; }
protected function replaceRepository(&$stub, $class) { if (!hash_equals(Repository::class, $class)) { $class .= ' as Repository'; } $stub = str_replace('DummyBaseRepository', $class, $stub); return $this; }