Wednesday, May 1, 2019

Python TCP keepalive on http request

The issue

So a while ago, while working on a project, I encountered an endpoint that required some heavy computations to produce the response and as a result the response usually took a bit more than 5 minutes.

 The examples that existed showcasing the usage of said endpoint were all done with curl.

So, my turn comes to consume this endpoint and lo and behold! The request hangs. Okay, weird. Let's try curl again. Works fine. Python, nope. Let's check with wget then, no luck.

In my desperation I tried all the Python libraries I had used in the past (requests, the built in http.client and aiohttp) obviously setting all the applicable timeouts sky high. Still no luck!

So what's so special about curl, what did it do that both wget and my Python implementation failed to?


Troubleshooting

Desperate times call for desperate measures I told my self and I grabbed my trusty strace brewed a big ol cup of coffee and got to work.

First thing that is immediately obvious to me is that curl does indeed do something different as strace tells me that curl blocks with epoll while both wget and my Python solutions block with select. This gives me a first clue that curl does indeed do 'something else' (TM) besides just waiting for a response but leaves me with not much more to follow on.

I decide to switch context and go from the lowest possible (for me at least) level to my most high level approach: replicate the Python solutions with insanely high timeouts and monitor its behavior. This yields an interesting result! The target endpoint supports a notation for the client to specify the seconds until the request should timeout, but despite my explicit definition of it to 600 seconds (that's 10 minutes) the remote server hasn't sent me (or should I say I haven't gotten ;) ) an explicit timeout for more than 15 minutes. This brings back bad memories ... This uncannily resembles the behavior of a firewall that instead of dropping the packets it just filters them, this way the client never explicitly knows that it cannot connect and just waits.

But the reminder the curl worked perfectly quickly snaps this thought out of my mind. Time for another coffee (I could use the break anyways)! While I wait for my coffee to brew I start whining to (ehm .. I mean discussing with) a colleague (SysAdmin) about the issue and my findings. In a heartbeat he suggest a misbehaving firewall. But why! How could curl go through I still don't get it. It's nearly night and there's a weekend ahead of me so I call it a day.

Monday morning I find a set of netstat commands (one with curl running against said endpoint and one with wget) along with their result. Son of a female dog!

With curl:

$ netstat -at --timers

Proto Recv-Q Send-Q Local Address           Foreign Address         State       Timer
.....
tcp        0      0 localMachine:lPort        remoteMachine ESTABLISHED keepalive (60/0/0)
.....

With wget:

$ netstat -at --timers

Proto Recv-Q Send-Q Local Address           Foreign Address         State       Timer
.....
tcp        0      0 localMachine:lPort        remoteMachine ESTABLISHED off (0.00/0/0)
.....

So now I know! curl uses a TCP level keepalive which means that a TCP packet is transmitted in a fixed interval regardless of whether there are any actual data to transfer. So there is in deed a misconfigured firewall somewhere along the way that chops down long running connections (anything longer than 5 minutes as I found out with some troubleshooting) without informing either party that the connection was dropped.

And now what ?

So you know what kind of problem you have but this isn't even half the solution. Unfortunately I could find in none of the http libraries I use in Python a reliable way to enable TCP keepalive through their API.

Show me the code !

I took the simplest and more 'core' solution here because it's easier for showcasing the approach; the same logic would apply with any other library.

# construct your headers; maybe add a keepalive header here to avoid the remote server closing the connection
headers = {}
# create your connection object 
conn = http.client.HTTPSConnection(host, timeout=600)
conn.connect()
# Now you will need to access the socket object of your connection; how you access this will vary depending on the library you use 
s = conn.sock
# Set the following socket options (feel free to play with the values to find what works best for you)
# SO_KEEPALIVE: 1 => Enable TCP keepalive
# TCP_KEEPIDLE: 60 => Time in seconds until the first keepalive is sent
# TCP_KEEPINTVL: 60 => How often should the keepalive packet be sent
# TCP_KEEPCNT: 100 => The max number of keepalive packets to send
s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 60)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 100)
conn.request("GET", "/endpoint", {}, headers)
response = conn.getresponse()
data = response.read()

Thursday, January 17, 2019

[CVE-2018-1000814] Session reuse on aiohttp-session prior to 2.7.0

On Oct 08 2018 a session reuse vulnerability was discovered (and disclosed in aiohttp-session#325) in aiohttp-session that falls under CWE-287 (Improper Authentication) and is caused by the library's reliance on Storage technology for data expiration.

Due to this reliance storage backends with inherent expiry like Redis or Memcached were not vulnerable. On backends that solely rely on cookie storage for information storage, like EncryptedCookieStorage and NaClCookieStorage, however it is possible for a malicious client to re-create a cookie with the same session data. This effectively provides infinite lifetime sessions, thus defeating the purpose of session expiry which is to minimize the attack window on the most vulnerable part of an application's authentication, that is the session transfer.

On Oct 13 2018 the vulnerability was patched with aiohttp-session#331 and aiohttp-session v2.7.0 was released.

Finally on Dec 20 2018 this vulnerability was assigned CVE-2018-1000814.

Side effects

The applied patch of #331 does have some side effects. The patch breaks an implicit behavior of the library to create 'idle sessions'. So if you are not using one of the vulnerable backends and are utilizing aiohttp-session for idle sessions your best bet is to freeze your dependencies to aiohttp-session==2.6.0 until a fix is released.


Other references

Vulndb
NVD/NIST

Monday, June 25, 2018

[CVE-2018-1000519] Session Fixation on aiohttp-session prior to 2.4.0

tl;dr If you are using a version of aiohttp-session prior to 2.4.0 update!

 On Apr 30 2018 a session fixation vulnerability was discovered in aiohttp-session which was caused by improper session (in)validation. A detailed description of the vulnerability, steps to reproduce and Proof of Concept code can be found at aiohttp-session#272.

The gist of it is that when invalidating a session, the value of the session was set to equal `{}`. However, when validating a session (i.e. loading it) a session was considered valid if its value was `!= None`.

This could allow a malicious actor to acquire a session, invalidate it, inject the cookie to a victim's browser (before the victim authenticates) and then control the victims session after the victim authenticates (by knowing the session cookie's value).

On May 4 2018 the vulnerability was patched (with aiohttp-session#273) and aiohttp-session v2.4.0 was released.

On May 12 2018 aiohttp-session's API (and documentation) was expanded to allow explicit acquisition of new session (to be used on login functions) to safeguard from user-code oriented Session Fixation vulnerabilities.

Finally on Jun 22 2018 this vulnerability was assigned CVE-2018-1000519.

Sunday, February 12, 2017

Kali Linux on Android (Feb 2017)



So a few months back (Sept. 2016) I wrote a piece here about installing Kali Linux on an Android device. Unfortunately that guide is no longer valid, as Kali Sana the branch of Kali on which it was based has been deprecated and removed from the official repositories and is only available on backup repositories and is set to be removed from those too in the near future. So a new challenge appeared. The obvious route was to check if Linux Deploy's out of the box method was working this time. But again there were a few quirks prohibiting a smooth installation and execution. So this is an updated guide as of Feb. 2017 on how to install and lunch Kali Linux on an Android mobile device. You will notice that a lot of the steps are the same, that's because the base approach is the same it's a few details that had to be changed.

The Requirements

Preparation

  1. Partition the SD and format each partition (THIS WILL DELETE YOUR DATA). You'll need:
    • 1st Partition 512 MB formatted in FAT32
    • 2nd Partition the rest of the SD formatted in EXT2
  2.  Install the APPs listed above
  3. Open Link2SD
  4. You should be greeted by this screen

    1. Select ext2 and press ok
    2. When prompted reboot your device
  5. Open BusyBox
    1. Press INSALL 

    Installation

    1. Open Linux Deploy (From here on ensure constant Wifi connection and power)
      1. Press your phone's menu button
      2. Press status
      3. Under Available mount point there should be something like /data/sdext2, make note of that.
      4. Press the button on the right (looks like a download icon)
      5. In Distribution select Kali Linux
      6. In Distribution Suite select kali-rolling
      7. In Architecture select armhf
      8. In Installation type select Directory
      9. In Installation Path type in the path you took note of before
      10. (Optional)  Change Username & Password
      11. Set DNS server to 8.8.8.8 (Google's Public DNS server) since the default tends to fail
      12. Set Localization to en_US.UTF-8
      13. Under the Init Menu check enable
      14. Under Init System choose sysv
      15. Under SSH check enable
      16. Under SSH Settings > SSH options write the following
        1. ServerAliveInterval 15
        2. This will ensure the connection doesn't timeout during the installation of packets that can take up to hours.
      17. (Optional) Enable GUI options like VNC (won't get into it here)
      18. Press Menu > Install
      19. This might take a while ...
      20. When you see "<<<install" on Linux Deploy's logs the installation has finished
      21. Press Menu > Configure
      22. (If there was no error your system is now ready to boot).
      23. Here's where things change. DON'T PRESS START!
      24. Exit Linux Deploy by pressing the App's menu button and then Exit.
      25. Open Terminal Emulator
        1. su
        2. /data/data/ru.meefik.linuxdeploy/bin/linuxdeploy shell
        3. service ssh start
        4. exit
        5. exit
        6. This should Start Kali
      26. After every restart of the mobile device Kali has to start as demonstrated in the previous step (will provide automation script in following article)
      27. I have yet to find how to stop Kali without rebooting the device (which is what Linux Deploy does when you press stop). If anyone has any ideas feel free to drop a comment
    2. Now from ConnectBot ssh to yourusername@localhost
      1. sudo apt-get update
      2. sudo apt-get dist-upgrade
      3. (if prompted)
        sudo apt-get autoremove
      4. sudo apt-get install kali-linux-full
      5. PATIENCE, since this will download around 4GB of data
      6. The above is the most error prone part of the process. Ensure CONSTANT internet access and UNINTERRUPTED power to the mobile device. 
    3.  If everything went right you should now have a working setup of Kali Linux on your Android phone
    4. (Optional) If you don't need to SSH into you mobile's Kali from another device, consider limiting SSH access only from localhost.
    Hope this helps a few people skip a bit of the frustration. Have fun!

    Disclaimer: Make sure you understand what you are doing and follow the above AT YOUR OWN RISK. I had no problem during the above procedure, carried out multiple times on a couple devices, this isn't to say that problems cannot occur.

    Sunday, January 15, 2017

    How to change GitHub repo's preview image (sort of)

     Do you like having a photo of yourself as GitHub avatar but hate having it pop up as a preview when you post a repo on social media? Reed on!



    First things first, let me explain the "(sort of)" part o the title. Since there is no officially supported way from GitHub, at the time of writing, to achieve the desired result, the process described is a workaround, a hack, and thus entails a trade-off; you have to use a custom URL so anyone sharing directly the URL of your repo will get the original preview image.

    To achieve our goal we are going to utilize GitHub's project page generator that will generate a URL in the form : <username>.github.io/<repoName> (and this will be the link you will be sharing instead of the direct repo link that would be github.com/<username>/<repoName>). To better understand the process, we will see a general and an applied example in parallel. So in our case we will take one of my GitHub repos as an example github.com/panagiks/RSPET and the generated link will be panagiks.github.io/RSPET.

    GitHub's Project page generator

    GitHub provides a few ways to generate project pages, but for the purpose of this post we'll go with the gh-pages branch approach. First, create a new branch in your repo named "gh-pages" (no quotes) and empty it (delete all and any files that were at the source branch). Now create an empty file in the root of the newly created branch named "index.html". Now go to the repo's settings page and scroll down to the "GitHub Pages" section. There, in the "Source" section, you should see "gh-pages branch" selected in the drop-down menu, if not select it.

    Populating index.html

    The point is to create a webpage that will have the appropriate "meta" tags for social media to present it as if it was your GitHub repo, just changing the tags that correspond to the preview image. First make sure that you have uploaded the desired (new) preview image to a CDN (Content Distribution Network), I prefer Flikr for this because it's free and you can easily keep all your images in one place and also have them resized, but feel free to use any CDN you prefer the only thing that matters is that you have a URL pointing to the image. First is our example for github.com/panagiks/RSPET and following is the head section of the general index.html:

    In the body of index.html we only want it to redirect to the actual GitHub repo, to do that we do the following:



    Final Notes

    A helpful tool is Facebook's debug tool, from which you can see how Facebook will load and display your link as well as force its scrapper to rescrape your link. Finally, I intend to write a small script that will generate automatically the above "index.html" for any given GitHub repo, so stay tuned!
     

    Edit

    As promised, here's RGHPI, a script to automate the HTML generation step :)

    Friday, September 9, 2016

    Liked Elliot's one-tap command execution? Here you go!


    Did you like the way Elliot executed a PenTesting tool just by tapping a shortcut on his home screen? Well I'm going to show how to do this yourself. Now, there are a couple of ways this can be done, but the approach we're going to take here presumes you have a working installation of Kali Linux on your android. Without further delay, let's get to it!

    The Requirements

    1. A working installation of Kali Linux on your Android smartphone (as shown here)
    2. ConnectBot ssh client for Android
    3. Tasker for Android (Yes, I know, it costs 3)

    Preparation

    1. First we have to do away with the password requirement during ssh log-in
      1. To do that we will use ssh keys instead
      2. Open Linux Deploy (Make sure you have Kali's profile selected)
      3. Press "Start"
      4. Open ConnectBot
      5. Press your phone's menu button
      6. Select "Manage Pubkeys"
      7. You should see an empty screen (If you haven't already created another key, that is)
      8. Press your phone's menu button
      9. Select Generate
      10. Give a unique nickname to your key
      11. Select type and strength (I used RSA 4096bits)
      12. Leave the password blank
      13. Select "Load key in start"
      14. Now a key should appear in the previously empty screen
      15. Now we need to export the public key in order to provide it to the guest OS
      16. Long press on the key we just generated
      17. Select copy public key
      18. Now the public key is in the clipboard
      19. Go back and ssh into kali (with your password)
      20. Now in Kali run the following
        1. mkdir ~/.ssh
        2. nano ~/.ssh/authorized_keys
        3. Long press on the screen and paste the public key
        4. Send Ctrl+O 
          1. Tap once on the screen a small bar appears just above the keyboard
          2. On the far left there is a button that says ctrl, keep pressing that
          3. Press O from the on-screen keyboard
          4. You will be prompted for a file name just press enter
        5. Send Ctrl+X (the same way as Ctrl+O)
        6. sudo service ssh restart
        7. Press your phone's menu button
        8. Select Disconnect
    2. Second is the log-in automation and command execution
      1. On ConnectBot
      2. Type android@localhost in the field below and press Enter (this will create a new profile)
      3. You will be taken to the log-in prompt ignore it and go back to ConnectBot's main screen
      4. Long press on the profile that reads android@localhost
      5. Select Edit host
      6. In this example we will create a simple nmap execution
      7. So change the nickname to nmap (be careful to give each profile a unique nickname)
      8. Select Use pubkey authentication
      9. In the prompt select the key we created earlier
      10. Select Post-login automation (here you will write the commands the shortcut will execute)
      11. For our example 
        1. nmap 192.168.1.0/24
        2. Add a new line in the end (i.e. press Enter)
      12.  Press ok
      13. Now to test it go back to ConnectBot's main screen and tap on the profile named nmap
      14. If everything was done correctly it will log-in automatically and run an nmap scan on the 192.168.1.0/24 subnet
    3. And third is the home screen shortcut
      1. Open Tasker
      2. Go to the Tasks tab
      3. Press the + Sign
      4. Name your task (this name will show on the home screen) 
      5. In Task edit press the + sign 
      6. Select System
      7. Select send Intent
        1. Action : android.intent.action.VIEW
        2. Cat : Default
        3. Data : ssh://android@localhost/#nmap (in the position of nmap you put the ConnectBot profile you want to use each time)
        4. Target : Activity
      8. Go back to Task edit
      9. Press the play button (this will run the macro) 
      10. If everything was done correctly you will see ConnectBot opening logging into Kali and executing the nmap scan we set earlier
        1. If a prompt appears about what app to use select ConnectBot and press Always
      11. Go to your home screen
      12. Go to your add widget menu
      13. Select Task Shortcut
      14. Place the widget on the screen
      15. Tasker will open
      16. From Task Selection select nmap (or the task you want to add)
      17. Press the menu-like icon on the lower-right corner to select an icon
      18. Select the icon you prefer
      19. Press back
      20. You should now be able to see the icon you selected earlier on the screen
      21. Tap it
      22. If everything went well it will open ConnectBot log into Kali and execute the nmap command we set up earlier.

    Limitations/Considerations


    Unfortunately this method doesn't come without its flaws. For starters, Kali Linux has to be manually started through Linux Deploy (although it should be possible to make a one-tap task to automate that too so if anyone reading this has done it please leave a comment bellow). Secondly, if you close Tasker (not exit the interface, Close by selecting disable) tapping the shortcuts will do nothing so you will have to have Tasker running.

    Hope you found this guide helpful and easy to follow, if you have any suggestions/additions/corrections feel free to leave a comment bellow.

    Monday, September 5, 2016

    Installing Kali Linux on an Android smarthphone

    The problem

    In the time of writing a lot of the HOW-TOs available online, including Offensive Security's own guide, simply do not work. This post aims to guide anyone trying to install Kali Linux on his android smartphone.

    The Requirements

    • A ROOTED android smartphone (Tested on Android 4.4.4, MTK6752)
    • A 16 GB class 10 SD card (It should work with internal storage somehow but haven't tested)
    • Linux Deploy
    • BusyBox
    • Link2SD
    • (Optional) An ssh app (I used ConnectBot)
    • (Optional) A VNC viewer app (I used VNC Viewer

    Preparation

    1. Partition the SD and format each partition (THIS WILL DELETE YOUR DATA). You'll need:
      • 1st Partition 512 MB formatted in FAT32
      • 2nd Partition the rest of the SD formatted in EXT2
    2.  Install the APPs listed above
    3. Open Link2SD
    4. You should be greeted by this screen

      1. Select ext4 and press ok
      2. When prompted reboot your device
    5. Open BusyBox
      1. Press INSALL 

    Installation

    Update 2/2/17

      'sana' suit has now been removed from Kali's repositories and kali-rolling is installing correctly.
      1. Open Linux Deploy (From here on ensure constant Wifi connection and power)
        1. Press your phone's menu buton
        2. Press status
        3. Under Available mount point there should be something like /data/sdext2, make note of that.
        4. Press the button on the right (looks like a download icon)
        5. In Distribution select Kali Linux
        6. In Distribution Suite select kali-rolling
        7. In Architecture select armhf
        8. In Installation type select Directory
        9. In Installation Path type in the path you took note of before
        10. (Optional)  Change Username & Password
        11. Set DNS server to 8.8.8.8 (Google's Public DNS server) since the default tends to fail
        12. Finally, set Localization to en_US.UTF-8

        13. Make sure in Select Components that Kali Components IS NOT SELECTED
        14. Press Install
        15. This might take a while ...
        16. When you see "<<<install" on Linux Deploy's logs the installation has finished
        17. (If there was no error your system is now ready to boot).
        18. Press Start 
        19. Press Ok
        20. You should see something like this

        21. If you see a lot of skips then something went wrong during the installation
      2. Now from ConnectBot (or a machine in your local network) ssh to yourusername@theipontopofLinuxDeploy (in this case xxxx@192.168.1.2)
        1. sudo dpkg-reconfigure locales
        2. sudo locale-gen
        3. sudo nano /etc/apt/sources.list
        4. Delete all its contents and replace them with the following
        5. deb http://http.kali.org/kali/ kali-rolling main contrib non-free
          deb-src http://http.kali.org/kali/ kali-rolling main contrib non-free
          deb http://security.kali.org/kali-security kali-current/updates main contrib non-free
          deb-src http://security.kali.org/kali-security kali-current/updates main contrib non-free
        6. Send Ctrl+O (to save the file)
        7. Send Ctrl+X (to exit nano)
        8. sudo apt-get update
        9. sudo apt-get dist-upgrade
        10. (if prompted)
          sudo apt-get autoremove
        11. sudo apt-get install kali-linux-full
        12. PATIENCE, since this will download around 4GB of data
      3.  If everything went right you should now have a working setup of Kali Linux on your Android phone
      Hope this helps a few people skip a bit of the frustration. Have fun!

      Clarification: There is a reason behind selecting sana suite (initially) and then changing the deb sources to kali-rolling (and kali-current for security). When selecting Kali-Rolling as a suite the installation (step 15) was observed to repeatedly fail. On the other hand, sana suit being discontinued is lacking a few dependence (or has wrong versions) and will fail during upgrade sending you on a long trip of compiling dependencies from source and iterating.