Last Updated: November 21, 2019
·
347
· lbonanomi

Censor credentials in bash history

Small Go utility and Bash config to censor credential-like strings in bash history. Turn bash command histories like this:

$ history
...
 1021  curl -v -H "Authorization: token 3067a4993bd73e857b72d716055bc137283b3a83" https://api.github.com/user
 1022  curl https://lbonanomi:3067a4993bd73e857b72d716055bc137283b3a83@api.github.com/user
 1023  curl -u :3067a4993bd73e857b72d716055bc137283b3a83 https://api.github.com/user

into:

$ history
...
 curl -v -H AUTH_HEADER_REDACTED https://api.github.com/user
 curl https://REDACTED:REDACTED@api.github.com/user
 curl -u :REDACTED https://api.github.com/user
package main

import (
    "bufio"
    "fmt"
    "os"
    "regexp"
    "strings"
)

func curl_u(cmdline string)(after string) {
    curl := regexp.MustCompile(`:\S+?\s+\b`)
    after = curl.ReplaceAllString(cmdline, ":REDACTED ")
    return
}

func https_creds(cmdline string)(after string) {
    pattern := regexp.MustCompile(`https://(\S+?):\S+?@`)
    after = pattern.ReplaceAllString(cmdline, "https://REDACTED:REDACTED@")
    return
}

func header_creds(cmdline string)(after string) {
    pattern := regexp.MustCompile(`(-H|--header)\s.*?(token|auth.*?)\s\S+?\s`)
    after = pattern.ReplaceAllString(cmdline, "-H AUTH_HEADER_REDACTED ")
    return
}

func main() {
    reader := bufio.NewReader(os.Stdin)

    for {
        text, _ := reader.ReadString('\n')

        if (text == "") {
            break
        }

        newtext := ""

        for _, word := range(strings.Fields(text)[1:]) {    // Remove history line number
            newtext = newtext + " " + word                      //
        }

        // Redact credential patterns
        //

    text = newtext

        text = curl_u(text)
    text = https_creds(text)
    text = header_creds(text)

        fmt.Println(text)
    }
}

Setup a function to rewrite bash history:

function sterilize_history() {
    history | $HOME/revisionist > sterile && history -r sterile && rm sterile
}

Rewrite history after every command:

export PROMPT_COMMAND="sterilize_history"