Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for age. #688

Merged
merged 16 commits into from
Sep 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ SOPS: Secrets OPerationS
========================

**sops** is an editor of encrypted files that supports YAML, JSON, ENV, INI and BINARY
formats and encrypts with AWS KMS, GCP KMS, Azure Key Vault and PGP.
formats and encrypts with AWS KMS, GCP KMS, Azure Key Vault, age, and PGP.
(`demo <https://www.youtube.com/watch?v=YTEVyLXFiq0>`_)

.. image:: https://i.imgur.com/X0TM5NI.gif
Expand Down Expand Up @@ -178,6 +178,33 @@ the example files and pgp key provided with the repository::
This last step will decrypt ``example.yaml`` using the test private key.


Encrypting using age
~~~~~~~~~~~~~~~~~~~~

`age <https://age-encryption.org/>`_ is a simple, modern, and secure tool for
encrypting files. It's recommended to use age over PGP, if possible.

You can encrypt a file for one or more age recipients (comma separated) using
the ``--age`` option or the **SOPS_AGE_RECIPIENTS** environment variable:

.. code:: bash

$ sops --age age1yt3tfqlfrwdwx0z0ynwplcr6qxcxfaqycuprpmy89nr83ltx74tqdpszlw test.yaml > test.enc.yaml

When decrypting a file with the corresponding identity, sops will look for a
text file name ``keys.txt`` located in a ``sops`` subdirectory of your user
configuration directory. On Linux, this would be ``$XDG_CONFIG_HOME/sops/keys.txt``.
On macOS, this would be ``$HOME/Library/Application Support/sops/keys.txt``. On
Windows, this would be ``%AppData%\sops\keys.txt``. You can specify the location
of this file manually by setting the environment variable **SOPS_AGE_KEY_FILE**.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is a good middle ground.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1. Good work!


The contents of this key file should be a list of age X25519 identities, one
per line. Lines beginning with ``#`` are considered comments and ignored. Each
identity will be tried in sequence until one is able to decrypt the data.

Encrypting with SSH keys via age is not yet supported by sops.


Encrypting using GCP KMS
~~~~~~~~~~~~~~~~~~~~~~~~
GCP KMS uses `Application Default Credentials
Expand Down
3 changes: 3 additions & 0 deletions age/keys.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# created: 2020-07-18T03:16:47-07:00
# public key: age1yt3tfqlfrwdwx0z0ynwplcr6qxcxfaqycuprpmy89nr83ltx74tqdpszlw
AGE-SECRET-KEY-1NJT5YCS2LWU4V4QAJQ6R4JNU7LXPDX602DZ9NUFANVU5GDTGUWCQ5T59M6
195 changes: 195 additions & 0 deletions age/keysource.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
package age

import (
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"strings"

"filippo.io/age"
"github.com/sirupsen/logrus"
"go.mozilla.org/sops/v3/logging"
)

var log *logrus.Logger

func init() {
log = logging.NewLogger("AGE")
}

const privateKeySizeLimit = 1 << 24 // 16 MiB

// MasterKey is an age key used to encrypt and decrypt sops' data key.
type MasterKey struct {
Identity string // a Bech32-encoded private key
Recipient string // a Bech32-encoded public key
EncryptedKey string // a sops data key encrypted with age

parsedIdentity *age.X25519Identity // a parsed age private key
parsedRecipient *age.X25519Recipient // a parsed age public key
}

// Encrypt takes a sops data key, encrypts it with age and stores the result in the EncryptedKey field.
func (key *MasterKey) Encrypt(datakey []byte) error {
buffer := &bytes.Buffer{}

if key.parsedRecipient == nil {
parsedRecipient, err := parseRecipient(key.Recipient)

if err != nil {
log.WithField("recipient", key.parsedRecipient).Error("Encryption failed")
return err
}

key.parsedRecipient = parsedRecipient
}

w, err := age.Encrypt(buffer, key.parsedRecipient)
if err != nil {
return fmt.Errorf("failed to open file for encrypting sops data key with age: %v", err)
}

if _, err := w.Write(datakey); err != nil {
log.WithField("recipient", key.parsedRecipient).Error("Encryption failed")
return fmt.Errorf("failed to encrypt sops data key with age: %v", err)
}

if err := w.Close(); err != nil {
log.WithField("recipient", key.parsedRecipient).Error("Encryption failed")
return fmt.Errorf("failed to close file for encrypting sops data key with age: %v", err)
}

key.EncryptedKey = buffer.String()

log.WithField("recipient", key.parsedRecipient).Info("Encryption succeeded")

return nil
}

// EncryptIfNeeded encrypts the provided sops' data key and encrypts it if it hasn't been encrypted yet.
func (key *MasterKey) EncryptIfNeeded(datakey []byte) error {
if key.EncryptedKey == "" {
return key.Encrypt(datakey)
}

return nil
}

// EncryptedDataKey returns the encrypted data key this master key holds.
func (key *MasterKey) EncryptedDataKey() []byte {
return []byte(key.EncryptedKey)
}

// SetEncryptedDataKey sets the encrypted data key for this master key.
func (key *MasterKey) SetEncryptedDataKey(enc []byte) {
key.EncryptedKey = string(enc)
}

// Decrypt decrypts the EncryptedKey field with the age identity and returns the result.
func (key *MasterKey) Decrypt() ([]byte, error) {
ageKeyFilePath, ok := os.LookupEnv("SOPS_AGE_KEY_FILE")

if !ok {
userConfigDir, err := os.UserConfigDir()

if err != nil {
return nil, fmt.Errorf("user config directory could not be determined: %v", err)
}

ageKeyFilePath = filepath.Join(userConfigDir, "sops", "age", "keys.txt")
}

ageKeyFile, err := os.Open(ageKeyFilePath)

if err != nil {
return nil, fmt.Errorf("failed to open file: %v", err)
}

defer ageKeyFile.Close()

identities, err := age.ParseIdentities(ageKeyFile)

if err != nil {
return nil, err
}

buffer := &bytes.Buffer{}
reader := bytes.NewReader([]byte(key.EncryptedKey))
r, err := age.Decrypt(reader, identities...)

if err != nil {
return nil, fmt.Errorf("no age identity found in %q that could decrypt the data", ageKeyFilePath)
}

if _, err := io.Copy(buffer, r); err != nil {
return nil, fmt.Errorf("failed to copy decrypted data into bytes.Buffer")
}

return buffer.Bytes(), nil
}

// NeedsRotation returns whether the data key needs to be rotated or not.
func (key *MasterKey) NeedsRotation() bool {
return false
}

// ToString converts the key to a string representation.
func (key *MasterKey) ToString() string {
return key.Recipient
}

// ToMap converts the MasterKey to a map for serialization purposes.
func (key *MasterKey) ToMap() map[string]interface{} {
return map[string]interface{}{"recipient": key.Recipient, "enc": key.EncryptedKey}
}

// MasterKeysFromRecipients takes a comma-separated list of Bech32-encoded public keys and returns a
// slice of new MasterKeys.
func MasterKeysFromRecipients(commaSeparatedRecipients string) ([]*MasterKey, error) {
if commaSeparatedRecipients == "" {
// otherwise Split returns [""] and MasterKeyFromRecipient is unhappy
return make([]*MasterKey, 0), nil
}
recipients := strings.Split(commaSeparatedRecipients, ",")

var keys []*MasterKey

for _, recipient := range recipients {
key, err := MasterKeyFromRecipient(recipient)

if err != nil {
return nil, err
}

keys = append(keys, key)
}

return keys, nil
}

// MasterKeyFromRecipient takes a Bech32-encoded public key and returns a new MasterKey.
func MasterKeyFromRecipient(recipient string) (*MasterKey, error) {
parsedRecipient, err := parseRecipient(recipient)

if err != nil {
return nil, err
}

return &MasterKey{
Recipient: recipient,
parsedRecipient: parsedRecipient,
}, nil
}

// parseRecipient attempts to parse a string containing an encoded age public key
func parseRecipient(recipient string) (*age.X25519Recipient, error) {
parsedRecipient, err := age.ParseX25519Recipient(recipient)

if err != nil {
return nil, fmt.Errorf("failed to parse input as Bech32-encoded age public key: %v", err)
}

return parsedRecipient, nil
}
43 changes: 43 additions & 0 deletions age/keysource_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package age

import (
"os"
"path"
"runtime"
"testing"

"github.com/stretchr/testify/assert"
)

func TestMasterKeysFromRecipientsEmpty(t *testing.T) {
assert := assert.New(t)

commaSeparatedRecipients := ""
recipients, err := MasterKeysFromRecipients(commaSeparatedRecipients)

assert.NoError(err)

assert.Equal(recipients, make([]*MasterKey,0))
}

func TestAge(t *testing.T) {
assert := assert.New(t)

key, err := MasterKeyFromRecipient("age1yt3tfqlfrwdwx0z0ynwplcr6qxcxfaqycuprpmy89nr83ltx74tqdpszlw")

assert.NoError(err)
assert.Equal("age1yt3tfqlfrwdwx0z0ynwplcr6qxcxfaqycuprpmy89nr83ltx74tqdpszlw", key.ToString())

dataKey := []byte("abcdefghijklmnopqrstuvwxyz123456")

err = key.Encrypt(dataKey)
assert.NoError(err)

_, filename, _, _ := runtime.Caller(0)
err = os.Setenv("SOPS_AGE_KEY_FILE", path.Join(path.Dir(filename), "keys.txt"))
assert.NoError(err)

decryptedKey, err := key.Decrypt()
assert.NoError(err)
assert.Equal(dataKey, decryptedKey)
}
Loading