Search for a value in HashiCorp vault

4.6k views Asked by At

Is there a way to search for a value in Hashicorp Vault? I am trying to write Golang code to search and list all locations a value appears in vault. It would be similar to golang's walk function on directories. Does anyone have a good approach for this? I was thinking of using concurrency to search vault for a value. Thank you

Below is a sample of the code I came up with. I am looking on how to make this faster by using concurrency. Is there a way to traverse a directory concurrently?

func walkDir(client *api.Client, path string) {
    var value *api.Secret
    var err error
    if path != "" {
        value, err = client.Logical().List(path)
    } else {
        path = vault_path
        value, err = client.Logical().List(path)
    }
    if err != nil {
        fmt.Println(err)
    }
    var datamap map[string]interface{}
    datamap = value.Data
    data := datamap["keys"].([]interface{})
    for _, item := range data {
        itemString := item.(string)
        if strings.HasSuffix(itemString, "/") {
            walkDir(client, path+itemString)
        } else {
            //its a secret
            data := read(client, path+itemString)

            if *searchKey!="" && searchForKey(data,*searchKey){
                fmt.Println(path + itemString)
            }
            if *searchValue!="" && searchForValue(data,*searchValue){
                fmt.Println(path + itemString)
            }
        }
    }
}

func read(client *api.Client, path string) map[string]interface{} {
    value, err := client.Logical().Read(path)
    if err != nil {
        fmt.Println(err)
    }
    values := value.Data
    return values
}

func searchForValue(mapp map[string]interface{}, searchValue string) bool {
    for _, value := range mapp {
        if searchValue == value {
            return true
        }
    }
    return false
}

func searchForKey(mapp map[string]interface{}, searchKey string) bool {
    for key := range mapp {
        if searchKey == key {
            return true
        }
    }
    return false
}
1

There are 1 answers

2
lxop On BEST ANSWER

You can LIST "directories" in Vault (I'm assuming you're just looking at the kv engine). So treat it somewhat like a regular file-system: start at the root, list the entries, check the contents of each of them for that value, then iterate through each entry, listing its contents, and so forth.

https://www.vaultproject.io/api-docs/secret/kv/kv-v1#list-secrets