phpPHP

PHP Web Challenge

preg_replace()

It is used in string manipulation to search and replace specific patterns with strings.

$final_string = preg_replace($pattern,$replace,$input)

$pattern = strings being listed. $replace = to be replace if match $input = from user.

Example 1.

$input = " Hello Master "
$pattern = "/Master/i" // in regex, I represent case-insensitive.

$replace = "hacker!"

$result = preg_replace($pattern,$replace,$input)
echo $result

//Output : Hello hacker!

Sample CTF

The above code can be divided into multiple parts.

  1. Read Source Code

Providing the URL with value source. http://URL/index.php?source

  1. Get parameter

Supply the URL with value anime_is_bae with any text. Then it will store in $your_entered_string

  1. preg_replace

It will check the your_entered_string with preg_replace. The pattern here is /$intermediate_string/, if similar it will return, (whitespace).

  1. Condition check

Lastly, it will check final_strings with intermediate_string. If the condition meet, it will return super_secret_function()

Exploitation.

preg_replace check for all character. For example "hello", 'c' and etc.

If the input strings match 100% as the pattern. It will replace the strings with $replace.

In this case, the $intermediate_string check with $your_entered_string

As we can see, the user input can directly bypass since it only checks full words "hellotherehooman"

Another CTF

We can see the URL receive 3 GET inputs, namely as pat, rep and sub. For each GET, it represent pattern, replace and subject/input.

http://URL/index.php?pat=/As/&rep=as&sub=your exploit

Exploitation

PHP version 5.0 and below. Can execute /e/ modifier.

http://URL/index.php?pat=/a/e/&rep=phpinfo();&sub="Payload"

Proof that we can bypass it.

PHP Type Jungling

PHP will automatically perform conversion from one data type to another based on context. This is referred to as type juggling.

There are strict (===) and loose(==) comparisons.

In PHP, == is used for the loose comparison of variables. This means PHP will attempt to convert variables where it appears to make sense

The vulnerability occurs in loose comparison.

If (($username == _POST['username'] )==0) and (($password == _POST['password'] )==0) it will return to the endpoint /upload.php

Since the strcmp can be manipulated as an array. Assign the $username as an array to bypass comparison.

username[]=anything&password[]=anything

strcasecmp

Binary safe case-insensitive string comparison where trcasecmp(a,b) will return null when either a or b is not a string. In addition, null has the same numerical value as 0. Since we use == operator instead of === here, then null == 0.

Last updated