Light Sabers Unleashed: The Lazy Developer's Guide to Outsmarting Botnets
Tags: cybersecurity, webdev, javascript, botnets
Published: 2023-08-29 14:24:47


![R2D2 and C3PO from the movie Star wars](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j4acp35krdjs657q3qn8.jpg)
<figcaption style={{ marginBottom: "2rem", fontSize: "0.8rem" }}>Cover Image Credit: cc 2.0 www.flickr.com/photos/dwmoran/21548629573/</figcaption>

In a galaxy far, far away starships sail through the vast expanse of the universe and struggle against dark forces. In that galaxy, the noble bot C-3PO brings order and harmony, while in ours not all bots act with such benevolence. Here, we struggle against different types of dark forces, often perpetuated by malicious bots themselves.  With the power of Pangea’s APIs and just a few lines of code, you can safeguard your app from the dark side just like a Jedi!

[Pangea](https://pangea.cloud/?utm_source=hashnode&utm_medium=blog-post&utm_campaign=lightsabers-botnet-blog) recently partnered with [Team Cymru](https://pangea.cloud/docs/blog/pangea-and-team-cymru-the-better-together-story?utm_source=hashnode&utm_medium=blog-post&utm_campaign=lightsabers-botnet-blog) (a company with a state-of-the-art botnet detection dataset) to provide developers access to IP reputation data through Pangea’s APIs. Through the [Pangea IP Intel API](https://pangea.cloud/services/ip-intel/reputation/?utm_source=hashnode&utm_medium=blog-post&utm_campaign=lightsabers-botnet-blog), developers can wield Jedi-like powers to regulate access for critical user actions on an app, such as registrations, logins, and payments, effectively thwarting malicious bots from executing these operations.

## Why not use a [WAF](https://en.wikipedia.org/wiki/Web_application_firewall) or other DDOS protection?

Well, while DDOS attacks are one type of damage that bots can cause, botnets can't only be stopped by WAFs due to the nature of the different potential attack vectors. Attacks such as [Astroturfing](https://en.wikipedia.org/wiki/Astroturfing) allows botnets to post harmful content, spam various APIs, and degrade important functions in your app.  These attacks can be hard to prevent without advanced knowledge gained through botnet IP datasets such as the one offered by Pangea in partnership with Team Cymru.

**So, let’s see how it works:**

**Step 1:** Write a util file that makes the API call to Pangea’s IP reputation endpoint.

```typescript
import { PangeaConfig, IPIntelService, PangeaErrors } from "pangea-node-sdk";

// API credential stuff
const domain = process.env.PANGEA_DOMAIN;
const token = process.env.PANGEA_INTEL_TOKEN;
const config = new PangeaConfig({ domain: domain });
const ipIntel = new IPIntelService(String(token), config);

const botDetector = async (ipAddress: string) => {

    // Selecting Cymru provider to detect malicious bots and botnets
    const options = { provider: "cymru", verbose: true, raw: true };
    
    const response = await ipIntel.reputation(ipAddress, options);

    if (response.result.data.verdict == "malicious" || response.result.data.verdict == "suspicious") {
        return {isBotDetected: true, resultData: response.result.data}
    } else {
        // No bot detected
        return {isBotDetected: false, resultData: response.result.data}
    }
}
```

All this util file does is make a call to Pangea’s API with a given IP address and return whether it found the IP to be a `malicious` or `suspicious` bot.

Now this can be used like middleware in each of the app's critical API routes

**STEP 2:** Use the util file like middleware in every critical API route

```typescript
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const detectedIP = requestIp.getClientIp(req);
  const {isBotDetected, resultData} = await botDetector(detectedIP as string)
  let code = 200
  let message = ""
  if (!isBotDetected) {
    // Carry out critical action / user flow
    message = "Success, action was carried out"
  } else {
    // Bot throw an error
    // Throw captcha or block request action
    code = 429
    message = "Sorry you were classified as a bot, can't perform action."
  }
  res.status(code).json({ bot_status: isBotDetected, your_ip: detectedIP, message: message, data: resultData })
}
```

Notice how I’ve used isBotDetected to determine which action to take. When a malicious bot is detected, I return the appropriate error code. Otherwise, I return a success message and let the action continue.

**To see this in action**, you will need to deploy it on Vercel for it to be able to accurately collect your IP address. Check out the [GitHub repo](https://github.com/snpranav/pangea-bot-detection-demo#usage) with a small set of instructions to give it a try.

---

With this newly acquired lightsaber of middleware, you have completed your Jedi-like training and can now proceed to swiftly cut down botnets before they start harming your application.

The path to harness this power is accessible by signing up to the [Pangea API for free](https://pangea.cloud/services/ip-intel/reputation/?utm_source=hashnode&utm_medium=blog-post&utm_campaign=lightsabers-botnet-blog). Remember the wisdom of Master Yoda, “Do or do not. There is no try.” By only allowing access to friendly bots like C-3PO and thwarting malicious ones, you can safeguard your application's fate with Pangea's IP Intel API. Act now, and let your application flourish in the light of security!