• Stars
    star
    654
  • Rank 68,870 (Top 2 %)
  • Language
    TypeScript
  • Created almost 12 years ago
  • Updated 5 months ago

Reviews

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

Repository Details

HTTP Man In The Middle (MITM) Proxy

HTTP MITM Proxy

HTTP Man In The Middle (MITM) Proxy written in node.js. Supports capturing and modifying the request and response data.

NPM version Downloads Test Status

Install

npm install --save http-mitm-proxy

Node.js Compatibility

The library should work starting Node.js 8.x, but testing is only expected for currently supported LTS versions of Node.js starting Node.js 12.x . use on your own risk with non LTS Node.js versions.

Typescript

type definitions are now included in this project, no extra steps required.

Example

This example will modify any search results coming from google and replace all the result titles with "Pwned!".

const Proxy = require('http-mitm-proxy').Proxy;
// or using import/module (package.json -> "type": "module")
// import { Proxy } from "http-mitm-proxy";
const proxy = new Proxy();

proxy.onError(function(ctx, err) {
  console.error('proxy error:', err);
});

proxy.onRequest(function(ctx, callback) {
  if (ctx.clientToProxyRequest.headers.host == 'www.google.com'
    && ctx.clientToProxyRequest.url.indexOf('/search') == 0) {
    ctx.use(Proxy.gunzip);

    ctx.onResponseData(function(ctx, chunk, callback) {
      chunk = Buffer.from(chunk.toString().replace(/<h3.*?<\/h3>/g, '<h3>Pwned!</h3>'));
      return callback(null, chunk);
    });
  }
  return callback();
});

console.log('begin listening on 8081')
proxy.listen({port: 8081});

You can find more examples in the examples directory

SSL

Using node-forge allows the automatic generation of SSL certificates within the proxy. After running your app you will find options.sslCaDir + '/certs/ca.pem' which can be imported to your browser, phone, etc.

API

Proxy

Context

Context functions only effect the current request/response. For example you may only want to gunzip requests made to a particular host.

WebSocket Context

The context available in websocket handlers is a bit different

Proxy

proxy.listen

Starts the proxy listening on the given port.

Arguments

  • options - An object with the following options:
  • port - The port or named socket to listen on (default: 8080).
  • host - The hostname or local address to listen on (default: 'localhost'). Pass '::' to listen on all IPv4/IPv6 interfaces.
  • sslCaDir - Path to the certificates cache directory (default: process.cwd() + '/.http-mitm-proxy')
  • keepAlive - enable HTTP persistent connection
  • timeout - The number of milliseconds of inactivity before a socket is presumed to have timed out. Defaults to no timeout.
  • httpAgent - The http.Agent to use when making http requests. Useful for chaining proxys. (default: internal Agent)
  • httpsAgent - The https.Agent to use when making https requests. Useful for chaining proxys. (default: internal Agent)
  • forceSNI - force use of SNI by the client. Allow node-http-mitm-proxy to handle all HTTPS requests with a single internal server.
  • httpsPort - The port or named socket for https server to listen on. (forceSNI must be enabled)
  • forceChunkedRequest - Setting this option will remove the content-length from the proxy to server request, forcing chunked encoding.

Example

proxy.listen({ port: 80 });

proxy.close

Stops the proxy listening.

Example

proxy.close();

proxy.onError(fn) or ctx.onError(fn)

Adds a function to the list of functions to get called if an error occures.

Arguments

  • fn(ctx, err, errorKind) - The function to be called on an error.

Example

proxy.onError(function(ctx, err, errorKind) {
  // ctx may be null
  var url = (ctx && ctx.clientToProxyRequest) ? ctx.clientToProxyRequest.url : "";
  console.error(errorKind + ' on ' + url + ':', err);
});

proxy.onCertificateRequired = function(hostname, callback)

Allows the default certificate name/path computation to be overwritten.

The default behavior expects keys/{hostname}.pem and certs/{hostname}.pem files to be at self.sslCaDir.

Arguments

  • hostname - Requested hostname.
  • callback - The function to be called when certificate files' path were already computed.

Example 1

proxy.onCertificateRequired = function(hostname, callback) {
  return callback(null, {
    keyFile: path.resolve('/ca/certs/', hostname + '.key'),
    certFile: path.resolve('/ca/certs/', hostname + '.crt')
  });
};

Example 2: Wilcard certificates

proxy.onCertificateRequired = function(hostname, callback) {
  return callback(null, {
    keyFile: path.resolve('/ca/certs/', hostname + '.key'),
    certFile: path.resolve('/ca/certs/', hostname + '.crt'),
    hosts: ["*.mydomain.com"]
  });
};

proxy.onCertificateMissing = function(ctx, files, callback)

Allows you to handle missing certificate files for current request, for example, creating them on the fly.

Arguments

  • ctx - Context with the following properties
  • hostname - The hostname which requires certificates
  • data.keyFileExists - Whether key file exists or not
  • data.certFileExists - Whether certificate file exists or not
  • files - missing files names (files.keyFile, files.certFile and optional files.hosts)
  • callback - The function to be called to pass certificate data back (keyFileData and certFileData)

Example 1

proxy.onCertificateMissing = function(ctx, files, callback) {
  console.log('Looking for "%s" certificates',   ctx.hostname);
  console.log('"%s" missing', ctx.files.keyFile);
  console.log('"%s" missing', ctx.files.certFile);

  // Here you have the last chance to provide certificate files data
  // A tipical use case would be creating them on the fly
  //
  // return callback(null, {
  //   keyFileData: keyFileData,
  //   certFileData: certFileData
  // });
  };

Example 2: Wilcard certificates

proxy.onCertificateMissing = function(ctx, files, callback) {
  return callback(null, {
    keyFileData: keyFileData,
    certFileData: certFileData,
    hosts: ["*.mydomain.com"]
  });
};

proxy.onRequest(fn) or ctx.onRequest(fn)

Adds a function to get called at the beginning of a request.

Arguments

  • fn(ctx, callback) - The function that gets called on each request.

Example

proxy.onRequest(function(ctx, callback) {
  console.log('REQUEST:', ctx.clientToProxyRequest.url);
  return callback();
});

proxy.onRequestData(fn) or ctx.onRequestData(fn)

Adds a function to get called for each request data chunk (the body).

Arguments

  • fn(ctx, chunk, callback) - The function that gets called for each data chunk.

Example

proxy.onRequestData(function(ctx, chunk, callback) {
  console.log('REQUEST DATA:', chunk.toString());
  return callback(null, chunk);
});

proxy.onRequestEnd(fn) or ctx.onRequestEnd(fn)

Adds a function to get called when all request data (the body) was sent.

Arguments

  • fn(ctx, callback) - The function that gets called when all request data (the body) was sent.

Example

var chunks = [];

proxy.onRequestData(function(ctx, chunk, callback) {
  chunks.push(chunk);
  return callback(null, chunk);
});

proxy.onRequestEnd(function(ctx, callback) {
  console.log('REQUEST END', (Buffer.concat(chunks)).toString());
  return callback();
});

proxy.onResponse(fn) or ctx.onResponse(fn)

Adds a function to get called at the beginning of the response.

Arguments

  • fn(ctx, callback) - The function that gets called on each response.

Example

proxy.onResponse(function(ctx, callback) {
  console.log('BEGIN RESPONSE');
  return callback();
});

proxy.onResponseData(fn) or ctx.onResponseData(fn)

Adds a function to get called for each response data chunk (the body).

Arguments

  • fn(ctx, chunk, callback) - The function that gets called for each data chunk.

Example

proxy.onResponseData(function(ctx, chunk, callback) {
  console.log('RESPONSE DATA:', chunk.toString());
  return callback(null, chunk);
});

proxy.onResponseEnd(fn) or ctx.onResponseEnd(fn)

Adds a function to get called when the proxy request to server has ended.

Arguments

  • fn(ctx, callback) - The function that gets called when the proxy request to server as ended.

Example

proxy.onResponseEnd(function(ctx, callback) {
  console.log('RESPONSE END');
  return callback();
});

proxy.onWebSocketConnection(fn) or ctx.onWebSocketConnection(fn)

Adds a function to get called at the beginning of websocket connection

Arguments

  • fn(ctx, callback) - The function that gets called for each data chunk.

Example

proxy.onWebSocketConnection(function(ctx, callback) {
  console.log('WEBSOCKET CONNECT:', ctx.clientToProxyWebSocket.upgradeReq.url);
  return callback();
});

proxy.onWebSocketSend(fn) or ctx.onWebSocketSend(fn)

Adds a function to get called for each WebSocket message sent by the client.

Arguments

  • fn(ctx, message, flags, callback) - The function that gets called for each WebSocket message sent by the client.

Example

proxy.onWebSocketSend(function(ctx, message, flags, callback) {
  console.log('WEBSOCKET SEND:', ctx.clientToProxyWebSocket.upgradeReq.url, message);
  return callback(null, message, flags);
});

proxy.onWebSocketMessage(fn) or ctx.onWebSocketMessage(fn)

Adds a function to get called for each WebSocket message received from the server.

Arguments

  • fn(ctx, message, flags, callback) - The function that gets called for each WebSocket message received from the server.

Example

proxy.onWebSocketMessage(function(ctx, message, flags, callback) {
  console.log('WEBSOCKET MESSAGE:', ctx.clientToProxyWebSocket.upgradeReq.url, message);
  return callback(null, message, flags);
});

proxy.onWebSocketFrame(fn) or ctx.onWebSocketFrame(fn)

Adds a function to get called for each WebSocket frame exchanged (message, ping or pong).

Arguments

  • fn(ctx, type, fromServer, data, flags, callback) - The function that gets called for each WebSocket frame exchanged.

Example

proxy.onWebSocketFrame(function(ctx, type, fromServer, data, flags, callback) {
  console.log('WEBSOCKET FRAME ' + type + ' received from ' + (fromServer ? 'server' : 'client'), ctx.clientToProxyWebSocket.upgradeReq.url, data);
  return callback(null, data, flags);
});

proxy.onWebSocketError(fn) or ctx.onWebSocketError(fn)

Adds a function to the list of functions to get called if an error occures in WebSocket.

Arguments

  • fn(ctx, err) - The function to be called on an error in WebSocket.

Example

proxy.onWebSocketError(function(ctx, err) {
  console.log('WEBSOCKET ERROR:', ctx.clientToProxyWebSocket.upgradeReq.url, err);
});

proxy.onWebSocketClose(fn) or ctx.onWebSocketClose(fn)

Adds a function to get called when a WebSocket connection is closed

Arguments

  • fn(ctx, code, message, callback) - The function that gets when a WebSocket is closed.

Example

proxy.onWebSocketClose(function(ctx, code, message, callback) {
  console.log('WEBSOCKET CLOSED BY '+(ctx.closedByServer ? 'SERVER' : 'CLIENT'), ctx.clientToProxyWebSocket.upgradeReq.url, code, message);
  callback(null, code, message);
});

proxy.use(module) or ctx.use(module)

Adds a module into the proxy. Modules encapsulate multiple life cycle processing functions into one object.

Arguments

  • module - The module to add. Modules contain a hash of functions to add.

Example

proxy.use({
  onError: function(ctx, err) { },
  onCertificateRequired: function(hostname, callback) { return callback(); },
  onCertificateMissing: function(ctx, files, callback) { return callback(); },
  onRequest: function(ctx, callback) { return callback(); },
  onRequestData: function(ctx, chunk, callback) { return callback(null, chunk); },
  onResponse: function(ctx, callback) { return callback(); },
  onResponseData: function(ctx, chunk, callback) { return callback(null, chunk); },
  onWebSocketConnection: function(ctx, callback) { return callback(); },
  onWebSocketSend: function(ctx, message, flags, callback) { return callback(null, message, flags); },
  onWebSocketMessage: function(ctx, message, flags, callback) { return callback(null, message, flags); },
  onWebSocketError: function(ctx, err) {  },
  onWebSocketClose: function(ctx, code, message, callback) {  },
});

node-http-mitm-proxy provide some ready to use modules:

  • Proxy.gunzip Gunzip response filter (uncompress gzipped content before onResponseData and compress back after)
  • Proxy.wildcard Generates wilcard certificates by default (so less certificates are generated)

Context

ctx.addRequestFilter(stream)

Adds a stream into the request body stream.

Arguments

  • stream - The read/write stream to add in the request body stream.

Example

ctx.addRequestFilter(zlib.createGunzip());

ctx.addResponseFilter(stream)

Adds a stream into the response body stream.

Arguments

  • stream - The read/write stream to add in the response body stream.

Example

ctx.addResponseFilter(zlib.createGunzip());

License

Copyright (c) 2015 Joe Ferner

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:



The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.



THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

More Repositories

1

redis-commander

Redis management tool written in node.js
JavaScript
3,593
star
2

node-java

Bridge API to connect with existing Java APIs.
C++
1,840
star
3

node-oracle

node.js driver to connect with an oracle database.
C++
271
star
4

node-persist

Node.js ORM framework supporting MySQL and SQLite 3 relational databases.
JavaScript
252
star
5

node-bplist-parser

Binary plist parser.
JavaScript
99
star
6

node-java-maven

Utility for Node's java module to load mvn dependencies.
JavaScript
79
star
7

node-shark

Wrapper around libwireshark providing network packet dissection
C++
71
star
8

node-rtlsdr

Node bindings for rtl-sdr
C++
40
star
9

wxNode

node.js wrapper for wxWidgets
C++
39
star
10

node-gitgui

Git GUI written in node.js
JavaScript
33
star
11

pi-stm32-uart-bootloader

Raspberry PI STM32 USART Bootloader
TypeScript
26
star
12

node-portaudio

Node bindings for PortAudio
C++
24
star
13

kicadcloud.com

Source code for kicadcloud.com
JavaScript
24
star
14

node-sf

String formatting library for node.js
JavaScript
22
star
15

stm32-utils

C
21
star
16

kicad-library

My personal library of KiCad schematic symbols and footprints.
19
star
17

node-bplist-creator

Binary Mac OS X Plist (property list) creator.
JavaScript
18
star
18

node-mnm

Make Node Module is a build tool for making native node.js modules
JavaScript
14
star
19

fpga-spi

Simple SPI interface for FPGAs
C
13
star
20

stm32-cc3000

CC3000 Driver for STM32 Microcontrollers
C
13
star
21

node-tshark

Node wrapper around WireShark's tshark packet processor
JavaScript
13
star
22

stm32-wifi-ir

IR Receiver and Transmitter that can also broadcast and receive via WiFi
C
12
star
23

node-openport

Looks for an open port to start a server on
JavaScript
12
star
24

stm32-rfid-clone

STM32 RFID Reader / Writer
C
10
star
25

node-db-info

JavaScript
7
star
26

maple-usbMassStorage

Maple ARM USB Mass Storage Library
C
7
star
27

stm32-network-rs232

STM32 based network (ethernet) RS232 port.
KiCad Layout
6
star
28

node-readline-browserify

Readline implementation for browserify.
JavaScript
6
star
29

node-big-file-upload

Simple big file upload server
JavaScript
6
star
30

dc-electronic-load

DC Electronic Load
C
5
star
31

node-kicad2svg

Converts KiCad files to SVGs
JavaScript
5
star
32

node-chunkmatcher

Fast searching for multiple patterns accross multiple data chunks.
JavaScript
4
star
33

node-iverilog-gui

Icarus Verilog GUI
JavaScript
4
star
34

kicad-docker

KiCad docker container
Dockerfile
4
star
35

stm32-spi-bootloader

STM32 SPI Bootloader
Makefile
4
star
36

node-over

JavaScript function overloading framework.
JavaScript
4
star
37

stm32-st-lis3mdl

STM32 LIS3MDL: Digital output magnetic sensor Driver
C
3
star
38

telepresenceRobot

Telepresence Robot
JavaScript
3
star
39

node-redis-web

Connect middleware to proxy redis commands and pub/sub to a browser.
JavaScript
3
star
40

stm32-makefile

STM32 Makefile for working with STM32Cube
Makefile
3
star
41

node-dirdiff

Diffs two directories
JavaScript
3
star
42

stm32-48pin-devBoard

STM32 48pin Development Board.
C
3
star
43

tshark2json

Converts tshark to JSON
Shell
3
star
44

node-cmdparser

Command parser with support for completers.
JavaScript
3
star
45

stm32-microchip-rn4020

STM32 Library for the Microchip RN4020 Bluetooth Low Energy Module
C
3
star
46

tst-reflect-json-schema-generator

Generate JSON schema from tst-reflect types
TypeScript
3
star
47

stm32lib

Library for working with the STM32 line of processors
C
2
star
48

node-sdr

Software Defined Radio written in node.js
JavaScript
2
star
49

node-pi-rs232

Raspberry PI RS232 HTTP Rest relay
TypeScript
2
star
50

stm32-enc28j60

Microchip ENC28J60 10Mbs network controller driver for STM32
C
2
star
51

stm32-wifi-door-bell

STM32 WiFi Door Bell
C
2
star
52

node-kicad-tools

Collection of command line tools for working with KiCad files
JavaScript
2
star
53

node-rpncalc

RPN Calculator written with AppJS and Node.js
TypeScript
2
star
54

pigpio-ir

pigpio IR Receiver/Transmitter
TypeScript
1
star
55

pango-serialport

Pango component to work with serial ports
TypeScript
1
star
56

stm32-network

Network stack for STM32
C
1
star
57

breakoutBoards

Collection of break out boards
KiCad Layout
1
star
58

pango-gcc

Pango component to run gcc
TypeScript
1
star
59

node-tcp-reassemble

Reassembles TCP packets
JavaScript
1
star
60

stm32-ams-tcs3472

STM32 Library for the AMS TCS3472 Color Light-to-digital Converter
C
1
star
61

stm32f1DevBoard

STM32F1 Dev Board
C++
1
star
62

docker-vscode

Runs vscode inside a docker container
Shell
1
star
63

test-appjs-ajax

Tests appjs ajax calls
JavaScript
1
star
64

docker-lpcalculator

Shell
1
star
65

minirobot

A mini robot
KiCad Layout
1
star
66

node-pi-watchdog

Node wrapper for Raspberry Pi BCM2835 Watchdog
JavaScript
1
star
67

docker-flash-tool-lite

Docker image to run Intel's flash tool lite in non-debian linux.
Shell
1
star
68

arduinoPresentation

Basic Arduino Presentation
Java
1
star
69

node-delegate

Creates delegate functions automatically.
JavaScript
1
star
70

android-lengthFractionCalculator

Android app to help calculate length fractions.
Java
1
star