Detecting Attackers from Within
Tags: security, webdev, javascript, tutorial
Published: 2020-06-29 11:27:33

Modern secure development practices like *[“shift left”](https://cloud.google.com/solutions/devops/devops-tech-shifting-left-on-security)* security focus on resolving security issues early and within the development process. This includes the implementation of proactive controls, such as security logging and monitoring, which can give you insights into your application’s current security posture. In addition, knowing what goes on in your application from a security perspective can be further utilized to identify attacker activity by making your application attack-aware. 

Attack-aware applications, as described by the [OWASP AppSensor](https://owasp.org/www-pdf-archive/Owasp-appsensor-guide-v2.pdf) project, rely on detection points, controls in your application code that check for blatant indicators of attacker activity. To see such detection points in action, the following parts of this article will go through some of them implemented within a small demo application. The demo application is built with the [Express](https://expressjs.com/) web application framework and uses detection points built as validators from the [express-validator](https://express-validator.github.io/docs/index.html) module. 

The application itself is very limited in functionality and provides only one endpoint (`/ticket`) to submit user-controlled data. The submitted data is supposed to be a ticket, a JSON object consisting of three properties which will be validated by the detection points: 


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/nbjaviwxrcr7q9ojv6kk.png)


The demo application is available as a Glitch project (hit the **Remix to Edit** button to work on your own instance of the application):

{% glitch ticket-demo-application preview-first file=server.js no-attribution no-files %}

*Note: Use the [following link](https://glitch.com/edit/#!/ticket-demo-application) if the embedded glitch project is not loading*

# Intrusion Detection with Detection Points
As previously mentioned, the idea of detection points is to check for blatant indicators of attacker activity, activities that you would never expect from a benign user so to speak. In the demo application for example, a benign user can select only one of three possible ticket priority values from a dropdown menu. Being able to submit any other value is a sign of request tampering by using an interception proxy like [OWASP ZAP](https://owasp.org/www-project-zap/):


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/cyz84kk4eakq1twv17t0.png)
 
 
You can check for tampering activities with simple input validators such as those in the following code snippet:

```javascript
const detectionPoints = [
  body("priority")
  .exists().withMessage("Data Missing from Request").bail()
  .isIn(["low", "medium", "high"]).withMessage("Violation of Input Data Integrity"),

  body("title")
  .exists().withMessage("Data Missing from Request"),
  
  body("description")
  .exists().withMessage("Data Missing from Request")
];
```

The validators check only for the parameters provided in the request body (`body("priority")`, `body("title")`, `body("description)`) as these are the only ones of interest. For all three parameters, the first validator checks if the parameter `exists` since it might has been removed or modified. You can then chain further validators as done with the `priority` parameter where the next validator in the chain checks if the submitted priority value `isIn` the array of acceptable values.  

The detection points so far were implemented with the built-in validators, the express-validator module provides also a way to implement `custom` validators. This can be handy if you want to make use of existing modules such as [Isomorphic DOMPurify](https://www.npmjs.com/package/isomorphic-dompurify) for detection purposes:

```javascript
const detectionPoints = [
  // ...
  body("description")
  .exists().withMessage("Data Missing from Request")
  .custom(value => {
    if (DOMPurify.sanitize(value) !== value) {
      throw new Error("Cross Site Scripting Attempt");
    }
    return true;
  })
];
```

This custom validator does a lot more complex processing than the previous ones which is abstracted away from the developer behind a single method call. It is, however, this usable abstraction that makes it convenient to utilize DOMPurify for XSS detection, an attack class which is rather ineffective to detect with the use of simple input validation controls. 

This is an important aspect of implementing detection points as you will not want to spend too much time with *“detection engineering”*. The focus should be on implementing simple but effective detection points, be it by adding new detection points to your application or by enhancing existing input validation controls.

## Intrusion Response
With the previously listed detection points in place, the demo application is now capable of detecting attacker activity. The logs generated by the triggered detection points can give the development team important insights into which part of the application is attacked and which attack techniques are deployed. To take this one step further, the triggered detection points can also be utilized to respond back defensively.     

The decision whether and how to respond back can be based on a set of rules or thresholds that are exceeded. The demo application uses the latter approach to convey the idea of a defensive response:

```javascript
class AttackMonitor { 
    constructor(threshold = 4){ 
        this.threshold = threshold; 
        this.detections = 0; 
    } 
    log(error,request){ 
        console.log(`[*] ${error.msg} @ [${request.method}] ${request.route.path} - request.${error.location}.${error.param}`); 
        this.detections += 1; 
    } 
    isThresholdExceeded(){ 
        return (this.detections > this.threshold); 
    } 
}

// ...

app.post("/ticket", (request, response) => {
  if(attackMonitor.isThresholdExceeded()){ 
    console.log(`[*] Detection threshold exceeded - [${request.method}] ${request.route.path} is deactivated`); 
    response.end(); 
  } 
  else { 
    // ...
  }
});
```

The ticket creation logic above is skipped when the number of triggered detection points exceeds a predefined threshold value. For real-world applications, however, you will want to consider more realistic responses such as: 

* Requiring authentication for sensitive actions 
* Deactivating accounts associated with attacker activity 
* Reporting attacker activity to your development team on Slack 
* Redirecting attackers to a honeypot hosting the same application but prepared with believable dummy data  

These are just a few examples and your response capabilities are only limited by the technology with which your application is developed.  

## Conclusion
Accepting that the security measures in your application can and will be bypassed indicates a strong sense for security. It is therefore important that the security measures in place should not only focus on the preventive part but also provide the capabilities to detect and act on ongoing attacks in a timely fashion. 

Attack-aware applications make the best of preventive controls by utilizing them as detection points to establish an [attack-driven defense](https://www.oreilly.com/library/view/building-a-modern/9781492044680/ch01.html) within the application. 

## Your Thoughts
As intrusion detection and response within the application seems to be rather uncommon, it would be interesting to hear your thoughts on this concept. What do you think about this concept in general, what limitations and possibilities do you see from a developer's perspective?  

> *If you want to stay up-to-date on the latest developments on this topic with research papers, articles and also developer studies in which you are welcome to participate in, then feel free to follow me here on [DEV](https://dev.to/tolgadevsec) or [Twitter](https://twitter.com/tolgauedev).*

## Further Resources
I have gathered here a few resources that you can look into if you want to learn more about attack-aware applications as well as attack-driven defense. 

### Reading Material
* [Intrusion detection: doing it wrong](https://lcamtuf.blogspot.com/2010/06/intrusion-detection-doing-it-wrong.html)
The detection points effectivity relies heavily on its secrecy among others. While security-by-obscurity is not the best strategy in certain contexts, it is, however, quite effective for detection purposes as explained by Michał Zalewski. 

* [OWASP AppSensor Guide](https://owasp.org/www-pdf-archive/Owasp-appsensor-guide-v2.pdf) | [OWASP AppSensor](http://www.appsensor.org/)
Besides more than 50 detection points described in the OWASP AppSensor guide, the guide also includes 8 illustrative case studies on integrating attack awareness into different types of applications ranging from B2B web services to smart meters. The guide also covers advanced thresholds and responses in more detail.

* [OWASP Top 10 Proactive Controls 2018]
(https://owasp.org/www-project-proactive-controls/)
The proactive controls guide and especially the chapter on implementing security logging and monitoring provides more details and further references on the design and implementation of secure logging which was not covered in this article.  

* [For Real Security, Don't Let Failure Be Your Measure of Success](https://www.darkreading.com/risk/for-real-security-dont-let-failure-be-your-measure-of-success/a/d-id/1335237)
Zane Lackey writes in this article on the importance of not only focusing on how to keep the bad guys out (prevention) but also to think about what to do once they are in (detection and response).

### Videos
* **Security Vulnerabilities Decomposition: Another Way To Look At Vulnerabilities**

In this presentation, Katy Anton demonstrates how to decompose vulnerabilities into security controls (including detection points) that can be used by developers.

{% youtube 5Ee_mWgRRQk %}

* **Whatever happened to attack aware applications?**

Matthew Pendlebury talks in this presentation about attack-aware applications and why they still don't seem to be commonplace.

{% youtube HQxs3xn7tLA %}

* **Lessons learned defending web applications in the age of DevOps/Cloud**

In this keynote talk @ DevSecCon Singapore 2018, Zane Lackey shares his practical lessons learned at Etsy on how to defend modern web applications in a DevOps world. This talk will cover different topics, including obtaining security visibility.

{% youtube ygs3PDfGn6Y %}

* **AppSensor: Real-Time Event Detection and Response**

This talk, given by John Melton, presents the OWASP AppSensor project and the model of self-protecting applications.

{% youtube OumAlyUHMcY %}