Find this useful? Enter your email to receive occasional updates for securing PHP code.

Signing you up...

Thank you for signing up!

PHP Decode

<?php header("Access-Control-Allow-Origin: https://ssf.sead-ctf.student.iaik.tugraz.at");..

Decoded Output download

<?php 
header("Access-Control-Allow-Origin: https://ssf.sead-ctf.student.iaik.tugraz.at"); 
// Retrieve the request method and URI 
$requestMethod = $_SERVER['REQUEST_METHOD']; 
$requestUri = $_SERVER['REQUEST_URI']; 
$requestUri = strtok($requestUri, '?'); 
 
function handleError($e) { 
    http_response_code(500); 
    echo json_encode(['error' => 'Something has gone terribly wrong. Check backtrace.', 'bt' => $e->getTrace()], JSON_PARTIAL_OUTPUT_ON_ERROR); 
    exit(); 
} 
 
set_error_handler(function($num,$str,$file,$line) { 
    handleError(new ErrorException($str, 0, $num, $file, $line)); 
}); 
set_exception_handler('handleError'); 
 
// Route the request based on the method and URI 
switch ($requestUri) { 
    case '/': 
        if ($requestMethod == 'GET') { 
            handleRootRoute(); 
        } else { 
            http_response_code(405); // Method Not Allowed 
            echo json_encode(['error' => 'Method Not Allowed']); 
        } 
        break; 
    case '/login': 
        if ($requestMethod == 'POST' && isset($_SERVER['QUERY_STRING'])) { 
            $queryString = $_SERVER['QUERY_STRING']; 
            $urlParams = []; 
            if ($queryString) { 
                $urlParams = explode('&', $queryString); 
            } 
            handleLoginRoute($urlParams); 
        } else { 
            http_response_code(405); 
            echo json_encode(['error' => 'Method Not Allowed']); 
        } 
        break; 
    case '/register': 
        if ($requestMethod == 'POST' && isset($_SERVER['QUERY_STRING'])) { 
            $queryString = $_SERVER['QUERY_STRING']; 
            $urlParams = []; 
            if ($queryString) { 
                $urlParams = explode('&', $queryString); 
            } 
            handleRegisterRoute($urlParams); 
        } else { 
            http_response_code(405); 
            echo json_encode(['error' => 'Method Not Allowed']); 
        } 
        break; 
    case '/posts': 
        if ($requestMethod == 'GET') { 
            fetchPosts(); 
        } else { 
            http_response_code(405); // Method Not Allowed 
            echo json_encode(['error' => 'Method Not Allowed']); 
        } 
        break; 
    case '/files': 
        $queryString = $_SERVER['QUERY_STRING']; 
        $accessToken = explode('=', $queryString); 
        if (!isset($accessToken[1])) { 
            http_response_code(401); // Unauthorized 
            echo json_encode(['error' => 'Access token is required']); 
            return; 
        } 
        if ($requestMethod == 'GET') { 
            if (!checkAccessTokenExists($accessToken[1])) { 
                http_response_code(401); // Unauthorized 
                echo json_encode(['error' => 'Invalid access token']); 
                return; 
            } 
            fetchFiles(); 
        } else { 
            http_response_code(405); // Method Not Allowed 
            echo json_encode(['error' => 'Method Not Allowed']); 
        } 
        break; 
    case '/file': 
        if ($requestMethod == 'POST') { 
            $queryString = $_SERVER['QUERY_STRING']; 
            $urlParams = []; 
            if ($queryString) { 
                $urlParams = explode('&', $queryString); 
            } 
            handleFileRequest($urlParams); 
        } else { 
            http_response_code(405); // Method Not Allowed 
            echo json_encode(['error' => 'Method Not Allowed']); 
        } 
        break; 
    default: 
        http_response_code(404); // Not Found 
        echo json_encode(['error' => 'Route not found']); 
        break; 
} 
 
function handleRootRoute(): void 
{ 
    $response = [ 
        'message' => 'Hello, this is the webserver for Super Secure Forum (SSF)!' 
    ]; 
    echo json_encode($response); 
} 
 
// looks good enough to me 
function i0($f1, $e2): string { 
    $r3 = $f1 . $e2; 
    return hash(base64_decode('c2hhMjU2'), $r3); 
} 
 
function urlParamsOk(array $urlParams): array 
{ 
    if (count($urlParams) < 2 || !isset($urlParams[0]) || !isset($urlParams[1])) { 
        http_response_code(400); // Bad Request 
        echo json_encode(['error' => 'Username and password are required']); 
        return []; 
    } 
    $username = htmlspecialchars($urlParams[0]); 
    if (str_contains($username, '=')) { 
        $username = explode('=', $username)[1]; 
    } else { 
        http_response_code(400); // Bad Request 
        echo json_encode(['error' => 'Malformed Request for Username']); 
        return []; 
    } 
    $password = htmlspecialchars($urlParams[1]); 
    if (str_contains($password, '=')) { 
        $password = explode('=', $password)[1]; 
    } else { 
        http_response_code(400); // Bad Request 
        echo json_encode(['error' => 'Malformed Request for Password']); 
        return []; 
    } 
    $username = trim($username); 
    $password = trim($password); 
    if (strlen($username) < 5 || strlen($password) < 8) { 
        http_response_code(400); // Bad Request 
        echo json_encode(['error' => 'Username must be at least 5 characters long and password must be at least 8 characters long']); 
        return []; 
    } 
    if (str_contains($username, ':') 
        || str_contains($username, ' ') 
        || str_contains($password, ':') 
        || str_contains($password, ' ')) { 
        http_response_code(400); // Bad Request 
        echo json_encode(['error' => 'Username and password cannot contain spaces or colons']); 
        return []; 
    } 
    return [$username, $password]; 
} 
 
function handleLoginRoute(array $urlParams = []): void 
{ 
    $urlParams = urlParamsOk($urlParams); 
    if (empty($urlParams)) { 
        return; 
    } 
    [$username, $password] = $urlParams; 
    // check if user exists in file 
    if (!file_exists('server/users.txt')) { 
        http_response_code(500); // Internal Server Error 
        echo json_encode(['error' => 'Error while logging in']); 
        return; 
    } 
    $file = fopen('server/users.txt', 'r'); 
    if (!$file) { 
        http_response_code(500); // Internal Server Error 
        echo json_encode(['error' => 'Failed to open file']); 
        return; 
    } 
    while (($line = fgets($file)) !== false) { 
        $line = explode(':', $line); 
        if (count($line) < 3) { 
            continue; 
        } 
        if ($line[0] === $username) { 
            $hash = $line[1]; 
            if (i0($password, trim($line[2])) === $hash) { 
                // create a hash for the user that we can send him, save it to the users.txt file and return it 
                $accessToken = password_hash($username, PASSWORD_DEFAULT); 
                $tokens = fopen('server/tokens.txt', 'r+'); 
                if (!$tokens) { 
                    array_map('fclose', get_resources('stream')); 
                    http_response_code(500); // Internal Server Error 
                    echo json_encode(['error' => 'An error occurred.']); 
                    return; 
                } 
                while (($line = fgets($tokens)) !== false) { 
                    $line = explode(':', $line); 
                    if (count($line) < 2) { 
                        continue; 
                    } 
                    if ($line[0] === $username) { 
                        array_map('fclose', get_resources('stream')); 
                        http_response_code(500); // Internal Server Error 
                        echo json_encode(['error' => 'You have already received your token!']); 
                        return; 
                    } 
                } 
                fwrite($tokens, "$username:$accessToken" . PHP_EOL); 
                echo json_encode(['message' => 'Login successful, your token has been sent (check your cookies after dismissing this message). ' . 
                    'Make sure you do not lose it as it can not be generated again!', 'token' => $accessToken]); 
            } else { 
                http_response_code(401); // Unauthorized 
                echo json_encode(['error' => 'Invalid password']); 
            } 
            array_map('fclose', get_resources('stream')); 
            return; 
        } 
    } 
    array_map('fclose', get_resources('stream')); 
    http_response_code(404); 
    echo json_encode(['error' => 'User not found']); 
} 
 
function handleRegisterRoute(array $urlParams = []): void 
{ 
    $urlParams = urlParamsOk($urlParams); 
    if (empty($urlParams)) { 
        return; 
    } 
    [$username, $password] = $urlParams; 
    $timestamp = time(); 
    $hPw = i0($password, $timestamp); 
    if (!file_exists('server/users.txt')) { 
        http_response_code(500); // Internal Server Error 
        echo json_encode(['error' => 'An error occurred']); 
        return; 
    } 
    $file = fopen('server/users.txt', 'a+'); 
    if (!$file) { 
        http_response_code(500); // Internal Server Error 
        echo json_encode(['error' => 'Failed to open file']); 
        return; 
    } 
    //check if user exists in file 
    while (($line = fgets($file)) !== false) { 
        $line = explode(':', $line); 
        if ($line[0] === $username) { 
            http_response_code(409); // Conflict 
            echo json_encode(['error' => 'Username already in use']); 
            return; 
        } 
    } 
    fwrite($file, "$username:$hPw:$timestamp" . PHP_EOL); 
    fclose($file); 
    echo json_encode(['message' => 'User registered successfully, you can now login.']); 
} 
 
function fetchPosts(): void 
{ 
    $response = [ 
        'posts' => [ 
            [ 
                "id" => 103, 
                "title" => "The Mystery of the Vanishing Mouse Pointer", 
                "content" => "My mouse pointer disappeared! I tried following its tracks, but they vanished into thin air.", 
                "user" => "MouseTracker99", 
                "date" => "04/23/2024 10:45" 
            ], 
            [ 
                "id" => 104, 
                "title" => "The Great Keyboard Rebellion", 
                "content" => "My keyboard rebelled against me. It started typing gibberish and refused to obey my commands!", 
                "user" => "KeyboardWarrior88", 
                "date" => "04/24/2024 14:20" 
            ], 
            [ 
                "id" => 1044, 
                "title" => "The Flag must be nearby ...", 
                "content" => "https://rb.gy/8bejaj", 
                "user" => "HintyHintman", 
                "date" => "04/24/2024 16:20" 
            ], 
            [ 
                "id" => 105, 
                "title" => "Error 404: Sleep Not Found", 
                "content" => "Tried to get some sleep last night, but all I got was an error 404: Sleep not found!", 
                "user" => "InsomniacDreamer", 
                "date" => "04/25/2024 18:55" 
            ], 
            [ 
                "id" => 106, 
                "title" => "The Case of the Missing Semicolon", 
                "content" => "Spent hours trying to figure out why my code wasn't working. Turns out, it was just a missing semicolon!", 
                "user" => "SyntaxSleuth", 
                "date" => "04/26/2024 21:10" 
            ], 
            [ 
                "id" => 107, 
                "title" => "The Tale of the Unresponsive Button", 
                "content" => "Clicked the button, but nothing happened. Turns out, it was just ignoring me like a stubborn teenager!", 
                "user" => "ButtonMasher88", 
                "date" => "04/27/2024 09:30" 
            ], 
            [ 
                "id" => 108, 
                "title" => "Code Poetry", 
                "content" => "Roses are red, violets are blue. Unexpected token on line 32.", 
                "user" => "PoeticProgrammer", 
                "date" => "04/28/2024 12:45" 
            ], 
            [ 
                "id" => 109, 
                "title" => "Mystery of the Vanishing Cursor", 
                "content" => "Where did my cursor go? It vanished like socks in the laundry!", 
                "user" => "CursorChaser123", 
                "date" => "04/29/2024 15:00" 
            ], 
            [ 
                "id" => 110, 
                "title" => "Help! I'm Trapped in a Loop!", 
                "content" => "I'm stuck in an infinite loop. Send help before my computer explodes!", 
                "user" => "LoopLunatic55", 
                "date" => "04/30/2024 17:30" 
            ], 
            [ 
                'id' => 101, 
                'title' => 'It is dangerous to walk alone ...', 
                'content' => 'No hints here ... or are there some?', 
                'user' => 'HintyHintman', 
                'date' => '04/23/2024 13:37' 
            ], 
            [ 
                "id" => 111, 
                "title" => "The Curious Case of the Disappearing Code", 
                "content" => "Wrote a perfect piece of code, then it disappeared into thin air! Must be magic.", 
                "user" => "CodeMagician99", 
                "date" => "05/01/2024 10:50" 
            ], 
            [ 
                "id" => 112, 
                "title" => "Spilled Coffee", 
                "content" => "Just spilled coffee on my keyboard. Now I have a 'Java' error!", 
                "user" => "CaffeineLover82", 
                "date" => "05/02/2024 09:15" 
            ], 
            [ 
                'id' => 100, 
                'title' => 'Complaints', 
                'content' => 'Why is there such a weird interface? I have never seen such a weird interface.  
                Why can I not register normally here? I want to create a new user but the registration seems to be disabled.', 
                'user' => 'LongTimeFan1', 
                'date' => '04/22/2024 13:37' 
            ], 
            [ 
                'id' => 69, 
                'title' => 'It is nice having a secure forum', 
                'content' => 'Finally, even with tight deadlines, we are able to successfully launch our forum!  
                I just created my account yesterday evening at 20:29:51. I\'m not sure if the timezone is messed up and it is set to GMT+0000. Or was it GMT+0200?  
                I always get confused with summer time. I will look into that soon, so I have disabled registration for now until the issue is fixed. Anyways, we may or may not have had to cut a few features and rush development a bit, but at the end of the day: WHO CARES?! 
                Am I right? Obviously. After all, CEOs are always right, and developers worry way too much about security! 
                We have no vulnerabilities, after all ChatGPT even said that our code base looks perfectly secure. 
                Imagine wasting money on developers which are working in Information Security!', 
                'user' => 'admin', 
                'date' => '05/02/2024 16:20' 
            ] 
        ] 
    ]; 
    echo json_encode($response); 
} 
 
function fetchFiles(): void 
{ 
    $files = scandir('server/assets/files'); 
    $response = [ 
        'files' => [] 
    ]; 
    foreach ($files as $file) { 
        if ($file === '.' || $file === '..') { 
            continue; 
        } 
        $response['files'][] = ['name' => $file, 'owner' => 'admin', 'date' => (new DateTime())->format('m/d/Y')]; 
    } 
    echo json_encode($response); 
} 
 
function getParamValue(string $param): ?string 
{ 
    $param = htmlspecialchars($param); 
    if (str_contains($param, '=')) { 
        return explode('=', $param)[1]; 
    } else { 
        http_response_code(400); // Bad Request 
        echo json_encode(['error' => 'Malformed Request for file']); 
        return null; 
    } 
} 
 
function handleFileRequest(array $urlParams): void 
{ 
    if (count($urlParams) < 3 && !isset($urlParams[0]) && !isset($urlParams[1]) && !isset($urlParams[2])) { 
        http_response_code(400); // Bad Request 
        echo json_encode(['error' => 'Invalid Request for file']); 
        return; 
    } 
    $token = getParamValue($urlParams[0]); 
    if (!$token) { 
        http_response_code(400); // Bad Request 
        return; 
    } 
    $fileName = getParamValue($urlParams[1]); 
    if (!$fileName) { 
        http_response_code(400); // Bad Request 
        return; 
    } 
    $givenPass = getParamValue($urlParams[2]); 
    if (!checkAccessTokenExists($token)) { 
        http_response_code(401); // Unauthorized 
        echo json_encode(['error' => 'Unauthorized request for file']); 
        return; 
    } 
    $fileName = checkFilePath($fileName); 
    if (!$fileName) { 
        array_map('fclose', get_resources('stream')); 
        http_response_code(404); // Not Found 
        echo json_encode(['error' => 'File not found']); 
        return; 
    } 
    $fileOwner = getFileOwner($fileName); 
    $fileContent = file_get_contents("server/assets/files/$fileName"); 
    printFileContentIfPasswordMatches($fileContent, $fileOwner, $givenPass); 
} 
 
function checkAccessTokenExists(string $accessToken): bool { 
    $tokens = fopen('server/tokens.txt', 'r'); 
    if (!$tokens) { 
        return false; 
    } 
    while (($line = fgets($tokens)) !== false) { 
        $line = explode(':', $line); 
        if (count($line) < 2) { 
            continue; 
        } 
        if (trim($line[1]) === $accessToken) { 
            fclose($tokens); 
            return true; 
        } 
    } 
    fclose($tokens); 
    return false; 
} 
 
function checkFilePath($path) { 
    $fileName = basename($path); 
    if (!file_exists("server/assets/files/$fileName")) return false; 
    return $fileName; 
} 
 
function getFileOwner($fileName) { 
    $fileOwners = fopen('server/fileOwners.txt', 'r'); 
    assert(!!$fileOwners); 
    while (($line = fgets($fileOwners)) !== false) { 
        $line = explode(':', $line); 
        if (count($line) < 3) { 
            continue; 
        } 
        if (trim($line[0]) === $fileName) { 
            fclose($fileOwners); 
            return [trim($line[1]),trim($line[2])]; 
        } 
    } 
    fclose($fileOwners); 
    return null; 
} 
 
function printFileContentIfPasswordMatches($fileContent, $fileOwner, $givenPass) { 
    if ($fileOwner != null) { 
        list($fileOwnerUser, $filePass) = $fileOwner; 
        $users = fopen('server/users.txt', 'r'); 
        if (!$users) { 
            array_map('fclose', get_resources('stream')); 
            http_response_code(500); // Internal Server Error 
            echo json_encode(['error' => 'An error occurred']); 
            return; 
        } 
        while (($line = fgets($users)) !== false) { 
            $line = explode(':', $line); 
            if (count($line) < 3) { 
                continue; 
            } 
            if (trim($line[0]) === $fileOwnerUser) { 
                $hPw = trim($line[1]); 
                if ($givenPass === $hPw) { 
                   array_map('fclsoe', get_resources('stream')); 
                   http_response_code(400); // Bad Request 
                   echo json_encode(['error' => 'Use the file password, not your user password!']); 
                   return; 
                } 
                break; 
            } 
        } 
        if ($filePass && !password_verify($givenPass, $filePass)) { 
            array_map('fclose', get_resources('stream')); 
            http_response_code(401); // Unauthorized 
            echo json_encode(['error' => 'Invalid password for file']); 
            return; 
        } 
    } 
    array_map('fclose', get_resources('stream')); 
    http_response_code(200); 
    echo json_encode(['file' => $fileContent]); 
} 
 ?>

Did this file decode correctly?

Original Code

<?php
header("Access-Control-Allow-Origin: https://ssf.sead-ctf.student.iaik.tugraz.at");
// Retrieve the request method and URI
$requestMethod = $_SERVER['REQUEST_METHOD'];
$requestUri = $_SERVER['REQUEST_URI'];
$requestUri = strtok($requestUri, '?');

function handleError($e) {
    http_response_code(500);
    echo json_encode(['error' => 'Something has gone terribly wrong. Check backtrace.', 'bt' => $e->getTrace()], JSON_PARTIAL_OUTPUT_ON_ERROR);
    exit();
}

set_error_handler(function($num,$str,$file,$line) {
    handleError(new ErrorException($str, 0, $num, $file, $line));
});
set_exception_handler('handleError');

// Route the request based on the method and URI
switch ($requestUri) {
    case '/':
        if ($requestMethod == 'GET') {
            handleRootRoute();
        } else {
            http_response_code(405); // Method Not Allowed
            echo json_encode(['error' => 'Method Not Allowed']);
        }
        break;
    case '/login':
        if ($requestMethod == 'POST' && isset($_SERVER['QUERY_STRING'])) {
            $queryString = $_SERVER['QUERY_STRING'];
            $urlParams = [];
            if ($queryString) {
                $urlParams = explode('&', $queryString);
            }
            handleLoginRoute($urlParams);
        } else {
            http_response_code(405);
            echo json_encode(['error' => 'Method Not Allowed']);
        }
        break;
    case '/register':
        if ($requestMethod == 'POST' && isset($_SERVER['QUERY_STRING'])) {
            $queryString = $_SERVER['QUERY_STRING'];
            $urlParams = [];
            if ($queryString) {
                $urlParams = explode('&', $queryString);
            }
            handleRegisterRoute($urlParams);
        } else {
            http_response_code(405);
            echo json_encode(['error' => 'Method Not Allowed']);
        }
        break;
    case '/posts':
        if ($requestMethod == 'GET') {
            fetchPosts();
        } else {
            http_response_code(405); // Method Not Allowed
            echo json_encode(['error' => 'Method Not Allowed']);
        }
        break;
    case '/files':
        $queryString = $_SERVER['QUERY_STRING'];
        $accessToken = explode('=', $queryString);
        if (!isset($accessToken[1])) {
            http_response_code(401); // Unauthorized
            echo json_encode(['error' => 'Access token is required']);
            return;
        }
        if ($requestMethod == 'GET') {
            if (!checkAccessTokenExists($accessToken[1])) {
                http_response_code(401); // Unauthorized
                echo json_encode(['error' => 'Invalid access token']);
                return;
            }
            fetchFiles();
        } else {
            http_response_code(405); // Method Not Allowed
            echo json_encode(['error' => 'Method Not Allowed']);
        }
        break;
    case '/file':
        if ($requestMethod == 'POST') {
            $queryString = $_SERVER['QUERY_STRING'];
            $urlParams = [];
            if ($queryString) {
                $urlParams = explode('&', $queryString);
            }
            handleFileRequest($urlParams);
        } else {
            http_response_code(405); // Method Not Allowed
            echo json_encode(['error' => 'Method Not Allowed']);
        }
        break;
    default:
        http_response_code(404); // Not Found
        echo json_encode(['error' => 'Route not found']);
        break;
}

function handleRootRoute(): void
{
    $response = [
        'message' => 'Hello, this is the webserver for Super Secure Forum (SSF)!'
    ];
    echo json_encode($response);
}

// looks good enough to me
function i0($f1, $e2): string {
    $r3 = $f1 . $e2;
    return hash(base64_decode('c2hhMjU2'), $r3);
}

function urlParamsOk(array $urlParams): array
{
    if (count($urlParams) < 2 || !isset($urlParams[0]) || !isset($urlParams[1])) {
        http_response_code(400); // Bad Request
        echo json_encode(['error' => 'Username and password are required']);
        return [];
    }
    $username = htmlspecialchars($urlParams[0]);
    if (str_contains($username, '=')) {
        $username = explode('=', $username)[1];
    } else {
        http_response_code(400); // Bad Request
        echo json_encode(['error' => 'Malformed Request for Username']);
        return [];
    }
    $password = htmlspecialchars($urlParams[1]);
    if (str_contains($password, '=')) {
        $password = explode('=', $password)[1];
    } else {
        http_response_code(400); // Bad Request
        echo json_encode(['error' => 'Malformed Request for Password']);
        return [];
    }
    $username = trim($username);
    $password = trim($password);
    if (strlen($username) < 5 || strlen($password) < 8) {
        http_response_code(400); // Bad Request
        echo json_encode(['error' => 'Username must be at least 5 characters long and password must be at least 8 characters long']);
        return [];
    }
    if (str_contains($username, ':')
        || str_contains($username, ' ')
        || str_contains($password, ':')
        || str_contains($password, ' ')) {
        http_response_code(400); // Bad Request
        echo json_encode(['error' => 'Username and password cannot contain spaces or colons']);
        return [];
    }
    return [$username, $password];
}

function handleLoginRoute(array $urlParams = []): void
{
    $urlParams = urlParamsOk($urlParams);
    if (empty($urlParams)) {
        return;
    }
    [$username, $password] = $urlParams;
    // check if user exists in file
    if (!file_exists('server/users.txt')) {
        http_response_code(500); // Internal Server Error
        echo json_encode(['error' => 'Error while logging in']);
        return;
    }
    $file = fopen('server/users.txt', 'r');
    if (!$file) {
        http_response_code(500); // Internal Server Error
        echo json_encode(['error' => 'Failed to open file']);
        return;
    }
    while (($line = fgets($file)) !== false) {
        $line = explode(':', $line);
        if (count($line) < 3) {
            continue;
        }
        if ($line[0] === $username) {
            $hash = $line[1];
            if (i0($password, trim($line[2])) === $hash) {
                // create a hash for the user that we can send him, save it to the users.txt file and return it
                $accessToken = password_hash($username, PASSWORD_DEFAULT);
                $tokens = fopen('server/tokens.txt', 'r+');
                if (!$tokens) {
                    array_map('fclose', get_resources('stream'));
                    http_response_code(500); // Internal Server Error
                    echo json_encode(['error' => 'An error occurred.']);
                    return;
                }
                while (($line = fgets($tokens)) !== false) {
                    $line = explode(':', $line);
                    if (count($line) < 2) {
                        continue;
                    }
                    if ($line[0] === $username) {
                        array_map('fclose', get_resources('stream'));
                        http_response_code(500); // Internal Server Error
                        echo json_encode(['error' => 'You have already received your token!']);
                        return;
                    }
                }
                fwrite($tokens, "$username:$accessToken" . PHP_EOL);
                echo json_encode(['message' => 'Login successful, your token has been sent (check your cookies after dismissing this message). ' .
                    'Make sure you do not lose it as it can not be generated again!', 'token' => $accessToken]);
            } else {
                http_response_code(401); // Unauthorized
                echo json_encode(['error' => 'Invalid password']);
            }
            array_map('fclose', get_resources('stream'));
            return;
        }
    }
    array_map('fclose', get_resources('stream'));
    http_response_code(404);
    echo json_encode(['error' => 'User not found']);
}

function handleRegisterRoute(array $urlParams = []): void
{
    $urlParams = urlParamsOk($urlParams);
    if (empty($urlParams)) {
        return;
    }
    [$username, $password] = $urlParams;
    $timestamp = time();
    $hPw = i0($password, $timestamp);
    if (!file_exists('server/users.txt')) {
        http_response_code(500); // Internal Server Error
        echo json_encode(['error' => 'An error occurred']);
        return;
    }
    $file = fopen('server/users.txt', 'a+');
    if (!$file) {
        http_response_code(500); // Internal Server Error
        echo json_encode(['error' => 'Failed to open file']);
        return;
    }
    //check if user exists in file
    while (($line = fgets($file)) !== false) {
        $line = explode(':', $line);
        if ($line[0] === $username) {
            http_response_code(409); // Conflict
            echo json_encode(['error' => 'Username already in use']);
            return;
        }
    }
    fwrite($file, "$username:$hPw:$timestamp" . PHP_EOL);
    fclose($file);
    echo json_encode(['message' => 'User registered successfully, you can now login.']);
}

function fetchPosts(): void
{
    $response = [
        'posts' => [
            [
                "id" => 103,
                "title" => "The Mystery of the Vanishing Mouse Pointer",
                "content" => "My mouse pointer disappeared! I tried following its tracks, but they vanished into thin air.",
                "user" => "MouseTracker99",
                "date" => "04/23/2024 10:45"
            ],
            [
                "id" => 104,
                "title" => "The Great Keyboard Rebellion",
                "content" => "My keyboard rebelled against me. It started typing gibberish and refused to obey my commands!",
                "user" => "KeyboardWarrior88",
                "date" => "04/24/2024 14:20"
            ],
            [
                "id" => 1044,
                "title" => "The Flag must be nearby ...",
                "content" => "https://rb.gy/8bejaj",
                "user" => "HintyHintman",
                "date" => "04/24/2024 16:20"
            ],
            [
                "id" => 105,
                "title" => "Error 404: Sleep Not Found",
                "content" => "Tried to get some sleep last night, but all I got was an error 404: Sleep not found!",
                "user" => "InsomniacDreamer",
                "date" => "04/25/2024 18:55"
            ],
            [
                "id" => 106,
                "title" => "The Case of the Missing Semicolon",
                "content" => "Spent hours trying to figure out why my code wasn't working. Turns out, it was just a missing semicolon!",
                "user" => "SyntaxSleuth",
                "date" => "04/26/2024 21:10"
            ],
            [
                "id" => 107,
                "title" => "The Tale of the Unresponsive Button",
                "content" => "Clicked the button, but nothing happened. Turns out, it was just ignoring me like a stubborn teenager!",
                "user" => "ButtonMasher88",
                "date" => "04/27/2024 09:30"
            ],
            [
                "id" => 108,
                "title" => "Code Poetry",
                "content" => "Roses are red, violets are blue. Unexpected token on line 32.",
                "user" => "PoeticProgrammer",
                "date" => "04/28/2024 12:45"
            ],
            [
                "id" => 109,
                "title" => "Mystery of the Vanishing Cursor",
                "content" => "Where did my cursor go? It vanished like socks in the laundry!",
                "user" => "CursorChaser123",
                "date" => "04/29/2024 15:00"
            ],
            [
                "id" => 110,
                "title" => "Help! I'm Trapped in a Loop!",
                "content" => "I'm stuck in an infinite loop. Send help before my computer explodes!",
                "user" => "LoopLunatic55",
                "date" => "04/30/2024 17:30"
            ],
            [
                'id' => 101,
                'title' => 'It is dangerous to walk alone ...',
                'content' => 'No hints here ... or are there some?',
                'user' => 'HintyHintman',
                'date' => '04/23/2024 13:37'
            ],
            [
                "id" => 111,
                "title" => "The Curious Case of the Disappearing Code",
                "content" => "Wrote a perfect piece of code, then it disappeared into thin air! Must be magic.",
                "user" => "CodeMagician99",
                "date" => "05/01/2024 10:50"
            ],
            [
                "id" => 112,
                "title" => "Spilled Coffee",
                "content" => "Just spilled coffee on my keyboard. Now I have a 'Java' error!",
                "user" => "CaffeineLover82",
                "date" => "05/02/2024 09:15"
            ],
            [
                'id' => 100,
                'title' => 'Complaints',
                'content' => 'Why is there such a weird interface? I have never seen such a weird interface. 
                Why can I not register normally here? I want to create a new user but the registration seems to be disabled.',
                'user' => 'LongTimeFan1',
                'date' => '04/22/2024 13:37'
            ],
            [
                'id' => 69,
                'title' => 'It is nice having a secure forum',
                'content' => 'Finally, even with tight deadlines, we are able to successfully launch our forum! 
                I just created my account yesterday evening at 20:29:51. I\'m not sure if the timezone is messed up and it is set to GMT+0000. Or was it GMT+0200? 
                I always get confused with summer time. I will look into that soon, so I have disabled registration for now until the issue is fixed. Anyways, we may or may not have had to cut a few features and rush development a bit, but at the end of the day: WHO CARES?!
                Am I right? Obviously. After all, CEOs are always right, and developers worry way too much about security!
                We have no vulnerabilities, after all ChatGPT even said that our code base looks perfectly secure.
                Imagine wasting money on developers which are working in Information Security!',
                'user' => 'admin',
                'date' => '05/02/2024 16:20'
            ]
        ]
    ];
    echo json_encode($response);
}

function fetchFiles(): void
{
    $files = scandir('server/assets/files');
    $response = [
        'files' => []
    ];
    foreach ($files as $file) {
        if ($file === '.' || $file === '..') {
            continue;
        }
        $response['files'][] = ['name' => $file, 'owner' => 'admin', 'date' => (new DateTime())->format('m/d/Y')];
    }
    echo json_encode($response);
}

function getParamValue(string $param): ?string
{
    $param = htmlspecialchars($param);
    if (str_contains($param, '=')) {
        return explode('=', $param)[1];
    } else {
        http_response_code(400); // Bad Request
        echo json_encode(['error' => 'Malformed Request for file']);
        return null;
    }
}

function handleFileRequest(array $urlParams): void
{
    if (count($urlParams) < 3 && !isset($urlParams[0]) && !isset($urlParams[1]) && !isset($urlParams[2])) {
        http_response_code(400); // Bad Request
        echo json_encode(['error' => 'Invalid Request for file']);
        return;
    }
    $token = getParamValue($urlParams[0]);
    if (!$token) {
        http_response_code(400); // Bad Request
        return;
    }
    $fileName = getParamValue($urlParams[1]);
    if (!$fileName) {
        http_response_code(400); // Bad Request
        return;
    }
    $givenPass = getParamValue($urlParams[2]);
    if (!checkAccessTokenExists($token)) {
        http_response_code(401); // Unauthorized
        echo json_encode(['error' => 'Unauthorized request for file']);
        return;
    }
    $fileName = checkFilePath($fileName);
    if (!$fileName) {
        array_map('fclose', get_resources('stream'));
        http_response_code(404); // Not Found
        echo json_encode(['error' => 'File not found']);
        return;
    }
    $fileOwner = getFileOwner($fileName);
    $fileContent = file_get_contents("server/assets/files/$fileName");
    printFileContentIfPasswordMatches($fileContent, $fileOwner, $givenPass);
}

function checkAccessTokenExists(string $accessToken): bool {
    $tokens = fopen('server/tokens.txt', 'r');
    if (!$tokens) {
        return false;
    }
    while (($line = fgets($tokens)) !== false) {
        $line = explode(':', $line);
        if (count($line) < 2) {
            continue;
        }
        if (trim($line[1]) === $accessToken) {
            fclose($tokens);
            return true;
        }
    }
    fclose($tokens);
    return false;
}

function checkFilePath($path) {
    $fileName = basename($path);
    if (!file_exists("server/assets/files/$fileName")) return false;
    return $fileName;
}

function getFileOwner($fileName) {
    $fileOwners = fopen('server/fileOwners.txt', 'r');
    assert(!!$fileOwners);
    while (($line = fgets($fileOwners)) !== false) {
        $line = explode(':', $line);
        if (count($line) < 3) {
            continue;
        }
        if (trim($line[0]) === $fileName) {
            fclose($fileOwners);
            return [trim($line[1]),trim($line[2])];
        }
    }
    fclose($fileOwners);
    return null;
}

function printFileContentIfPasswordMatches($fileContent, $fileOwner, $givenPass) {
    if ($fileOwner != null) {
        list($fileOwnerUser, $filePass) = $fileOwner;
        $users = fopen('server/users.txt', 'r');
        if (!$users) {
            array_map('fclose', get_resources('stream'));
            http_response_code(500); // Internal Server Error
            echo json_encode(['error' => 'An error occurred']);
            return;
        }
        while (($line = fgets($users)) !== false) {
            $line = explode(':', $line);
            if (count($line) < 3) {
                continue;
            }
            if (trim($line[0]) === $fileOwnerUser) {
                $hPw = trim($line[1]);
                if ($givenPass === $hPw) {
                   array_map('fclsoe', get_resources('stream'));
                   http_response_code(400); // Bad Request
                   echo json_encode(['error' => 'Use the file password, not your user password!']);
                   return;
                }
                break;
            }
        }
        if ($filePass && !password_verify($givenPass, $filePass)) {
            array_map('fclose', get_resources('stream'));
            http_response_code(401); // Unauthorized
            echo json_encode(['error' => 'Invalid password for file']);
            return;
        }
    }
    array_map('fclose', get_resources('stream'));
    http_response_code(200);
    echo json_encode(['file' => $fileContent]);
}

Function Calls

None

Variables

None

Stats

MD5 eb5434912c47590155db5ab32db5253b
Eval Count 0
Decode Time 52 ms