Quick MITM Proxy Toggle for macOS

0 reads
I often use HAR files when I want to capture outbound network traffic from a website in my browser.

You can create a HAR file by opening your browser network tab, toggling the record button, then making some network calls.

Record Network Traffic in Browser

When you want to stop recording, you can click this save button to write the results to a HAR file.

Save to HAR

This file will contain an unencrypted log of all your outbound network traffic during the recording session.

Sometimes though, I want to be able to capture outbound traffic from other applications beyond just my web browser. I recently set up mitmproxy on my Mac for this use case. Mitmproxy acts as a local proxy server, adding an extra local hop to your network path where you can capture, decrypt, and log all your HTTP and HTTPS traffic. While stepping through the onboarding guide I created some bash functions to be able to easily toggle the configuration without leaving the root cert laying around in my Mac Keychain. I added the following to my .zshrc:
bash
MITM_SERVICE="Wi-Fi" # Change to "Ethernet" if needed MITM_CERT="$HOME/Downloads/mitmproxy-ca-cert.pem" mitmup() { networksetup -setwebproxy "$MITM_SERVICE" localhost 8080 && networksetup -setsecurewebproxy "$MITM_SERVICE" localhost 8080 && sudo security add-trusted-cert -d -r trustRoot \ -k /Library/Keychains/System.keychain "$MITM_CERT" && echo "mitmproxy enabled and cert added" } mitmdown() { networksetup -setwebproxystate "$MITM_SERVICE" off && networksetup -setsecurewebproxystate "$MITM_SERVICE" off && sudo security delete-certificate -c mitmproxy /Library/Keychains/System.keychain && echo "mitmproxy disabled and cert removed" } mitmstatus() { GREEN='\033[0;32m' RED='\033[0;31m' NC='\033[0m' # No Color echo "========== Proxy Status ==========" for proto in webproxy securewebproxy; do proxy_status=$(networksetup -get${proto} "$MITM_SERVICE") enabled=$(echo "$proxy_status" | grep "Enabled: Yes") PROTO_UPPER=$(echo "$proto" | tr '[:lower:]' '[:upper:]') if [ -n "$enabled" ]; then echo -e "${PROTO_UPPER} : ${GREEN}ENABLED${NC}" else echo -e "${PROTO_UPPER} : ${RED}DISABLED${NC}" fi echo "$proxy_status" | grep -E "Server:|Port:" done echo "========== mitmproxy Certificate ==========" if security find-certificate -c mitmproxy /Library/Keychains/System.keychain > /dev/null 2>&1; then echo -e "mitmproxy certificate: ${GREEN}PRESENT${NC}" else echo -e "mitmproxy certificate: ${RED}NOT PRESENT${NC}" fi echo "===========================================" }
Now I can quickly run mitmup to flip on a proxy to localhost:8080 and add the trusted root cert to my Keychain. MITM Up Status I can then capture network traffic as needed, and when I'm done just run mitmdown to flip off the proxies and remove the root cert. MITM Down Status

These are some very simple tools that reduce the friction of toggling mitmproxy on and off as needed, similar to using HAR files in the browser.