Php escape serialized string

[CTF]PHP deserialization summary

brief introduction
Serialization is actually transforming data into a reversible data structure. Naturally, the reverse process is called deserialization.

Find a more vivid example on the Internet

For example, now we all buy tables on Taobao. How can we transport such irregular things from one city to another? At this time, we usually tear them down into boards and put them in boxes, so that they can be sent by express, This process is similar to our serialization process (converting data into a form that can be stored or transmitted). When the buyer receives the goods, he needs to assemble these boards into a table. This process is like a reverse sequence process (converting into the original data object).

php uses two functions to serialize and deserialize data

serialize formats objects into ordered strings

unserialize restores the string to the original object

The purpose of serialization is to facilitate data transmission and storage. In PHP, serialization and deserialization are generally used as caching, such as session caching, cookie s, etc.

Читайте также:  Html css современные шаблоны

Common serialization formats
Just understand

Binary format
Byte array
json string
xml string
Case introduction
Simple example (take array as an example)

a:3: Array ( [0] => xiao [1] => shi [2] => zi )

Let’s give a brief explanation of the above example to facilitate you to get started

a:3: a:array Represents an array. The following 3 descriptions have three properties i:Represents integer data int,The following 0 is the array subscript s:Represents a string, followed by 4 because xiao Length 4 And so on

The serialized content has only member variables and no member functions, such as the following example

a = "xiaoshizi";$this->b="laoshizi";> function happy()a;> > $a = new test(); echo serialize($a); ?>

Output (O stands for Object, which means Object and class)

If the variable is protected, then \ x00 * \ x00 will be added before the variable name, and private will add \ x00 class name \ x00 before the variable name. url encoding is generally required for output. base64 encoding is recommended for local storage, as follows:

a = "xiaoshizi";$this->b="laoshizi";> function happy()a;> > $a = new test(); echo serialize($a); echo urlencode(serialize($a)); ?>

Output will result in the loss of the invisible character \ x00

Common magic methods in deserialization
__ wakeup() / / this function will be called first when executing unserialize()
__ sleep() / / this function will be called first when you execute serialize()
__ Destroy() / / triggered when the object is destroyed
__ call() / / triggers in an object context when an invocable method is invoked.
__ callStatic() / / triggering an invocable method in a static context
__ get() / / used to read data from inaccessible properties or call this method if this key does not exist
__ set() / / used to write data to inaccessible attributes
__ Isset() / / triggered by calling isset() or empty() on an inaccessible property
__ Unset() / / triggered when unset() is used on an inaccessible property
__ toString() / / triggered when a class is used as a string
__ invoke() / / triggered when an attempt is made to call an object as a function

Deserialization bypasses little Trick

php7.1 + deserialization is not sensitive to class attributes

As we said earlier, if the variable is protected, the serialization result will add \ x00*\x00 before the variable name

However, in a specific version above 7.1, it is not sensitive to class attributes. For example, the following example will still output abc even without \ x00*\x00

a = 'abc'; > public function __destruct()< echo $this->a; > > unserialize('O:4:"test":1:');

Bypass__ wakeup(CVE-2016-7124)

Utilization method: when the value representing the number of object attributes in the serialized string is greater than the actual number of attributes, it will be skipped__ Implementation of wakeup

For the following custom class

a = 'abc'; > public function __wakeup()< $this->a='666'; > public function __destruct()< echo $this->a; > >

If you execute unserialize(‘O:4:»test»:1: ‘); The output is 666

Increase the value of the number of object attributes and execute unserialize(‘O:4:»test»:2: ‘); The output result is abc

Bypass partial regularization
preg_match(‘/^O:\d + /’) matches whether the serialized string starts with the object string, which has been a similar test point in CTF

Bypass by using the plus sign (note that + should be encoded as% 2B when passing parameters in the url)
serialize(array(a ) ) ; / / a));//a));//a is the object to be deserialized (the serialization result starts with a and does not affect the destruct of $a as an array element)

a = 'abc'; > public function __destruct()< echo $this->a.PHP_EOL; > > function match($data)< if (preg_match('/^O:\d+/',$data))< die('you lose!'); >else < return $data; >> $a = 'O:4:"test":1:'; // +Number bypass $b = str_replace('O:4','O:+4', $a); unserialize(match($b)); // serialize(array($a)); unserialize('a:1:');

Use reference

a = 'abc'; $this->b= &$this->a; > public function __destruct()< if($this->a===$this->b) < echo 666; >> > $a = serialize(new test());

In the above example, setting $b as a reference to $a can make $a equal to $b forever

Hexadecimal bypass character filtering

O:4:"test":2: Can be written as O:4:"test":2: That represents the character type s When capitalized, it will be parsed as hexadecimal.
username = 'admin'; > public function __destruct() < echo 666; >> function check($data) < if(stristr($data, 'username')!==False)< echo("You can't get around!!".PHP_EOL); >else < return $data; >> // Before treatment $a = 'O:4:"test":1:'; $a = check($a); unserialize($a); // After processing, \ 75 is hexadecimal of u $a = 'O:4:"test":1:'; $a = check($a); unserialize($a);

PHP deserialization character escape

Case 1: more characters after filtering

First, the local php code is given. It is very simple. Without too much explanation, it is to replace one x after deserialization with two

 $name = $_GET['name']; $age = "I am 11"; $arr = array($name,$age); echo "Deserialize string:"; var_dump(serialize($arr)); echo "
"; echo "After filtration:"; $old = change(serialize($arr)); $new = unserialize($old); var_dump($new); echo "
At this point, age=$new[1]";

Normally, name=mao is passed in

Let’s first look at the results and then explain

We pass in name = maoxxxxxxxxxxxxxxxxxx «; I: 1; s: 6:» Woaini «;>
«; i:1;s:6:»woaini «;> This part has twenty characters in total
Since one X will be replaced by two, we have entered a total of 20 x, now it is 40. The extra 20 x actually replace our 20 characters «; i:1;s:6:»woaini «;>, resulting in»; i:1;s:6:»woaini»;> And «closes the previous string, making our string escape successfully, which can be deserialized and output Woaini
Last;> Closing the whole process of deserialization causes the original «; i:1;s:7:»I am 11 «;>» to be discarded without affecting the deserialization process

$arr[‘name’] = $_GET[‘name’]; $arr[‘age’] = $_GET[‘age’]; echo «Deserialize string:»; var_dump(serialize($arr)); echo «
«; echo «After filtration:»; $old = change(serialize($arr)); var_dump($old); echo «
«; $new = unserialize($old); var_dump($new); echo «
At this point, age blog-tags»>Keywords: PHP

Added by beginneratphp on Thu, 23 Dec 2021 20:29:00 +0200

  • Java — 6234
  • Python — 2579
  • Javascript — 2100
  • Database — 1608
  • Linux — 1477
  • Back-end — 1449
  • Front-end — 1432
  • Spring — 1358
  • Algorithm — 1311
  • Android — 1124
  • MySQL — 1040
  • C++ — 1022
  • Programming — 966
  • network — 827
  • data structure — 820
  • Attribute — 785
  • C — 721
  • github — 646
  • less — 645
  • SQL — 639

Источник

php — Escaping and Inserting Serialized Data to MySQL

I have the following data as an example:

$a = addslashes('hello\'s'); $b = serialize($a); // As you know, $b looks like this s:8:"hello\'s"; 

Now when I insert $b to MySQL, the data now looks like this s:8:»hello’s» inside MySQL. MySQL removes the \ and now I have an invalid serialized data.

What’s the best way to fix this? Thanks

Answer

Solution:

For escaping parameters to go into an SQL query you do not use addslashes, but mysql_real_escape_string .

This is the correct way to escape SQL-parameters.
Or even better use PDO with prepared statements, then you don’t have to escape at all.

Answer

Solution:

First serialize the value you want and then use the mysql_real_escape_string. That’s the string you are going to put in the database after all. Try to avoid addslashes.

If you don’t want to have an active connection at the time, try this function:

function mysql_escape_no_conn( $input ) < if( is_array( $input ) ) < return array_map( __METHOD__, $input ); >if( !empty( $input ) && is_string( $input ) ) < return str_replace( array( '\\', "\0", "\n", "\r", "'", '"', "\x1a" ), array( '\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z' ), $input ); >return $input; 

Answer

Solution:

use mysql_real_escape_string function!

Answer

Solution:

As others have said, mysql_real_escape_string() should be called!

I just wanted to add that I always find it safe to base64_encode() all serialized arrays/objects I store in a database. All you then have to do is call base64_decode() upon retrieval of the stored value. I do this because ; and other characters are liable to cause «Warning: Error at offset. » errors.

Answer

Solution:

You need to escape the string in $b by using mysql_real_escape_string() .

$a = addslashes('hello\'s'); $b = serialize($a); $sql = "UPDATE `table` SET `field`='".mysql_real_escape_string($b)."'" ; 

You should always escape input into a db to stop SQL injection.

Share solution ↓

Additional Information:

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Similar questions

Find the answer in similar questions on our website.

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

About the technologies asked in this question

PHP

PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/

MySQL

DBMS is a database management system. It is designed to change, search, add and delete information in the database. There are many DBMSs designed for similar purposes with different features. One of the most popular is MySQL. It is a software tool designed to work with relational SQL databases. It is easy to learn even for site owners who are not professional programmers or administrators. MySQL DBMS also allows you to export and import data, which is convenient when moving large amounts of information.
https://www.mysql.com/

Welcome to programmierfrage.com

programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.

Get answers to specific questions

Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.

Help Others Solve Their Issues

Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.

Источник

Оцените статью