diff --git a/plugin/safe/plugin.go b/plugin/safe/plugin.go new file mode 100644 index 000000000..f646b3f5b --- /dev/null +++ b/plugin/safe/plugin.go @@ -0,0 +1,250 @@ +package main + +import ( + "encoding/json" + "io/ioutil" + "os" + + fmt "github.com/jhunt/go-ansi" + + "github.com/starkandwayne/safe/vault" + "github.com/starkandwayne/shield/plugin" +) + +var () + +func main() { + p := SafePlugin{ + Name: "Safe Backup Plugin", + Author: "Stark & Wayne", + Version: "0.0.1", + Features: plugin.PluginFeatures{ + Target: "yes", + Store: "no", + }, + Example: ` +{ + "vault_url" : "https://safe.myorg.mycompany.com", # REQUIRED + "auth_token" : "b8714fec-0df9-3f66-d262-35a57e414120", # REQUIRED + "skip_ssl_validation" : true, # REQUIRED +} +`, + Defaults: ` +{ + "skip_ssl_validation" : false, +} +`, + Fields: []plugin.Field{ + plugin.Field{ + Mode: "target", + Name: "vault_url", + Type: "string", + Title: "Vault URL", + Help: "The url address of your Vault server, including the protocol.", + Example: "https://safe.myorg.mycompany.com", + Required: true, + }, + plugin.Field{ + Mode: "target", + Name: "auth_token", + Type: "string", + Title: "Auth Token", + Help: "The auth token for a user with privileges to read and write the entire secret/ tree", + Required: true, + }, + plugin.Field{ + Mode: "target", + Name: "skip_ssl_validation", + Type: "bool", + Title: "Skip SSL Validation", + Help: "Set to true if using a self-signed cert", + Default: "false", + }, + }, + } + + plugin.Run(p) +} + +type SafePlugin plugin.PluginInfo + +func (p SafePlugin) Meta() plugin.PluginInfo { + return plugin.PluginInfo(p) +} + +func (p SafePlugin) Validate(endpoint plugin.ShieldEndpoint) error { + var ( + s string + err error + fail bool + ) + + s, err = endpoint.StringValue("vault_url") + if err != nil { + fmt.Printf("@R{\u2717 vault_url %s}\n", err) + fail = true + } else { + fmt.Printf("@G{\u2713 vault_url} @C{%s}\n", s) + } + + s, err = endpoint.StringValue("auth_token") + if err != nil { + fmt.Printf("@R{\u2717 auth_token %s}\n", err) + fail = true + } else { + fmt.Printf("@G{\u2713 auth_token} @C{%s}\n", plugin.Redact(s)) + } + + skipValidation, err := endpoint.BooleanValueDefault("skip_ssl_validation", false) + if err != nil { + fmt.Printf("@R{\u2717 skip_ssl_validation %s}\n", err) + fail = true + } else { + fmt.Printf("@G{\u2713 skip_ssl_validation} @C{%t}\n", skipValidation) + } + + if fail { + return fmt.Errorf("safe: invalid configuration") + } + return nil +} + +func (p SafePlugin) Backup(endpoint plugin.ShieldEndpoint) error { + + v, err := connect(endpoint) + if err != nil { + return err + } + + plugin.DEBUG("Reading secrets from the Vault...") + data := make(SafeContents) + if err = data.ReadFromVault(v, "secret"); err != nil { + return err + } + + return data.WriteToStdout() +} + +func (p SafePlugin) Restore(endpoint plugin.ShieldEndpoint) error { + + v, err := connect(endpoint) + if err != nil { + return err + } + + plugin.DEBUG("Reading secrets backup from stdin...") + data := make(SafeContents) + err = data.ReadFromStdin() + if err != nil { + return err + } + + plugin.DEBUG("Grabbing Safe metadata for current Vault") + sealKeysData := make(SafeContents) + sealKeysErr := sealKeysData.ReadFromVault(v, "secret/vault/seal/keys") + if sealKeysErr != nil && !vault.IsNotFound(sealKeysErr) { + return sealKeysErr + } + + plugin.DEBUG("Cleaning out the old secrets from the Vault...") + if err = v.DeleteTree("secret"); err != nil && !vault.IsNotFound(err) { + return err + } + + plugin.DEBUG("Restoring backup contents to the Vault") + err = data.WriteToVault(v) + if err != nil { + return err + } + + if sealKeysErr == nil { + plugin.DEBUG("Rewriting Safe metadata to the Vault") + return sealKeysData.WriteToVault(v) + } + return nil +} + +func (p SafePlugin) Store(endpoint plugin.ShieldEndpoint) (string, int64, error) { + return "", 0, plugin.UNIMPLEMENTED +} + +func (p SafePlugin) Retrieve(endpoint plugin.ShieldEndpoint, file string) error { + return plugin.UNIMPLEMENTED +} + +func (p SafePlugin) Purge(endpoint plugin.ShieldEndpoint, file string) error { + return plugin.UNIMPLEMENTED +} + +func connect(endpoint plugin.ShieldEndpoint) (*vault.Vault, error) { + url, err := endpoint.StringValue("vault_url") + if err != nil { + return nil, err + } + plugin.DEBUG("VAULT_URL: '%s'", url) + + token, err := endpoint.StringValue("auth_token") + if err != nil { + return nil, err + } + plugin.DEBUG("AUTH_TOKEN: '%s'", token) + + skipSslValidation, err := endpoint.BooleanValueDefault("skip_ssl_validation", false) + if err != nil { + return nil, err + } + if skipSslValidation { + plugin.DEBUG("Skipping SSL validation") + os.Setenv("VAULT_SKIP_VERIFY", "1") + } + v, err := vault.NewVault(url, token, true) + return v, err +} + +type SafeContents map[string]*vault.Secret + +func (sc SafeContents) ReadFromVault(v *vault.Vault, path string) error { + + tree, err := v.Tree(path, vault.TreeOptions{ + StripSlashes: true, + }) + if err != nil { + return err + } + for _, sub := range tree.Paths("/") { + s, err := v.Read(sub) + if err != nil { + return err + } + sc[sub] = s + } + return nil +} + +func (sc SafeContents) ReadFromStdin() error { + b, err := ioutil.ReadAll(os.Stdin) + if err != nil { + return err + } + return json.Unmarshal(b, &sc) +} + +func (sc SafeContents) WriteToVault(v *vault.Vault) error { + for path, s := range sc { + err := v.Write(path, s) + if err != nil { + return err + } + plugin.DEBUG(" -- wrote contents to %s", path) + } + return nil +} + +func (sc SafeContents) WriteToStdout() error { + b, err := json.Marshal(sc) + if err != nil { + return err + } + fmt.Printf("%s\n", string(b)) + return nil +} diff --git a/vendor/github.com/starkandwayne/goutils/ansi/printf.go b/vendor/github.com/starkandwayne/goutils/ansi/printf.go new file mode 100644 index 000000000..0782331e0 --- /dev/null +++ b/vendor/github.com/starkandwayne/goutils/ansi/printf.go @@ -0,0 +1,89 @@ +package ansi + +import ( + "fmt" + "io" + "os" + "regexp" + "unicode" + + "github.com/mattn/go-isatty" +) + +var ( + colors = map[string]string{ + "k": "00;30", // black + "K": "01;30", // black (BOLD) + + "r": "00;31", // red + "R": "01;31", // red (BOLD) + + "g": "00;32", // green + "G": "01;32", // green (BOLD) + + "y": "00;33", // yellow + "Y": "01;33", // yellow (BOLD) + + "b": "00;34", // blue + "B": "01;34", // blue (BOLD) + + "m": "00;35", // magenta + "M": "01;35", // magenta (BOLD) + "p": "00;35", // magenta + "P": "01;35", // magenta (BOLD) + + "c": "00;36", // cyan + "C": "01;36", // cyan (BOLD) + + "w": "00;37", // white + "W": "01;37", // white (BOLD) + } + + re = regexp.MustCompile(`(?s)@[kKrRgGyYbBmMpPcCwW*]{.*?}`) +) + +var colorable = isatty.IsTerminal(os.Stdout.Fd()) + +func Color(c bool) { + colorable = c +} + +func colorize(s string) string { + return re.ReplaceAllStringFunc(s, func(m string) string { + if !colorable { + return m[3 : len(m)-1] + } + if m[1:2] == "*" { + rainbow := "RYGCBM" + skipCount := 0 + s := "" + for i, c := range m[3 : len(m)-1] { + if unicode.IsSpace(c) { //No color wasted on whitespace + skipCount++ + s += string(c) + continue + } + j := (i - skipCount) % len(rainbow) + s += "\033[" + colors[rainbow[j:j+1]] + "m" + string(c) + "\033[00m" + } + return s + } + return "\033[" + colors[m[1:2]] + "m" + m[3:len(m)-1] + "\033[00m" + }) +} + +func Printf(format string, a ...interface{}) (int, error) { + return fmt.Printf(colorize(format), a...) +} + +func Fprintf(out io.Writer, format string, a ...interface{}) (int, error) { + return fmt.Fprintf(out, colorize(format), a...) +} + +func Sprintf(format string, a ...interface{}) string { + return fmt.Sprintf(colorize(format), a...) +} + +func Errorf(format string, a ...interface{}) error { + return fmt.Errorf(colorize(format), a...) +} diff --git a/vendor/github.com/starkandwayne/goutils/tree/cursor.go b/vendor/github.com/starkandwayne/goutils/tree/cursor.go new file mode 100644 index 000000000..0971beb9e --- /dev/null +++ b/vendor/github.com/starkandwayne/goutils/tree/cursor.go @@ -0,0 +1,476 @@ +package tree + +import ( + "bytes" + "fmt" + "strconv" + "strings" +) + +// Cursor ... +type Cursor struct { + Nodes []string +} + +var NameFields = []string{"name", "key", "id"} + +func listFind(l []interface{}, fields []string, key string) (interface{}, uint64, bool) { + for _, field := range fields { + for i, v := range l { + switch v.(type) { + case map[string]interface{}: + value, ok := v.(map[string]interface{})[field] + if ok && value == key { + return v, uint64(i), true + } + case map[interface{}]interface{}: + value, ok := v.(map[interface{}]interface{})[field] + if ok && value == key { + return v, uint64(i), true + } + } + } + } + return nil, 0, false +} + +// ParseCursor ... +func ParseCursor(s string) (*Cursor, error) { + var nodes []string + node := bytes.NewBuffer([]byte{}) + bracketed := false + + push := func() { + if node.Len() == 0 { + return + } + s := node.String() + if len(nodes) == 0 && s == "$" { + node.Reset() + return + } + + nodes = append(nodes, s) + node.Reset() + } + + for pos, c := range s { + switch c { + case '.': + if bracketed { + node.WriteRune(c) + } else { + push() + } + + case '[': + if bracketed { + return nil, SyntaxError{ + Problem: "unexpected '['", + Position: pos, + } + } + push() + bracketed = true + + case ']': + if !bracketed { + return nil, SyntaxError{ + Problem: "unexpected ']'", + Position: pos, + } + } + push() + bracketed = false + + default: + node.WriteRune(c) + } + } + push() + + return &Cursor{ + Nodes: nodes, + }, nil +} + +// Copy ... +func (c *Cursor) Copy() *Cursor { + other := &Cursor{Nodes: []string{}} + for _, node := range c.Nodes { + other.Nodes = append(other.Nodes, node) + } + return other +} + +// Contains ... +func (c *Cursor) Contains(other *Cursor) bool { + if len(other.Nodes) < len(c.Nodes) { + return false + } + match := false + for i := range c.Nodes { + if c.Nodes[i] != other.Nodes[i] { + return false + } + match = true + } + return match +} + +// Under ... +func (c *Cursor) Under(other *Cursor) bool { + if len(c.Nodes) <= len(other.Nodes) { + return false + } + match := false + for i := range other.Nodes { + if c.Nodes[i] != other.Nodes[i] { + return false + } + match = true + } + return match +} + +// Pop ... +func (c *Cursor) Pop() string { + if len(c.Nodes) == 0 { + return "" + } + last := c.Nodes[len(c.Nodes)-1] + c.Nodes = c.Nodes[0 : len(c.Nodes)-1] + return last +} + +// Push ... +func (c *Cursor) Push(n string) { + c.Nodes = append(c.Nodes, n) +} + +// String ... +func (c *Cursor) String() string { + return strings.Join(c.Nodes, ".") +} + +// Depth ... +func (c *Cursor) Depth() int { + return len(c.Nodes) +} + +// Parent ... +func (c *Cursor) Parent() string { + if len(c.Nodes) < 2 { + return "" + } + return c.Nodes[len(c.Nodes)-2] +} + +// Component ... +func (c *Cursor) Component(offset int) string { + offset = len(c.Nodes) + offset + if offset < 0 || offset >= len(c.Nodes) { + return "" + } + return c.Nodes[offset] +} + +// Canonical ... +func (c *Cursor) Canonical(o interface{}) (*Cursor, error) { + canon := &Cursor{Nodes: []string{}} + + for _, k := range c.Nodes { + switch o.(type) { + case []interface{}: + i, err := strconv.ParseUint(k, 10, 0) + if err == nil { + // if k is an integer (in string form), go by index + if int(i) >= len(o.([]interface{})) { + return nil, NotFoundError{ + Path: canon.Nodes, + } + } + o = o.([]interface{})[i] + } else { + // if k is a string, look for immediate map descendants who have + // 'name', 'key' or 'id' fields matching k + var found bool + o, i, found = listFind(o.([]interface{}), NameFields, k) + if !found { + return nil, NotFoundError{ + Path: canon.Nodes, + } + } + } + canon.Push(fmt.Sprintf("%d", i)) + + case map[string]interface{}: + canon.Push(k) + var ok bool + o, ok = o.(map[string]interface{})[k] + if !ok { + return nil, NotFoundError{ + Path: canon.Nodes, + } + } + + case map[interface{}]interface{}: + canon.Push(k) + v, ok := o.(map[interface{}]interface{})[k] + if !ok { + /* key might not actually be a string. let's iterate */ + k2 := fmt.Sprintf("%v", k) + for k1, v1 := range o.(map[interface{}]interface{}) { + if fmt.Sprintf("%v", k1) == k2 { + v, ok = v1, true + break + } + } + if !ok { + return nil, NotFoundError{ + Path: canon.Nodes, + } + } + } + o = v + + default: + return nil, TypeMismatchError{ + Path: canon.Nodes, + Wanted: "a map or a list", + Got: "a scalar", + } + } + } + + return canon, nil +} + +// Glob ... +func (c *Cursor) Glob(tree interface{}) ([]*Cursor, error) { + var resolver func(interface{}, []string, []string, int) ([]interface{}, error) + resolver = func(o interface{}, here, path []string, pos int) ([]interface{}, error) { + if pos == len(path) { + return []interface{}{ + (&Cursor{Nodes: here}).Copy(), + }, nil + } + + paths := []interface{}{} + k := path[pos] + if k == "*" { + switch o.(type) { + case []interface{}: + for i, v := range o.([]interface{}) { + sub, err := resolver(v, append(here, fmt.Sprintf("%d", i)), path, pos+1) + if err != nil { + if _, ok := err.(NotFoundError); !ok { + return nil, err + } + } + paths = append(paths, sub...) + } + + case map[string]interface{}: + for k, v := range o.(map[string]interface{}) { + sub, err := resolver(v, append(here, k), path, pos+1) + if err != nil { + if _, ok := err.(NotFoundError); !ok { + return nil, err + } + } + paths = append(paths, sub...) + } + + case map[interface{}]interface{}: + for k, v := range o.(map[interface{}]interface{}) { + sub, err := resolver(v, append(here, fmt.Sprintf("%v", k)), path, pos+1) + if err != nil { + if _, ok := err.(NotFoundError); !ok { + return nil, err + } + } + paths = append(paths, sub...) + } + + default: + return nil, TypeMismatchError{ + Path: path, + Wanted: "a map or a list", + Got: "a scalar", + } + } + + } else { + switch o.(type) { + case []interface{}: + i, err := strconv.ParseUint(k, 10, 0) + if err == nil { + // if k is an integer (in string form), go by index + if int(i) >= len(o.([]interface{})) { + return nil, NotFoundError{ + Path: path[0 : pos+1], + } + } + return resolver(o.([]interface{})[i], append(here, k), path, pos+1) + } + + // if k is a string, look for immediate map descendants who have + // 'name', 'key' or 'id' fields matching k + var found bool + o, _, found = listFind(o.([]interface{}), NameFields, k) + if !found { + return nil, NotFoundError{ + Path: path[0 : pos+1], + } + } + return resolver(o, append(here, k), path, pos+1) + + case map[string]interface{}: + v, ok := o.(map[string]interface{})[k] + if !ok { + return nil, NotFoundError{ + Path: path[0 : pos+1], + } + } + return resolver(v, append(here, k), path, pos+1) + + case map[interface{}]interface{}: + v, ok := o.(map[interface{}]interface{})[k] + if !ok { + /* key might not actually be a string. let's iterate */ + k2 := fmt.Sprintf("%v", k) + for k1, v1 := range o.(map[interface{}]interface{}) { + if fmt.Sprintf("%v", k1) == k2 { + v, ok = v1, true + break + } + } + if !ok { + return nil, NotFoundError{ + Path: path[0 : pos+1], + } + } + } + return resolver(v, append(here, k), path, pos+1) + + default: + return nil, TypeMismatchError{ + Path: path[0:pos], + Wanted: "a map or a list", + Got: "a scalar", + } + } + } + + return paths, nil + } + + var path []string + for _, s := range c.Nodes { + path = append(path, s) + } + + l, err := resolver(tree, []string{}, path, 0) + if err != nil { + return nil, err + } + + cursors := []*Cursor{} + for _, c := range l { + cursors = append(cursors, c.(*Cursor)) + } + return cursors, nil +} + +// Resolve ... +func (c *Cursor) Resolve(o interface{}) (interface{}, error) { + var path []string + + for _, k := range c.Nodes { + path = append(path, k) + + switch o.(type) { + case map[string]interface{}: + v, ok := o.(map[string]interface{})[k] + if !ok { + return nil, NotFoundError{ + Path: path, + } + } + o = v + + case map[interface{}]interface{}: + v, ok := o.(map[interface{}]interface{})[k] + if !ok { + /* key might not actually be a string. let's iterate */ + k2 := fmt.Sprintf("%v", k) + for k1, v1 := range o.(map[interface{}]interface{}) { + if fmt.Sprintf("%v", k1) == k2 { + v, ok = v1, true + break + } + } + if !ok { + return nil, NotFoundError{ + Path: path, + } + } + } + o = v + + case []interface{}: + i, err := strconv.ParseUint(k, 10, 0) + if err == nil { + // if k is an integer (in string form), go by index + if int(i) >= len(o.([]interface{})) { + return nil, NotFoundError{ + Path: path, + } + } + o = o.([]interface{})[i] + continue + } + + // if k is a string, look for immediate map descendants who have + // 'name', 'key' or 'id' fields matching k + var found bool + o, _, found = listFind(o.([]interface{}), NameFields, k) + if !found { + return nil, NotFoundError{ + Path: path, + } + } + + default: + path = path[0 : len(path)-1] + return nil, TypeMismatchError{ + Path: path, + Wanted: "a map or a list", + Got: "a scalar", + Value: o, + } + } + } + + return o, nil +} + +// ResolveString ... +func (c *Cursor) ResolveString(tree interface{}) (string, error) { + o, err := c.Resolve(tree) + if err != nil { + return "", err + } + + switch o.(type) { + case string: + return o.(string), nil + case int: + return fmt.Sprintf("%d", o.(int)), nil + } + return "", TypeMismatchError{ + Path: c.Nodes, + Wanted: "a string", + } +} diff --git a/vendor/github.com/starkandwayne/goutils/tree/err.go b/vendor/github.com/starkandwayne/goutils/tree/err.go new file mode 100644 index 000000000..1689a103a --- /dev/null +++ b/vendor/github.com/starkandwayne/goutils/tree/err.go @@ -0,0 +1,47 @@ +package tree + +import ( + "fmt" + "github.com/starkandwayne/goutils/ansi" + "strings" +) + +// SyntaxError ... +type SyntaxError struct { + Problem string + Position int +} + +// Error ... +func (e SyntaxError) Error() string { + return fmt.Sprintf("syntax error: %s at position %d", e.Problem, e.Position) +} + +// TypeMismatchError ... +type TypeMismatchError struct { + Path []string + Wanted string + Got string + Value interface{} +} + +// Error ... +func (e TypeMismatchError) Error() string { + if e.Got == "" { + return ansi.Sprintf("@c{%s} @R{is not} @m{%s}", strings.Join(e.Path, "."), e.Wanted) + } + if e.Value != nil { + return ansi.Sprintf("@c{$.%s} @R{[=%v] is %s (not} @m{%s}@R{)}", strings.Join(e.Path, "."), e.Value, e.Got, e.Wanted) + } + return ansi.Sprintf("@C{$.%s} @R{is %s (not} @m{%s}@R{)}", strings.Join(e.Path, "."), e.Got, e.Wanted) +} + +// NotFoundError ... +type NotFoundError struct { + Path []string +} + +// Error ... +func (e NotFoundError) Error() string { + return ansi.Sprintf("@R{`}@c{$.%s}@R{` could not be found in the datastructure}", strings.Join(e.Path, ".")) +} diff --git a/vendor/github.com/starkandwayne/goutils/tree/find.go b/vendor/github.com/starkandwayne/goutils/tree/find.go new file mode 100644 index 000000000..515678a28 --- /dev/null +++ b/vendor/github.com/starkandwayne/goutils/tree/find.go @@ -0,0 +1,124 @@ +package tree + +import "fmt" +import "reflect" + +// Attemts to find the value at `path` inside data structure `o`. +// If found, attempts to cast it as a string. Errors will be +// returned for data of invalid type, or nonexistent paths. +func FindString(o interface{}, path string) (string, error) { + obj, err := Find(o, path) + if err != nil { + return "", err + } + if s, ok := obj.(string); ok { + return s, nil + } else { + return "", fmt.Errorf("Invalid data type - wanted string, got %s", reflect.TypeOf(obj)) + } +} + +// Attemts to find the value at `path` inside data structure `o`. +// If found, attempts to cast it as a Number. Errors will be +// returned for data of invalid type, or nonexistent paths. +func FindNum(o interface{}, path string) (Number, error) { + var num Number + obj, err := Find(o, path) + if err != nil { + return num, err + } + switch obj.(type) { + case float64: + num = Number(obj.(float64)) + case int: + num = Number(float64(obj.(int))) + default: + return num, fmt.Errorf("Invalid data type - wanted number, got %s", reflect.TypeOf(obj)) + } + return num, nil +} + +// Attemts to find the value at `path` inside data structure `o`. +// If found, attempts to cast it as a bool. Errors will be +// returned for data of invalid type, or nonexistent paths. +func FindBool(o interface{}, path string) (bool, error) { + obj, err := Find(o, path) + if err != nil { + return false, err + } + if b, ok := obj.(bool); ok { + return b, nil + } else { + return false, fmt.Errorf("Invalid data type - wanted bool, got %s", reflect.TypeOf(obj)) + } +} + +// Attemts to find the value at `path` inside data structure `o`. +// If found, attempts to cast it as a map[string]interface{}. Errors will be +// returned for data of invalid type, or nonexistent paths. +func FindMap(o interface{}, path string) (map[string]interface{}, error) { + obj, err := Find(o, path) + if err != nil { + return map[string]interface{}{}, err + } + if m, ok := obj.(map[string]interface{}); ok { + return m, nil + } else { + return map[string]interface{}{}, fmt.Errorf("Invalid data type - wanted map, got %s", reflect.TypeOf(obj)) + } +} + +// Attemts to find the value at `path` inside data structure `o`. +// If found, attempts to cast it as an interface{} slice. Errors will be +// returned for data of invalid type, or nonexistent paths. +func FindArray(o interface{}, path string) ([]interface{}, error) { + obj, err := Find(o, path) + if err != nil { + return []interface{}{}, err + } + if arr, ok := obj.([]interface{}); ok { + return arr, nil + } else { + return []interface{}{}, fmt.Errorf("Invalid data type - wanted array, got %s", reflect.TypeOf(obj)) + } +} + +// Attemts to find the value at `path` inside data structure `o`. +// If found, returns it as a plain interface{} type, for you to +// typecheck + cast as you see fit. Errors will be +// returned for data of invalid type, or nonexistent paths. +func Find(o interface{}, path string) (interface{}, error) { + c, err := ParseCursor(path) + if err != nil { + return nil, err + } + return c.Resolve(o) +} + +type Number float64 + +// Returns an `int64` representation of the Number. If the value +// is not an integer, returns an error, so you do not accidentally +// lose precision while trying to see if it is an integer value. +func (n Number) Int64() (int64, error) { + i := int64(n) + if Number(i) != n { + return 0, fmt.Errorf("%f does not represent an integer, cannot auto-convert", float64(n)) + } + return i, nil +} + +// Returns a `float64` representation of the Number. +func (n Number) Float64() float64 { + return float64(n) +} + +// Returns a string representation of the Number +func (n Number) String() string { + intVal, err := n.Int64() + if err == nil { + return fmt.Sprintf("%d", intVal) + } + + return fmt.Sprintf("%f", n.Float64()) +} diff --git a/vendor/github.com/starkandwayne/goutils/tree/tree.go b/vendor/github.com/starkandwayne/goutils/tree/tree.go new file mode 100644 index 000000000..7ecbc316f --- /dev/null +++ b/vendor/github.com/starkandwayne/goutils/tree/tree.go @@ -0,0 +1,83 @@ +package tree + +import ( + "bytes" + "fmt" + "io" + "strings" +) + +type Node struct { + Name string + Sub []Node +} + +func New(name string, sub ...Node) Node { + return Node{ + Name: name, + Sub: sub, + } +} + +func (n Node) render(out io.Writer, prefix string, tail bool) { + interim := "├── " + if tail { + interim = "└── " + } + nkids := len(n.Sub) + + ss := strings.Split(strings.Trim(n.Name, "\n"), "\n") + for _, s := range ss { + fmt.Fprintf(out, "%s%s%s\n", prefix, interim, s) + interim = "│ " + if tail { + interim = " " + } + } + + for i, c := range n.Sub { + c.render(out, prefix+interim, i == nkids-1) + } +} + +func (n *Node) Append(child Node) { + n.Sub = append(n.Sub, child) +} + +func (n Node) Draw() string { + var out bytes.Buffer + fmt.Fprintf(&out, ".\n") + n.render(&out, "", true) + return out.String() +} + +func (n Node) flatten(prefix, sep string) []string { + ss := make([]string, 0) + if len(n.Sub) == 0 { + return append(ss, fmt.Sprintf("%s%s", prefix, n.Name)) + } + for _, k := range n.Sub { + for _, s := range k.flatten(prefix+n.Name+sep, sep) { + ss = append(ss, s) + } + } + return ss +} + +func (n Node) Paths(sep string) []string { + return n.flatten("", sep) +} + +func (n Node) PathSegments() [][]string { + if len(n.Sub) == 0 { + return [][]string{[]string{n.Name}} + } + paths := make([][]string, 0) + for _, child := range n.Sub { + for _, segments := range child.PathSegments() { + segments := append([]string{n.Name}, segments...) + paths = append(paths, segments) + } + } + return paths +} diff --git a/vendor/github.com/starkandwayne/safe/LICENSE b/vendor/github.com/starkandwayne/safe/LICENSE new file mode 100644 index 000000000..a9261d389 --- /dev/null +++ b/vendor/github.com/starkandwayne/safe/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018 James Hunt + +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. diff --git a/vendor/github.com/starkandwayne/safe/prompt/prompt.go b/vendor/github.com/starkandwayne/safe/prompt/prompt.go new file mode 100644 index 000000000..3e0a5799d --- /dev/null +++ b/vendor/github.com/starkandwayne/safe/prompt/prompt.go @@ -0,0 +1,38 @@ +package prompt + +import ( + "bufio" + "os" + "strings" + + "github.com/jhunt/go-ansi" + "github.com/mattn/go-isatty" + "golang.org/x/crypto/ssh/terminal" +) + +var in *bufio.Reader + +func readline() string { + if in == nil { + in = bufio.NewReader(os.Stdin) + } + + s, _ := in.ReadString('\n') + return strings.TrimSuffix(s, "\n") +} + +func Normal(label string, args ...interface{}) string { + ansi.Fprintf(os.Stderr, label, args...) + return readline() +} + +func Secure(label string, args ...interface{}) string { + if !isatty.IsTerminal(os.Stdin.Fd()) { + return readline() + } + + ansi.Fprintf(os.Stderr, label, args...) + b, _ := terminal.ReadPassword(int(os.Stdin.Fd())) + ansi.Fprintf(os.Stderr, "\n") + return string(b) +} diff --git a/vendor/github.com/starkandwayne/safe/vault/dhparam.go b/vendor/github.com/starkandwayne/safe/vault/dhparam.go new file mode 100644 index 000000000..3f0a54c8f --- /dev/null +++ b/vendor/github.com/starkandwayne/safe/vault/dhparam.go @@ -0,0 +1,19 @@ +package vault + +import ( + "fmt" + "os" + "os/exec" +) + +func genDHParam(bits int) (string, error) { + cmd := exec.Command("openssl", "dhparam", fmt.Sprintf("%d", bits)) + cmd.Stderr = os.Stderr + + // output runs command and returns output + output, err := cmd.Output() + if err != nil { + return "", err + } + return string(output), nil +} diff --git a/vendor/github.com/starkandwayne/safe/vault/errors.go b/vendor/github.com/starkandwayne/safe/vault/errors.go new file mode 100644 index 000000000..fa9519635 --- /dev/null +++ b/vendor/github.com/starkandwayne/safe/vault/errors.go @@ -0,0 +1,54 @@ +package vault + +import "fmt" + +type secretNotFound struct { + secret string +} + +func (e secretNotFound) Error() string { + return fmt.Sprintf("no secret exists at path `%s`", e.secret) +} + +type keyNotFound struct { + secret string + key string +} + +func (e keyNotFound) Error() string { + return fmt.Sprintf("no key `%s` exists in secret `%s`", e.key, e.secret) +} + +//IsNotFound returns true if the given error is a SecretNotFound error +// or a KeyNotFound error. Returns false otherwise. +func IsNotFound(err error) bool { + return IsSecretNotFound(err) || IsKeyNotFound(err) +} + +//NewSecretNotFoundError returns an error with a message descibing the path +// which could not be found in the secret backend. +func NewSecretNotFoundError(path string) error { + return secretNotFound{path} +} + +//IsSecretNotFound returns true if the given error was created with +// NewSecretNotFoundError(). False otherwise. +func IsSecretNotFound(err error) bool { + _, is := err.(secretNotFound) + return is +} + +//NewKeyNotFoundError returns an error object describing the key that could not +// be located within the secret it was searched for in. Returning a KeyNotFound +// error should semantically mean that the secret it would've been contained in +// was located in the vault. +func NewKeyNotFoundError(path, key string) error { + return keyNotFound{secret: path, key: key} +} + +//IsKeyNotFound returns true if the given error was created with +// NewKeyNotFoundError(). False otherwise. +func IsKeyNotFound(err error) bool { + _, is := err.(keyNotFound) + return is +} diff --git a/vendor/github.com/starkandwayne/safe/vault/init.go b/vendor/github.com/starkandwayne/safe/vault/init.go new file mode 100644 index 000000000..b2fa65831 --- /dev/null +++ b/vendor/github.com/starkandwayne/safe/vault/init.go @@ -0,0 +1,63 @@ +package vault + +import ( + "bytes" + "encoding/json" + "fmt" + "io/ioutil" + "net/http" +) + +func (v *Vault) Init(nkeys, threshold int) ([]string, string, error) { + if threshold > nkeys { + return nil, "", fmt.Errorf("cannot require %d/%d keys -- threshold is too high!", threshold, nkeys) + } + + in := struct { + Keys int `json:"secret_shares"` + Threshold int `json:"secret_threshold"` + }{ + Keys: nkeys, + Threshold: threshold, + } + b, err := json.Marshal(&in) + if err != nil { + return nil, "", err + } + + req, err := http.NewRequest("POST", v.url("/v1/sys/init"), bytes.NewReader(b)) + if err != nil { + return nil, "", err + } + + res, err := v.request(req) + if err != nil { + return nil, "", err + } + + b, err = ioutil.ReadAll(res.Body) + if err != nil { + return nil, "", err + } + + var out struct { + Keys []string `json:"keys_base64"` + Token string `json:"root_token"` + + Errors []string `json:"errors"` + } + err = json.Unmarshal(b, &out) + if err != nil { + return nil, "", err + } + + if res.StatusCode != 200 { + if len(out.Errors) > 0 { + return nil, "", fmt.Errorf("%s", out.Errors[0]) + } else { + return nil, "", fmt.Errorf("an unspecified error has occurred.") + } + } + + return out.Keys, out.Token, nil +} diff --git a/vendor/github.com/starkandwayne/safe/vault/random.go b/vendor/github.com/starkandwayne/safe/vault/random.go new file mode 100644 index 000000000..74604c6be --- /dev/null +++ b/vendor/github.com/starkandwayne/safe/vault/random.go @@ -0,0 +1,30 @@ +package vault + +import ( + "bytes" + "crypto/rand" + "math/big" + "regexp" +) + +var ( + chars = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" +) + +func random(n int, policy string) (string, error) { + re := regexp.MustCompile("[^" + policy + "]") + keep := re.ReplaceAllString(chars, "") + + var buffer bytes.Buffer + + for i := 0; i < n; i++ { + index, err := rand.Int(rand.Reader, big.NewInt(int64(len(keep)))) + if err != nil { + return "", err + } + indexInt := index.Int64() + buffer.WriteString(string(keep[indexInt])) + } + + return buffer.String(), nil +} diff --git a/vendor/github.com/starkandwayne/safe/vault/rekey.go b/vendor/github.com/starkandwayne/safe/vault/rekey.go new file mode 100644 index 000000000..235ec70fe --- /dev/null +++ b/vendor/github.com/starkandwayne/safe/vault/rekey.go @@ -0,0 +1,159 @@ +package vault + +import ( + "encoding/json" + "io/ioutil" + "os" + "os/signal" + "syscall" + + "github.com/jhunt/go-ansi" + "github.com/starkandwayne/safe/prompt" + "golang.org/x/crypto/ssh/terminal" +) + +type RekeyOpts struct { + SecretShares int `json:"secret_shares"` + SecretThreshold int `json:"secret_threshold"` + PGPKeys []string `json:"pgp_keys,omitempty"` + Backup bool `json:"backup,omitempty"` +} + +type RekeyUpdateOpts struct { + Key string `json:"key"` + Nonce string `json:"nonce"` +} + +type RekeyResponse struct { + Errors []string `json:"errors"` + Complete bool `json:"complete"` + Progress int `json:"progress"` + Required int `json:"required"` + Nonce string `json:"nonce"` + Keys []string `json:"keys"` +} + +var shouldCancelRekey bool = false +var termState *terminal.State + +func (v *Vault) cancelRekey() { + if termState != nil { + terminal.Restore(int(os.Stdin.Fd()), termState) + } + if shouldCancelRekey { + resp, err := v.Curl("DELETE", "sys/rekey/init", nil) + if err != nil { + ansi.Fprintf(os.Stderr, "Failed to cancel rekey process (you may need to manually cancel to rekey next time): %s\n", err.Error()) + return + } + if resp.StatusCode >= 400 { + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + ansi.Fprintf(os.Stderr, "Unable to read body from rekey cancelation response (you may need to manually cancel to rekey next time): %s\n", err) + return + } + ansi.Fprintf(os.Stderr, "Failed to cancel rekey process (you may need to manually cancel to rekey next time): %s\n", body) + return + } + ansi.Fprintf(os.Stderr, "@y{Vault rekey canceled successfully}\n") + } +} + +func (v *Vault) ReKey(unsealKeyCount, numToUnseal int, pgpKeys []string) ([]string, error) { + backup := len(pgpKeys) > 0 + rekeyOptions := RekeyOpts{ + SecretShares: unsealKeyCount, + SecretThreshold: numToUnseal, + PGPKeys: pgpKeys, + Backup: backup, + } + rekeyJSON, err := json.Marshal(rekeyOptions) + if err != nil { + return nil, err + } + + resp, err := v.Curl("POST", "sys/rekey/init", rekeyJSON) + if err != nil { + return nil, ansi.Errorf("Error re-keying Vault: %s", err.Error()) + } + + b, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + rekeyResp := RekeyResponse{} + if err = json.Unmarshal(b, &rekeyResp); err != nil { + return nil, err + } + + if rekeyResp.Errors != nil && len(rekeyResp.Errors) > 0 { + errorList, err := json.Marshal(rekeyResp.Errors) + if err != nil { + return nil, err + } + return nil, ansi.Errorf("Failed to start rekeying vault:\n%s", errorList) + } + if resp.StatusCode >= 400 { + return nil, ansi.Errorf("Failed to start rekeying vault: %s\nServer said:\n%s", resp.Status, string(b)) + } + + // we successfully started a rekey, we should now cancel on failure, unless we finish rekeying + shouldCancelRekey = true + defer v.cancelRekey() + sighandler := make(chan os.Signal, 4) + signal.Ignore(os.Interrupt, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT) + signal.Notify(sighandler, os.Interrupt, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT) + go func() { + for _ = range sighandler { + v.cancelRekey() + os.Exit(1) + } + }() + + if terminal.IsTerminal(int(os.Stdin.Fd())) { + termState, err = terminal.GetState(int(os.Stdin.Fd())) + if err != nil { + return nil, err + } + } + for rekeyResp.Progress < rekeyResp.Required && rekeyResp.Complete == false { + unsealKey := prompt.Secure("Unseal Key %d: ", rekeyResp.Progress+1) + updateOpts := RekeyUpdateOpts{ + Key: unsealKey, + Nonce: rekeyResp.Nonce, + } + updateOptsJSON, err := json.Marshal(updateOpts) + if err != nil { + return nil, err + } + resp, err = v.Curl("POST", "sys/rekey/update", updateOptsJSON) + if err != nil { + return nil, ansi.Errorf("Error validating the Vault rekey: %s", err.Error()) + } + + b, err = ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + if err = json.Unmarshal(b, &rekeyResp); err != nil { + return nil, err + } + + if resp.StatusCode >= 400 { + // grab 'errors' from json, print it out + if rekeyResp.Errors != nil && len(rekeyResp.Errors) > 0 { + errStr, err := json.Marshal(rekeyResp.Errors) + if err != nil { + return nil, err + } + return nil, ansi.Errorf("Error processing unseal key:\n%s", errStr) + } else { + return nil, ansi.Errorf("Error processing unseal key:\n%s", string(b)) + } + } + } + // vault should be rekeyed by here, as our progress met the requirement + shouldCancelRekey = false + + return rekeyResp.Keys, nil +} diff --git a/vendor/github.com/starkandwayne/safe/vault/renew.go b/vendor/github.com/starkandwayne/safe/vault/renew.go new file mode 100644 index 000000000..f8ca2a162 --- /dev/null +++ b/vendor/github.com/starkandwayne/safe/vault/renew.go @@ -0,0 +1,23 @@ +package vault + +import ( + "fmt" + "net/http" +) + +func (v *Vault) RenewLease() error { + req, err := http.NewRequest("POST", v.url("/v1/auth/token/renew-self"), nil) + if err != nil { + return err + } + res, err := v.request(req) + if err != nil { + return err + } + + if res.StatusCode != 200 { + return fmt.Errorf("received HTTP %d response", res.StatusCode) + } + + return nil +} diff --git a/vendor/github.com/starkandwayne/safe/vault/root.go b/vendor/github.com/starkandwayne/safe/vault/root.go new file mode 100644 index 000000000..512d30cc4 --- /dev/null +++ b/vendor/github.com/starkandwayne/safe/vault/root.go @@ -0,0 +1,122 @@ +package vault + +import ( + "crypto/rand" + "encoding/base64" + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "strings" +) + +func (v *Vault) NewRootToken(keys []string) (string, error) { + // cancel any previous generate-root attempts (get a new nonce!) + req, err := http.NewRequest("DELETE", v.url("/v1/sys/generate-root/attempt"), nil) + if err != nil { + return "", err + } + res, err := v.request(req) + if err != nil { + return "", err + } + if res.StatusCode != 204 { + return "", fmt.Errorf("failed to cancel previous generate-root attempt: HTTP %d response", res.StatusCode) + } + + // generate a 16-byte one-time password, base64-encoded + otp := make([]byte, 16) + otp64 := make([]byte, 24) // does this need pre-alloc'd? + _, err = rand.Read(otp) + if err != nil { + return "", fmt.Errorf("unable to generate a one-time password: %s", err) + } + base64.StdEncoding.Encode(otp64, otp) + + // initiate a new generate-root attempt, with our one-time password in play + req, err = http.NewRequest("PUT", v.url("/v1/sys/generate-root/attempt"), strings.NewReader(`{"otp":"`+string(otp64)+`"}`)) + if err != nil { + return "", err + } + res, err = v.request(req) + if err != nil { + return "", err + } + if res.StatusCode != 200 { + return "", fmt.Errorf("failed to start a new generate-root attempt: HTTP %d response", res.StatusCode) + } + + // extract the nonce for this generate-root attempt go-round + var attempt struct { + Nonce string `json:"nonce"` + } + b, err := ioutil.ReadAll(res.Body) + if err != nil { + return "", err + } + err = json.Unmarshal(b, &attempt) + if err != nil { + return "", err + } + + encoded := "" + for _, k := range keys { + // for each key, pass back the nonce, provide the key, and go! + payload := `{"key":"` + k + `","nonce":"` + attempt.Nonce + `"}` + req, err := http.NewRequest("PUT", v.url("/v1/sys/generate-root/update"), strings.NewReader(payload)) + if err != nil { + return "", err + } + res, err := v.request(req) + if err != nil { + return "", err + } + if res.StatusCode != 200 { + return "", fmt.Errorf("failed to provide seal key to Vault: HTTP %d response", res.StatusCode) + } + + // parse the response and save the encoded (token^otp) token + var out struct { + //encoded_root_token was changed to encoded_token in vault 0.9.0 + EncodedToken string `json:"encoded_token"` + EncodedRootToken string `json:"encoded_root_token"` + Complete bool `json:"complete"` + } + b, err := ioutil.ReadAll(res.Body) + if err != nil { + return "", err + } + err = json.Unmarshal(b, &out) + if err != nil { + return "", err + } + if out.Complete { + encoded = out.EncodedToken + if out.EncodedRootToken != "" { + encoded = out.EncodedRootToken + } + } + } + + if encoded == "" { + return "", fmt.Errorf("failed to generate new root token") + } + + tok64 := []byte(encoded) + tok := make([]byte, base64.StdEncoding.DecodedLen(len(tok64))) + if len(tok64) != len(otp64) { + return "", fmt.Errorf("failed to decode new root token") + } + + base64.StdEncoding.Decode(tok, tok64) + for i := 0; i < 16; i++ { + tok[i] ^= otp[i] + } + + return fmt.Sprintf("%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", + tok[0], tok[1], tok[2], tok[3], + tok[4], tok[5], + tok[6], tok[7], + tok[8], tok[9], + tok[10], tok[11], tok[12], tok[13], tok[14], tok[15]), nil +} diff --git a/vendor/github.com/starkandwayne/safe/vault/rsa.go b/vendor/github.com/starkandwayne/safe/vault/rsa.go new file mode 100644 index 000000000..34b8fa056 --- /dev/null +++ b/vendor/github.com/starkandwayne/safe/vault/rsa.go @@ -0,0 +1,35 @@ +package vault + +import ( + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/pem" +) + +func rsakey(bits int) (string, string, error) { + key, err := rsa.GenerateKey(rand.Reader, bits) + if err != nil { + return "", "", err + } + + private := pem.EncodeToMemory( + &pem.Block{ + Type: "RSA PRIVATE KEY", + Bytes: x509.MarshalPKCS1PrivateKey(key), + }, + ) + + b, err := x509.MarshalPKIXPublicKey(key.Public()) + if err != nil { + return "", "", err + } + public := pem.EncodeToMemory( + &pem.Block{ + Type: "PUBLIC KEY", + Bytes: b, + }, + ) + + return string(private), string(public), nil +} diff --git a/vendor/github.com/starkandwayne/safe/vault/seal.go b/vendor/github.com/starkandwayne/safe/vault/seal.go new file mode 100644 index 000000000..92447b484 --- /dev/null +++ b/vendor/github.com/starkandwayne/safe/vault/seal.go @@ -0,0 +1,93 @@ +package vault + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "regexp" + "strings" +) + +func (v *Vault) SealKeys() (int, error) { + req, err := http.NewRequest("GET", v.url("/v1/sys/seal-status"), nil) + if err != nil { + return 0, err + } + res, err := v.request(req) + if err != nil { + return 0, err + } + + if res.StatusCode != 200 { + return 0, fmt.Errorf("received HTTP %d response (to /v1/sys/seal-status)", res.StatusCode) + } + + b, err := ioutil.ReadAll(res.Body) + if err != nil { + return 0, err + } + + var data = struct { + Keys int `json:"t"` + }{} + err = json.Unmarshal(b, &data) + if err != nil { + return 0, err + } + return data.Keys, nil +} + +func (v *Vault) Seal() (bool, error) { + req, err := http.NewRequest("PUT", v.url("/v1/sys/seal"), nil) + if err != nil { + return false, err + } + res, err := v.request(req) + if err != nil { + return false, err + } + + if res.StatusCode == 500 { + if b, err := ioutil.ReadAll(res.Body); err == nil { + if matched, _ := regexp.Match("cannot seal when in standby mode", b); matched { + return false, nil + } + } + } + if res.StatusCode != 204 { + return false, fmt.Errorf("received HTTP %d response", res.StatusCode) + } + return true, nil +} + +func (v *Vault) Unseal(keys []string) error { + req, err := http.NewRequest("PUT", v.url("/v1/sys/unseal"), strings.NewReader(`{"reset":true}`)) + if err != nil { + return err + } + res, err := v.request(req) + if err != nil { + return err + } + + if res.StatusCode != 200 { + return fmt.Errorf("received HTTP %d response", res.StatusCode) + } + + for _, k := range keys { + req, err := http.NewRequest("PUT", v.url("/v1/sys/unseal"), strings.NewReader(`{"key":"`+k+`"}`)) + if err != nil { + return err + } + res, err := v.request(req) + if err != nil { + return err + } + + if res.StatusCode != 200 { + return fmt.Errorf("received HTTP %d response", res.StatusCode) + } + } + return nil +} diff --git a/vendor/github.com/starkandwayne/safe/vault/secret.go b/vendor/github.com/starkandwayne/safe/vault/secret.go new file mode 100644 index 000000000..504fd9947 --- /dev/null +++ b/vendor/github.com/starkandwayne/safe/vault/secret.go @@ -0,0 +1,284 @@ +package vault + +import ( + "encoding/base64" + "encoding/json" + "fmt" + "reflect" + "sort" + + "github.com/jhunt/go-ansi" + "github.com/tredoe/osutil/user/crypt/md5_crypt" + "github.com/tredoe/osutil/user/crypt/sha256_crypt" + "github.com/tredoe/osutil/user/crypt/sha512_crypt" + "golang.org/x/crypto/bcrypt" + "gopkg.in/yaml.v2" +) + +// A Secret contains a set of key/value pairs that store anything you +// want, including passwords, RSAKey keys, usernames, etc. +type Secret struct { + data map[string]string +} + +func NewSecret() *Secret { + return &Secret{make(map[string]string)} +} + +func (s Secret) MarshalJSON() ([]byte, error) { + return json.Marshal(s.data) +} + +func (s *Secret) UnmarshalJSON(b []byte) error { + return json.Unmarshal(b, &s.data) +} + +// Has returns true if the Secret has defined the given key. +func (s *Secret) Has(key string) bool { + _, ok := s.data[key] + return ok +} + +// Get retrieves the value of the given key, or "" if no such key exists. +func (s *Secret) Get(key string) string { + x, _ := s.data[key] + return x +} + +func (s *Secret) Keys() []string { + keys := reflect.ValueOf(s.data).MapKeys() + str_keys := make([]string, len(keys)) + for i := 0; i < len(keys); i++ { + str_keys[i] = keys[i].String() + } + sort.Strings(str_keys) + return str_keys +} + +// Set stores a value in the Secret, under the given key. +func (s *Secret) Set(key, value string, skipIfExists bool) error { + if s.Has(key) && skipIfExists { + return ansi.Errorf("@R{BUG: Something tried to overwrite the} @C{%s} @R{key, but it already existed, and --no-clobber was specified}", key) + } + s.data[key] = value + return nil +} + +// Delete removes the entry with the given key from the Secret. +// Returns true if there was a matching object to delete. False otherwise. +func (s *Secret) Delete(key string) bool { + if !s.Has(key) { + return false + } + delete(s.data, key) + return true +} + +// Empty returns true if there are no key-value pairs in this Secret object. +// False otherwise. +func (s *Secret) Empty() bool { + return len(s.data) == 0 +} + +func (s *Secret) Format(oldKey, newKey, fmtType string, skipIfExists bool) error { + if !s.Has(oldKey) { + return NewSecretNotFoundError(oldKey) + } + oldVal := s.Get(oldKey) + switch fmtType { + case "crypt-md5": + newVal, err := crypt_md5(oldVal) + if err != nil { + return err + } + err = s.Set(newKey, newVal, skipIfExists) + if err != nil { + return err + } + + case "crypt-sha256": + newVal, err := crypt_sha256(oldVal) + if err != nil { + return err + } + err = s.Set(newKey, newVal, skipIfExists) + if err != nil { + return err + } + + case "crypt-sha512": + newVal, err := crypt_sha512(oldVal) + if err != nil { + return err + } + err = s.Set(newKey, newVal, skipIfExists) + if err != nil { + return err + } + + case "bcrypt": + newVal, err := crypt_bcrypt(oldVal) + if err != nil { + return err + } + err = s.Set(newKey, newVal, skipIfExists) + if err != nil { + return err + } + + case "base64": + err := s.Set(newKey, base64.StdEncoding.EncodeToString([]byte(oldVal)), skipIfExists) + if err != nil { + return err + } + default: + return fmt.Errorf("%s is not a valid encoding for the `safe fmt` command", fmtType) + } + + return nil +} + +func (s *Secret) DHParam(length int, skipIfExists bool) error { + dhparam, err := genDHParam(length) + if err != nil { + return err + } + err = s.Set("dhparam-pem", dhparam, skipIfExists) + if err != nil { + return err + } + return nil +} + +// Password creates and stores a new randomized password. +func (s *Secret) Password(key string, length int, policy string, skipIfExists bool) error { + r, err := random(length, policy) + if err != nil { + return err + } + err = s.Set(key, r, skipIfExists) + if err != nil { + return err + } + return nil +} + +func crypt_md5(pass string) (string, error) { + c := md5_crypt.New() + salt, err := random(16, "a-zA-Z") + if err != nil { + return "", err + } + md5, err := c.Generate([]byte(pass), []byte("$1$"+salt)) + if err != nil { + return "", fmt.Errorf("Error generating MD5 crypt for password: %s\n", err) + } + return md5, err +} + +func crypt_sha256(pass string) (string, error) { + c := sha256_crypt.New() + salt, err := random(16, "a-zA-Z") + if err != nil { + return "", err + } + sha, err := c.Generate([]byte(pass), []byte("$5$"+salt)) + if err != nil { + return "", fmt.Errorf("Error generating SHA-256 crypt for password: %s\n", err) + } + return sha, err +} + +func crypt_sha512(pass string) (string, error) { + c := sha512_crypt.New() + salt, err := random(16, "a-zA-Z") + if err != nil { + return "", err + } + sha, err := c.Generate([]byte(pass), []byte("$6$"+salt)) + if err != nil { + return "", fmt.Errorf("Error generating SHA-512 crypt for password: %s\n", err) + } + return sha, err +} + +func crypt_bcrypt(pass string) (string, error) { + // for now, use a fixed worker cost of 12 + hashed, err := bcrypt.GenerateFromPassword([]byte(pass), 12) + if err != nil { + return "", err + } + return string(hashed), nil +} + +func (s *Secret) keypair(private, public string, fingerprint string, skipIfExists bool) error { + err := s.Set("private", private, skipIfExists) + if err != nil { + return err + } + err = s.Set("public", public, skipIfExists) + if err != nil { + return err + } + if fingerprint != "" { + err = s.Set("fingerprint", fingerprint, skipIfExists) + if err != nil { + return err + } + } + return nil +} + +// RSAKey generates a new public/private keypair, and stores +// it in the secret, under the 'public' and 'private' keys. +func (s *Secret) RSAKey(bits int, skipIfExists bool) error { + private, public, err := rsakey(bits) + if err != nil { + return err + } + return s.keypair(private, public, "", skipIfExists) +} + +// SSHKey generates a new public/private keypair, and stores +// it in the secret, under the 'public' and 'private' keys. +func (s *Secret) SSHKey(bits int, skipIfExists bool) error { + private, public, fingerprint, err := sshkey(bits) + if err != nil { + return err + } + return s.keypair(private, public, fingerprint, skipIfExists) +} + +// JSON converts a Secret to its JSON representation and returns it as a string. +// Returns an empty string if there were any errors. +func (s *Secret) JSON() string { + b, err := json.Marshal(s.data) + if err != nil { + return "" + } + return string(b) +} + +// YAML converts a Secret to its YAML representation and returns it as a string. +// Returns an empty string if there were any errors. +func (s *Secret) YAML() string { + b, err := yaml.Marshal(s.data) + if err != nil { + return "" + } + return string(b) +} + +// SingleValue converts a secret to a string representing the value extracted. +// Returns an error if there are not exactly one results in the secret +// object +func (s *Secret) SingleValue() (string, error) { + if len(s.data) != 1 { + return "", fmt.Errorf("%d results in secret, 1 expected", len(s.data)) + } + var ret string + for _, v := range s.data { + ret = v + } + return ret, nil +} diff --git a/vendor/github.com/starkandwayne/safe/vault/ssh.go b/vendor/github.com/starkandwayne/safe/vault/ssh.go new file mode 100644 index 000000000..9eaea7645 --- /dev/null +++ b/vendor/github.com/starkandwayne/safe/vault/ssh.go @@ -0,0 +1,42 @@ +package vault + +import ( + "crypto/md5" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/pem" + "fmt" + "golang.org/x/crypto/ssh" + "strings" +) + +func sshkey(bits int) (string, string, string, error) { + key, err := rsa.GenerateKey(rand.Reader, bits) + if err != nil { + return "", "", "", err + } + + private := pem.EncodeToMemory( + &pem.Block{ + Type: "RSA PRIVATE KEY", + Bytes: x509.MarshalPKCS1PrivateKey(key), + }, + ) + + pub := key.Public() + pubkey, err := ssh.NewPublicKey(pub) + if err != nil { + return "", "", "", err + } + public := ssh.MarshalAuthorizedKey(pubkey) + + var fp []string + f := []byte(fmt.Sprintf("%x", md5.Sum(pubkey.Marshal()))) + for i := 0; i < len(f); i += 2 { + fp = append(fp, string(f[i:i+2])) + } + fingerprint := strings.Join(fp, ":") + + return string(private), string(public), string(fingerprint), nil +} diff --git a/vendor/github.com/starkandwayne/safe/vault/strongbox.go b/vendor/github.com/starkandwayne/safe/vault/strongbox.go new file mode 100644 index 000000000..548c2a5ce --- /dev/null +++ b/vendor/github.com/starkandwayne/safe/vault/strongbox.go @@ -0,0 +1,41 @@ +package vault + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "net/url" + "regexp" +) + +func (v *Vault) Strongbox() (map[string]string, error) { + m := make(map[string]string) + + u, err := url.Parse(v.URL) + if err != nil { + return m, err + } + + c := &http.Client{} + re := regexp.MustCompile(`:[0-9]+$`) + + uri := "http://" + re.ReplaceAllString(u.Host, "") + ":8484/strongbox" + req, err := http.NewRequest("GET", uri, nil) + if err != nil { + return m, err + } + + res, err := c.Do(req) + if err != nil { + return m, err + } + + if res.StatusCode != 200 { + return m, fmt.Errorf("received an HTTP %d response from %s", res.StatusCode, uri) + } + + b, err := ioutil.ReadAll(res.Body) + err = json.Unmarshal(b, &m) + return m, err +} diff --git a/vendor/github.com/starkandwayne/safe/vault/utils.go b/vendor/github.com/starkandwayne/safe/vault/utils.go new file mode 100644 index 000000000..711bc4863 --- /dev/null +++ b/vendor/github.com/starkandwayne/safe/vault/utils.go @@ -0,0 +1,35 @@ +package vault + +import ( + "regexp" + "strings" +) + +// ParsePath splits the given path string into its respective secret path +// and contained key parts +func ParsePath(path string) (secret, key string) { + secret = path + if idx := strings.LastIndex(path, ":"); idx >= 0 { + secret = path[:idx] + key = path[idx+1:] + } + secret = Canonicalize(secret) + return +} + +// PathHasKey returns true if the given path has a key specified in its syntax. +// False otherwise. +func PathHasKey(path string) bool { + _, key := ParsePath(path) + return key != "" +} + +func Canonicalize(p string) string { + p = strings.TrimSuffix(p, "/") + p = strings.TrimPrefix(p, "/") + + re := regexp.MustCompile("//+") + p = re.ReplaceAllString(p, "/") + + return p +} diff --git a/vendor/github.com/starkandwayne/safe/vault/vault.go b/vendor/github.com/starkandwayne/safe/vault/vault.go new file mode 100644 index 000000000..37b269cce --- /dev/null +++ b/vendor/github.com/starkandwayne/safe/vault/vault.go @@ -0,0 +1,1037 @@ +package vault + +import ( + "bytes" + "crypto/tls" + "crypto/x509" + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "net/http/httputil" + "net/url" + "os" + "strings" + + "github.com/jhunt/go-ansi" + "github.com/starkandwayne/goutils/tree" +) + +// A Vault represents a means for interacting with a remote Vault +// instance (unsealed and pre-authenticated) to read and write secrets. +type Vault struct { + URL string + Token string + Client *http.Client +} + +// NewVault creates a new Vault object. If an empty token is specified, +// the current user's token is read from ~/.vault-token. +func NewVault(url, token string, auth bool) (*Vault, error) { + if auth { + if token == "" { + b, err := ioutil.ReadFile(fmt.Sprintf("%s/.vault-token", os.Getenv("HOME"))) + if err != nil { + return nil, err + } + token = string(b) + } + + if token == "" { + return nil, fmt.Errorf("no vault token specified; are you authenticated?") + } + } + + roots, err := x509.SystemCertPool() + if err != nil { + return nil, fmt.Errorf("unable to retrieve system root certificate authorities: %s", err) + } + + return &Vault{ + URL: strings.TrimSuffix(url, "/"), + Token: token, + Client: &http.Client{ + Transport: &http.Transport{ + Proxy: http.ProxyFromEnvironment, + TLSClientConfig: &tls.Config{ + RootCAs: roots, + InsecureSkipVerify: os.Getenv("VAULT_SKIP_VERIFY") != "", + }, + }, + CheckRedirect: func(req *http.Request, via []*http.Request) error { + if len(via) > 10 { + return fmt.Errorf("stopped after 10 redirects") + } + req.Header.Add("X-Vault-Token", token) + return nil + }, + }, + }, nil +} + +func (v *Vault) url(f string, args ...interface{}) string { + return v.URL + fmt.Sprintf(f, args...) +} + +func shouldDebug() bool { + d := strings.ToLower(os.Getenv("DEBUG")) + return d != "" && d != "false" && d != "0" && d != "no" && d != "off" +} + +func (v *Vault) request(req *http.Request) (*http.Response, error) { + var ( + body []byte + err error + ) + if req.Body != nil { + body, err = ioutil.ReadAll(req.Body) + if err != nil { + return nil, err + } + } + + req.Header.Add("X-Vault-Token", v.Token) + for i := 0; i < 10; i++ { + if req.Body != nil { + req.Body = ioutil.NopCloser(bytes.NewReader(body)) + } + if shouldDebug() { + r, _ := httputil.DumpRequest(req, true) + fmt.Fprintf(os.Stderr, "Request:\n%s\n----------------\n", r) + } + res, err := v.Client.Do(req) + if shouldDebug() { + r, _ := httputil.DumpResponse(res, true) + fmt.Fprintf(os.Stderr, "Response:\n%s\n----------------\n", r) + } + if err != nil { + return nil, err + } + // Vault returns a 307 to redirect during HA / Auth + switch res.StatusCode { + case 307: + // Note: this does not handle relative Location headers + url, err := url.Parse(res.Header.Get("Location")) + if err != nil { + return nil, err + } + req.URL = url + // ... and try again. + + default: + return res, err + } + } + + return nil, fmt.Errorf("redirection loop detected") +} + +func (v *Vault) Curl(method string, path string, body []byte) (*http.Response, error) { + path = Canonicalize(path) + req, err := http.NewRequest(method, v.url("/v1/%s", path), bytes.NewBuffer(body)) + if err != nil { + return nil, err + } + return v.request(req) +} + +func (v *Vault) Configure(path string, params map[string]string) error { + data, err := json.Marshal(params) + if err != nil { + return err + } + + res, err := v.Curl("POST", path, data) + if err != nil { + return err + } + + if res.StatusCode != 200 && res.StatusCode != 204 { + return fmt.Errorf("configuration via '%s' failed", path) + } + + return nil +} + +// Read checks the Vault for a Secret at the specified path, and returns it. +// If there is nothing at that path, a nil *Secret will be returned, with no +// error. +func (v *Vault) Read(path string) (secret *Secret, err error) { + //split at last colon, if present + path, key := ParsePath(path) + + secret = NewSecret() + req, err := http.NewRequest("GET", v.url("/v1/%s", path), nil) + if err != nil { + return + } + res, err := v.request(req) + if err != nil { + return + } + + switch res.StatusCode { + case 200: + break + case 404: + err = NewSecretNotFoundError(path) + return + default: + err = fmt.Errorf("API %s", res.Status) + return + } + + b, err := ioutil.ReadAll(res.Body) + if err != nil { + return + } + + var raw map[string]interface{} + if err = json.Unmarshal(b, &raw); err != nil { + return + } + + if rawdata, ok := raw["data"]; ok { + if data, ok := rawdata.(map[string]interface{}); ok { + for k, v := range data { + if (key != "" && k == key) || key == "" { + if s, ok := v.(string); ok { + secret.data[k] = s + } else { + b, err = json.Marshal(v) + if err != nil { + return + } + secret.data[k] = string(b) + } + } + } + + if key != "" && len(secret.data) == 0 { + err = NewKeyNotFoundError(path, key) + } + return + } + } + err = fmt.Errorf("malformed response from vault") + return +} + +// List returns the set of (relative) paths that are directly underneath +// the given path. Intermediate path nodes are suffixed with a single "/", +// whereas leaf nodes (the secrets themselves) are not. +func (v *Vault) List(path string) (paths []string, err error) { + path = Canonicalize(path) + + req, err := http.NewRequest("GET", v.url("/v1/%s?list=1", path), nil) + if err != nil { + return + } + res, err := v.request(req) + if err != nil { + return + } + + switch res.StatusCode { + case 200: + break + case 404: + req, err = http.NewRequest("GET", v.url("/v1/%s", path), nil) + if err != nil { + return + } + res, err = v.request(req) + if err != nil { + return + } + switch res.StatusCode { + case 200: + break + case 404: + err = NewSecretNotFoundError(path) + return + default: + err = fmt.Errorf("API %s", res.Status) + return + } + default: + err = fmt.Errorf("API %s", res.Status) + return + } + + b, err := ioutil.ReadAll(res.Body) + if err != nil { + return + } + + var r struct{ Data struct{ Keys []string } } + if err = json.Unmarshal(b, &r); err != nil { + return + } + return r.Data.Keys, nil +} + +type TreeOptions struct { + UseANSI bool /* Use ANSI colorizing sequences */ + HideLeaves bool /* Hide leaf nodes of the tree (actual secrets) */ + ShowKeys bool /* Include keys in the output */ + InSubbranch bool /* If true, suppresses key output on branches */ + StripSlashes bool /* If true, strip the trailing slashes from interior nodes */ +} + +func (v *Vault) walktree(path string, options TreeOptions) (tree.Node, int, error) { + t := tree.New(path) + l, err := v.List(path) + if err != nil { + return t, 0, err + } + + var key_fmt string + if options.UseANSI { + key_fmt = "@Y{:%s}" + } else { + key_fmt = ":%s" + } + if options.ShowKeys && !options.InSubbranch { + if s, err := v.Read(path); err == nil { + for _, key := range s.Keys() { + key_name := ansi.Sprintf(key_fmt, key) + t.Append(tree.New(key_name)) + } + } + } + options.InSubbranch = true + for _, p := range l { + if strings.HasSuffix(p, "/") { + kid, n, err := v.walktree(path+"/"+p[0:len(p)-1], options) + if err != nil { + return t, 0, err + } + if n == 0 { + fmt.Fprintf(os.Stderr, "%s\n", kid.Name) + continue + } + if options.StripSlashes { + p = p[0 : len(p)-1] + } + if options.UseANSI { + kid.Name = ansi.Sprintf("@B{%s}", p) + } else { + kid.Name = p + } + t.Append(kid) + + } else if options.HideLeaves { + continue + + } else { + var name string + if options.UseANSI { + name = ansi.Sprintf("@G{%s}", p) + } else { + name = p + } + leaf := tree.New(name) + if options.ShowKeys { + if s, err := v.Read(path + "/" + p); err == nil { + for _, key := range s.Keys() { + key_name := ansi.Sprintf(key_fmt, key) + leaf.Append(tree.New(key_name)) + } + } else { + fmt.Fprintf(os.Stderr, "error: %s\n", err) + } + + } + t.Append(leaf) + } + } + return t, len(l), nil +} + +// Tree returns a tree that represents the hierarchy of paths contained +// below the given path, inside of the Vault. +func (v *Vault) Tree(path string, options TreeOptions) (tree.Node, error) { + path = Canonicalize(path) + + t, _, err := v.walktree(path, options) + if err != nil { + return t, err + } + if options.UseANSI { + t.Name = ansi.Sprintf("@C{%s}", path) + } else { + t.Name = path + } + return t, nil +} + +// Write takes a Secret and writes it to the Vault at the specified path. +func (v *Vault) Write(path string, s *Secret) error { + path = Canonicalize(path) + if strings.Contains(path, ":") { + return fmt.Errorf("cannot write to paths in /path:key notation") + } + + //If our secret has become empty (through key deletion, most likely) + // make sure to clean up the secret + if s.Empty() { + return v.deleteIfPresent(path) + } + + raw := s.JSON() + + req, err := http.NewRequest("POST", v.url("/v1/%s", path), strings.NewReader(raw)) + if err != nil { + return err + } + res, err := v.request(req) + if err != nil { + return err + } + + switch res.StatusCode { + case 200: + break + case 204: + break + default: + return fmt.Errorf("API %s", res.Status) + } + + return nil +} + +//errIfFolder returns an error with your provided message if the given path exists, +// either as a secret or a folder. +// Can also throw an error if contacting the backend failed, in which case that error +// is returned. +func (v *Vault) errIfFolder(path, message string, args ...interface{}) error { + path = Canonicalize(path) + + //need to check if length of list is 0 because prior to vault 0.6.0, no 404 is + //given for attempting to list a path which does not exist. + if paths, err := v.List(path); err == nil && len(paths) != 0 { //...see if it is a subtree "folder" + // the "== nil" is not a typo. if there is an error, NotFound or otherwise, + // simply fall through to the error return below + // Otherwise, give a different error signifying that the problem is that + // the target is a directory when we expected a secret. + return fmt.Errorf(message, args...) + } else if err != nil && !IsNotFound(err) { + return err + } + return nil +} + +func (v *Vault) verifySecretExists(path string) error { + path = Canonicalize(path) + + _, err := v.Read(path) + if err != nil && IsNotFound(err) { //if this was not a leaf node (secret)... + if folderErr := v.errIfFolder(path, "`%s` points to a folder, not a secret", path); folderErr != nil { + return folderErr + } + } + return err +} + +//DeleteTree recursively deletes the leaf nodes beneath the given root until +// the root has no children, and then deletes that. +func (v *Vault) DeleteTree(root string) error { + root = Canonicalize(root) + + tree, err := v.Tree(root, TreeOptions{ + StripSlashes: true, + }) + if err != nil { + return err + } + for _, path := range tree.Paths("/") { + err = v.deleteEntireSecret(path) + if err != nil { + return err + } + } + return v.deleteEntireSecret(root) +} + +// Delete removes the secret or key stored at the specified path. +func (v *Vault) Delete(path string) error { + path = Canonicalize(path) + + if err := v.verifySecretExists(path); err != nil { + return err + } + + secret, key := ParsePath(path) + if key == "" { + return v.deleteEntireSecret(path) + } + return v.deleteSpecificKey(secret, key) +} + +func (v *Vault) deleteEntireSecret(path string) error { + + req, err := http.NewRequest("DELETE", v.url("/v1/%s", path), nil) + if err != nil { + return err + } + res, err := v.request(req) + if err != nil { + return err + } + + switch res.StatusCode { + case 200: + break + case 204: + break + default: + return fmt.Errorf("API %s", res.Status) + } + + return nil +} + +func (v *Vault) deleteSpecificKey(path, key string) error { + secret, err := v.Read(path) + if err != nil { + return err + } + deleted := secret.Delete(key) + if !deleted { + return NewKeyNotFoundError(path, key) + } + err = v.Write(path, secret) + return err +} + +//deleteIfPresent first checks to see if there is a Secret at the given path, +// and if so, it deletes it. Otherwise, no error is thrown +func (v *Vault) deleteIfPresent(path string) error { + secretpath, _ := ParsePath(path) + if _, err := v.Read(secretpath); err != nil { + if IsSecretNotFound(err) { + return nil + } + return err + } + + err := v.Delete(path) + if IsKeyNotFound(err) { + return nil + } + return err +} + +// Copy copies secrets from one path to another. +// With a secret:key specified: key -> key is good. +// key -> no-key is okay - we assume to keep old key name +// no-key -> key is bad. That makes no sense and the user should feel bad. +// Returns KeyNotFoundError if there is no such specified key in the secret at oldpath +func (v *Vault) Copy(oldpath, newpath string, skipIfExists bool, quiet bool) error { + oldpath = Canonicalize(oldpath) + newpath = Canonicalize(newpath) + + if err := v.verifySecretExists(oldpath); err != nil { + return err + } + if skipIfExists { + if _, err := v.Read(newpath); err == nil { + if !quiet { + ansi.Fprintf(os.Stderr, "@R{Cowardly refusing to copy/move data into} @C{%s}@R{, as that would clobber existing data}\n", newpath) + } + return nil + } else if !IsNotFound(err) { + return err + } + } + + srcPath, _ := ParsePath(oldpath) + srcSecret, err := v.Read(srcPath) + if err != nil { + return err + } + + var copyFn func(string, string, *Secret, bool) error + if PathHasKey(oldpath) { + copyFn = v.copyKey + } else { + copyFn = v.copyEntireSecret + } + + return copyFn(oldpath, newpath, srcSecret, skipIfExists) +} + +func (v *Vault) copyEntireSecret(oldpath, newpath string, src *Secret, skipIfExists bool) (err error) { + if PathHasKey(newpath) { + return fmt.Errorf("Cannot move full secret `%s` into specific key `%s`", oldpath, newpath) + } + if skipIfExists { + if _, err := v.Read(newpath); err == nil { + return ansi.Errorf("@R{BUG: Tried to replace} @C{%s} @R{with} @C{%s}@R{, but it already exists}", oldpath, newpath) + } else if !IsNotFound(err) { + return err + } + } + return v.Write(newpath, src) +} + +func (v *Vault) copyKey(oldpath, newpath string, src *Secret, skipIfExists bool) (err error) { + _, srcKey := ParsePath(oldpath) + if !src.Has(srcKey) { + return NewKeyNotFoundError(oldpath, srcKey) + } + + dstPath, dstKey := ParsePath(newpath) + //If destination has no key, then assume to give it the same key as the src + if dstKey == "" { + dstKey = srcKey + } + dst, err := v.Read(dstPath) + if err != nil { + if !IsSecretNotFound(err) { + return err + } + dst = NewSecret() //If no secret is already at the dst, initialize a new one + } + err = dst.Set(dstKey, src.Get(srcKey), skipIfExists) + if err != nil { + return err + } + return v.Write(dstPath, dst) +} + +//MoveCopyTree will recursively copy all nodes from the root to the new location. +// This function will get confused about 'secret:key' syntax, so don't let those +// get routed here - they don't make sense for a recursion anyway. +func (v *Vault) MoveCopyTree(oldRoot, newRoot string, f func(string, string, bool, bool) error, skipIfExists bool, quiet bool) error { + oldRoot = Canonicalize(oldRoot) + newRoot = Canonicalize(newRoot) + + tree, err := v.Tree(oldRoot, TreeOptions{}) + if err != nil { + return err + } + if skipIfExists { + newTree, err := v.Tree(newRoot, TreeOptions{}) + if err != nil && !IsNotFound(err) { + return err + } + existing := map[string]bool{} + for _, path := range newTree.Paths("/") { + existing[path] = true + } + existingPaths := []string{} + for _, path := range tree.Paths("/") { + newPath := strings.Replace(path, oldRoot, newRoot, 1) + if existing[newPath] { + existingPaths = append(existingPaths, newPath) + } + } + if len(existingPaths) > 0 { + if !quiet { + ansi.Fprintf(os.Stderr, "@R{Cowardly refusing to copy/move data into} @C{%s}@R{, as the following paths would be clobbered:}\n", newRoot) + for _, path := range existingPaths { + ansi.Fprintf(os.Stderr, "@R{- }@C{%s}\n", path) + } + } + return nil + } + } + for _, path := range tree.Paths("/") { + newPath := strings.Replace(path, oldRoot, newRoot, 1) + err = f(path, newPath, skipIfExists, quiet) + if err != nil { + return err + } + } + + if _, err := v.Read(oldRoot); !IsNotFound(err) { // run through a copy unless we successfully got a 404 from this node + return f(oldRoot, newRoot, skipIfExists, quiet) + } + return nil +} + +// Move moves secrets from one path to another. +// A move is semantically a copy and then a deletion of the original item. For +// more information on the behavior of Move pertaining to keys, look at Copy. +func (v *Vault) Move(oldpath, newpath string, skipIfExists bool, quiet bool) error { + oldpath = Canonicalize(oldpath) + newpath = Canonicalize(newpath) + + if err := v.verifySecretExists(oldpath); err != nil { + return err + } + + err := v.Copy(oldpath, newpath, skipIfExists, quiet) + if err != nil { + return err + } + err = v.Delete(oldpath) + if err != nil { + return err + } + return nil +} + +type mountpoint struct { + Type string `json:"type"` + Description string `json:"description"` + Config map[string]interface{} `json:"config"` +} + +func convertMountpoint(o interface{}) (mountpoint, bool) { + mount := mountpoint{} + if m, ok := o.(map[string]interface{}); ok { + if t, ok := m["type"].(string); ok { + mount.Type = t + } else { + return mount, false + } + if d, ok := m["description"].(string); ok { + mount.Description = d + } else { + return mount, false + } + if c, ok := m["config"].(map[string]interface{}); ok { + mount.Config = c + } else { + return mount, false + } + return mount, true + } + return mount, false +} + +func (v *Vault) Mounts(typ string) ([]string, error) { + res, err := v.Curl("GET", "sys/mounts", nil) + if err != nil { + return nil, err + } + + body, err := ioutil.ReadAll(res.Body) + if err != nil { + return nil, err + } + + if res.StatusCode != 200 { + return nil, DecodeErrorResponse(body) + } + + mm := make(map[string]interface{}) + if err := json.Unmarshal(body, &mm); err != nil { + return nil, fmt.Errorf("Received invalid JSON '%s' from Vault: %s\n", + body, err) + } + + l := make([]string, 0) + for k, m := range mm { + if mount, ok := convertMountpoint(m); ok { + if typ == "" || mount.Type == typ { + l = append(l, strings.TrimSuffix(k, "/")+"/") + } + } + } + return l, nil +} + +func (v *Vault) IsMounted(typ, path string) (bool, error) { + mounts, err := v.Mounts(typ) + if err != nil { + return false, err + } + + for _, at := range mounts { + if at == path || at == path+"/" { + return true, nil + } + } + return false, nil +} + +func (v *Vault) Mount(typ, path string, params map[string]interface{}) error { + mounted, err := v.IsMounted(typ, path) + if err != nil { + return err + } + + if !mounted { + p := mountpoint{ + Type: typ, + Description: "(managed by safe)", + Config: params, + } + data, err := json.Marshal(p) + if err != nil { + return err + } + + res, err := v.Curl("POST", fmt.Sprintf("sys/mounts/%s", path), data) + if err != nil { + return err + } + + if res.StatusCode != 204 { + body, err := ioutil.ReadAll(res.Body) + if err != nil { + return err + } + return DecodeErrorResponse(body) + } + + } else { + data, err := json.Marshal(params) + if err != nil { + return err + } + + res, err := v.Curl("POST", fmt.Sprintf("sys/mounts/%s/tune", path), data) + if err != nil { + return err + } + + if res.StatusCode != 204 { + body, err := ioutil.ReadAll(res.Body) + if err != nil { + return err + } + return DecodeErrorResponse(body) + } + } + + return nil +} + +func (v *Vault) RetrievePem(backend, path string) ([]byte, error) { + if err := v.CheckPKIBackend(backend); err != nil { + return nil, err + } + + res, err := v.Curl("GET", fmt.Sprintf("/%s/%s/pem", backend, path), nil) + if err != nil { + return nil, err + } + + body, err := ioutil.ReadAll(res.Body) + if err != nil { + return nil, err + } + + if res.StatusCode != 200 { + return nil, DecodeErrorResponse(body) + } + + return body, nil +} + +func DecodeErrorResponse(body []byte) error { + var raw map[string]interface{} + + if err := json.Unmarshal(body, &raw); err != nil { + return fmt.Errorf("Received non-200 with non-JSON payload:\n%s\n", body) + } + + if rawErrors, ok := raw["errors"]; ok { + var errors []string + if elems, ok := rawErrors.([]interface{}); ok { + for _, elem := range elems { + if err, ok := elem.(string); ok { + errors = append(errors, err) + } + } + return fmt.Errorf(strings.Join(errors, "\n")) + } else { + return fmt.Errorf("Received unexpected format of Vault error messages:\n%v\n", errors) + } + } else { + return fmt.Errorf("Received non-200 with no error messagess:\n%v\n", raw) + } +} + +type CertOptions struct { + CN string `json:"common_name"` + TTL string `json:"ttl,omitempty"` + AltNames string `json:"alt_names,omitempty"` + IPSans string `json:"ip_sans,omitempty"` + ExcludeCNFromSans bool `json:"exclude_cn_from_sans,omitempty"` +} + +func (v *Vault) CreateSignedCertificate(backend, role, path string, params CertOptions, skipIfExists bool) error { + if err := v.CheckPKIBackend(backend); err != nil { + return err + } + + data, err := json.Marshal(params) + if err != nil { + return err + } + res, err := v.Curl("POST", fmt.Sprintf("%s/issue/%s", backend, role), data) + if err != nil { + return err + } + + body, err := ioutil.ReadAll(res.Body) + if err != nil { + return err + } + + if res.StatusCode >= 400 { + return fmt.Errorf("Unable to create certificate %s: %s\n", params.CN, DecodeErrorResponse(body)) + } + + var raw map[string]interface{} + if err = json.Unmarshal(body, &raw); err == nil { + if d, ok := raw["data"]; ok { + if data, ok := d.(map[string]interface{}); ok { + var cert, key, serial string + var c, k, s interface{} + var ok bool + if c, ok = data["certificate"]; !ok { + return fmt.Errorf("No certificate found when issuing certificate %s:\n%v\n", params.CN, data) + } + if cert, ok = c.(string); !ok { + return fmt.Errorf("Invalid data type for certificate %s:\n%v\n", params.CN, data) + } + if k, ok = data["private_key"]; !ok { + return fmt.Errorf("No private_key found when issuing certificate %s:\n%v\n", params.CN, data) + } + if key, ok = k.(string); !ok { + return fmt.Errorf("Invalid data type for private_key %s:\n%v\n", params.CN, data) + } + if s, ok = data["serial_number"]; !ok { + return fmt.Errorf("No serial_number found when issuing certificate %s:\n%v\n", params.CN, data) + } + if serial, ok = s.(string); !ok { + return fmt.Errorf("Invalid data type for serial_number %s:\n%v\n", params.CN, data) + } + + secret, err := v.Read(path) + if err != nil && !IsNotFound(err) { + return err + } + err = secret.Set("cert", cert, skipIfExists) + if err != nil { + return err + } + err = secret.Set("key", key, skipIfExists) + if err != nil { + return err + } + err = secret.Set("combined", cert+key, skipIfExists) + if err != nil { + return err + } + err = secret.Set("serial", serial, skipIfExists) + if err != nil { + return err + } + return v.Write(path, secret) + } else { + return fmt.Errorf("Invalid response datatype requesting certificate %s:\n%v\n", params.CN, d) + } + } else { + return fmt.Errorf("No data found when requesting certificate %s:\n%v\n", params.CN, d) + } + } else { + return fmt.Errorf("Unparseable json creating certificate %s:\n%s\n", params.CN, body) + } +} + +func (v *Vault) RevokeCertificate(backend, serial string) error { + if err := v.CheckPKIBackend(backend); err != nil { + return err + } + + if strings.ContainsRune(serial, '/') { + secret, err := v.Read(serial) + if err != nil { + return err + } + if !secret.Has("serial") { + return fmt.Errorf("Certificate specified using path %s, but no serial secret was found there", serial) + } + serial = secret.Get("serial") + } + + d := struct { + Serial string `json:"serial_number"` + }{Serial: serial} + + data, err := json.Marshal(d) + if err != nil { + return err + } + + res, err := v.Curl("POST", fmt.Sprintf("%s/revoke", backend), data) + if err != nil { + return err + } + + if res.StatusCode >= 400 { + body, err := ioutil.ReadAll(res.Body) + if err != nil { + return err + } + return fmt.Errorf("Unable to revoke certificate %s: %s\n", serial, DecodeErrorResponse(body)) + } + return nil +} + +func (v *Vault) CheckPKIBackend(backend string) error { + if mounted, _ := v.IsMounted("pki", backend); !mounted { + return fmt.Errorf("The PKI backend `%s` has not been configured. Try running `safe pki init --backend %s`\n", backend, backend) + } + return nil +} + +func (v *Vault) FindSigningCA(cert *X509, certPath string, signPath string) (*X509, string, error) { + /* find the CA */ + if signPath != "" { + if certPath == signPath { + return cert, certPath, nil + } else { + s, err := v.Read(signPath) + if err != nil { + return nil, "", err + } + ca, err := s.X509() + if err != nil { + return nil, "", err + } + return ca, signPath, nil + } + } else { + // Check if this cert is self-signed If so, don't change the value + // of s, because its already the cert we loaded in. #Hax + err := cert.Certificate.CheckSignature( + cert.Certificate.SignatureAlgorithm, + cert.Certificate.RawTBSCertificate, + cert.Certificate.Signature, + ) + if err == nil { + return cert, certPath, nil + } else { + // Lets see if we can guess the CA if none was provided + caPath := certPath[0:strings.LastIndex(certPath, "/")] + "/ca" + s, err := v.Read(caPath) + if err != nil { + return nil, "", fmt.Errorf("No signing authority provided and no 'ca' sibling found") + } + ca, err := s.X509() + if err != nil { + return nil, "", err + } + return ca, caPath, nil + } + } +} + +func (v *Vault) SaveSealKeys(keys []string) { + path := "secret/vault/seal/keys" + s := NewSecret() + for i, key := range keys { + s.Set(fmt.Sprintf("key%d", i+1), key, false) + } + v.Write(path, s) +} diff --git a/vendor/github.com/starkandwayne/safe/vault/x509.go b/vendor/github.com/starkandwayne/safe/vault/x509.go new file mode 100644 index 000000000..bda7699d4 --- /dev/null +++ b/vendor/github.com/starkandwayne/safe/vault/x509.go @@ -0,0 +1,505 @@ +package vault + +import ( + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "fmt" + "math/big" + "net" + "regexp" + "strconv" + "strings" + "time" +) + +type X509 struct { + Certificate *x509.Certificate + PrivateKey *rsa.PrivateKey + Serial *big.Int + CRL *pkix.CertificateList + + KeyUsage x509.KeyUsage + ExtKeyUsage []x509.ExtKeyUsage +} + +func (s Secret) X509() (*X509, error) { + if !s.Has("certificate") { + return nil, fmt.Errorf("not a valid certificate (missing the `certificate` attribute)") + } + if !s.Has("key") { + return nil, fmt.Errorf("not a valid certificate (missing the `key` attribute)") + } + + v := s.Get("certificate") + block, rest := pem.Decode([]byte(v)) + if block == nil { + return nil, fmt.Errorf("not a valid certificate (failed to decode certificate PEM block)") + } + if len(rest) > 0 { + return nil, fmt.Errorf("contains multiple certificates (is this a bundle?)") + } + if block.Type != "CERTIFICATE" { + return nil, fmt.Errorf("not a valid certificate (type '%s' != 'CERTIFICATE')", block.Type) + } + + cert, err := x509.ParseCertificate(block.Bytes) + if err != nil { + return nil, fmt.Errorf("not a valid certificate (%s)", err) + } + + v = s.Get("key") + block, rest = pem.Decode([]byte(v)) + if block == nil { + return nil, fmt.Errorf("not a valid certificate (failed to decode key PEM block)") + } + if len(rest) > 0 { + return nil, fmt.Errorf("contains multiple keys (what?)") + } + if block.Type != "RSA PRIVATE KEY" { + return nil, fmt.Errorf("not a valid certificate (type '%s' != 'RSA PRIVATE KEY')", block.Type) + } + + key, err := x509.ParsePKCS1PrivateKey(block.Bytes) + if err != nil { + return nil, fmt.Errorf("not a valid private key (%s)", err) + } + + o := &X509{ + Certificate: cert, + PrivateKey: key, + KeyUsage: cert.KeyUsage, + ExtKeyUsage: cert.ExtKeyUsage, + } + + if s.Has("serial") { + v = s.Get("serial") + i, err := strconv.ParseInt(v, 16, 64) + if err != nil { + return nil, fmt.Errorf("not a valid CA certificate (serial '%s' is malformed)", v) + } + o.Serial = big.NewInt(i) + } + + if s.Has("crl") { + v = s.Get("crl") + crl, err := x509.ParseCRL([]byte(v)) + if err != nil { + return nil, fmt.Errorf("not a valid CA certificate (CRL parsing failed: %s)", err) + } + o.CRL = crl + } + + return o, nil +} + +func formatSubject(name pkix.Name) string { + ss := []string{} + if name.CommonName != "" { + ss = append(ss, fmt.Sprintf("cn=%s", name.CommonName)) + } + for _, s := range name.Country { + ss = append(ss, fmt.Sprintf("c=%s", s)) + } + for _, s := range name.Province { + ss = append(ss, fmt.Sprintf("st=%s", s)) + } + for _, s := range name.Locality { + ss = append(ss, fmt.Sprintf("l=%s", s)) + } + for _, s := range name.Organization { + ss = append(ss, fmt.Sprintf("o=%s", s)) + } + for _, s := range name.OrganizationalUnit { + ss = append(ss, fmt.Sprintf("ou=%s", s)) + } + + return strings.Join(ss, ",") +} + +func (x *X509) Subject() string { + return formatSubject(x.Certificate.Subject) +} + +func (x *X509) Issuer() string { + return formatSubject(x.Certificate.Issuer) +} + +func parseSubject(subj string) (pkix.Name, error) { + /* parse subject names that look like this: + /cn=foo.bl/c=us/st=ny/l=buffalo/o=stark & wayne/ou=r&d + and CN=foo.bl,C=us,ST=ny,L=buffalo,O=stark & wayne,OU=r&d + */ + + var ( + pairs []string + name pkix.Name + ) + + if subj[0] == '/' { + pairs = strings.Split(subj[1:], "/") + } else { + pairs = strings.Split(subj, ",") + } + + kvre := regexp.MustCompile(" *= *") + for _, pair := range pairs { + kv := kvre.Split(pair, 2) + if len(kv) != 2 { + return name, fmt.Errorf("malformed subject component '%s'", pair) + } + switch kv[0] { + case "CN", "cn": + if name.CommonName != "" { + return name, fmt.Errorf("multiple common names (CN) found in '%s'", subj) + } + name.CommonName = kv[1] + case "C", "c": + name.Country = append(name.Country, kv[1]) + case "ST", "st": + name.Province = append(name.Province, kv[1]) + case "L", "l": + name.Locality = append(name.Locality, kv[1]) + case "O", "o": + name.Organization = append(name.Organization, kv[1]) + case "OU", "ou": + name.OrganizationalUnit = append(name.OrganizationalUnit, kv[1]) + default: + return name, fmt.Errorf("unrecognized subject component '%s=%s'", kv[0], kv[1]) + } + } + + return name, nil +} + +func categorizeSANs(in []string) (ips []net.IP, domains, emails []string) { + ips = make([]net.IP, 0) + domains = make([]string, 0) + emails = make([]string, 0) + + for _, s := range in { + ip := net.ParseIP(s) + if ip != nil { + ips = append(ips, ip) + continue + } + + if strings.Index(s, "@") > 0 { + emails = append(emails, s) + } else { + domains = append(domains, s) + } + } + + return +} + +var keyUsageLookup = map[string]x509.KeyUsage{ + "digital_signature": x509.KeyUsageDigitalSignature, + "non_repudiation": x509.KeyUsageContentCommitment, + "content_commitment": x509.KeyUsageContentCommitment, + "key_encipherment": x509.KeyUsageKeyEncipherment, + "data_encipherment": x509.KeyUsageDataEncipherment, + "key_agreement": x509.KeyUsageKeyAgreement, + "key_cert_sign": x509.KeyUsageCertSign, + "crl_sign": x509.KeyUsageCRLSign, + "encipher_only": x509.KeyUsageEncipherOnly, + "decipher_only": x509.KeyUsageDecipherOnly, +} + +var extendedKeyUsageLookup = map[string]x509.ExtKeyUsage{ + "client_auth": x509.ExtKeyUsageClientAuth, + "server_auth": x509.ExtKeyUsageServerAuth, + "code_signing": x509.ExtKeyUsageCodeSigning, + "email_protection": x509.ExtKeyUsageEmailProtection, + "timestamping": x509.ExtKeyUsageTimeStamping, +} + +func translateKeyUsage(input []string) (keyUsage x509.KeyUsage, err error) { + var found bool + + for i, usage := range input { + var thisKeyUsage x509.KeyUsage + if thisKeyUsage, found = keyUsageLookup[usage]; !found { + continue + } + + input[i] = "" + keyUsage = keyUsage | thisKeyUsage + } + + return +} + +func translateExtendedKeyUsage(input []string) (extendedKeyUsage []x509.ExtKeyUsage, err error) { + var found bool + + for _, extUsage := range input { + var thisExtKeyUsage x509.ExtKeyUsage + //Was interpreted as a normal key usage + if extUsage == "" { + continue + } + + if thisExtKeyUsage, found = extendedKeyUsageLookup[extUsage]; !found { + err = fmt.Errorf("%s is not a valid x509 key usage", extUsage) + break + } + extendedKeyUsage = append(extendedKeyUsage, thisExtKeyUsage) + } + return +} + +func NewCertificate(subj string, names, keyUsage []string, bits int) (*X509, error) { + if bits != 1024 && bits != 2048 && bits != 4096 { + return nil, fmt.Errorf("invalid RSA key strength '%d', must be one of: 1024, 2048, 4096", bits) + } + + name, err := parseSubject(subj) + if err != nil { + return nil, err + } + + ips, domains, emails := categorizeSANs(names) + + key, err := rsa.GenerateKey(rand.Reader, bits) + if err != nil { + return nil, err + } + + //Hyphens, underscores, spaces, oh my! + for i, _ := range keyUsage { + keyUsage[i] = strings.Replace(keyUsage[i], "-", "_", -1) + keyUsage[i] = strings.Replace(keyUsage[i], " ", "_", -1) + } + + translatedKeyUsage, err := translateKeyUsage(keyUsage) + if err != nil { + return nil, err + } + + translatedExtKeyUsage, err := translateExtendedKeyUsage(keyUsage) + if err != nil { + return nil, err + } + + return &X509{ + PrivateKey: key, + Certificate: &x509.Certificate{ + SignatureAlgorithm: x509.SHA512WithRSA, /* FIXME: hard-coded */ + PublicKeyAlgorithm: x509.RSA, + Subject: name, + DNSNames: domains, + EmailAddresses: emails, + IPAddresses: ips, + KeyUsage: translatedKeyUsage, + ExtKeyUsage: translatedExtKeyUsage, + /* ExtraExtensions */ + }, + }, nil +} + +func (x X509) Validate() error { + if x.Certificate.PublicKeyAlgorithm != x509.RSA { + return fmt.Errorf("invalid (non-RSA) public key algorithm found in certificate") + } + + pub := x.Certificate.PublicKey.(*rsa.PublicKey) + if pub.N.Cmp(x.PrivateKey.N) != 0 { + return fmt.Errorf("modulus for private key does not match modulus in certificate") + } + if pub.E != x.PrivateKey.E { + return fmt.Errorf("exponent for private key does not match exponent in certificate") + } + + return nil +} + +func (x X509) CheckStrength(bits ...int) error { + for _, b := range bits { + if x.PrivateKey.N.BitLen() == b { + return nil + } + } + return fmt.Errorf("key is a %d-bit RSA key", x.PrivateKey.N.BitLen()) +} + +func (x X509) IsCA() bool { + return x.Certificate.IsCA && x.Certificate.BasicConstraintsValid +} + +func (x X509) Expired() bool { + now := time.Now() + return now.After(x.Certificate.NotAfter) || now.Before(x.Certificate.NotBefore) +} + +func (x X509) ValidForIP(ip net.IP) bool { + for _, valid := range x.Certificate.IPAddresses { + if valid.Equal(ip) { + return true + } + } + return false +} + +func (x X509) ValidForDomain(domain string) bool { + for _, valid := range x.Certificate.DNSNames { + if strings.HasPrefix(valid, "*.") { + a := strings.Split(valid, ".") + b := strings.Split(domain, ".") + for len(a) > 0 && len(b) > 0 && a[0] == "*" { + a = a[1:] + b = b[1:] + } + if len(a) == 0 || len(b) == 0 || a[0] == "*" { + return false + } + + if strings.Join(a, ".") == strings.Join(b, ".") { + return true + } + } else { + if valid == domain { + return true + } + } + } + return false +} + +func (x X509) ValidForEmail(email string) bool { + for _, valid := range x.Certificate.EmailAddresses { + if valid == email { + return true + } + } + return false +} + +func (x X509) ValidFor(names ...string) (bool, error) { + ips, domains, emails := categorizeSANs(names) + + for _, ip := range ips { + if !x.ValidForIP(ip) { + return false, fmt.Errorf("certificate is not valid for IP '%s'", ip) + } + } + + for _, domain := range domains { + if !x.ValidForDomain(domain) { + return false, fmt.Errorf("certificate is not valid for DNS domain '%s'", domain) + } + } + + for _, email := range emails { + if !x.ValidForEmail(email) { + return false, fmt.Errorf("certificate is not valid for email address '%s'", email) + } + } + + return true, nil +} + +func (x *X509) MakeCA(serial int64) { + x.Certificate.BasicConstraintsValid = true + x.Certificate.IsCA = true + x.Certificate.MaxPathLen = 1 + x.Serial = big.NewInt(serial) + x.CRL = &pkix.CertificateList{} + x.CRL.TBSCertList.RevokedCertificates = make([]pkix.RevokedCertificate, 0) +} + +func (x X509) Secret(skipIfExists bool) (*Secret, error) { + s := NewSecret() + + cert := string(pem.EncodeToMemory(&pem.Block{ + Type: "CERTIFICATE", + Bytes: x.Certificate.Raw, + })) + key := string(pem.EncodeToMemory(&pem.Block{ + Type: "RSA PRIVATE KEY", + Bytes: x509.MarshalPKCS1PrivateKey(x.PrivateKey), + })) + + err := s.Set("certificate", cert, skipIfExists) + if err != nil { + return s, err + } + err = s.Set("key", key, skipIfExists) + if err != nil { + return s, err + } + err = s.Set("combined", cert+key, skipIfExists) + if err != nil { + return s, err + } + + if x.IsCA() { + err = s.Set("serial", x.Serial.Text(16), skipIfExists) + if err != nil { + return s, err + } + + b, err := x.Certificate.CreateCRL(rand.Reader, x.PrivateKey, x.CRL.TBSCertList.RevokedCertificates, time.Now(), time.Now().Add(10*365*24*time.Hour)) + if err != nil { + return s, err + } + err = s.Set("crl", string(pem.EncodeToMemory(&pem.Block{ + Type: "X509 CRL", + Bytes: b, + })), skipIfExists) + if err != nil { + return s, err + } + } + + return s, nil +} + +func (ca *X509) SaveTo(v *Vault, path string, skipIfExists bool) error { + s, err := ca.Secret(skipIfExists) + if err != nil { + return err + } + return v.Write(path, s) +} + +func (ca *X509) Sign(x *X509, ttl time.Duration) error { + if ca.Serial == nil { + x.Certificate.SerialNumber = big.NewInt(1) + } else { + x.Certificate.SerialNumber = ca.Serial + ca.Serial.Add(ca.Serial, big.NewInt(1)) + } + + x.Certificate.NotBefore = time.Now() + x.Certificate.NotAfter = time.Now().Add(ttl) + raw, err := x509.CreateCertificate(rand.Reader, x.Certificate, ca.Certificate, x.PrivateKey.Public(), ca.PrivateKey) + if err != nil { + return err + } + x.Certificate.Raw = raw + return nil +} + +func (ca *X509) Revoke(cert *X509) { + if ca.HasRevoked(cert) { + return + } + + ca.CRL.TBSCertList.RevokedCertificates = append(ca.CRL.TBSCertList.RevokedCertificates, pkix.RevokedCertificate{ + SerialNumber: cert.Certificate.SerialNumber, + RevocationTime: time.Now(), + }) +} + +func (ca *X509) HasRevoked(cert *X509) bool { + for _, rvk := range ca.CRL.TBSCertList.RevokedCertificates { + if rvk.SerialNumber.Cmp(cert.Certificate.SerialNumber) == 0 { + return true + } + } + return false +} diff --git a/vendor/github.com/tredoe/osutil/LICENSE-MPL.txt b/vendor/github.com/tredoe/osutil/LICENSE-MPL.txt new file mode 100644 index 000000000..52d135112 --- /dev/null +++ b/vendor/github.com/tredoe/osutil/LICENSE-MPL.txt @@ -0,0 +1,374 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. + diff --git a/vendor/github.com/tredoe/osutil/user/crypt/AUTHORS.md b/vendor/github.com/tredoe/osutil/user/crypt/AUTHORS.md new file mode 100644 index 000000000..8eb23dd0c --- /dev/null +++ b/vendor/github.com/tredoe/osutil/user/crypt/AUTHORS.md @@ -0,0 +1,8 @@ +### Initial author + +[Jeramey Crawford](https://github.com/jeramey) + +### Other authors + +[Jonas mg](https://github.com/tredoe) + diff --git a/vendor/github.com/tredoe/osutil/user/crypt/LICENSE b/vendor/github.com/tredoe/osutil/user/crypt/LICENSE new file mode 100644 index 000000000..c39e0de5d --- /dev/null +++ b/vendor/github.com/tredoe/osutil/user/crypt/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2012, Jeramey Crawford +Copyright (c) 2013, Jonas mg +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/tredoe/osutil/user/crypt/README.md b/vendor/github.com/tredoe/osutil/user/crypt/README.md new file mode 100644 index 000000000..cbcfb2e52 --- /dev/null +++ b/vendor/github.com/tredoe/osutil/user/crypt/README.md @@ -0,0 +1,25 @@ +crypt +===== +A password hashing library. + +The goal of crypt is to bring a library of many common and popular password +hashing algorithms to Go and to provide a simple and consistent interface to +each of them. As every hashing method is implemented in pure Go, this library +should be as portable as Go itself. + +All hashing methods come with a test suite which verifies their operation +against itself as well as the output of other password hashing implementations +to ensure compatibility with them. + +I hope you find this library to be useful and easy to use! + +Note: forked from + +## Installation + + go get github.com/tredoe/osutil/user/crypt + +## License + +The source files are distributed under a BSD-style license that can be found +in the LICENSE file. diff --git a/vendor/github.com/tredoe/osutil/user/crypt/common/base64.go b/vendor/github.com/tredoe/osutil/user/crypt/common/base64.go new file mode 100644 index 000000000..ed057d5c9 --- /dev/null +++ b/vendor/github.com/tredoe/osutil/user/crypt/common/base64.go @@ -0,0 +1,60 @@ +// Copyright 2012, Jeramey Crawford +// Copyright 2013, Jonas mg +// All rights reserved. +// +// Use of this source code is governed by a BSD-style license +// that can be found in the LICENSE file. + +package common + +const alphabet = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + +// Base64_24Bit is a variant of Base64 encoding, commonly used with password +// hashing algorithms to encode the result of their checksum output. +// +// The algorithm operates on up to 3 bytes at a time, encoding the following +// 6-bit sequences into up to 4 hash64 ASCII bytes. +// +// 1. Bottom 6 bits of the first byte +// 2. Top 2 bits of the first byte, and bottom 4 bits of the second byte. +// 3. Top 4 bits of the second byte, and bottom 2 bits of the third byte. +// 4. Top 6 bits of the third byte. +// +// This encoding method does not emit padding bytes as Base64 does. +func Base64_24Bit(src []byte) (hash []byte) { + if len(src) == 0 { + return []byte{} // TODO: return nil + } + + hashSize := (len(src) * 8) / 6 + if (len(src) % 6) != 0 { + hashSize += 1 + } + hash = make([]byte, hashSize) + + dst := hash + for len(src) > 0 { + switch len(src) { + default: + dst[0] = alphabet[src[0]&0x3f] + dst[1] = alphabet[((src[0]>>6)|(src[1]<<2))&0x3f] + dst[2] = alphabet[((src[1]>>4)|(src[2]<<4))&0x3f] + dst[3] = alphabet[(src[2]>>2)&0x3f] + src = src[3:] + dst = dst[4:] + case 2: + dst[0] = alphabet[src[0]&0x3f] + dst[1] = alphabet[((src[0]>>6)|(src[1]<<2))&0x3f] + dst[2] = alphabet[(src[1]>>4)&0x3f] + src = src[2:] + dst = dst[3:] + case 1: + dst[0] = alphabet[src[0]&0x3f] + dst[1] = alphabet[(src[0]>>6)&0x3f] + src = src[1:] + dst = dst[2:] + } + } + + return +} diff --git a/vendor/github.com/tredoe/osutil/user/crypt/common/doc.go b/vendor/github.com/tredoe/osutil/user/crypt/common/doc.go new file mode 100644 index 000000000..8eb6aff2d --- /dev/null +++ b/vendor/github.com/tredoe/osutil/user/crypt/common/doc.go @@ -0,0 +1,13 @@ +// Copyright 2012, Jeramey Crawford +// Copyright 2013, Jonas mg +// All rights reserved. +// +// Use of this source code is governed by a BSD-style license +// that can be found in the LICENSE file. + +// Package common contains routines used by multiple password hashing +// algorithms. +// +// Generally, you will never import this package directly. Many of the +// *_crypt packages will import this package if they require it. +package common diff --git a/vendor/github.com/tredoe/osutil/user/crypt/common/salt.go b/vendor/github.com/tredoe/osutil/user/crypt/common/salt.go new file mode 100644 index 000000000..22f51cc67 --- /dev/null +++ b/vendor/github.com/tredoe/osutil/user/crypt/common/salt.go @@ -0,0 +1,105 @@ +// Copyright 2012, Jeramey Crawford +// Copyright 2013, Jonas mg +// All rights reserved. +// +// Use of this source code is governed by a BSD-style license +// that can be found in the LICENSE file. + +package common + +import ( + "crypto/rand" + "errors" + "strconv" +) + +var ( + ErrSaltPrefix = errors.New("invalid magic prefix") + ErrSaltFormat = errors.New("invalid salt format") + ErrSaltRounds = errors.New("invalid rounds") +) + +// Salt represents a salt. +type Salt struct { + MagicPrefix []byte + + SaltLenMin int + SaltLenMax int + + RoundsMin int + RoundsMax int + RoundsDefault int +} + +// Generate generates a random salt of a given length. +// +// The length is set thus: +// +// length > SaltLenMax: length = SaltLenMax +// length < SaltLenMin: length = SaltLenMin +func (s *Salt) Generate(length int) []byte { + if length > s.SaltLenMax { + length = s.SaltLenMax + } else if length < s.SaltLenMin { + length = s.SaltLenMin + } + + saltLen := (length * 6 / 8) + if (length*6)%8 != 0 { + saltLen += 1 + } + salt := make([]byte, saltLen) + rand.Read(salt) + + out := make([]byte, len(s.MagicPrefix)+length) + copy(out, s.MagicPrefix) + copy(out[len(s.MagicPrefix):], Base64_24Bit(salt)) + return out +} + +// GenerateWRounds creates a random salt with the random bytes being of the +// length provided, and the rounds parameter set as specified. +// +// The parameters are set thus: +// +// length > SaltLenMax: length = SaltLenMax +// length < SaltLenMin: length = SaltLenMin +// +// rounds < 0: rounds = RoundsDefault +// rounds < RoundsMin: rounds = RoundsMin +// rounds > RoundsMax: rounds = RoundsMax +// +// If rounds is equal to RoundsDefault, then the "rounds=" part of the salt is +// removed. +func (s *Salt) GenerateWRounds(length, rounds int) []byte { + if length > s.SaltLenMax { + length = s.SaltLenMax + } else if length < s.SaltLenMin { + length = s.SaltLenMin + } + if rounds < 0 { + rounds = s.RoundsDefault + } else if rounds < s.RoundsMin { + rounds = s.RoundsMin + } else if rounds > s.RoundsMax { + rounds = s.RoundsMax + } + + saltLen := (length * 6 / 8) + if (length*6)%8 != 0 { + saltLen += 1 + } + salt := make([]byte, saltLen) + rand.Read(salt) + + roundsText := "" + if rounds != s.RoundsDefault { + roundsText = "rounds=" + strconv.Itoa(rounds) + } + + out := make([]byte, len(s.MagicPrefix)+len(roundsText)+length) + copy(out, s.MagicPrefix) + copy(out[len(s.MagicPrefix):], []byte(roundsText)) + copy(out[len(s.MagicPrefix)+len(roundsText):], Base64_24Bit(salt)) + return out +} diff --git a/vendor/github.com/tredoe/osutil/user/crypt/crypt.go b/vendor/github.com/tredoe/osutil/user/crypt/crypt.go new file mode 100644 index 000000000..5ded2da8c --- /dev/null +++ b/vendor/github.com/tredoe/osutil/user/crypt/crypt.go @@ -0,0 +1,108 @@ +// Copyright 2013, Jonas mg +// All rights reserved. +// +// Use of this source code is governed by a BSD-style license +// that can be found in the LICENSE file. + +// Package crypt provides interface for password crypt functions and collects +// common constants. +package crypt + +import ( + "errors" + "strings" + + "github.com/tredoe/osutil/user/crypt/common" +) + +var ErrKeyMismatch = errors.New("hashed value is not the hash of the given password") + +// Crypter is the common interface implemented by all crypt functions. +type Crypter interface { + // Generate performs the hashing algorithm, returning a full hash suitable + // for storage and later password verification. + // + // If the salt is empty, a randomly-generated salt will be generated with a + // length of SaltLenMax and number RoundsDefault of rounds. + // + // Any error only can be got when the salt argument is not empty. + Generate(key, salt []byte) (string, error) + + // Verify compares a hashed key with its possible key equivalent. + // Returns nil on success, or an error on failure; if the hashed key is + // diffrent, the error is "ErrKeyMismatch". + Verify(hashedKey string, key []byte) error + + // Cost returns the hashing cost (in rounds) used to create the given hashed + // key. + // + // When, in the future, the hashing cost of a key needs to be increased in + // order to adjust for greater computational power, this function allows one + // to establish which keys need to be updated. + // + // The algorithms based in MD5-crypt use a fixed value of rounds. + Cost(hashedKey string) (int, error) + + // SetSalt sets a different salt. It is used to easily create derivated + // algorithms, i.e. "apr1_crypt" from "md5_crypt". + SetSalt(salt common.Salt) +} + +// Crypt identifies a crypt function that is implemented in another package. +type Crypt uint + +const ( + APR1 Crypt = iota + 1 // import "github.com/tredoe/osutil/user/crypt/apr1_crypt" + MD5 // import "github.com/tredoe/osutil/user/crypt/md5_crypt" + SHA256 // import "github.com/tredoe/osutil/user/crypt/sha256_crypt" + SHA512 // import "github.com/tredoe/osutil/user/crypt/sha512_crypt" + maxCrypt +) + +var cryptPrefixes = make([]string, maxCrypt) + +var crypts = make([]func() Crypter, maxCrypt) + +// RegisterCrypt registers a function that returns a new instance of the given +// crypt function. This is intended to be called from the init function in +// packages that implement crypt functions. +func RegisterCrypt(c Crypt, f func() Crypter, prefix string) { + if c >= maxCrypt { + panic("crypt: RegisterHash of unknown crypt function") + } + crypts[c] = f + cryptPrefixes[c] = prefix +} + +// New returns a new crypter. +func New(c Crypt) Crypter { + f := crypts[c] + if f != nil { + return f() + } + panic("crypt: requested crypt function is unavailable") +} + +// NewFromHash returns a new Crypter using the prefix in the given hashed key. +func NewFromHash(hashedKey string) Crypter { + var f func() Crypter + + if strings.HasPrefix(hashedKey, cryptPrefixes[SHA512]) { + f = crypts[SHA512] + } else if strings.HasPrefix(hashedKey, cryptPrefixes[SHA256]) { + f = crypts[SHA256] + } else if strings.HasPrefix(hashedKey, cryptPrefixes[MD5]) { + f = crypts[MD5] + } else if strings.HasPrefix(hashedKey, cryptPrefixes[APR1]) { + f = crypts[APR1] + } else { + toks := strings.SplitN(hashedKey, "$", 3) + prefix := "$" + toks[1] + "$" + panic("crypt: unknown cryp function from prefix: " + prefix) + } + + if f != nil { + return f() + } + panic("crypt: requested cryp function is unavailable") +} diff --git a/vendor/github.com/tredoe/osutil/user/crypt/md5_crypt/md5_crypt.go b/vendor/github.com/tredoe/osutil/user/crypt/md5_crypt/md5_crypt.go new file mode 100644 index 000000000..33091c8cc --- /dev/null +++ b/vendor/github.com/tredoe/osutil/user/crypt/md5_crypt/md5_crypt.go @@ -0,0 +1,166 @@ +// Copyright 2012, Jeramey Crawford +// Copyright 2013, Jonas mg +// All rights reserved. +// +// Use of this source code is governed by a BSD-style license +// that can be found in the LICENSE file. + +// Package md5_crypt implements the standard Unix MD5-crypt algorithm created by +// Poul-Henning Kamp for FreeBSD. +package md5_crypt + +import ( + "bytes" + "crypto/md5" + + "github.com/tredoe/osutil/user/crypt" + "github.com/tredoe/osutil/user/crypt/common" +) + +func init() { + crypt.RegisterCrypt(crypt.MD5, New, MagicPrefix) +} + +// NOTE: Cisco IOS only allows salts of length 4. + +const ( + MagicPrefix = "$1$" + SaltLenMin = 1 // Real minimum is 0, but that isn't useful. + SaltLenMax = 8 + RoundsDefault = 1000 +) + +type crypter struct{ Salt common.Salt } + +// New returns a new crypt.Crypter computing the MD5-crypt password hashing. +func New() crypt.Crypter { + return &crypter{GetSalt()} +} + +func (c *crypter) Generate(key, salt []byte) (string, error) { + if len(salt) == 0 { + salt = c.Salt.Generate(SaltLenMax) + } + if !bytes.HasPrefix(salt, c.Salt.MagicPrefix) { + return "", common.ErrSaltPrefix + } + + saltToks := bytes.Split(salt, []byte{'$'}) + + if len(saltToks) < 3 { + return "", common.ErrSaltFormat + } else { + salt = saltToks[2] + } + if len(salt) > 8 { + salt = salt[0:8] + } + + // Compute alternate MD5 sum with input KEY, SALT, and KEY. + Alternate := md5.New() + Alternate.Write(key) + Alternate.Write(salt) + Alternate.Write(key) + AlternateSum := Alternate.Sum(nil) // 16 bytes + + A := md5.New() + A.Write(key) + A.Write(c.Salt.MagicPrefix) + A.Write(salt) + // Add for any character in the key one byte of the alternate sum. + i := len(key) + for ; i > 16; i -= 16 { + A.Write(AlternateSum) + } + A.Write(AlternateSum[0:i]) + + // The original implementation now does something weird: + // For every 1 bit in the key, the first 0 is added to the buffer + // For every 0 bit, the first character of the key + // This does not seem to be what was intended but we have to follow this to + // be compatible. + for i = len(key); i > 0; i >>= 1 { + if (i & 1) == 0 { + A.Write(key[0:1]) + } else { + A.Write([]byte{0}) + } + } + Csum := A.Sum(nil) + + // In fear of password crackers here comes a quite long loop which just + // processes the output of the previous round again. + // We cannot ignore this here. + for i = 0; i < RoundsDefault; i++ { + C := md5.New() + + // Add key or last result. + if (i & 1) != 0 { + C.Write(key) + } else { + C.Write(Csum) + } + // Add salt for numbers not divisible by 3. + if (i % 3) != 0 { + C.Write(salt) + } + // Add key for numbers not divisible by 7. + if (i % 7) != 0 { + C.Write(key) + } + // Add key or last result. + if (i & 1) == 0 { + C.Write(key) + } else { + C.Write(Csum) + } + + Csum = C.Sum(nil) + } + + out := make([]byte, 0, 23+len(c.Salt.MagicPrefix)+len(salt)) + out = append(out, c.Salt.MagicPrefix...) + out = append(out, salt...) + out = append(out, '$') + out = append(out, common.Base64_24Bit([]byte{ + Csum[12], Csum[6], Csum[0], + Csum[13], Csum[7], Csum[1], + Csum[14], Csum[8], Csum[2], + Csum[15], Csum[9], Csum[3], + Csum[5], Csum[10], Csum[4], + Csum[11], + })...) + + // Clean sensitive data. + A.Reset() + Alternate.Reset() + for i = 0; i < len(AlternateSum); i++ { + AlternateSum[i] = 0 + } + + return string(out), nil +} + +func (c *crypter) Verify(hashedKey string, key []byte) error { + newHash, err := c.Generate(key, []byte(hashedKey)) + if err != nil { + return err + } + if newHash != hashedKey { + return crypt.ErrKeyMismatch + } + return nil +} + +func (c *crypter) Cost(hashedKey string) (int, error) { return RoundsDefault, nil } + +func (c *crypter) SetSalt(salt common.Salt) { c.Salt = salt } + +func GetSalt() common.Salt { + return common.Salt{ + MagicPrefix: []byte(MagicPrefix), + SaltLenMin: SaltLenMin, + SaltLenMax: SaltLenMax, + RoundsDefault: RoundsDefault, + } +} diff --git a/vendor/github.com/tredoe/osutil/user/crypt/sha256_crypt/sha256_crypt.go b/vendor/github.com/tredoe/osutil/user/crypt/sha256_crypt/sha256_crypt.go new file mode 100644 index 000000000..fe30746d9 --- /dev/null +++ b/vendor/github.com/tredoe/osutil/user/crypt/sha256_crypt/sha256_crypt.go @@ -0,0 +1,243 @@ +// Copyright 2012, Jeramey Crawford +// Copyright 2013, Jonas mg +// All rights reserved. +// +// Use of this source code is governed by a BSD-style license +// that can be found in the LICENSE file. + +// Package sha256_crypt implements Ulrich Drepper's SHA256-crypt password +// hashing algorithm. +// +// The specification for this algorithm can be found here: +// http://www.akkadia.org/drepper/SHA-crypt.txt +package sha256_crypt + +import ( + "bytes" + "crypto/sha256" + "strconv" + + "github.com/tredoe/osutil/user/crypt" + "github.com/tredoe/osutil/user/crypt/common" +) + +func init() { + crypt.RegisterCrypt(crypt.SHA256, New, MagicPrefix) +} + +const ( + MagicPrefix = "$5$" + SaltLenMin = 1 + SaltLenMax = 16 + RoundsMin = 1000 + RoundsMax = 999999999 + RoundsDefault = 5000 +) + +var _rounds = []byte("rounds=") + +type crypter struct{ Salt common.Salt } + +// New returns a new crypt.Crypter computing the SHA256-crypt password hashing. +func New() crypt.Crypter { + return &crypter{GetSalt()} +} + +func (c *crypter) Generate(key, salt []byte) (string, error) { + var rounds int + var isRoundsDef bool + + if len(salt) == 0 { + salt = c.Salt.GenerateWRounds(SaltLenMax, RoundsDefault) + } + if !bytes.HasPrefix(salt, c.Salt.MagicPrefix) { + return "", common.ErrSaltPrefix + } + + saltToks := bytes.Split(salt, []byte{'$'}) + if len(saltToks) < 3 { + return "", common.ErrSaltFormat + } + + if bytes.HasPrefix(saltToks[2], _rounds) { + isRoundsDef = true + pr, err := strconv.ParseInt(string(saltToks[2][7:]), 10, 32) + if err != nil { + return "", common.ErrSaltRounds + } + rounds = int(pr) + if rounds < RoundsMin { + rounds = RoundsMin + } else if rounds > RoundsMax { + rounds = RoundsMax + } + salt = saltToks[3] + } else { + rounds = RoundsDefault + salt = saltToks[2] + } + + if len(salt) > 16 { + salt = salt[0:16] + } + + // Compute alternate SHA256 sum with input KEY, SALT, and KEY. + Alternate := sha256.New() + Alternate.Write(key) + Alternate.Write(salt) + Alternate.Write(key) + AlternateSum := Alternate.Sum(nil) // 32 bytes + + A := sha256.New() + A.Write(key) + A.Write(salt) + // Add for any character in the key one byte of the alternate sum. + i := len(key) + for ; i > 32; i -= 32 { + A.Write(AlternateSum) + } + A.Write(AlternateSum[0:i]) + + // Take the binary representation of the length of the key and for every add + // the alternate sum, for every 0 the key. + for i = len(key); i > 0; i >>= 1 { + if (i & 1) != 0 { + A.Write(AlternateSum) + } else { + A.Write(key) + } + } + Asum := A.Sum(nil) + + // Start computation of P byte sequence. + P := sha256.New() + // For every character in the password add the entire password. + for i = 0; i < len(key); i++ { + P.Write(key) + } + Psum := P.Sum(nil) + // Create byte sequence P. + Pseq := make([]byte, 0, len(key)) + for i = len(key); i > 32; i -= 32 { + Pseq = append(Pseq, Psum...) + } + Pseq = append(Pseq, Psum[0:i]...) + + // Start computation of S byte sequence. + S := sha256.New() + for i = 0; i < (16 + int(Asum[0])); i++ { + S.Write(salt) + } + Ssum := S.Sum(nil) + // Create byte sequence S. + Sseq := make([]byte, 0, len(salt)) + for i = len(salt); i > 32; i -= 32 { + Sseq = append(Sseq, Ssum...) + } + Sseq = append(Sseq, Ssum[0:i]...) + + Csum := Asum + + // Repeatedly run the collected hash value through SHA256 to burn CPU cycles. + for i = 0; i < rounds; i++ { + C := sha256.New() + + // Add key or last result. + if (i & 1) != 0 { + C.Write(Pseq) + } else { + C.Write(Csum) + } + // Add salt for numbers not divisible by 3. + if (i % 3) != 0 { + C.Write(Sseq) + } + // Add key for numbers not divisible by 7. + if (i % 7) != 0 { + C.Write(Pseq) + } + // Add key or last result. + if (i & 1) != 0 { + C.Write(Csum) + } else { + C.Write(Pseq) + } + + Csum = C.Sum(nil) + } + + out := make([]byte, 0, 80) + out = append(out, c.Salt.MagicPrefix...) + if isRoundsDef { + out = append(out, []byte("rounds="+strconv.Itoa(rounds)+"$")...) + } + out = append(out, salt...) + out = append(out, '$') + out = append(out, common.Base64_24Bit([]byte{ + Csum[20], Csum[10], Csum[0], + Csum[11], Csum[1], Csum[21], + Csum[2], Csum[22], Csum[12], + Csum[23], Csum[13], Csum[3], + Csum[14], Csum[4], Csum[24], + Csum[5], Csum[25], Csum[15], + Csum[26], Csum[16], Csum[6], + Csum[17], Csum[7], Csum[27], + Csum[8], Csum[28], Csum[18], + Csum[29], Csum[19], Csum[9], + Csum[30], Csum[31], + })...) + + // Clean sensitive data. + A.Reset() + Alternate.Reset() + P.Reset() + for i = 0; i < len(Asum); i++ { + Asum[i] = 0 + } + for i = 0; i < len(AlternateSum); i++ { + AlternateSum[i] = 0 + } + for i = 0; i < len(Pseq); i++ { + Pseq[i] = 0 + } + + return string(out), nil +} + +func (c *crypter) Verify(hashedKey string, key []byte) error { + newHash, err := c.Generate(key, []byte(hashedKey)) + if err != nil { + return err + } + if newHash != hashedKey { + return crypt.ErrKeyMismatch + } + return nil +} + +func (c *crypter) Cost(hashedKey string) (int, error) { + saltToks := bytes.Split([]byte(hashedKey), []byte{'$'}) + if len(saltToks) < 3 { + return 0, common.ErrSaltFormat + } + + if !bytes.HasPrefix(saltToks[2], _rounds) { + return RoundsDefault, nil + } + roundToks := bytes.Split(saltToks[2], []byte{'='}) + cost, err := strconv.ParseInt(string(roundToks[1]), 10, 0) + return int(cost), err +} + +func (c *crypter) SetSalt(salt common.Salt) { c.Salt = salt } + +func GetSalt() common.Salt { + return common.Salt{ + MagicPrefix: []byte(MagicPrefix), + SaltLenMin: SaltLenMin, + SaltLenMax: SaltLenMax, + RoundsDefault: RoundsDefault, + RoundsMin: RoundsMin, + RoundsMax: RoundsMax, + } +} diff --git a/vendor/github.com/tredoe/osutil/user/crypt/sha512_crypt/sha512_crypt.go b/vendor/github.com/tredoe/osutil/user/crypt/sha512_crypt/sha512_crypt.go new file mode 100644 index 000000000..fd55e8812 --- /dev/null +++ b/vendor/github.com/tredoe/osutil/user/crypt/sha512_crypt/sha512_crypt.go @@ -0,0 +1,254 @@ +// Copyright 2012, Jeramey Crawford +// Copyright 2013, Jonas mg +// All rights reserved. +// +// Use of this source code is governed by a BSD-style license +// that can be found in the LICENSE file. + +// Package sha512_crypt implements Ulrich Drepper's SHA512-crypt password +// hashing algorithm. +// +// The specification for this algorithm can be found here: +// http://www.akkadia.org/drepper/SHA-crypt.txt +package sha512_crypt + +import ( + "bytes" + "crypto/sha512" + "strconv" + + "github.com/tredoe/osutil/user/crypt" + "github.com/tredoe/osutil/user/crypt/common" +) + +func init() { + crypt.RegisterCrypt(crypt.SHA512, New, MagicPrefix) +} + +const ( + MagicPrefix = "$6$" + SaltLenMin = 1 + SaltLenMax = 16 + RoundsMin = 1000 + RoundsMax = 999999999 + RoundsDefault = 5000 +) + +var _rounds = []byte("rounds=") + +type crypter struct{ Salt common.Salt } + +// New returns a new crypt.Crypter computing the SHA512-crypt password hashing. +func New() crypt.Crypter { + return &crypter{GetSalt()} +} + +func (c *crypter) Generate(key, salt []byte) (string, error) { + var rounds int + var isRoundsDef bool + + if len(salt) == 0 { + salt = c.Salt.GenerateWRounds(SaltLenMax, RoundsDefault) + } + if !bytes.HasPrefix(salt, c.Salt.MagicPrefix) { + return "", common.ErrSaltPrefix + } + + saltToks := bytes.Split(salt, []byte{'$'}) + if len(saltToks) < 3 { + return "", common.ErrSaltFormat + } + + if bytes.HasPrefix(saltToks[2], _rounds) { + isRoundsDef = true + pr, err := strconv.ParseInt(string(saltToks[2][7:]), 10, 32) + if err != nil { + return "", common.ErrSaltRounds + } + rounds = int(pr) + if rounds < RoundsMin { + rounds = RoundsMin + } else if rounds > RoundsMax { + rounds = RoundsMax + } + salt = saltToks[3] + } else { + rounds = RoundsDefault + salt = saltToks[2] + } + + if len(salt) > SaltLenMax { + salt = salt[0:SaltLenMax] + } + + // Compute alternate SHA512 sum with input KEY, SALT, and KEY. + Alternate := sha512.New() + Alternate.Write(key) + Alternate.Write(salt) + Alternate.Write(key) + AlternateSum := Alternate.Sum(nil) // 64 bytes + + A := sha512.New() + A.Write(key) + A.Write(salt) + // Add for any character in the key one byte of the alternate sum. + i := len(key) + for ; i > 64; i -= 64 { + A.Write(AlternateSum) + } + A.Write(AlternateSum[0:i]) + + // Take the binary representation of the length of the key and for every add + // the alternate sum, for every 0 the key. + for i = len(key); i > 0; i >>= 1 { + if (i & 1) != 0 { + A.Write(AlternateSum) + } else { + A.Write(key) + } + } + Asum := A.Sum(nil) + + // Start computation of P byte sequence. + P := sha512.New() + // For every character in the password add the entire password. + for i = 0; i < len(key); i++ { + P.Write(key) + } + Psum := P.Sum(nil) + // Create byte sequence P. + Pseq := make([]byte, 0, len(key)) + for i = len(key); i > 64; i -= 64 { + Pseq = append(Pseq, Psum...) + } + Pseq = append(Pseq, Psum[0:i]...) + + // Start computation of S byte sequence. + S := sha512.New() + for i = 0; i < (16 + int(Asum[0])); i++ { + S.Write(salt) + } + Ssum := S.Sum(nil) + // Create byte sequence S. + Sseq := make([]byte, 0, len(salt)) + for i = len(salt); i > 64; i -= 64 { + Sseq = append(Sseq, Ssum...) + } + Sseq = append(Sseq, Ssum[0:i]...) + + Csum := Asum + + // Repeatedly run the collected hash value through SHA512 to burn CPU cycles. + for i = 0; i < rounds; i++ { + C := sha512.New() + + // Add key or last result. + if (i & 1) != 0 { + C.Write(Pseq) + } else { + C.Write(Csum) + } + // Add salt for numbers not divisible by 3. + if (i % 3) != 0 { + C.Write(Sseq) + } + // Add key for numbers not divisible by 7. + if (i % 7) != 0 { + C.Write(Pseq) + } + // Add key or last result. + if (i & 1) != 0 { + C.Write(Csum) + } else { + C.Write(Pseq) + } + + Csum = C.Sum(nil) + } + + out := make([]byte, 0, 123) + out = append(out, c.Salt.MagicPrefix...) + if isRoundsDef { + out = append(out, []byte("rounds="+strconv.Itoa(rounds)+"$")...) + } + out = append(out, salt...) + out = append(out, '$') + out = append(out, common.Base64_24Bit([]byte{ + Csum[42], Csum[21], Csum[0], + Csum[1], Csum[43], Csum[22], + Csum[23], Csum[2], Csum[44], + Csum[45], Csum[24], Csum[3], + Csum[4], Csum[46], Csum[25], + Csum[26], Csum[5], Csum[47], + Csum[48], Csum[27], Csum[6], + Csum[7], Csum[49], Csum[28], + Csum[29], Csum[8], Csum[50], + Csum[51], Csum[30], Csum[9], + Csum[10], Csum[52], Csum[31], + Csum[32], Csum[11], Csum[53], + Csum[54], Csum[33], Csum[12], + Csum[13], Csum[55], Csum[34], + Csum[35], Csum[14], Csum[56], + Csum[57], Csum[36], Csum[15], + Csum[16], Csum[58], Csum[37], + Csum[38], Csum[17], Csum[59], + Csum[60], Csum[39], Csum[18], + Csum[19], Csum[61], Csum[40], + Csum[41], Csum[20], Csum[62], + Csum[63], + })...) + + // Clean sensitive data. + A.Reset() + Alternate.Reset() + P.Reset() + for i = 0; i < len(Asum); i++ { + Asum[i] = 0 + } + for i = 0; i < len(AlternateSum); i++ { + AlternateSum[i] = 0 + } + for i = 0; i < len(Pseq); i++ { + Pseq[i] = 0 + } + + return string(out), nil +} + +func (c *crypter) Verify(hashedKey string, key []byte) error { + newHash, err := c.Generate(key, []byte(hashedKey)) + if err != nil { + return err + } + if newHash != hashedKey { + return crypt.ErrKeyMismatch + } + return nil +} + +func (c *crypter) Cost(hashedKey string) (int, error) { + saltToks := bytes.Split([]byte(hashedKey), []byte{'$'}) + if len(saltToks) < 3 { + return 0, common.ErrSaltFormat + } + + if !bytes.HasPrefix(saltToks[2], _rounds) { + return RoundsDefault, nil + } + roundToks := bytes.Split(saltToks[2], []byte{'='}) + cost, err := strconv.ParseInt(string(roundToks[1]), 10, 0) + return int(cost), err +} + +func (c *crypter) SetSalt(salt common.Salt) { c.Salt = salt } + +func GetSalt() common.Salt { + return common.Salt{ + MagicPrefix: []byte(MagicPrefix), + SaltLenMin: SaltLenMin, + SaltLenMax: SaltLenMax, + RoundsDefault: RoundsDefault, + RoundsMin: RoundsMin, + RoundsMax: RoundsMax, + } +} diff --git a/vendor/vendor.json b/vendor/vendor.json index 40784e0af..40cee024a 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -412,6 +412,60 @@ "revision": "a0006b13c722f7f12368c00a3d3c2ae8a999a0c6", "revisionTime": "2017-07-14T08:24:55Z" }, + { + "checksumSHA1": "+bqkymIDXrOgmsuUHjWsdpcwn+8=", + "path": "github.com/starkandwayne/goutils/ansi", + "revision": "d28cacc19462737f05e67bfee385190ffa593d65", + "revisionTime": "2017-05-30T16:16:10Z" + }, + { + "checksumSHA1": "a+CBFnEuiiR6Qp/Y/2NM6K/mlBE=", + "path": "github.com/starkandwayne/goutils/tree", + "revision": "d28cacc19462737f05e67bfee385190ffa593d65", + "revisionTime": "2017-05-30T16:16:10Z" + }, + { + "checksumSHA1": "b66cLatMBdcrTuAUeKQguEoBmHQ=", + "path": "github.com/starkandwayne/safe/prompt", + "revision": "3cf6c887f8adf4230e6069f4ea4266d05917ea8a", + "revisionTime": "2018-06-09T13:39:22Z" + }, + { + "checksumSHA1": "bhzxyrmHJFo+e3pe6H2B9WCwGsU=", + "path": "github.com/starkandwayne/safe/vault", + "revision": "3cf6c887f8adf4230e6069f4ea4266d05917ea8a", + "revisionTime": "2018-06-09T13:39:22Z" + }, + { + "checksumSHA1": "MFwXW+d+HJR+bLmIjhSV6XnDs9A=", + "path": "github.com/tredoe/osutil/user/crypt", + "revision": "7d3ee1afa71c90fd1514c8f557ae6c5f414208eb", + "revisionTime": "2016-11-30T13:35:08Z" + }, + { + "checksumSHA1": "QEuwxVISS6InjeaZiEJPwgAE24A=", + "path": "github.com/tredoe/osutil/user/crypt/common", + "revision": "7d3ee1afa71c90fd1514c8f557ae6c5f414208eb", + "revisionTime": "2016-11-30T13:35:08Z" + }, + { + "checksumSHA1": "23JmRA3tf9pKWNQZKqjfaDHqPv0=", + "path": "github.com/tredoe/osutil/user/crypt/md5_crypt", + "revision": "7d3ee1afa71c90fd1514c8f557ae6c5f414208eb", + "revisionTime": "2016-11-30T13:35:08Z" + }, + { + "checksumSHA1": "+vU+2y6sL7lgRzp58njnRayirnU=", + "path": "github.com/tredoe/osutil/user/crypt/sha256_crypt", + "revision": "7d3ee1afa71c90fd1514c8f557ae6c5f414208eb", + "revisionTime": "2016-11-30T13:35:08Z" + }, + { + "checksumSHA1": "LIBKbI2B9xyUQ49RVmyO5aisGDo=", + "path": "github.com/tredoe/osutil/user/crypt/sha512_crypt", + "revision": "7d3ee1afa71c90fd1514c8f557ae6c5f414208eb", + "revisionTime": "2016-11-30T13:35:08Z" + }, { "checksumSHA1": "z2kAtVle4NFV2OExI85fZoTcsI4=", "path": "github.com/ulikunitz/xz",