• Stars
    star
    190
  • Rank 199,459 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 6 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Express.js middleware for "Host" and "Referer" header validation to protect against DNS rebinding attacks.

Host Validation

Build Status Coverage Status

NPM

Express.js middleware that protects Node.js servers from DNS Rebinding attacks by validating Host and Referer [sic] headers from incoming requests. If a request doesn't contain a whitelisted Host/Referer header, host-validation will respond with a 403 Forbidden HTTP error.

DNS Rebinding is a savvy exploit that hasn't gotten the attention it deserves over the years. For this reason tons of services are vulnerable to it because of lack of developer knowledge of the attack or simply negligence and indifference to patch against it. Don't be that person.

Getting Started

# install using npm
npm install host-validation
const express        = require('express')
const hostValidation = require('host-validation')

const app = express()

// allow development hosts, a domain name, and a regex for all subdomains.
// any requests that don't supply a whitelisted Host will be rejected
// with a 403 HTTP status code 
// NOTE: custom errors can be returned by a config.fail function. see "custom 
// failure handlers" below.
app.use(hostValidation({ hosts: ['127.0.0.1:3000',
                                 'localhost:3000',
                                 'mydomain.com', 
                                 /.*\.mydomain\.com$/] }))

app.get('/', (req, res) => {
    res.send('Hello trusted client, thanks for including a whitelisted Host header.')
})

app.listen(3000, () => {
    console.log('server accepting requests w/ valid Host headers port 3000')
})

What is DNS Rebinding and why should I care?

DNS Rebinding is a clever technique used to bypass the browser's Same-Origin Policy. This policy blocks malicious websites or HTML advertisements from making arbitrary requests to other servers. Imagine a scenario where you are surfing a news website that serves banner ads. One of those ads contains malicious JavaScript that POSTs default router credentials to http://192.168.1.1/router_login.php, a common IP address for routers on home networks, in an attempt to open an inbound connections from the Internet. Even if 5% of users don't change there router admin panel login (not their WiFi network login) that attack could still be successful hundreds of thousands of times a day depending on the reach of the malicious ad.

Now, because of Same-Origin Policy, your web browser actually blocks that request to 192.168.1.1 from ever taking place. It notices that http://malicious-ad.com is a different host than 192.168.1.1 (which doesn't have Cross Origin Resource Sharing (CORS) headers enabled) and stops the request dead in it's tracks. All, good right?

Not so fast. Enter DNS Rebinding. In the above scenario, your browser won't allow the malicious ad to make a request to http://192.168.1.1/router_login.php, but it would allow a request to http://malicious-ad.com/router_login.php. That doesn't seem like a problem because there is no way that http://malicious-ad.com could be hosting our router login page, right? Technically, yes, that is true, but what if http://malicious-ad.com could act as a proxy to your home router. Better yet, what if the domain name http://malicious-ad.com actually resolved to 192.168.1.1 so that it could trick your browser into thinking it is making a request to the same host but the request is actually made to your home router. This is exactly what DNS Rebinding does. It uses a malicious DNS server (like FakeDNS) to respond to the same DNS request with different results at different times. A common DNS Rebinding server might be configured to respond to http://2dfaa01a-59bf-47db-a7cc-ddf4245e68b9.malicious-ad.com with 157.218.13.52, the real IP address of the HTTP server serving the malicious ad the first time it is requested, and then 192.168.1.1 every time that same domain name is requested thereafter.

Who is vulnerable to DNS Rebinding?

Any HTTP server that 1) doesn't use HTTPS or 2) has no user authentication and 3) doesn't validate the Host header of incoming requests is vulnerable to DNS Rebind attacks.

This package protects you from #2. If you are using HTTPS you don't need to use this package (good job!). But hey... I bet you don't use HTTPS when when you are developing on your local machine/network. Local networks are among the top targets for DNS Rebind attacks, so you should probably validate Host headers in that circumstance too.

The reason that "Host" header validation mitigates against DNS rebinding is that malicious requests sent from web browsers will have "Host" values that don't match the ones you would expect your server to have. For instance, your home router should expect to see "Host" values like 192.168.1.1, 192.168.0.1, or maybe router.asus.com, but definitely not http://malicious-ad.com. Simply checking that the "Host" header contains the value that you expect will prevent DNS rebinding attacks and leave your users protected.

Examples and usage

This package is dead simple. Include a few new lines of code and protect yourself from DNS Rebind attacks without ever thinking about it again.

Simple Host validation

// host and referrer headers can accept strings or regular expressions
app.use(hostValidation({ hosts: ['mydomain.com', /.*\.mydomain\.com$/] }))

Simple Referer validation

// host and referrer headers can accept strings or regular expressions
app.use(hostValidation({ referers: ['http://trusted-site.com/login.php', 
                                    /^http:\/\/othersite\.com\/login\/.*/] }))
// only accept POSTs from HTTPS referrers
app.use(hostValidation({ referers: [/^https:\/\//]}))

Host and/or Referer validation

// you can include both host and referer values in the config
// by default, only requests that match BOTH Host and Referer values will be allowed
app.use(hostValidation({ hosts: ['trusted-host.com'], 
                         referers: ['https://trusted-host.com/login.php'] }))
// you can use the { mode: 'either' } value in the config accept requests that match
// either the hosts or the referers requirements. Accepted values for mode include 
// 'both' and 'either'. The default value is 'both' if none is specified.  
app.use(hostValidation({ hosts: ['trusted-host.com'], 
                         referers: ['https://trusted-host.com/login.php'],
                         mode: 'either' }))

Custom rules for custom routes

// route-specific rules can be specified like any Express.js middleware
app.use('/login', hostValidation({ hosts: ['trusted-host.com'] }))
app.use('/from-twitter', hostValidation({ referrers: [/^https:\/\/twitter.com\//] }))

Custom failure handlers

Add a custom error handler that's run when host or referer validation fails. This function overwrites the default behavior of responding to failed requests with a 403 Forbidden error.

// 
app.use('/brew-tea', hostValidation({ 
	hosts: ['office-teapot'],
	fail: (req, res, next) => {
        // send a 418 "I'm a Teapot" Error
		res.status(418).send('I\'m the office teapot. Refer to me only as such.')
	}
}))

Testing

For more example usage see test.js

# navigate to the module directory
cd node_modules/host-validation

# install the dev dependencies
npm install --dev

# run the tests in test.js
npm test

More Repositories

1

wifi-cracking

Crack WPA/WPA2 Wi-Fi Routers with Airodump-ng and Aircrack-ng/Hashcat
10,642
star
2

PassGAN

A Deep Learning Approach for Password Guessing (https://arxiv.org/abs/1709.00440)
Python
1,726
star
3

naive-hashcat

Crack password hashes without the fuss 🐈
C
1,075
star
4

chattervox

πŸ“‘ An AX.25 packet radio chat protocol with support for digital signatures and binary compression. Like IRC over radio waves.
TypeScript
743
star
5

whonow

A "malicious" DNS server for executing DNS Rebinding attacks on the fly (public instance running on rebind.network:53)
JavaScript
615
star
6

dns-rebind-toolkit

A front-end JavaScript toolkit for creating DNS rebinding attacks.
JavaScript
481
star
7

sniff-probes

Plug-and-play bash script for sniffing 802.11 probes requests πŸ‘ƒ
Shell
231
star
8

apibuilder

Easy API builder mini library for PHP
PHP
202
star
9

distributed-password-cracking

Borrow CPU cycles from visitor's web browsers to crack MD5 password hashes 😲
JavaScript
180
star
10

midi-rnn

Generate monophonic melodies with machine learning using a basic LSTM RNN
Python
155
star
11

ProbeKit

SSID Probe Request Collection Workshop
JavaScript
133
star
12

keras_weight_animator

Save keras weight matrices as short animated videos during training
Python
105
star
13

ml4music-workshop

Machine Learning for Music and Sound Synthesis workshop
Jupyter Notebook
104
star
14

GloVe-experiments

GloVe word vector embedding experiments (similar to Word2Vec)
Python
60
star
15

radio-thermostat

Radio Thermostat CT50 & CT80 REST API notes
32
star
16

letterpress

A nefarious keylogger for Ubuntu. Encrypts keylogs and uploads to pastebin.
Python
26
star
17

the-wandering-dreamer

The Wandering Dreamer: An Synthetic Feedback Loop
JavaScript
22
star
18

pw

Generate strong passwords using /dev/urandom πŸ‘»
Shell
15
star
19

markov-passwords

Markov-chain password generator
Python
13
star
20

chattervox-examples

A collection of example applications and use cases for the Chattervox protocol
Python
11
star
21

quartzite

Auto-log screenshots and metadata to your personal cloud server when surfing the web
PHP
11
star
22

xmrig-k8s

Mine Monero using leftover resources in a Kubernetes cluster
10
star
23

aprsc-docker

A dockerized aprsc APRS-IS server
Dockerfile
10
star
24

chirp-files

A collection of notable radio frequencies near Philadelphia PA and beyond
9
star
25

chattervox-keys

A public chattervox key server πŸ”‘
Python
9
star
26

cve

A collection of vulnerabilities found through independent security research.
8
star
27

DreamMachines

Research into using Machine Learning to hallucinate circuit board schematics
KiCad Layout
8
star
28

pokemods

A small collection of PokΓ©mon Red & Blue Gameboy game mods.
Assembly
7
star
29

attacker-personas

πŸ΄β€β˜ οΈ Use attacker personas to improve your threat modeling and cybersecurity practices
7
star
30

vanity-keygen

A vanity key generator for the P224, P256, P384, and P521 elliptic curves.
Go
7
star
31

go-runway

A small Go module for interfacing with RunwayML
Go
7
star
32

helm-charts

A small collection of helm charts
HTML
6
star
33

ofTutoring

Course repository for 1-on-1 openFrameworks/C++ tutoring
6
star
34

markov

A small Markov chain generator πŸ“ƒ
Go
5
star
35

distance-sort

Sort geographic locations by their distance from eachother
Python
5
star
36

twilio-cleverbot

Talk to Cleverbot from your phone
JavaScript
4
star
37

BetweenTheTwoOfThese

Custom openFrameworks applications for an 80ft projection installation in Atlanta
C++
4
star
38

spectrum-wrangler-docker

A Dockerized version of Spectrum Wrangler that downloads and geo indexes public FCC license data
Dockerfile
4
star
39

indexd

Archive and connect independent artists websites
PHP
4
star
40

exchatter

A personalized chatbot framework for Node js
JavaScript
4
star
41

application-security-workshop

HTML
4
star
42

LANlockED

PirateBox style LAN tutorial website for EmptyBox
HTML
3
star
43

LEDWallVideoPlayer

Video player application for the Moment LED wall installation at Dolby Labs
C++
3
star
44

pastebin-mirror-docker

A dockerized version of the pastebin-mirror service.
Dockerfile
3
star
45

manifesto

A young art and technologist's manifesto
3
star
46

picamstreaming

Stream directly to Youtube from the Raspberry Pi camera module
Python
2
star
47

thisisatrackingdevice

An interactive map to display data from a public tracking device project
Processing
2
star
48

osm-museums

Open Street Maps data for all museums on earth (36,694 as of June 5th, 2017)
Python
2
star
49

gpssandbox

Sandbox to play with gps/gpx data visualization using google maps api
Processing
2
star
50

kiss-tnc

Talk to a packet radio KISS TNC over a serial port.
JavaScript
2
star
51

runway-glove

A Runway model for experimenting with GloVe vector embeddings
Python
2
star
52

rtl-433-influxdb-importer

Import data from an Acurite 5-in-1 weather station into influxdb
Python
2
star
53

osm-syria-poi

Open Street Maps data for cultural/historic points of interest in Syria
Python
2
star
54

ofxCanvasEvents

Broadcasts mouse, touch, and key events from an HTML5 Canvas to an openFrameworks app
JavaScript
2
star
55

P5AlbersColorTheory

Materials for an introduction to P5.js lecture themed around Josef Albers inspired color theory.
JavaScript
1
star
56

projectortracking

A sandbox repo for projects aimed to make any projector touch screen
Processing
1
star
57

OculusWebcamExperiments

Experimental webcam projects for the Oculus Rift. Built with openFrameworks.
C++
1
star
58

nodesandbox

A sandbox repo for node.js + RPi experiments
JavaScript
1
star
59

ChessEmbeddings

GloVe vector embeddings of chess moves
Jupyter Notebook
1
star
60

ofBook_IntroToGraphics

1
star
61

looplamp

Raspberry Pi + Node.js interactive lamp project
JavaScript
1
star
62

ml-sandbox

Machine Learning sandbox
Python
1
star
63

brannondorsey.com

My portfolio website
PHP
1
star
64

tvtalker-app

TVTalker Display app made with openFrameworks
C++
1
star
65

website

Personal Website. Using Kirby CMS.
PHP
1
star
66

scarecrow

A Node.js chat bot that learns.
JavaScript
1
star
67

oculusself

Self reflection with the Oculus Rift
C++
1
star
68

OpenNIWebSocketDaemon

Stream depth and skeleton tracking data from OpenNI2 + NiTE2 to the browser via WebSockets
JavaScript
1
star
69

UBox

Generalized modular framework to create software like PirateBox or LibraryBox
JavaScript
1
star
70

oFMaskTool

C
1
star
71

webconnections

A node.js powered command-line app for illustrating the degrees of separation between webpages
JavaScript
1
star
72

brbxoxo

PHP
1
star
73

vectorpi

C++
1
star
74

LEDWallInteractive

Interactive scenes for the Moment LED wall installation at Dolby Labs (Authored by Jason Van Cleave and Brannon Dorsey)
C++
1
star
75

exes

A romantic artificial intelligence project
Python
1
star
76

zetamaze

Repo for the Zetamaze threejs project
JavaScript
1
star
77

ProgrammingForArtists

Art && Programming Lecture @ The School of the Art Institute of Chicago, March 2017
JavaScript
1
star