Secrets of Linux forensics, USB connection tracking techniques

24 January 2024 7 minutes Author: Cyber Witcher

Linux Forensics: Traces of USB Connections in Digital Investigations

Linux forensics in the context of tracking the history of connecting USB devices is an important part of cyber-malware investigation. This process makes it possible to identify and analyze the activities of vendors, which may be key to the identified breach of security or unauthorized access to data. The article describes how, using additional Linux commands, you can connect and disconnect USB devices, as well as techniques that allow you to analyze data in detail. They are considered both standard features of the operating system and specialized forensic security programs. We also emphasize the importance of knowing and using various Linux tools and commands to track USB connections that may reveal potential cyber threats.

In an article, you will find a comprehensive study of a specific topic related to technology or programming. The article includes in-depth analysis, detailed explanations, and possibly step-by-step instructions or examples related to the topic. It serves technology professionals or enthusiasts by offering ideas and knowledge to deepen understanding or solve specific technical problems.

  • Disclaimer: This article is intended for educational purposes. It describes Linux forensics techniques and USB connection tracking methods to help readers understand these processes and learn how to improve their cybersecurity.

Linux USB Forensics

Today we will tell you about one very interesting project. It’s called usbrip and it’s a small open source console utility for Linux forensics, namely for working with the connection history of USB devices. The program is written in pure Python 3 (using some third-party modules) and requires no dependencies other than the Python 3.x interpreter and a couple of lines from requirements.txt , which are enabled as single lines with pip.

Screenshots

Getting connection history of removable USB devices.

Search for additional information about a USB device by model identifier (PID):

Description

As you know, operating systems based on GNU/Linux are very sensitive to logging various events, and connecting/disconnecting USB devices is no exception. In conjunction with one of the points of the UNIX philosophy about “text streams as universal interfaces”, information about the artifacts of such events (with varying degrees of detail depending on the distribution) can be found in one or more of the following text files:

  • /var/log/kern.log*;

  • /var/log/syslog*;

  • /var/log/messages*;

  • /var/log/dmesg*;

  • /var/log/daemon.log*

FORENSIC-PROOF even shows us this picture about it (a little incomplete, but never mind):

For its work, usbrip finds log files universal for all Linux builds based on Debian (Ubuntu, Linux Mint, etc.) and RPM (CentOS, Fedora, openSUSE, etc.), namely: /var/log/syslog* or /var/log/messages*, parses them for the necessary information and displays the found traces of USB device connections in beautiful plates (or lists – whatever).

usbrip can also:

  • Create lists of authorized (trusted) devices in the form of JSON files;

  • Search for “offending events” based on the list of trusted devices: the following events (USB connect/disconnect) involving USB devices not listed as trusted;

  • Search for additional information about a USB device by its VID (Vendor ID) and/or PID (Product ID).

Сertificate

Get a list of available modules:

$ python3 usbrip.py -h

Get a list of available submodules for a specific module:

$ python3 usbrip.py <модуль> -h

Get a list of available options for a specific submodule:

$ python3 usbrip.py <модуль> <підмодуль> -h

Syntax

$ python3 usbrip.py banner
Виведення на екран банера утиліти.

$ python3 usbrip.py events history [-q] [-t | -l] [-e] [-n КІЛЬКІСТЬ_ПОДІЙ] [-d ДАТА [ДАТА ...]] [-c СТОЛБЕЦЬ [СТОЛБЕЦЬ ...]] [-f ЛОГ_ФАЙЛ [ЛОГ_ФАЙЛ ...]]
Перегляд історії USB-з'єднань.

$ python3 usbrip.py events gen_auth <ВИХІДНИЙ_ФАЙЛ.JSON> [-a ОЗНАК [ОЗНАК ...]] [-q] [-e] [-n КІЛЬКІСТЬ ПОДІЙ] [-d ДАТА [ДАТА ...]] [-f ЛОГ_ФАЙЛ [ЛОГ_ФАЙЛ ...]]
Формування списку авторизованих (довірених) USB-пристроїв.

$ python3 usbrip.py events violations <ВХІДНИЙ_ФАЙЛ.JSON> [-a ОЗНАК [Ознака ...]] [-q] [-t | -l] [-e] [-n КІЛЬКІСТЬ_ПОДІЙ] [-d ДАТА [ДАТА ...]] [-c СТОЛБЕЦЬ [СТОЛБЕЦЬ ...]] [-f ЛОГ_ФАЙЛ [ЛОГ_ФАЙЛ ...]]
Пошук "подій-порушників" на основі списку довірених пристроїв.

$ python3 usbrip.py ids search [-q] [--vid VID] [--pid PID] [--offline]
Пошук додаткової інформації про пристрій за його VID та/або PID базою даних ідентифікаторів.

$ python3 usbrip.py ids download [-q]

Options

Опції, що підтримуються підмодулями 'events history', 'events gen_auth', 'events violations', 'ids search', 'ids download':
    -q, --quiet
   опустити виведення банера, інформаційних (зелених) повідомлень, а також не ставити запитання щодо виконання

#####################################################################################

Опції, що підтримуються підмодулями 'events history', 'events gen_auth', 'events violations':
    -e, --external
    шукати тільки знімні USB-пристрої (які мають інформацію про від'єднання)

    -n КІЛЬКІСТЬ_ПОДІЙ, --number КІЛЬКІСТЬ_ПОДІЙ
    кількість останніх за датою подій, яка буде виведена

    -d ДАТА [ДАТА ...], --date ДАТА [ДАТА ...]
    список дат, за якими буде проводиться фільтрація подій під час пошуку

    -f ЛОГ_ФАЙЛ [ЛОГ_ФАЙЛ ...], --file ЛОГ_ФАЙЛ [ЛОГ_ФАЙЛ ...]
    список лог-файлів (якщо не вказано, пошук історії подій буде здійснено за лог-файлами за замовчуванням: /var/log/syslog* або /var/log/messages* залежно від версії ОС)
#####################################################################################

Опції, що підтримуються підмодулями 'events history', 'events violations':
    -t, --table
   сформувати висновок у вигляді таблиці (якщо розміру вікна терміналу не вистачає для коректного відображення таблиці, висновок автоматично буде сформовано у вигляді списку; при вказівці прапора -t висновок буде сформовано у вигляді таблиці примусово)

    -l, --list
    сформувати висновок у вигляді списку

    -c Стовпець [Стовпець ...], --column Стовпець [Стовпець ...]
    список стовпців, які будуть використані при побудові таблиці (має дію лише при формуванні виводу у вигляді таблиці); дозволені ключі: "conn", "user", "vid", "pid", "prod", "manufact", "serial", "port", "disconn".

#####################################################################################

Опції, що підтримуються підмодулями 'events gen_auth', 'events violations':
    -a ОЗНАК [ОЗНАК ...], --attribute ОЗНАК [ОЗНАК ...]
    список ознак, які будуть використані при побудові списку авторизованих пристроїв (а також при пошуку подій-порушників у разі підмодуля 'events violations'); дозволені ключі: "vid", "pid", "prod", "manufact", "serial".

#####################################################################################

Опції, що підтримуються підмодулями 'ids search', 'ids download':
    --vid VID
    vendor ID або ідентифікатор виробника USB-пристрою (зазвичай 4 шістнадцяткові цифри)

    --vid PID
    product ID або ідентифікатор моделі USB-пристрою (зазвичай 4 шістнадцяткові цифри)

    --offline
    якщо зазначено, пошук додаткової інформації про USB-пристрій за базою даних ідентифікаторів буде здійснено без попереднього її (бази) оновлення

Examples of use

Show the connection history of all USB devices, omitting the banner, informational (green) messages, and also not asking questions during the execution (-q, –quite), forming the output in the form of a list (-l, –list), including in the last 100 events found (-n NUMBER OF EVENTS, –number NUMBER OF EVENTS):

$ python3 usbrip.py events history -ql -n 100

Show connection history of removable USB devices (-e, –external) by generating output in the form of a table with fields (columns) “Connected”, “VID”, “PID”, “Disconnected” and “Serial Number” ( ) -c Column [Column …], –column Column [Column …], filtering the search by dates (-d DATE [DATE …], –date DATE [DATE …]), taking the information from external log files (-f LOG_FILE [LOG_FILE …], –file LOG_FILE [LOG_FILE …]):

$ python3 usbrip.py events history -et -c conn vid pid disconn serial -d "Dec  9" "Dec 10" -f /var/log/syslog.1 /var/log/syslog.2.gz

Build a connection history table of all USB devices and redirect the output to a file for further analysis. In the event that the output stream is not standard stdout (for example, “|” or “>”), the output will not contain spec. characters that are responsible for the font color in the terminal, so the text file will not be cluttered with unreadable characters. It should also be noted that usbrip uses some UNICODE constants, so it would be good to immediately convert the encoding of the generated file to UTF-8 for their correct display (for example, using encov), and also use Windows-style newline characters for better portability (e.g. using awk):

$ python3 usbrip.py history events -t | awk '{ sub("$", "\r"); print }' > usbrip.txt && enconv -x UTF8 usbrip.txt

Note: Get rid of spec. of the symbols responsible for the color is also possible if the output has already been sent to stdout. To do this, you need to copy the received data into a new usbrip.txt file and add one more awk instruction:

$ awk '{ sub("$", "\r"); gsub("\\x1B\\[[0-?]*[ -/]*[@-~]", ""); print }' usbrip.txt && enconv -x UTF8 usbrip.txt

Create a list of trusted devices as a JSON file (trusted/auth.json) containing the “VID” and “PID” fields of the first three devices connected on September 26:

$ python3 usbrip.py events gen_auth trusted/auth.json -a vid pid -n 3 -d "Sep 26"

Find “offending events” among the connection history of removable USB devices based on the list of trusted devices (trusted/auth.json) by the “PID” field and generate the output in the form of a table with the “Connected”, “VID” and “PID” fields:

$ python3 usbrip.py events violations trusted/auth.json -a pid -et -c conn vid pid

Find additional information about a USB device based on its VID and PID:

$ python3 usbrip.py ids search --vid 0781 --pid 5580

Download/Update USB Device ID Database (source here):

$ python3 usbrip.py ids download

Link

The utility can be downloaded from Github, all dependencies for launch and correct operation are listed in requirements.txt.

Other related articles
Found an error?
If you find an error, take a screenshot and send it to the bot.