예제 #1
0
    		// ссылка в блеке
    		// убиваем ссылку
    		cdim('db','query',"DELETE FROM `proxy` WHERE `id` = '".$proxy->id."';");
    		// еще раз пытаемся подобрать ссылку
    		$proxy = getPROXY();
    	} else {
    		// проверка чистая
    		// обновим последнюю проверку
    		cdim('db','query',"UPDATE `proxy` SET `last_check` = ".time()." WHERE `id` = ".$proxy->id.";");
    	}
      }
    */
    return $proxy;
}
include 'gears/RC4.php';
$rc4 = new RC4();
$detoken = unserialize($rc4->crypt_str($config['options']['rc4key'], base64url_decode($apitoken)));
$user_id = intval(trim($detoken[0]));
$flow_id = intval(trim($detoken[1]));
checkTarif($user_id);
$user = checkToken($user_id, $flow_id);
$token = getToken($flow_id);
/***** BLOCK ALL, witchout this list ******/
$user_ip_addr = $_SERVER['REMOTE_ADDR'];
$block_list_way = 'manage/addl/block_list_' . $user_id . '.lst';
if (file_exists($block_list_way)) {
    $file_arr = array();
    $file_data = file_get_contents($block_list_way);
    $file_arr = unserialize($file_data);
    if (isset($file_arr[$flow_id])) {
        if (count($file_arr[$flow_id]) > 0 && !in_array($user_ip_addr, $file_arr[$flow_id])) {
예제 #2
0
파일: Random.php 프로젝트: bitking/sysPass
 /**
  * Generate a random string.
  *
  * Although microoptimizations are generally discouraged as they impair readability this function is ripe with
  * microoptimizations because this function has the potential of being called a huge number of times.
  * eg. for RSA key generation.
  *
  * @param int $length
  * @throws \RuntimeException if a symmetric cipher is needed but not loaded
  * @return string
  */
 static function string($length)
 {
     if (version_compare(PHP_VERSION, '7.0.0', '>=')) {
         try {
             return random_bytes($length);
         } catch (\Error $e) {
             // If a sufficient source of randomness is unavailable, random_bytes() will emit a warning.
             // We don't actually need to do anything here. The string() method should just continue
             // as normal. Note, however, that if we don't have a sufficient source of randomness for
             // random_bytes(), most of the other calls here will fail too, so we'll end up using
             // the PHP implementation.
         }
     }
     if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
         // method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call.
         // ie. class_alias is a function that was introduced in PHP 5.3
         if (extension_loaded('mcrypt') && function_exists('class_alias')) {
             return mcrypt_create_iv($length);
         }
         // method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was,
         // to quote <http://php.net/ChangeLog-5.php#5.3.4>, "possible blocking behavior". as of 5.3.4
         // openssl_random_pseudo_bytes and mcrypt_create_iv do the exact same thing on Windows. ie. they both
         // call php_win32_get_random_bytes():
         //
         // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/openssl/openssl.c#L5008
         // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1392
         //
         // php_win32_get_random_bytes() is defined thusly:
         //
         // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80
         //
         // we're calling it, all the same, in the off chance that the mcrypt extension is not available
         if (extension_loaded('openssl') && version_compare(PHP_VERSION, '5.3.4', '>=')) {
             return openssl_random_pseudo_bytes($length);
         }
     } else {
         // method 1. the fastest
         if (extension_loaded('openssl')) {
             return openssl_random_pseudo_bytes($length);
         }
         // method 2
         static $fp = true;
         if ($fp === true) {
             // warning's will be output unles the error suppression operator is used. errors such as
             // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc.
             $fp = @fopen('/dev/urandom', 'rb');
         }
         if ($fp !== true && $fp !== false) {
             // surprisingly faster than !is_bool() or is_resource()
             return fread($fp, $length);
         }
         // method 3. pretty much does the same thing as method 2 per the following url:
         // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391
         // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're
         // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir
         // restrictions or some such
         if (extension_loaded('mcrypt')) {
             return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
         }
     }
     // at this point we have no choice but to use a pure-PHP CSPRNG
     // cascade entropy across multiple PHP instances by fixing the session and collecting all
     // environmental variables, including the previous session data and the current session
     // data.
     //
     // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively)
     // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but
     // PHP isn't low level to be able to use those as sources and on a web server there's not likely
     // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use
     // however, a ton of people visiting the website. obviously you don't want to base your seeding
     // soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled
     // by the user and (2) this isn't just looking at the data sent by the current user - it's based
     // on the data sent by all users. one user requests the page and a hash of their info is saved.
     // another user visits the page and the serialization of their data is utilized along with the
     // server envirnment stuff and a hash of the previous http request data (which itself utilizes
     // a hash of the session data before that). certainly an attacker should be assumed to have
     // full control over his own http requests. he, however, is not going to have control over
     // everyone's http requests.
     static $crypto = false, $v;
     if ($crypto === false) {
         // save old session data
         $old_session_id = session_id();
         $old_use_cookies = ini_get('session.use_cookies');
         $old_session_cache_limiter = session_cache_limiter();
         $_OLD_SESSION = isset($_SESSION) ? $_SESSION : false;
         if ($old_session_id != '') {
             session_write_close();
         }
         session_id(1);
         ini_set('session.use_cookies', 0);
         session_cache_limiter('');
         session_start();
         $v = $seed = $_SESSION['seed'] = pack('H*', sha1(serialize($_SERVER) . serialize($_POST) . serialize($_GET) . serialize($_COOKIE) . serialize($GLOBALS) . serialize($_SESSION) . serialize($_OLD_SESSION)));
         if (!isset($_SESSION['count'])) {
             $_SESSION['count'] = 0;
         }
         $_SESSION['count']++;
         session_write_close();
         // restore old session data
         if ($old_session_id != '') {
             session_id($old_session_id);
             session_start();
             ini_set('session.use_cookies', $old_use_cookies);
             session_cache_limiter($old_session_cache_limiter);
         } else {
             if ($_OLD_SESSION !== false) {
                 $_SESSION = $_OLD_SESSION;
                 unset($_OLD_SESSION);
             } else {
                 unset($_SESSION);
             }
         }
         // in SSH2 a shared secret and an exchange hash are generated through the key exchange process.
         // the IV client to server is the hash of that "nonce" with the letter A and for the encryption key it's the letter C.
         // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the
         // original hash and the current hash. we'll be emulating that. for more info see the following URL:
         //
         // http://tools.ietf.org/html/rfc4253#section-7.2
         //
         // see the is_string($crypto) part for an example of how to expand the keys
         $key = pack('H*', sha1($seed . 'A'));
         $iv = pack('H*', sha1($seed . 'C'));
         // ciphers are used as per the nist.gov link below. also, see this link:
         //
         // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives
         switch (true) {
             case class_exists('\\phpseclib\\Crypt\\AES'):
                 $crypto = new AES(Base::MODE_CTR);
                 break;
             case class_exists('\\phpseclib\\Crypt\\Twofish'):
                 $crypto = new Twofish(Base::MODE_CTR);
                 break;
             case class_exists('\\phpseclib\\Crypt\\Blowfish'):
                 $crypto = new Blowfish(Base::MODE_CTR);
                 break;
             case class_exists('\\phpseclib\\Crypt\\TripleDES'):
                 $crypto = new TripleDES(Base::MODE_CTR);
                 break;
             case class_exists('\\phpseclib\\Crypt\\DES'):
                 $crypto = new DES(Base::MODE_CTR);
                 break;
             case class_exists('\\phpseclib\\Crypt\\RC4'):
                 $crypto = new RC4();
                 break;
             default:
                 throw new \RuntimeException(__CLASS__ . ' requires at least one symmetric cipher be loaded');
         }
         $crypto->setKey($key);
         $crypto->setIV($iv);
         $crypto->enableContinuousBuffer();
     }
     //return $crypto->encrypt(str_repeat("\0", $length));
     // the following is based off of ANSI X9.31:
     //
     // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf
     //
     // OpenSSL uses that same standard for it's random numbers:
     //
     // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c
     // (do a search for "ANS X9.31 A.2.4")
     $result = '';
     while (strlen($result) < $length) {
         $i = $crypto->encrypt(microtime());
         // strlen(microtime()) == 21
         $r = $crypto->encrypt($i ^ $v);
         // strlen($v) == 20
         $v = $crypto->encrypt($r ^ $i);
         // strlen($r) == 20
         $result .= $r;
     }
     return substr($result, 0, $length);
 }
예제 #3
0
        errorHandler(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
    }
}
set_error_handler('errorHandler');
register_shutdown_function('fatalErrorShutdownHandler');
include_once '../../config.php';
// берем конфиг
include_once '../../gears/functions.php';
// подключаем функции
include_once '../../gears/di.php';
// подключаем класс библиотеки класов
include_once '../../gears/db.php';
// подключаем класс базы
// создаем подключение к базе
cdim('db', 'connect', $config);
// забираем из базы опции и кладем их в конфиг
$options = cdim('db', 'query', "SELECT * FROM options");
// кладем в конфиг все что забрали из базы (все опции)
if (isset($options)) {
    foreach ($options as $k => $v) {
        $config['options'][$v->option_name] = $v->option_value;
    }
}
// авторизация
include_once '../auth/auth.php';
include_once '../../gears/RC4.php';
$rc4 = new RC4();
$apitoken = serialize(array($config['user']['id'], intval($_POST['flow_id'])));
$apitoken = base64url_encode($rc4->crypt_str($config['options']['rc4key'], $apitoken));
$link = $config['options']['siteurl'] . '/api.php?apitoken=' . $apitoken;
exit(json_encode(array('type' => 'success', 'msg' => $link)));
예제 #4
0
$vds = base64url_decode($query[0]);
$token = base64url_decode($query[1]);
if (isset($_GET['debug']) && $_GET['debug'] == 1) {
    echo $token . "<br>";
}
$rc4 = new RC4();
$vds = $rc4->crypt_str($key, $vds);
if (isset($_GET['debug']) && $_GET['debug'] == 1) {
    echo $vds . "<br>";
}
// надо определить каким способом передавать данные
// тут я попозже допишу...
// отправляем курлом наши параметры
$data = proxyStream($vds, $token, $post);
if (isset($_GET['debug']) && $_GET['debug'] == 1) {
    echo $data;
}
if ($data === false) {
    exit('_');
}
// распаковываем ответ
$rc4 = new RC4();
$data = unserialize($rc4->crypt_str($key, base64_decode($data)));
if (isset($data['headers']) && $data['headers'] != '' && is_array($data['headers'])) {
    foreach ($data['headers'] as $k => $v) {
        header($v);
    }
}
if (isset($data['data']) && $data['data'] != '') {
    echo $data['data'];
}
예제 #5
0
 /**
  * @dataProvider sentences
  */
 public function testEncodingWithMethod($key, $sentence, $crypt)
 {
     $obj = new RC4($key);
     $this->assertEquals($crypt, $obj->rc4($sentence));
 }
예제 #6
0
 function decryptDataUAM($data, $key, $status = "1")
 {
     if ($status == "1") {
         $key = $this->GenerateSecretKeyUAM($key);
     }
     $objRC4 = new RC4();
     $rc4Data = $this->hex2bin($data);
     $decryptData = $objRC4->rc4_decrypt($key, $rc4Data);
     return $decryptData;
 }
예제 #7
0
/**
 * Generate a random value.
 *
 * On 32-bit machines, the largest distance that can exist between $min and $max is 2**31.
 * If $min and $max are farther apart than that then the last ($max - range) numbers.
 *
 * Depending on how this is being used, it may be worth while to write a replacement.  For example,
 * a PHP-based web app that stores its data in an SQL database can collect more entropy than this function
 * can.
 *
 * @param optional Integer $min
 * @param optional Integer $max
 * @return Integer
 * @access public
 */
function Random($min = 0, $max = 0x7fffffff)
{
    if ($min == $max) {
        return $min;
    }
    // see http://en.wikipedia.org/wiki//dev/random
    static $urandom = true;
    if ($urandom === true) {
        // Warning's will be output unles the error suppression operator is used.  Errors such as
        // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc.
        $urandom = @fopen('/dev/urandom', 'rb');
    }
    if (!is_bool($urandom)) {
        extract(unpack('Nrandom', fread($urandom, 4)));
        // say $min = 0 and $max = 3.  if we didn't do abs() then we could have stuff like this:
        // -4 % 3 + 0 = -1, even though -1 < $min
        return abs($random) % ($max - $min) + $min;
    }
    /* Prior to PHP 4.2.0, mt_srand() had to be called before mt_rand() could be called.
           Prior to PHP 5.2.6, mt_rand()'s automatic seeding was subpar, as elaborated here:
    
           http://www.suspekt.org/2008/08/17/mt_srand-and-not-so-random-numbers/
    
           The seeding routine is pretty much ripped from PHP's own internal GENERATE_SEED() macro:
    
           http://svn.php.net/viewvc/php/php-src/branches/PHP_5_3_2/ext/standard/php_rand.h?view=markup */
    if (version_compare(PHP_VERSION, '5.2.5', '<=')) {
        static $seeded;
        if (!isset($seeded)) {
            $seeded = true;
            mt_srand(fmod(time() * getmypid(), 0x7fffffff) ^ fmod(1000000 * lcg_value(), 0x7fffffff));
        }
    }
    static $crypto;
    // The CSPRNG's Yarrow and Fortuna periodically reseed.  This function can be reseeded by hitting F5
    // in the browser and reloading the page.
    if (!isset($crypto)) {
        $key = $iv = '';
        for ($i = 0; $i < 8; $i++) {
            $key .= pack('n', mt_rand(0, 0xffff));
            $iv .= pack('n', mt_rand(0, 0xffff));
        }
        switch (true) {
            case class_exists('AES'):
                $crypto = new AES(AES_MODE_CTR);
                break;
            case class_exists('TripleDES'):
                $crypto = new TripleDES(DES_MODE_CTR);
                break;
            case class_exists('DES'):
                $crypto = new DES(DES_MODE_CTR);
                break;
            case class_exists('RC4'):
                $crypto = new RC4();
                break;
            default:
                extract(unpack('Nrandom', pack('H*', sha1(mt_rand(0, 0x7fffffff)))));
                return abs($random) % ($max - $min) + $min;
        }
        $crypto->setKey($key);
        $crypto->setIV($iv);
        $crypto->enableContinuousBuffer();
    }
    extract(unpack('Nrandom', $crypto->encrypt("")));
    return abs($random) % ($max - $min) + $min;
}