Ejemplo n.º 1
0
func ResolveStringValue(s StringSource) (string, error) {
	var value string
	switch {
	case len(s.Value) > 0:
		value = s.Value
	case len(s.Env) > 0:
		value = os.Getenv(s.Env)
	case len(s.File) > 0:
		data, err := ioutil.ReadFile(s.File)
		if err != nil {
			return "", err
		}
		value = string(data)
	default:
		value = ""
	}

	if len(s.KeyFile) == 0 {
		// value is cleartext, return
		return value, nil
	}

	keyData, err := ioutil.ReadFile(s.KeyFile)
	if err != nil {
		return "", err
	}

	secretBlock, ok := pemutil.BlockFromBytes([]byte(value), StringSourceEncryptedBlockType)
	if !ok {
		return "", fmt.Errorf("no valid PEM block of type %q found in data", StringSourceEncryptedBlockType)
	}

	keyBlock, ok := pemutil.BlockFromBytes(keyData, StringSourceKeyBlockType)
	if !ok {
		return "", fmt.Errorf("no valid PEM block of type %q found in key", StringSourceKeyBlockType)
	}

	data, err := x509.DecryptPEMBlock(secretBlock, keyBlock.Bytes)
	return string(data), err
}
Ejemplo n.º 2
0
func (o *DecryptOptions) Decrypt() error {
	// Get PEM data block
	var data []byte
	switch {
	case len(o.EncryptedFile) > 0:
		if d, err := ioutil.ReadFile(o.EncryptedFile); err != nil {
			return err
		} else {
			data = d
		}
	case len(o.EncryptedData) > 0:
		data = o.EncryptedData
	case o.EncryptedReader != nil && !util.IsTerminalReader(o.EncryptedReader):
		if d, err := ioutil.ReadAll(o.EncryptedReader); err != nil {
			return err
		} else {
			data = d
		}
	}
	if len(data) == 0 {
		return fmt.Errorf("no input data specified")
	}
	dataBlock, ok := pemutil.BlockFromBytes(data, configapi.StringSourceEncryptedBlockType)
	if !ok {
		return fmt.Errorf("input does not contain a valid PEM block of type %q", configapi.StringSourceEncryptedBlockType)
	}

	// Get password
	keyBlock, ok, err := pemutil.BlockFromFile(o.KeyFile, configapi.StringSourceKeyBlockType)
	if err != nil {
		return err
	}
	if !ok {
		return fmt.Errorf("%s does not contain a valid PEM block of type %q", o.KeyFile, configapi.StringSourceKeyBlockType)
	}
	if len(keyBlock.Bytes) == 0 {
		return fmt.Errorf("%s does not contain a key", o.KeyFile)
	}
	password := keyBlock.Bytes

	// Decrypt
	plaintext, err := x509.DecryptPEMBlock(dataBlock, password)
	if err != nil {
		return err
	}

	// Write decrypted data
	switch {
	case len(o.DecryptedFile) > 0:
		if err := ioutil.WriteFile(o.DecryptedFile, plaintext, os.FileMode(0600)); err != nil {
			return err
		}
	case o.DecryptedWriter != nil:
		fmt.Fprint(o.DecryptedWriter, string(plaintext))
		if util.IsTerminalWriter(o.DecryptedWriter) {
			fmt.Fprintln(o.DecryptedWriter)
		}
	}

	return nil
}