Category Archives: Os

Integrating OSVDB into Ubuntu/Unity

OSVDB LensRecently I upgraded my laptop with the latest Ubuntu release (12.04-LTS). For a few releases, Ubuntu switched from Gnome to Unity and I’m happy to use it since the 11.04 version! I know that this choice has caused a lot of debates between the aficionados of both GUI but it always worked fine for me. Of course, no interface is perfect but it does its job. I just like the way it presents applications and files. Most are accessible with a few key presses. After the upgrade, I made the new proprietary tour and decided to look deeper into the Unity “Dash” feature. This is the main feature of Unity. It allows you to quickly search for information on your local filesystems (applications, files, bookmarks, …) or on the Internet (Wikipedia). To achieve this, the “Dash” uses “Lenses“. And those use “Scopes” that are small scripts which perform the search requests. “Lenses” are based on (briefly resumed):

  • A .lens file to let Unity load it
  • A daemon with a well-known name on D-Bus
  • A D-Bus .service file to let Unity activate the Lens

When Unity is started, it parses the configuration files and spawns the small daemons responsible for the searches. On a stock Ubuntu, you can see the following daemons running:

$ ps ax|grep lens
 2741 ?        Sl     0:05 /usr/lib/unity-lens-applications/unity-applications-daemon
 2743 ?        Sl     0:04 /usr/lib/unity-lens-files/unity-files-daemon
 2745 ?        Sl     0:00 /usr/lib/unity-lens-music/unity-music-daemon
 2747 ?        Sl     0:01 /usr/bin/python /usr/lib/unity-lens-video/unity-lens-video
 2777 ?        Sl     0:00 /usr/lib/unity-lens-music/unity-musicstore-daemon

If you’re interested in learning more about Lenses, there is a good documentation available here. Some people started to write their own Lenses to search for useful online data. Some popular ones are:

  • Wikipedia
  • Google Contacts
  • Youtube
  • Torrents
  • Flickr

Basically, any website that proposes a search feature can be integrated into Unity as well as any online service! (ex: whois) The daemon needs to send the query based on the provided keywords and format the results into something usable by Unity (via D-Bus).

I decided to learn how to build my own Lens. Why not create one with more focus on information security? What can be interesting to search for if you’re an infosec guy? Vulnerabilities of course! Let’s imagine, you are performing a pentest and you find a unpatched Solaris box running an Apache server. It could be nice to search for vulnerabilities affecting those solutions. That’s the purpose of my Lens: searching the OSVDB database for vulnerabilities.

Type some terms (or dates) and relevant OSVDB entries will be displayed directly in Unity. Click on them to open a browser to the direct page!

Unity Lens OSVDB Screenshot

(Click to enlarge)

By default (empty search), the latest vulnerabilities are displayed (sorted by time). You can also search for a specific period by specifying a month and a year (ex: “Apr 2012“). The full-text search feature of OSVDB is used (ex: “Cisco IOS 12.1“). There is nothing fancy, most of the code is based on another publicly available Lens. It was first of all a good opportunity for me to write my first piece of code in Python! ;-)

Source files are available on github.com. A Debian package (.deb) is ready to be installed. A logout is required to restart Unity and makes it recognize the new Lens. Once installed click on the little “OSVDB” icon on the bottom of your Dash to search for vulnerabilities. Feel free to use it, patch it or submit your comments! Enjoy!

Vulnerability Management: OSSEC & Secunia PSI

Secunia_OSSECVulnerability Management“… This is an important topic for your corporate security. One of the steps in this process is the monitoring of your applications and operating systems. With hundreds (thousands?) of devices connected to your network, how to keep an eye on the applications and patches installed on all of them? There exists plenty of vulnerability management tools which allow you to track/install patches from a central place. But again, most small organizations don’t have the resources or budget to deploy this kind software and users have to keep your laptops/workstations up-to-date. This article will show you how to implement a basic control of your pool of Windows workstations based on Secunia PSI and OSSEC.

Secunia PSI (“Personal Software Inspector“) is a free tool which scan your computer at regular intervals and reports uninstalled patches, unsafe (or end-of-life) applications.

Secunia PSI Dashboard

(Source: secunia.com)

Secunia PSI can be integrated to their commercial product called “CSI” (“Corporate Software Inspector“). About OSSEC, I won’t present the product once more. If you follow my blog, you already know that it’s one of my favorite tool.

The goal will be to configure OSSEC to keep track of changes detected by Secunia PSI. How? Secunia stores all the data about your computer in their own “cloud”. Nothing is kept local. An API is available (examples here) but it’s not easy to use it from OSSEC. Fortunately, there is an interesting log file located in “C:\Program Files\Secunia\PSI\psialog.txt“. Just a remember: your system are full of logs! In our case, it contains all the required material to perform basic alerting like:

  • Report applications changes (added, removed, clean, unsafe, …)
  • Report of the PSI score is not 100%

A few words about how Secunia stores the scan results. You must be aware of this. Your computer profile is sent to the Secunia cloud (psi.secunia.com) via HTTPS:

  POST /psi_api/2004/?type=data& \
       scantype=4& \
       tz=-3600& \
       domain=0& \
       uid=6X4EUbXhif39a59e330eea22c2d56acaxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx& \
       ui=agent& \
       langroup=LAB& \
       host=WIN7LAB

Your UID (stored in the Windows registry) is randomly generated during the software installation. Keep this in mind: they know a lot of details about you and your company. Example: the workgroup or domain is sent to Secunia. As most organization use their domain name, it’s easy for Secunia to know which software is used in which company. Of course, based on all the collected data, they’re able to perform nice statistics.

Now, the recipe:

  • An OSSEC server
  • OSSEC Windows agents properly configured
  • Secunia PSI properly deployed and configured
  • Some decoders and rules

Let’s have a look at the PSI log file. Two types of events are important. A first one gives details about the application being scanned (new, unsafe, etc) and the second one gives details about the scan results (this one contains the percentage).

  [11/25 19:17:54.288] Setting state of 'Adobe Flash Player 11.x' to clean
  [11/26 14:19:24.791] server.showBalloon('Secunia PSI - Scan Completed Successfully', \
  'You have insecure programs on your PC.

    Secunia System Score: 67%

    Based on the following detections:
    5 Insecure programs
    1 End-of-Life programs
    12 Patched programs
  ')

First, let’s write decoders to handle those events:

  <decoder name="secunia-psi-event">
    <prematch>^[\d\d/\d\d \d\d:\d\d:\d\d.\d+] Setting state of</prematch>
    <regex>Setting state of '(\.+)' to (\S+)$</regex>
    <order>extra_data, action</order>
  </decoder>
  <decoder name="secunia-psi-score">
    <prematch>Secunia System Score:</prematch>
    <regex offset="after_prematch">(\d+)%</regex>
    <order>status</order>
  </decoder>

In the first rule, the variable “extra_data” will contain the application name and “action” its status. The different status I already detected are: “determining“, “clean“, “created“, “added“, “approved“, “downloading“, “downloaded“, “entry“, “queued“, “condfailt“, “started” (they are maybe others, let me know if you have more information). In the second decoder, the variable “status” will contain the integer representing the scan score (0-100). Now we can define some rules:

  <rule id="110000" level="0">
    <decoded_as>secunia-psi-score</decoded_as>
    <description>Secunia Scan Results</description>
  </rule>

  <rule id="110001" level="9">
    <if_sid>110000</if_sid>
    <regex>: \d\d%</regex>
    <description>Vulnerabilities found. Secunia scan score not 100%</description>
  </rule>

  <rule id="110002" level="0">
    <decoded_as>secunia-psi-event</decoded_as>
    <description>Secunia PSI Event</description>
  </rule>

  <rule id="110004" level="9">
    <if_sid>110002</if_sid>
    <match>added</match>
    <description>New application detected by Secunia</description>
  </rule>

Results will look like:

  OSSEC HIDS Notification.
  2011 Nov 28 20:55:40

  Received From: (win7lab) 192.168.254.240->\Program Files\Secunia\PSI\psialog.txt
  Rule: 110003 fired (level 9) -> "New application detected by Secunia"
  Portion of the log(s):

  [11/28 20:49:14.130] Setting state of 'Adobe Flash Player 11.x' to added

  --END OF NOTIFICATION
  OSSEC HIDS Notification.
  2011 Nov 28 20:59:27

  Received From: (win7lab) 192.168.254.240->\Program Files\Secunia\PSI\psialog.txt
  Rule: 110001 fired (level 9) -> "Secunia scan score not 100%"
  Portion of the log(s):

  Secunia System Score: 98%

  --END OF NOTIFICATION

Simple and efficient! However, it’s not complete. At the moment, I don’t know where to find the status of the Windows patches. I’m trying to get more info from Secunia. I’m not aware of commercial SIEM nor log management solutions which interpret Secunia PSI results; this is good for OSSEC. You can imagine plenty of scenarios: hosts with a scan score below 100% can be stored to temporary tables. Dangerous applications can also be stored in a table and used to write correlation rules…

Data Integrity: MD5/SHA1 are Your Best Friends!

IntegrityYesterday, I faced a very strange story that I would like to tell you to prove the importance of “integrity” in information security. Wikipedia defines data integrity as following:

Data Integrity in its broadest meaning refers to the trustworthiness of system resources over their entire life cycle.

The “entire life cycle” is very important in this case. I had to upgrade the firmware of an appliance manufactured by “A”. I visited (over HTTPS) the support website  of “A”, went to the download sections and grabbed the necessary files to perform the maintenance. The website provided MD5 hashes for all the files. Good practice! Once the files transferred on my laptop, md5sum reported the same hashes. My files were ready!

Just a small reminder for those who don’t know what’s a hashing algorithm. Based on a variable amount of data, a hashing algorithm computes a fixed size message digest. Well know algorithms are MD5, SHA1 or HMAC. Practically, the generated message digest will uniquely identify the original data. Example, almost all operating systems have tools to compute the MD5 or SHA1 digest of files:

  $ md5sum /tmp/file.txt
  451024bdf01d5d4f64567bea70c402be  /tmp/file.txt
  $ sha1sum /tmp/file.txt
  93c6c7c22e0846ca1944f76ceb6981a2f49ce70e  /tmp/file.txt

This is a common way to control the integrity of files distributed online. Hashes are given on the original website. You perform the same operation on your local files, if the message digest is the same, files are identical!

Once at the customer premises, another good security practice: I was not authorized to connect my laptop on their management network. I simply copied the files to a clean (read: safe, scanned) USB stick to transfer them to the management workstation. Finally, I uploaded the files on the appliance and launched the upgrade procedure. After many coffees, the device was still decompressing the firmware (a 670MB archive). Strange, I decided to investigate…

I checked the USB stick: the firmware file looked ok, I could read it, even the file size was the same as the original. I generated the MD5 hash on the file directly from the USB stick and… it was not the same! The file was corrupted during the transfer between my laptop to the USB stick!? No error message was displayed during the copy operation, the stick was properly unmounted, no USB/SCSI errors were reported by my laptop kernel. I’m still wondering what happened!

Hopefully, the second attempt to upgrade the appliance was successful. What are the lessons learned from this story?

  • Integrity is a key element in information security (That’s the “I” in the CIA triad)
  • MD5/SHA1 hashes are a common way to verify the integrity of files downloaded via public resources. It must be checked not only while receiving the data from the source itself but during the complete data life-cycle: transfer, storage and retrieval. (what I omitted to do in this story – shame on me!)
  • Data integrity can be compromised by multiple factors:
    • Security threads (ex: a virus)
    • Human errors
    • Physical factors (ex: a bad sector on a disk)
    • Software bugs

If I failed (and we learn by our mistakes) to check the integrity of the files from A to Z, the vendor “A” also failed somewhere:

  • The process to decompress the firmware image did not report a problem with the file and crashed silently leaving the web console with a time counter running.
  • Some vendors still fail to implement integrity checks on the firmware they have to process. Distributed files are simply not signed. It means that can be altered and injected in the device (MitM attack). There exist solutions to validate the integrity of a file from a consistency point of view (using CRC or “Cyclic Redundant Checks“).

Keep this in mind and stay safe!

Note: For a while, MD5 is considered as broken. It has been proven that MD5 is vulnerable to collision attacks. But it remains mainly used to check downloaded files integrity.

 

 

 

Back(Up) to the Future

Back to the Future Ah, backups… What a nice boring topic! Everyone agrees on the fact that a strong backup procedure is mandatory for any computer (server, workstation, PDA or anything else which carry data). But lot of us also agree to say that backup are so boring to perform and, even more, maintain! To the question “Do you have a backup procedure?“, most of us will be proud to say “Yes!“. And about your restore procedure? ;-)

For my private activities, I own a Macbook Air and I’m addicted to the Apple backup system called “Time Machine“. There is certainly no ideal backup solution but it does its job quite well and… without user interaction! Time Machine saves my data using a SMB share on a RAID-1 NAS using an automated procedure: mount the SMB share if I’m at home, perform the backup and umount it. Time Machine is based on the principle of incremental backups. Only the data changed since the last backup are saved.

I was looking for the same kind of solution for my Linux laptops. Google gave me three names: TimeVault, flyback and Back In Time. They are all based on the principle of “snapshots“. When a backup is performed, the unchanged files are just backuped as a symbolic link to the previous backup – without consuming disk space.

TimeVault has a deep integration with Nautilus. Unfortunately, the project looks abandoned and no 64-bits package is provided. This can look stupid but I don’t have time to compile big projects from the source code and I don’t want to install a full Gnome development environment on my laptops. That’s a reason why I use Ubuntu: to use packages!

flyback looks still maintained even if the last update has been released a few months ago. Unfortunately, flyback has been immediately set aside due to a major feature missing: backups must be started manually!

Back In Time has been inspired, as explained on the website, by the two first solutions. Basically, Back In Time is a front-end to manage backups performed using strong UNIX tools like rsync and diff (amongst others). The main window presents the available snapshots and allow to restore your data:

Back In Time GUI

To configure a backup, several profiles can be created. A profile is just a set of  core parameters :

  • The directory to backup
  • The filesystem (destination) where the snapshot will be stored
  • When perform the backup
  • The files to include/exclude (based on regular expressions)
  • Snapshot maintenance (how long to keep them)
  • Performance related parameters (use of the “nice” command etc…)

Once a profile has been defined, a corresponding entry is added to the user’s crontab.  Cool stuff, there is an integration with Gnome: When a backup is running, an icon is display in your notification area. The availability of the destination path is performed at backup start. If the directory is not present, the backup is simply aborted.

But the feature which made me choose Back In Time as my backup solution is the “user-callback” script (located in your $HOME/.config/backintime). This script is called several times during the backup process with the following arguments:

  $HOME/.sysconfig/backintime/user-callback <profileID> \
                                            <profileName> \
                                            <Reason> [Error]

<Reason> is an integer:

  1. Backup process begins.
  2. Backup process ends.
  3. A new snapshot was taken. The extra arguments are snapshot ID and snapshot path.
  4. There was an error. The second argument is the error code:
    • The application is not configured
    • A “take snapshot” process is already running.
    • Can’t find snapshots directory (is it on a removable drive ?).
    • A snapshot for “now” already exist.

Based on those information, you are free to add your own features to Back In Time like:

  • To kill a process before a backup and restar it once done, sending
  • To send notifications to a monitoring tool,
  • To mount a filesystem dedicated to the snapshots and much more!
  • Use your imagination!

As Back In Time does not try to mount the destination filesystem by itself, here is an example of a user-callback script which (u)mount the required volume:

  #!/bin/bash
  # Get arguments from command line
  PROFILEID=$1
  PROFILENAME=$2
  REASON=$3
  ERRORCODE=$4

  LOG="/var/log/backintime-user-callback.log"
  NOW=`date +"%Y-%m-%d %H:%M:%S"`
  LOCALIP="192.168.254.200"
  INT=eth0
  MYIP=`ifconfig $INT | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'`

  echo "$NOW Profile=$PROFILEID ($PROFILENAME), reason $REASON:$ERRORCODE" >>$LOG
  case $REASON in
    "1") # Backup process started
         if [ "$MYIP" == "$LOCALIP" ]; then
           # Try to mount the local NFS share
           /bin/mount /media/backup
         fi
         ;;
    "2") # Backup process ended
         if [ "$MYIP" == "$LOCALIP" ]; then
           # Try to umount the local NFS share
           /bin/umount /media/backup
         fi
         ;;
    "3") # New snapshot taken
         ;;
    "4") # Error detected
         ;;
      *) # Unknown reason
         ;;
esac
exit 0

Just by sending some backup information into a dedicated logfile or to your Syslog host via the “logger” command, you add more value to the backup by processing those events via your log management tool. Tools like “Time Machine” or “Back In Time” are easy to deploy and help you to restore lost file at a certain point. Very useful if you work on projects with a lot of files updated regularly.

Protect Your Applications Using EMET

Bullet ProofIs there a way to make your Windows environment certainly not bullet-proof but stronger enough against attacks? A few weeks ago, Microsoft released an interesting add-on called EMET for its Windows operating systems range.  EMET stands for “Enhanced Mitigation Experience Toolkit” and is designed to increase the security of your Windows executables. How?

Microsoft Windows is a very common operating system and became a regular target for the bad guys for years now (more systems are targeted, more chances you have to compromise them). Still today, it remains the preferred target of most worms, viruses and trojans. A common attack vector is to abuse the stack with a “stack overflow” (There are plenty of examples based on this weakness). Wikipedia defines a stack overflow like this:

In software, a stack overflow occurs when too much memory is used on the call stack. The call stack contains a limited amount of memory, often determined at the start of the program. The size of the call stack depends on many factors, including the programming language, machine architecture, multi-threading, and amount of available memory. When too much memory is used on the call stack the stack is said to overflow, typically resulting in a program crash.
Source: wikipedia.org.

Indeed, the result of a stack overflow in an application is a crash which can be defined as a DoS (“Deny of Service”) attack. But, in worst cases, this can be exploited to execute some attacker’s code. The goal of EMET is to protect the running processes against this type of attack by implementing six mitigations:

  • SEHOP – “Structure Exception Handler Overwrite Protection
    Implemented since Windows XP SP1 and able to be turned on or off in Windows 7, this feature protects the process against the most common technique to exploit stack overflows. It prevents an attacker to change the execution stack.
  • DEP – “Dynamic Data Execution Prevention
    Also available since Windows XP, DEP prevents code in memory from being executed if not flagged as executable. DEP was available for applications compiled with a specific flag. EMET allows to activate DEP even without this compilation option.
  • Heapspray Allocations
    Attackers use this technique to place several copies of their malicious code in memory. This way, they increase the chances of a successful exploitation.EMET pre-allocates commonly used pages to prevent exploits to use them.
  • Null page allocation
    Like heapspray allocations above, this technique is designed to prevent potential null dereference issues in user mode.
  • ASLR – “Address Space Layout Randomization
    Attackers are good to predict the locations of functions and data in memory. By using ASLR, allocations are randomized. Like DEP, this is normally enabled at compilation time.
  • EAF – “Export Address Table Access Filtering
    Exploits need to call APIs and need to find them in memory. This technique makes it more difficult to find them and will block the malicious code.

Note that all the mitigation techniques are not available on all supported operating systems! Also, changing the behavior of some processes may affect the stability. Before implementing EMET in a production environment, test it in a lab!

The installation is a straight away process. Once done, run the GUI and configure your default setting using the “Configure System” button:

EMET Settings

Click to enlarge

Note that changing the default settings, requires a system reboot. Then, you can configure your applications one by one with more granularity:

EMET Applications

Click to enlarge

To be clear, EMET does not bring new techniques to protect against malicious code. Example: DEP has been made available since the Windows XP ServicePack 2. But, executables have to be compiled with a specific flag to enable it. Today, EMET allows you to enable it for any applications even if not compiled for the right flags. No need to recompile a bunch of source files.

Is EMET the definitive solution to prevent execution of malicious code? Certainly not! But it’s a step forward to increase the system security. It does not prevent you to keep your environment protected with a up-to-date antivirus solution. Execution of suspicious applications in a sandbox is also certainly a good idea. But EMET is easy to implement and can protect even your legacy application.

Related info:

Book Review: IT Inventory and Resource Management With OCS Inventory NG 1.02

Book  Cover During my holidays, I finally took the time to finish to read the book “IT Inventory and Resources Management with OCS Inventory NV 1.02” which covers the application with the same name. Even if the inventory of devices connected to a network is primarily a system administration task, it has also one foot in the security field. By knowing the devices used in your organization, you can better respond to potential threats.

The book takes the reader by the hand from the installation steps, the deployment of the agents and the web interface to the maintenance and debugging of complex configurations. The first chapters are quickly read: what are the benefit of systems inventory (who still doubts of them?) and how to install the application. OCS is a classic LAMP application, no big issue. Note that it can also be installed on a Windows platform using XAMPP.

The next chapters covers the agents. They are the critical components of the architecture as they will collect the following informations from the hosts: Hardware, BIOS, Processors, Memory, Video, Storage, Network, I/O (keyboard, mouse, ports), Sofware, OS, Installed software, Custom registry entries (for Windows agents). They must perform an effective job without being too invasive in terms of resources usage.

Agents are deployed on the target devices using multiple paths but they also offer an auto-discovery feature. They can detect hosts not yet inventoried. This process is based on Nmap. About the installation, it’s important to keep in mind the following points:

  • Agents use HTTP(S) to communicate with the server
  • Agents keep a local copy of the grabbed data using XML files
  • Agents always initiate the communication with the server (this allow agents to be deployed behind NATed networks)
  • Windows agens run under the “LocalSystem” account.

The deployment is an important topic. There are multiple methods available (depending on the target Operating System): Manually (using a “next-next-finish” method), via a GPO, via login scrip, via PsExec.

On Linux systems, it is performed locally or via remote access (SSH). Note that installation can be performed with or without user interaction. Other supported systems are: Apple computers (MacOS) and mobile devices (Windows Mobile or Java). There is also a export/import procedure to collect data from non-networked agents or agents not directly reachable.

On Windows hosts, an interesting feature is the ability to track certain registry keys. Very useful to track non-standard activities or specific software configurations on remote hosts. Once deployed, the agents will collect the informations and send all the stuff to the central server.

The following chapter will cover the web GUI, how to work with the collected data and how to broaden the OCS Inventory Management with other tools like GLPI for advanced features like reporting and ticketing system. Finally, the last chapters will review how to fine-tune and debug your environment.

The book is accessible to all readers. Implementing an inventory solution is not very difficult from a technical point of view but how to extract the real-value of the collected data? From to a security point of view now. Several useful information can extracted from the database:

  • What are the operating systems and versions used in the organization
  • What is the software base installed
  • IP settings : is there a rogue DNS or gateway used?

Those collected information might be very useful to track suspicious devices.  The primary usage of OCS Inventory Manager is to collect information in a “read-only” fashion. But the ability to deploy packages through the installed agents is an interesting feature. Example to deploy security patches or to deploy new configurations. This is covered by a dedicated chapter. A complete overview of the features is presented in a nice poster on the application website:

OCS Inventory NG Features

Source: www.ocsinventory-ng.org

Related link:

Configuring Conditional SSH Connections

Road Sign Years after years, OpenSSH became the default SSH daemon on most of UNIX environments as well as other systems. It offers a lot of features which make it terribly customizable and powerful.

For a while, the ‘Match” keyword appeared in the list of directives. It allows conditional blocks of configuration directives. If the criteria(s) defined are matched, new directives may overwrite the default ones. This is extremely useful to build complex configurations.

Examples: Users connecting from an internal subnet can use their password but must use their RSA key to authenticate when connecting from unknown hosts. Port forwarding can be restricted to users of a specific group.

The current version of OpenSSH supports four criteria with the “Match” directive:

  • User – To match one or more local users
  • Group – To match one or more local groups
  • Host – To match a FQDN or domain name
  • Address – To match a single address or subnet.

Each condition may contain a single or comma-separated values and support patterns:

  • Host *.rootshell.be
  • User john, leo, !chris
  • Address 192.168.1.16/28

When a condition is met, all the directives below will be applied until the next “Match” section or the end-of-file. This is why, they must be defined at the end of your sshd_config file. Let’s have a look at the following example:

   # Allow administrators to use the agent & X11 forwarding
   Match Group admin
      AllowAgentForwarding yes
      X11Forwarding yes

   # Regular users cannot forward TCP sessions and cannot use a password
   Match Group users
      AllowTcpForwarding no
      PasswordAuthentication no
      Banner banner.users

   # Users from the DMZ are chroot'd
   Match Address 192.168.0.0/24
      ChrootDirectory /var/sandbox

This is very powerful! But when you start to play with such nice features, you quickly become frustrated by the limited criteria, only four in the current version. This afternoon, I discussed with my friend Chris John Riley about the “Match” feature. He wished to be able to use different authentication types depending on the port used to connect to a host. It looks indeed a cool feature. Let’s dive into the OpenSSH source code.

First, it’s good to know that OpenSSH allow multiple instances of the directives “Port” and “ListenAddress”. In my sshd_config file, I use:

   Port 22
   Port 443

Then, I wrote a small patch which implements a new “Match” criteria called “Localport“. In the source code, a function already exists to return the local port used:

   /* Returns remote/local port number for the current connection. */
   static int
   get_port(int local)
   {
        /*
         * If the connection is not a socket, return 65535.  This is
         * intentionally chosen to be an unprivileged port number.
         */
        if (!packet_connection_is_on_socket())
                return 65535;

        /* Get socket and return the port number. */
        return get_sock_port(packet_get_connection_in(), local);
   }

It’s easy to use it and compare the returned value with the port(s) defined in the “Match” condition. Now, I can use the following conditions:

   Match LocalPort 22
      PasswordAuthentication yes
      RSAAuthentication no

   Match LocalPort 443
      PasswordAuthentication no
      KerberosAuthentication yes
      AllowTcpForwarding no

Etc… Interesting isn’t? And, by using different ports, it is possible to increase the server security. It is also possible to play with QoS. Port 22 can be assigned to regular users and port 443 (with reserved bandwidth) to administrators. This way, you will be able to reach your server even in case of heavy network load.

Remark: not all directives can be used in conditional blocks! Check out the sshd_config man page for the list of supported directives.

My OpenSSH patch is available here. It is based on the source code of OpenSSH 5.5p1. As usual, there is warranty at all. Use it at your own risks.

BackTrack4-R1 + AWUS036NH = Win!

BackTrack4 R1This is a long story… but it is finally solved thanks to the developers of the BackTrack distribution! For a long time, I used a good old Orinoco PCMCIA card to play around with WiFi networks. But it died and I was looking for a brand new toy. After reviewing some discussion groups and asking for advices, I decided to buy a brand new card from Alpha Networks. They produce good devices and not very expansive. There was two cards in competition: The AWUS036N and AWUS036NH. The second one is the new model. It offers more signal and is 802.11n compatible. Unfortunately, like a lot of new devices, the card was not supported by the “old” release of BackTrack. More precisely, it was available as a standard card to connect to a wireless network but injection of packets was not possible.

During BlackHat 2010, a new version (R1) was released with the following changes:

  • Kernel 2.6.34 – With fragmentation patches, etc.
  • Updated tools, such as Maltego and SET.
  • Improved driver support, broader range of wireless cards supported.
  • Faster desktop experience due to kernel.
  • Fluxbox environment added.

Yes! A new kernel and support for a broaden set of wireless cards! A few days after the conference, it was released to the public. Unfortunately, still no out-of-the-box support for the AWUS036NH card! I re-installed my BackTrack persistent USB-key using the wonderful tutorial provided by Kevin Riggins on infosecramblings.com. After more investigations and compilations, I’m finally able to use my card for monitoring and injection! Here are the steps I followed.

First, keep your BackTrack environment up to date:

  # apt-get update && apt-get upgrade && apt-get install firmware-ralink

Mine was already ok. Then, compile and install the Linux wireless compatibility package. This one is provided on the BackTrack media but not installed (no idea why?). There is already a new version available on wireless.kernel.org (2010-07-24) but I did not tested it. Install the driver using the following commands:

  # cd /usr/src/drivers/compat-wireless-2010-07-10
  # ./scripts/driver-select rt2x00
  # make
  # make install
  # make unload
  # modprobe rt2800usb

Normally, it should be fine but, in doubt, just reboot! Once done, connect your USB Wireless card and you should see something like this in /var/log/messages:

  usbcore: registered new interface driver rt2800usb
  usb 1-1: new high speed USB device using ehci_hcd and address 4
  rt2800usb 1-1: firmware: requesting rt2870.bin

Now, let’s test the interface in monitor mode:

  # airmon-ng start wlan0

  Interface  Chipset             Driver
  wlan0      RaLink RT2870/3070  rt2800usb - [phy0]
                                 (monitor mode enabled on mon0)

  # airdump-ng mon0

You will see the detected WiFi network and all the classic stuff (beacons, packets, etc). Now, let’s test the injection:

  # airdump --test mon0
  15:40:51  Trying broadcast probe requests...
  15:40:51  Injection is working!
  15:40:52  Found 1 AP

  15:40:52  Trying directed probe requests...
  15:40:52  xx:xx:xx:xx:xx:xx - channel: 11 - 'xxxxxxxxx'
  15:40:53  Ping (min/avg/max): 0.203ms/2.512ms/4.130ms Power: 3.86
  15:40:53  29/30:  96%

Looks good! But a new problem popped up:

  # aireplay-ng -1 0 -e xxxxx -a xx:xx:xx:xx:xx:xx -h xx:xx:xx:xx:xx:xx mon0
  16:26:45  Waiting for beacon frame (BSSID: xx:xx:xx:xx:xx:xx) on channel -1
  16:26:45  mon0 is on channel -1, but the AP uses channel 11

Once again, some reading of online material revealed that this is a know problem. To fix this, apply the following patch (credits go to DomInat3):

  # cd /usr/src/drivers/compat-wireless-2010-07-10/net/wireless
  # patch -p0 <chan.patch

And recompile the driver as already describe above. After reboot, try injection again:

  # aireplay-ng -1 0 -e xxxxx -a xx:xx:xx:xx:xx:xx -h xx:xx:xx:xx:xx:xx mon0
  19:17:57  Waiting for beacon frame (BSSID: xx:xx:xx:xx:xx:xx) on channel 11
  19:17:57  Sending Authentication Request (Open System) [ACK]
  19:17:57  Authentication successful
  19:17:57  Sending Association Request [ACK]
  19:17:57  Association successful :-&#41; (AID: 1)
  #

Case closed! The installed driver worked for me. My WiFi adapter is a AWUS036NH (802.11b/g/n Long-Range Wireless USB Adapter) but the procedure should stay the same for others.

Happy wireless hacking…

Packet Inspection Using Divert Sockets

DiversionFor a long time ago, I did not write about OpenBSD which remains one of my favorite operating system. The last version (4.7) was released in May and introduced, as usual, a lot of interesting changes.

OpenBSD comes of course with it’s own firewall called pf (“packet filter“). Plenty of features are available but pf gained even more power since the last OpenBSD release with the introduction of the divert sockets support (for both IPv4 & IPv6). What’s this?

First, divert sockets are not new. They are available for a while on FreeBSD (also supporting the pf firewall) or Linux since kernel version 2.2). When you need to intercept packets passing through your UNIX server, you use the library libpcap (and the associated tools like tcpdump) or raw sockets. But this operation remains “read only” – I mean – you just grab a copy of the packets for further analyze. Did you ever dream about a cool way to process packets outside the core firewall process and, even better, re-injecting them in the traffic flow? That’s the purpose of the divert sockets.

First of all, some important remarks:

  • Packets sent to a divert socket will be processed in user space! This could have huge security impacts.
  • Processing packets and re-injecting them use lot of time (compared to the time required by the firewall to process them), this could lead to huge performance impacts.
  • Altering the payload of some TCP packets can be dangerous. No big issue if the payload size remains the same but if it changes, the TCP session between the hosts will be desynchronized! (issue related to the sequence number).

If you always keep in mind those remarks, let’s see how divert sockets work. Let’s imagine a firewall between a private network and the Internet (see figure below). We can instruct the firewall to divert all outgoing packets on port TCP/80 to a process running on user space.

Diver Socket
(Click to enlarge)

How to achieve this? At pf level, we configure the divers socket (via your pf.conf):

    pass out on $int from any to any port 80 divert $divert_port keep state

The process running in user space utilizes a special type of RAW socket called divert (IPPROTO_DIVERT) that allows you to receive and send like a regular socket. But here, the divert socket is bound to a port which is used by the firewall ($divert_port in the example above) to send packets. A basic example in C:

    printf("Creating a divert socket\n");
    fd=socket(AF_INET, SOCK_RAW, IPPROTO_DIVERT);
    if (fd==-1) {
       printf("Could not open a divert socket\n");
       exit(1);
    }
    bindPort.sin_family=AF_INET;
    bindPort.sin_port=8000;
    bindPort.sin_addr.s_addr=0;
    printf("Binding a socket\n");
    s=bind(fd, &bindPort, sizeof(struct sockaddr_in));

Once done, wait for incoming packets, process them and re-inject them (optional):

    sinlen=sizeof(struct sockaddr_in);
    printf("Waiting for some packets...\n");
    while(1) {
       n=recvfrom(fd, packet, BUFSIZE, 0, &sin, &sinlen);
       hdr=(struct iphdr*)packet;

       processPacket(packet);

       printf("Reinjecting packet\n");
       n=sendto(fd, packet, n ,0, &sin, sinlen);
    }

If you prefer to develop in Perl, there is a Net::Divert module available on the CPAN repository. Here is a little example:

    use Net::Divert;
    my $divsocket = Net::Divert->new('127.0.0.1',9999);
    $divsocket->getPackets(\&processPacket);

    sub processPacket {
       my ($packet,$tag) = @_;

       # ... Perform further processing ...

       # Re-inject the packet
       $divsocket->putPacket($packet,$tag);
    }

Those are simple example, I’m not a developer ;-) . What can you do with divert sockets? There are plenty of implementations:

  • Data Leakage Prevention (DLP): Generate alerts when patterns are detected in the payload of inspected packets. In case of re-injection, hide sensitive date (SSN, CC, …) with “XXXXXX”.
  • Quality of Service
  • Statistics
  • IDS
  • URL filtering
  • DNS answer rewriting

Use your imagination! But, once again, take care of the security! Diverted packets will travel across different rings during the inspection!

Related information:

How to Prevent the Windows Screensaver Autolock Feature?

Locked Computer A quick and dirty tip if you need to keep a Windows workstation or server console unlocked. This can be required for several purposes, good or bad. In my case, I’m working on a workstation to access network resources. I don’t have a login and cannot know the local password. Every time the screen gets locked, I need to ask a local administrator to unlock it for me. Fortunately, most Windows environments are installed with the default set of softwares. In this case the interesting tool is the Windows Media Player!

To prevent the screensaver activation (and the auto lock of the session), just start the Windows Media Player, play a dump system WAV sound (they are located in c:\windows\media), set the volume to zero, play in loop and minimize the windows. By default, the Windows Media Player is configured to disable the screensaver during playback. Check the status of this option in Tools -> Options: “Allow screensaver during playback” must be disabled. The big advantage is this method: no changes are required in the current configuration.

Use this with care and don’t forget to stop the media player once your work done or if you need to leave the screen for a while. This can break the local security policies!

From a security point of view, this enforces one of my last post: to prevent people to bypass security rules, procedures and tools must be adapted to allow them to to their job in good conditions. For the story, it did not started the media player by myself. It was suggested by a local administrator bored to be disturbed after each screen autolock ;-)