Octo-Shell

A custom Unix shell built from scratch in C — with encrypted file transfer & intrusion detection!

Spider Inductions Task 2 · NIT Trichy

Codecrafters Shell Challenge Completed

proof - all base stages completed on Codecrafters

Project videos

Level 1 demo

Leve1 2 & 3 Demo

Level 4 Demo

What is this project?

Octo-Shell is a custom shell written entirely in C. Think of it like building your own mini version of bash/zsh from scratch.

Project Structure

Spider_Task_2/
├── include/          # Header files (.h)
│   ├── shell.h       # Shell prototypes + RadioHeader struct
│   └── crypto.h      # DH key exchange + keystream functions
├── src/              # Source code (.c)
│   ├── main.c        # REPL loop
│   ├── execute.c     # Tokenizer + fork/exec engine
│   ├── nittalk.c     # File transfer protocol
│   ├── crypto.c      # Modular exponentiation + LCG
│   └── tripwire.c    # Raw socket IDS
├── tests/            # Dummy files for testing
├── Makefile          # Build automation
└── README.md         # You are here :)
            

Setup — Before You Start

Important: This project uses POSIX headers (unistd.h, sys/wait.h) so it must be compiled on Linux. On Windows, use WSL (Windows Subsystem for Linux).

Step 1: Open WSL

Open your terminal and launch Ubuntu:

wsl -d ubuntu

Step 2: Install build tools (first time only)

sudo apt update
sudo apt install build-essential

Step 3: Navigate to the project

cd /mnt/c/path/to/Hiba_spider_task2

Replace the path with wherever you cloned/downloaded the project on your machine.

Step 4: Compile everything

make clean && make

Or compile manually:

gcc -Wall -Wextra -Iinclude src/main.c src/execute.c src/nittalk.c src/crypto.c -o octo-shell

If it compiles without errors, you'll see an octo-shell executable. You're good to go! 🚀

Don't use Git Bash or MinGW — they don't support POSIX headers. Always use WSL Ubuntu.
If you see Exec format error, you're trying to run a Linux binary from Windows. Switch back to WSL.

Level 1 — The Core Shell

This is where it all begins. We build a basic REPL (Read-Eval-Print Loop) — the heart of any shell.

How it works

  1. main.c prints the prompt octo-shell$ and reads your input
  2. execute.c tokenizes the input (splits it into words)
  3. If it's a builtin (exit, cd, echo), handle it directly
  4. Otherwise, fork() a child process and use execvp() to run external programs

Testing Level 1

1. Open WSL (Ubuntu)

Since this project uses POSIX headers (unistd.h, sys/wait.h), it must be compiled inside Linux.
On Windows, launch Ubuntu via WSL:

wsl -d ubuntu

2. Navigate to the project folder

Move into the root project directory containing your src and include folders (e.g., Hiba_spider_task2):

cd /path/to/Hiba_spider_task2

3. Compile the program

Use gcc to compile all the source files into an executable named octo-shell:

gcc -Iinclude src/main.c src/execute.c src/nittalk.c src/crypto.c -o octo-shell

If compilation succeeds, you'll see a new file called octo-shell in the directory.

4. Run the shell

Execute the program:

./octo-shell

You should now see your custom shell prompt:

$

5. Test builtins and external commands

Try out the builtins:

echo hello world
type ls
exit

And external programs:

ls -l
cat main.c
grep int main.c

6. Exit the shell

Type:

exit

to quit.

Notes
- Do not compile/run in Git Bash or MinGW — they don't support POSIX headers. Always use WSL Ubuntu.
- If you see Exec format error, it means you tried to run a Linux binary from Windows. Switch back to WSL.
- Codecrafters tests will run your program in a Linux environment, so WSL matches the expected setup.

Key concept: fork() + execvp()

This is the classic Unix pattern for running commands:

pid_t pid = fork();        // Split into parent + child
if (pid == 0) {
    execvp(args[0], args); // Child becomes the command
} else {
    waitpid(pid, NULL, 0); // Parent waits for child
}

The parent process (our shell) creates a clone of itself. The child clone then replaces itself with whatever command you typed. The parent just waits.

Level 2 — NITTalk File Transfer

Now we add nittalk — a custom command inside our shell that can send files over the network using TCP sockets.

The 72-Byte Protocol Header

Since TCP is just a stream of bytes, the receiver needs to know: "what file is coming and how big is it?"

We solve this with a fixed-size header:

Field Size Purpose
Verification 4 bytes "NIT\0" — confirms it's our protocol
Filename 64 bytes Name of the file being sent
Payload Size 4 bytes File size in network byte order
Total 72 bytes

We use __attribute__((packed)) to prevent the compiler from adding hidden padding bytes.

How to test (you need 2 terminals!)

First, compile:

make clean && make

Or, if you don't have a Makefile configured yet, compile the source files manually:

gcc -g -Iinclude src/main.c src/execute.c src/nittalk.c -o octo-shell

Terminal A — The Listener (Receiver)

./octo-shell
octo-shell$ nittalk -listen

You should see:

[] Initializing covert listening post on port 8080...
[📡] Beacon online. Awaiting inbound transmission...

Terminal B — The Sender

echo "SPIDER network test transmission." > secrets.txt
./octo-shell
octo-shell$ nittalk -s 127.0.0.1 secrets.txt

Sender output:

[*] Preparing stealth transmission payload to 127.0.0.1...
[+] Link established! Transmitting 72-byte radio header...
[+] Metadata broadcast complete.
[] Initiating file transmission stream...
All bytes deployed over the wire successfully.

Listener output:

[] Target connected! Secure link established.
[*] Synchronizing stream windows... Awaiting 72-byte header...
[] Header Verified! Incoming File: 'secrets.txt' | Size: 84 bytes
[] Downloading payload streams...
 Success! File transmission complete.

Verify it worked

cat secrets.txt

Level 3 — Encryption (Diffie-Hellman + XOR Cipher)

Now we make the file transfer encrypted. Nobody snooping on the network can read the files!

The Math

Problem: How do two computers agree on a secret key without ever sending the key?

Answer: Diffie-Hellman Key Exchange!

Both sides know: p = 9973 (prime), g = 5 (generator)

  1. Each side picks a random private key (a and b) — never shared
  2. Each computes a public key: A = ga mod p, B = gb mod p
  3. They swap public keys over the network
  4. Each computes the shared secret: K = Ba mod p = Ab mod p

Both get the same K, but an attacker who only sees A and B can't figure it out!

Encryption with XOR

The shared secret seeds a Linear Congruential Generator (LCG) that produces a stream of pseudorandom bytes:

next = (1664525 × current + 1013904223) mod 2³²

Each file byte gets XOR'd with a keystream byte:

encrypted = plaintext XOR keystream_byte
decrypted = encrypted XOR keystream_byte  // XOR reverses itself!

How to test

echo "Hi!" > test.txt
make

Terminal 1 (Receiver)

./octo-shell
nittalk -listen

Terminal 2 (Sender)

./octo-shell
nittalk -s 127.0.0.1 test.txt

What to check ✅

Sender   → Shared Secret: 1571
Receiver → Shared Secret: 1571
Keystream: 186 209 252 43 142 149 240 ...  (must match!)

Level 4 — Tripwire IDS (Intrusion Detection)

The final boss. We build a raw socket packet sniffer that monitors network traffic and flags unauthorized connections.

How it works

Compile the tripwire

gcc src/tripwire.c -o src/tripwire
⚠️ Needs sudo! Raw sockets require root privileges.

Sudo stands for "SuperUser DO." It is a command that allows a permitted user to execute a command with the security privileges of another user—specifically, the root (superuser).

We are using sudo because of the socket(AF_INET, SOCK_RAW, IPPROTO_TCP) call. When you use SOCK_RAW, you are telling the kernel: "I want to bypass your standard networking rules and talk directly to the network interface card (NIC) hardware."

Access to Hardware: Raw access is incredibly powerful. A program with raw socket access can sniff private passwords, hijack connections, or spoof identities.

The Restriction: Because this is a massive security risk, the Linux kernel strictly prohibits standard users from opening raw sockets.

Only the root user is trusted with this level of access.

Testing on one laptop (3 terminals)

Terminal 1 — Compile the code:

gcc src/tripwire.c -o src/tripwire

Run the Tripwire

sudo ./src/tripwire

output

Tripwire Active. Monitoring traffic...

Terminal 2 — Act as the Receiver

nc -l 8080

Terminal 3 — Act as the "Teammate"

nc YOUR_IP_ADDRESS 8080

Type something and hit Enter. Check Terminal 1:

[*] Authorized traffic from: 172.17.66.30

- Now test the intruder alert

curl -I https://www.google.com

Check Terminal 1:

[!] ALERT: Intruder detected! Source: 142.250.x.x

Tripwire Testing Guide with 2 laptops

Scenario Overview

To verify the functionality of the Tripwire module, we will simulate a scenario using two machines on the same local network:

Prerequisites

  1. Both machines must be connected to the same Local Area Network (LAN).
  2. Machine A must be running a Linux environment (or WSL) with gcc installed, since raw sockets require POSIX capabilities.
  3. Administrative (root/sudo) privileges are required on Machine A to bind to SOCK_RAW.

Step 1: Network Configuration

Identify the local IP addresses of both machines.

Step 2: Configure the Trusted Teammate

  1. On Machine A, open the source code file src/tripwire.c.
  2. Locate the #define directive for the teammate's IP address.
  3. Update the value to match the IP address of Machine B:
#define TEAMMATE_IP "192.168.1.15"

Save the file.

Step 3: Compilation and Execution

cd src
gcc tripwire.c -o tripwire
sudo ./tripwire

Expected Output:

Tripwire Active. Monitoring traffic...

Step 4: Simulating Authorized Traffic (Teammate)

  1. On Machine B, send a request to Machine A:
curl http://192.168.1.10

Verification: On Machine A’s terminal, Tripwire should output:

[*] Authorized traffic from: 192.168.1.15

Step 5: Simulating Unauthorized Traffic (Intruder)

  1. From an unauthorized device (e.g., IP 192.168.1.50):
curl http://192.168.1.10

Verification: On Machine A’s terminal, Tripwire should output:

[!] ALERT: Intruder detected! Source: 192.168.1.50

If you see Green for the teammate and Red for the intruder, your Tripwire IDS is working correctly.


Problem Encountered

Laptop B was unable to ping Laptop A or communicate with the WSL instance.

Symptoms

  • ping 192.168.1.39 → Request timed out.
  • Test-NetConnection → Ping failed.
  • WSL IP (172.17.66.30) was visible, but communication from another laptop was not possible.

Step 1: Verify WSL IP

ip a
hostname -I

Result: WSL IP = 172.17.66.30

Step 2: Verify Windows Wi-Fi IP

ipconfig

Result: Wi-Fi IP = 192.168.1.39

Step 3: Test Network Connectivity

ping 192.168.1.39

Result: Request timed out → Problem lies with Windows networking, not WSL.

Step 4: Check Network Profile

Get-NetConnectionProfile

Result: NetworkCategory : Public

A Public network blocks many incoming connections by default.

Step 5: Change Network to Private

Set-NetConnectionProfile -InterfaceAlias "Wi-Fi" -NetworkCategory Private
Get-NetConnectionProfile

Result: NetworkCategory : Private

Step 6: Enable Ping Through Firewall

Enable-NetFirewallRule -Name FPS-ICMP4-ERQ-In

This allows incoming ICMP (ping) requests.

Step 7: Test Again

ping 192.168.1.39

Result: Reply from 192.168.1.39 → Communication successful.

Root Cause

The Windows Wi-Fi network was configured as Public, causing Windows Firewall to block incoming ICMP and network traffic. Since Laptop B could not reach Windows on Laptop A, the issue was unrelated to WSL.

Solution Summary

  1. Verified WSL IP using ip a.
  2. Verified Windows Wi-Fi IP using ipconfig.
  3. Tested connectivity using ping.
  4. Checked network profile using Get-NetConnectionProfile.
  5. Changed the network from Public to Private.
  6. Enabled Windows Firewall ICMP rule (Enable-NetFirewallRule -Name FPS-ICMP4-ERQ-In).
  7. Confirmed successful communication by pinging Laptop A from Laptop B.

Quick Reference — All Commands

What Command
Open WSL wsl -d ubuntu
Compile everything make clean && make
Run the shell ./octo-shell
Start listener nittalk -listen
Send a file nittalk -s 127.0.0.1 filename.txt
Compile tripwire gcc src/tripwire.c -o src/tripwire
Run tripwire sudo ./src/tripwire