private function ivSetup(Binary $iv) { $this->state[12] = $iv->getByte(0) + ($iv->getByte(1) << 8); $this->state[13] = $iv->getByte(2) + ($iv->getByte(3) << 8); $this->state[14] = $iv->getByte(4) + ($iv->getByte(5) << 8); $this->state[15] = $iv->getByte(6) + ($iv->getByte(7) << 8); $this->state[16] = 0; $this->state[17] = 0; $this->state[18] = 0; $this->state[19] = 0; }
public function testBinary() { $binary = new Binary(); $binary->sequence = 123; $binary->flags = "b38c"; $binary->publicKey = "89f5ffe70d747869dfe8"; $binary->identifier = hex2bin("3a60e6850a1e4cc15f3bfd4b42bc6b3e"); $msg = $binary->serialize(); $this->assertSame("740caf04158436b4a81b844135a8a1dc9e4f8a54", sha1($msg)); $binaryRcvd = new Binary($msg); $binaryRcvd->unserialize(); $msg = $binaryRcvd->serialize(); $this->assertSame("740caf04158436b4a81b844135a8a1dc9e4f8a54", sha1($msg)); $this->assertEquals($binary, $binaryRcvd); }
function __construct($left, $right = self::ASC) { if (!in_array($right, array(self::ASC, self::DESC))) { throw new \InvalidArgumentException("Sort Direction {$right} is\\\n not supported, use Order::ASC or ORDER::DESC instead."); } parent::__construct($left, $right); }
public function testBoxAByteUnit() { $byteUnitInMetricSystem = Metric::bytes(42); $byteUnitInBinarySystem = Binary::bytes(42); $this->assertEquals($byteUnitInMetricSystem, box($byteUnitInMetricSystem)); $this->assertEquals($byteUnitInBinarySystem, box($byteUnitInBinarySystem)); }
public function testNumberOfBytes() { $this->assertEquals('0', Binary::bytes(0)->numberOfBytes()); $this->assertEquals('1', Binary::bytes(1)->numberOfBytes()); $this->assertEquals('1024', Binary::bytes(1024)->numberOfBytes()); $this->assertEquals('1280', Binary::bytes(1280)->numberOfBytes()); $this->assertEquals('1572864', Binary::bytes(1572864)->numberOfBytes()); $this->assertEquals('1879048192', Binary::bytes(1879048192)->numberOfBytes()); $this->assertEquals('2199023255552', Binary::bytes(2199023255552)->numberOfBytes()); }
/** * Determines if the convert transcoder engine is available on the current system. * * @access public * @static * @author Oliver Lillie * @param PHPVideoToolkit\Config $config The configuration object. * @return boolean Returns true if this engine can be used, otherwise false. */ public static function available(Config $config) { if ($config->convert === null) { return false; } try { Binary::locate($config->convert); return true; } catch (BinaryException $e) { return false; } }
public function testCompareWithOtherUnitSystem() { $this->assertTrue(Metric::bytes(1)->isEqualTo(Binary::bytes(1))); $this->assertTrue(Metric::bytes(1)->isGreaterThanOrEqualTo(Binary::bytes(1))); $this->assertTrue(Metric::bytes(5)->isGreaterThan(Binary::bytes(1))); $this->assertTrue(Metric::bytes(1)->isLessThanOrEqualTo(Binary::bytes(1))); $this->assertTrue(Metric::bytes(1)->isLessThan(Binary::bytes(5))); $this->assertTrue(Binary::bytes(1)->isEqualTo(Metric::bytes(1))); $this->assertTrue(Binary::bytes(1)->isGreaterThanOrEqualTo(Metric::bytes(1))); $this->assertTrue(Binary::bytes(5)->isGreaterThan(Metric::bytes(1))); $this->assertTrue(Binary::bytes(1)->isLessThanOrEqualTo(Metric::bytes(1))); $this->assertTrue(Binary::bytes(1)->isLessThan(Metric::bytes(5))); }
public function testBase64() { $this->assertEquals('YQ==', Binary::base64Encode('a')); $this->assertEquals('YQ', Binary::base64Encode('a', true)); $original = '☢☣☯♥☺'; $b64 = Binary::base64Encode($original); $this->assertEquals($original, Binary::base64Decode($b64)); $b64 = Binary::base64Encode($original, true); $this->assertEquals($original, Binary::base64Decode($b64)); $this->assertEquals('/+4=', Binary::base64Encode("ÿî")); $this->assertEquals('_-4', Binary::base64Encode("ÿî", true)); $this->assertEquals("ÿî", Binary::base64Decode('/+4=')); $this->assertEquals("ÿî", Binary::base64Decode('_-4=')); $this->assertEquals("ÿî", Binary::base64Decode('/+4=', false)); $this->assertEquals('', Binary::base64Decode('_-4=', false)); }
public static function getFile($blueprint, $field, $id) { $tag = "Binary::getFile()"; Log::debug("{$tag}"); try { $binaryString = Binary::getString($blueprint, $field, $id); } catch (Exception $e) { throw $e; } $tmpFile = tmpfile(); $bytes = fwrite($tmpFile, $binaryString); if ($bytes) { return $tmpFile; } else { Log::error("{$tag}: Unable to write to temporary file"); throw new Exception("{$tag}: Unable to write to temporary file"); } }
/** * @route notary/verify */ public function verify() { // Input validation if (empty($_POST['challenge'])) { \Airship\json_response(['status' => 'error', 'message' => 'Expected a challenge=something HTTP POST parameter.']); } if (!\is_string($_POST['challenge'])) { \Airship\json_response(['status' => 'error', 'message' => 'Challenge must be a string.']); } if (Binary::safeStrlen($_POST['challenge']) < 20) { \Airship\json_response(['status' => 'error', 'message' => 'Challenge is too short. Continuum should be generating a long random nonce.']); } try { list($update, $signature) = $this->chanUp->verifyUpdate($this->sk, $_POST['challenge']); \Airship\json_response(['status' => 'OK', 'response' => $update, 'signature' => $signature]); } catch (\Exception $ex) { \Airship\json_response(['status' => 'error', 'message' => $ex->getMessage()]); } }
/** * Parse structure of labels * @param binary * @return string Dot-separated labels list */ public static function parseLabels(&$data, $orig = null) { $str = ''; while (strlen($data) > 0) { $l = ord($data[0]); if ($l >= 192) { $pos = Binary::bytes2int(chr($l - 192) . binarySubstr($data, 1, 1)); $data = binarySubstr($data, 2); $ref = binarySubstr($orig, $pos); return $str . Binary::parseLabels($ref); } $p = substr($data, 1, $l); $str .= $p . ($l !== 0 ? '.' : ''); $data = substr($data, $l + 1); if ($l === 0) { break; } } return $str; }
static function r2_functions($binary) { #calculate code_start and code_end $code_section = Binary::codeSection($binary); $imagebase = Pefile::imagebase($binary); $code_start = hexdec($code_section["va"]) + hexdec($imagebase); $code_end = hexdec($code_section["va"]) + hexdec($imagebase) + hexdec($code_section["srd"]["value"]); $cmd = "echo \"aa;af;e scr.interactive=false;echo BEGIN;afj\"|" . Config::$radare2_path . "/radare2 {$binary}"; @ob_start(); system($cmd); $res = ob_get_contents(); ob_end_clean(); $out = ""; $res = preg_replace("/.*BEGIN/s", "", $res); $res = preg_replace("/\\033\\[2K.*/s", "", $res); $items = array(); $lines = json_decode($res); if (count($lines)) { foreach ($lines as $line) { $item = array(); $item["address"] = "0x" . dechex($line->offset); $item["size"] = $line->size; $item["cc"] = $line->cc; $item["name"] = $line->name; $item["type"] = $line->type; $item["callrefs"] = count($line->callrefs); $item["datarefs"] = count($line->datarefs); if (hexdec($item["address"]) >= $code_start && hexdec($item["address"]) <= $code_end) { $item["incodesec"] = 1; } else { $item["incodesec"] = 0; } array_push($items, $item); } } @usort($items, array(self, "cmp_functions")); return $items; }
static function Results() { $basedir = Config::$sinjector_path . "/results"; if (!is_dir($basedir)) { die("ERROR - \"{$basedir}\" not found..."); } $files = @scandir($basedir); $res = array(); foreach ($files as $f) { if ($f[0] == ".") { continue; } $item = array(); $item["md5"] = $f; $item["type"] = Binary::magic("uploads/" . $f . ".bin"); $item["type"] = preg_replace("/executable for MS Windows/", "exec MSWin", $item["type"]); $item["art"] = array(); if (file_exists("art/{$f}" . "-0.png")) { $item["art"]["sections"] = "art/{$f}" . "-0.png"; } if (file_exists("art/{$f}" . "-1.png")) { $item["art"]["resources"] = "art/{$f}" . "-1.png"; } if (file_exists("art/{$f}" . "-2.png")) { $item["art"]["r2_functions"] = "art/{$f}" . "-2.png"; } $item["date"] = date("M d H:i:s", filemtime($basedir . "/" . $f)); $log = self::fullLog($f); if (count(preg_split("/\n/", $log)) <= 2) { $item["status"] = "Failed"; } else { $item["status"] = "Done"; } array_push($res, $item); } @usort($res, array(self, "cmp_samples")); return $res; }
/** * Convert a hexadecimal string into a binary string without cache-timing * leaks * * @param string $hex_string * @param bool $strictPadding * @return string (raw binary) * @throws \RangeException */ public static function decode(string $hexString, bool $strictPadding = false) : string { $hex_pos = 0; $bin = ''; $c_acc = 0; $hex_len = Binary::safeStrlen($hexString); $state = 0; if (($hex_len & 1) !== 0) { if ($strictPadding) { throw new \RangeException('Expected an even number of hexadecimal characters'); } else { $hexString = '0' . $hexString; ++$hex_len; } } $chunk = \unpack('C*', $hexString); while ($hex_pos < $hex_len) { ++$hex_pos; $c = $chunk[$hex_pos]; $c_num = $c ^ 48; $c_num0 = $c_num - 10 >> 8; $c_alpha = ($c & ~32) - 55; $c_alpha0 = ($c_alpha - 10 ^ $c_alpha - 16) >> 8; if (($c_num0 | $c_alpha0) === 0) { throw new \RangeException('hexEncode() only expects hexadecimal characters'); } $c_val = $c_num0 & $c_num | $c_alpha & $c_alpha0; if ($state === 0) { $c_acc = $c_val * 16; } else { $bin .= \pack('C', $c_acc | $c_val); } $state ^= 1; } return $bin; }
</pre> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> <?php } if (isset($_GET["rcdata"])) { print Templates::Load("templates/misc/rcdata_dump.php", array("")); } if (isset($_GET["rtbitmap"])) { print Templates::Load("templates/misc/rtbitmap_dump.php", array("")); } if (isset($_GET["rtstring"])) { print Templates::Load("templates/misc/rtstring_dump.php", array("")); } //check if we found the right section for dumping the resources $sectionFound = false; foreach (Binary::sections($binary) as $s) { if ($va == $s["va"]) { $sectionFound = true; } } if (!$sectionFound && $va) { print Common::Error("Error", "The section with VirtualAddress={$va} was not found"); }
public function toBinary() { return Binary::writeInt($this->parts[0]) . Binary::writeInt($this->parts[1]) . Binary::writeInt($this->parts[2]) . Binary::writeInt($this->parts[3]); }
$start = 0; $size = 0; foreach ($resources as $r) { if ($r["type"]["value"] != "RT_STRING") { continue; } $c++; if ($c == $id) { $start = $r["fo"]["value"]; $size = $r["size"]["value"]; } } if (!$start && !$size) { print Common::Error("Error", "That rt_string resource was not found..."); return; } if ($start[0] == "-") { print Common::Error("Error", "The rt_stirng information is invalid: Negative offset position."); return; } if ($size[0] == "-") { print Common::Error("Error", "The rt_string information is invalid: Negative size."); return; } $b = new Binary($binary); $bytes = $b->readBytesAtOffset($start, $size); print "<pre>"; $html = htmlentities($bytes, ENT_DISALLOWED, "iso-8859-1"); $html = preg_replace("/�/", " ", $html); print $html; print "</pre>";
/** * Create a unique ID (e.g. for permalinks) * * @param int $length * @return string */ function uniqueId(int $length = 24) : string { if ($length < 1) { return ''; } $n = (int) ceil($length * 0.75); $str = \random_bytes($n); return Binary::safeSubstr(Base64UrlSafe::encode($str), 0, $length); }
public function readByte() { $s = $this->read(1); return Binary::fromString($s, 1); }
<?php $md5 = Common::getMD5("report"); $id = Common::getInteger("id"); $binary = "uploads/{$md5}.bin"; $sections = Binary::sections($binary); if ($id > count($sections)) { print Website::Error("That section was not found..."); return; } $b = new Binary($binary); $bytes = $b->readBytesAtOffset($sections[$id - 1]["prd"]["value"], $sections[$id - 1]["srd"]["value"]); print "<pre>"; $html = htmlentities($bytes, ENT_DISALLOWED, "iso-8859-1"); $html = preg_replace("/�/", " ", $html); print $html; print "</pre>";
public static function randomUUID() { return Utils::toUUID(Binary::writeInt(time()) . Binary::writeShort(getmypid()) . Binary::writeShort(getmyuid()) . Binary::writeInt(mt_rand(-0x7fffffff, 0x7fffffff)) . Binary::writeInt(mt_rand(-0x7fffffff, 0x7fffffff)), 2); }
<?php $unicode_strings = trim(Binary::strings_unicode($vars["binary"])); if (strlen($unicode_strings)) { ?> <h4>Unicode UTF-16le Strings</h4> <pre> <?php echo htmlentities($unicode_strings, ENT_QUOTES, "iso-8859-1"); ?> </pre> <?php } ?> <h4>ASCII Strings</h4> <pre> <?php echo htmlentities(Binary::strings($vars["binary"]), ENT_QUOTES, "iso-8859-1"); ?> </pre>
<?php require_once __DIR__ . '/Binary.php'; $binary = new Binary(); $binary->decbin(2); var_dump((string) $binary); $binary->reset(); $binary->decbin(8); var_dump((string) $binary); $binary->reset(); $binary->decbin(16); var_dump((string) $binary); $binary->reset(); $binary->decbin(12343156); var_dump((string) $binary); var_dump(decbin(12343156));
/** * Adds the given debug string $msg, then the given binary string $bin as an * hex string, to the debug data if debug mode is on. * @param string $msg The 'normal' string to add to the debug data. * @param string $bin The binary string to print in hexa. */ public static function printDebugHexa($msg, $bin) { if (self::$debug) { self::$errordump .= self::makePrintable($msg . " :: " . Binary::fromString($bin)->asHexString()) . "\n"; } }
/** * Generate a random sequence of bytes. * * @param int $n * Number of bytes. * @param string $method * Output parameter for the method used to generate * bytes: 'php7', 'mcrypt', 'openssl', 'urandom', or 'mt_rand'. * @return string String of bytes. */ public static function bytes($n, &$method = null) { $bytes = self::php7Bytes($n); $method = 'php7'; if (!isset($bytes)) { $bytes = self::mcryptBytes($n); $method = 'mcrypt'; } if (!isset($bytes)) { $bytes = self::opensslBytes($n); $method = 'openssl'; } if (!isset($bytes)) { $bytes = self::urandomBytes($n); $method = 'urandom'; } if (!isset($bytes)) { $bytes = self::mtRandBytes($n); $method = 'mt_rand'; } $l = Binary::length($bytes); if ($l < $n) { $bytes .= self::mtRandBytes($n - $l); } return $bytes; }
public static function export(Blueprint $blueprint, $type = "tar", $where = NULL, array $filters = NULL) { // NOTE: type=(tar, csv) $tag = "EntityExporter::export()"; Log::notice("{$tag}"); // create export path $path_tmp = BPConfig::$path_tmp; $path_unique = $path_tmp . uniqid("bp") . "/"; $path_export = $path_unique . $blueprint->signature() . "/"; Log::debug("{$tag}: path_export = {$path_export}"); $fields = $blueprint->fields(); // get data to export try { $results = EntityExporter::prepareData($blueprint, $where, $filters); } catch (Exception $e) { throw $e; } // create tmp directory for tar files if ($type == "tar") { if (is_writable($path_tmp)) { if (!mkdir($path_export, 0777, true)) { throw new Exception("{$tag}: Failed to mkdir: {$path_export}"); } } else { throw new Exception("{$tag}: Cannot write to " . $path_tmp); } } // start output buffer $csv = ""; $csv .= "id,"; // add header row foreach ($fields as $f) { $displayAs = $f->getKey(); $csv .= "{$displayAs},"; if ($f->isForeignKey()) { // Add column header for foreign value $csv .= $f->getForeignValue() . ","; } } $csv = substr($csv, 0, strlen($csv) - 1); // remove trailing comma "," $csv .= "\n"; // add result rows for ($i = 0; $i < $results->get_num_rows(); $i++) { $row = $results->get_next_row(); $csv .= $row->id . ","; foreach ($fields as $f) { $key = $f->getKey(); // retrieve value if ($f->isForeignKey()) { // Insert local value before foreign value $value = $row->{$key}; $csv .= "{$value},"; // Retrieve foreign value and continue with formatting below... $foreignValue = str_replace(".", "_", $f->getForeignValue()); $value = $row->{$foreignValue}; } else { $value = $row->{$key}; } // format values if (!empty($value) || $value == 0) { // format values based on dataType switch ($f->getDataType()) { case "int": if ($f->isForeignKey()) { $value = "\"{$value}\""; } break; case "string": // encrypted values if ($f->getEncType() == "md5" || $f->getEncType() == "sha1") { $value = "******"; } else { $value = addslashes($value); $value = "\"{$value}\""; } break; case "text": $value = "\"{$value}\""; break; case "binary": // generate filename $filename_bin = $blueprint->getKey() . "." . $key . "." . $row->id . "." . Binary::extension($f->getMimeType()); // write binary data to file if ($type == "tar") { $path_bin = $path_export . $filename_bin; Log::debug("{$tag}: Creating binary file: {$path_bin}"); if (!file_put_contents($path_bin, $value)) { Log::warning("{$tag}: Failed to create binary file: {$path_bin}"); } } // replace raw data with filename $value = $filename_bin; break; default: $value = addslashes($value); } // TODO: format values based on ListBlueprint formatter } // END: if( (!empty($value)) || ($value==0) ) $csv .= "{$value},"; } $csv = substr($csv, 0, strlen($csv) - 1); // remove trailing comma "," $csv .= "\n"; } // create tar if ($type == "tar") { // create blueprint xml file in export path $path_blueprint = $path_export . $blueprint->signature(); $xmlStr = $blueprint->asXml(); file_put_contents($path_blueprint, $xmlStr); // create csv file in export path $path_csv = $path_export . $blueprint->getKey() . ".csv"; file_put_contents($path_csv, $csv); $path_tar = $path_unique . $blueprint->getKey() . ".tar"; $cmd = "tar --create --directory={$path_unique} --file={$path_tar} --gzip " . $blueprint->signature(); Log::debug("{$tag}: Executing: {$cmd}"); exec($cmd); // retrieve contents of tar file $tar = file_get_contents($path_tar); // cleanup $glob = glob($path_export . "*"); foreach ($glob as $path_clean) { if (!unlink($path_clean)) { Log::warning("{$tag}: Failed to unlink: {$path_clean}"); } } if (!rmdir($path_export)) { Log::warning("{$tag}: Failed to rmdir: {$path_export}"); } if (!unlink($path_tar)) { Log::warning("{$tag}: Failed to unlink: {$path_tar}"); } if (!rmdir($path_unique)) { Log::warning("{$tag}: Failed to rmdir: {$path_unique}"); } return $tar; } else { if ($type == "csv") { return $csv; } } }
<td><?php echo $vars["md5"]; ?> </td> </tr> <tr> <td class="active">File Size</td> <td><?php echo Binary::filesize($vars["binary"]); ?> </td> </tr> <tr> <td class="active">File Type</td> <td><?php echo Binary::magic($vars["binary"]); ?> </td> </tr> <tr> <td class="active">Internal Date</td> <td><?php echo date("Y-m-d H:i", $timedatestamp); ?> </td> </tr> <tr> <td class="active">Packer ID</td> <td><?php echo $packerid; ?>
/** * Magic method get * * This get's triggerd if there is a call made to an undefined property in * the App_Config instance or subInstance, so we throw an Exception * * @param string $name * @throws PHPVideoToolkit\ConfigSetException Thrown if any of the values for the related config settings is invalid. */ public function __set($key, $value) { switch ($key) { case 'ffmpeg': case 'ffprobe': case 'yamdi': case 'qtfaststart': case 'gifsicle': case 'convert': if ($value !== null) { if (strpos($value, '/') !== 0) { try { $value = Binary::locate($value); } catch (BinaryLocateException $e) { throw new ConfigSetException('Unable to locate the ' . $value . ' binary. Please specify the full path instead.'); } } } $this->{'_' . $key} = $value; return; case 'gif_transcoder': if (in_array($value, array('gifsicle', 'convert', 'php', null)) === false) { throw new ConfigSetException('Unrecognised gif transcoder engine.'); } $this->{'_' . $key} = $value; return; case 'cache_driver': $class = '\\PHPVideoToolkit\\Cache_' . $value; if (class_exists($class) === false) { throw new ConfigSetException('Unrecognised cache driver engine. The cache class must be within the PHPVideoToolkit namespace and be prefixed by `Cache_`.'); } if (is_subclass_of($class, '\\PHPVideoToolkit\\CacheAbstract') === false) { throw new ConfigSetException('Unrecognised cache driver engine. The cache driver provider must inherit from \\PHPVideoToolkit\\CacheAbstract.'); } $this->{'_' . $key} = $value; return; case 'gif_transcoder_convert_dither_order': if (preg_match('/o[0-9]+x[0-9]+,[0-9]+/', $value) === 0) { throw new ConfigSetException('Unrecognised dither order. Please enter in the following format: oNxN,N where N are numerics.'); } $this->{'_' . $key} = $value; return; case 'force_enable_qtfaststart': case 'php_exec_infinite_timelimit': case 'force_enable_flv_meta': case 'gif_transcoder_convert_use_dither': case 'gif_transcoder_convert_use_coalesce': case 'gif_transcoder_convert_use_map': case 'set_default_output_format': if (in_array($value, array(true, false)) === false) { throw new ConfigSetException('Unrecognised ' . $key . ' value. It must be a boolean value, either true or false.'); } $this->{'_' . $key} = $value; return; case 'temp_directory': $original_value = $value; $value = realpath($value); if (empty($value) === true || is_dir($value) === false) { throw new ConfigSetException('`temp_directory` "' . $original_value . '" does not exist or is not a directory.'); } else { if (is_readable($value) === false) { throw new ConfigSetException('`temp_directory` "' . $original_value . '" is not readable.'); } else { if (is_writable($value) === false) { throw new ConfigSetException('`temp_directory` "' . $original_value . '" is not writeable.'); } } } $this->{'_' . $key} = $value; return; } throw new ConfigSetException('Setting undefined configuration property: ' . $key); }
public static function nfuint32($n, $f) { return Binary::nuint32($n, fread($f, 4 * $n)); }
/** * @brief Fetch an object in its binary representation by name. * * Throws an exception if the object cannot be found. * * @param $objectName (string) name of the object (binary SHA1) * @returns (array) an array consisting of the object type (int) and the * binary representation of the object (string) */ protected function getRawObject($objectName) { static $cache = array(); /* FIXME allow limiting the cache to a certain size */ if (isset($cache[$objectName])) { return $cache[$objectName]; } $sha1 = Git::sha1Hex($objectName); $path = sprintf('%s/objects/%s/%s', $this->dir, substr($sha1, 0, 2), substr($sha1, 2)); if (file_exists($path)) { list($hdr, $objectData) = explode("", gzuncompress(file_get_contents($path)), 2); sscanf($hdr, "%s %d", $type, $objectSize); $objectType = Git::getTypeID($type); $result = array($objectType, $objectData); } elseif ($packedObject = $this->findPackedObject($objectName)) { list($packName, $objectOffset) = $packedObject; $pack = fopen(sprintf('%s/objects/pack/pack-%s.pack', $this->dir, sha1Hex($packName)), 'rb'); flock($pack, LOCK_SH); /* check magic and version */ $magic = fread($pack, 4); $version = Binary::fuint32($pack); if ($magic != 'PACK' || $version != 2) { throw new Exception('unsupported pack format'); } $result = $this->unpackObject($pack, $objectOffset); fclose($pack); } else { throw new Exception(sprintf('object not found: %s', sha1Hex($objectName))); } $cache[$objectName] = $result; return $result; }