added encryption support

This commit is contained in:
2024-12-19 10:37:21 +01:00
parent a515d4bb5e
commit 1b9ec48396
9 changed files with 246 additions and 25 deletions

View File

@@ -15,7 +15,14 @@ reasons:
anymore. The badger file format on the other hand changes very anymore. The badger file format on the other hand changes very
often, which is not good for a tool intended to be used for many often, which is not good for a tool intended to be used for many
years. years.
- more features - more features:
- better STDIN + pipe support
- supports JSON output
- supports more verbose tabular output
- filtering using regular expressions
- tagging
- filtering using tags
- encryption of entries
**anydb** can do all the things you can do with skate: **anydb** can do all the things you can do with skate:
@@ -83,6 +90,11 @@ anydb export -o backup.json
# and import it somewhere else # and import it somewhere else
anydb import -r backup.json anydb import -r backup.json
# you can encrypt entries. anydb asks for a passphrase
# and will do the same when you retrieve the key using the
# get command.
anydb set mypassword -e
# it comes with a manpage builtin # it comes with a manpage builtin
anydb man anydb man
``` ```
@@ -98,18 +110,23 @@ There are multiple ways to install **anydb**:
- The release page also contains a tarball for every supported platform. Unpack it - The release page also contains a tarball for every supported platform. Unpack it
to some temporary directory, extract it and execute the following command inside: to some temporary directory, extract it and execute the following command inside:
``` ```shell
sudo make install sudo make install
``` ```
- You can also install from source. Issue the following commands in your shell: - You can also install from source. Issue the following commands in your shell:
``` ```shell
git clone https://github.com/TLINDEN/anydb.git git clone https://github.com/TLINDEN/anydb.git
cd anydb cd anydb
make make
sudo make install sudo make install
``` ```
- Or, if you have the GO toolkit installed, just install it like this:
```shell
go install github.com/tlinden/anydb@latest
```
If you do not find a binary release for your platform, please don't If you do not find a binary release for your platform, please don't
hesitate to ask me about it, I'll add it. hesitate to ask me about it, I'll add it.

View File

@@ -14,6 +14,7 @@ type DbAttr struct {
Args []string Args []string
Tags []string Tags []string
File string File string
Encrypted bool
} }
func (attr *DbAttr) ParseKV() error { func (attr *DbAttr) ParseKV() error {

157
app/crypto.go Normal file
View File

@@ -0,0 +1,157 @@
package app
import (
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"os"
"syscall"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/chacha20poly1305"
"golang.org/x/term"
)
const (
ArgonMem uint32 = 64 * 1024
ArgonIter uint32 = 5
ArgonParallel uint8 = 2
ArgonSaltLen int = 16
ArgonKeyLen uint32 = 32
B64SaltLen int = 22
)
type Key struct {
Salt []byte
Key []byte
}
// called from interactive thread, hides input and returns clear text
// password
func AskForPassword() ([]byte, error) {
fmt.Fprint(os.Stderr, "Password: ")
pass, err := term.ReadPassword(int(syscall.Stdin))
if err != nil {
return nil, err
}
fmt.Fprintln(os.Stderr)
return pass, nil
}
// We're using the Argon2id key derivation algorithm to derive a
// secure key from the given password. This is important, because
// users might use unsecure passwords. The resulting encrypted data
// might of course easily be decrypted using brute force methods if a
// weak password was used, but that would cost, because of the key
// derivation. It does several rounds of hash calculations which take
// a considerable amount of cpu time. For our legal user that's no
// problem because it's being executed only once, but an attacker has
// to do it in a forever loop, which will take a lot of time.
func DeriveKey(password []byte, salt []byte) (*Key, error) {
if salt == nil {
// none given, new password
newsalt, err := GetRandom(ArgonSaltLen, ArgonSaltLen)
if err != nil {
return nil, err
}
salt = newsalt
}
hash := argon2.IDKey(
[]byte(password), salt,
ArgonIter,
ArgonMem,
ArgonParallel,
ArgonKeyLen,
)
return &Key{Key: hash, Salt: salt}, nil
}
// Retrieve a random chunk of given size
func GetRandom(size int, capacity int) ([]byte, error) {
buf := make([]byte, size, capacity)
_, err := rand.Read(buf)
if err != nil {
return nil, err
}
return buf, nil
}
// Encrypt clear text given in attr using ChaCha20 and auhtenticate
// using the mac Poly1305. The cipher text will be put into attr, thus
// modifying it.
//
// The cipher text consists of:
// base64(password-salt) + base64(12 byte nonce + ciphertext + 16 byte mac)
func Encrypt(pass []byte, attr *DbAttr) error {
key, err := DeriveKey(pass, nil)
if err != nil {
return err
}
aead, err := chacha20poly1305.New(key.Key)
if err != nil {
return err
}
var plain []byte
if attr.Val != "" {
plain = []byte(attr.Val)
} else {
plain = attr.Bin
}
total := aead.NonceSize() + len(plain) + aead.Overhead()
nonce, err := GetRandom(aead.NonceSize(), total)
if err != nil {
return err
}
cipher := aead.Seal(nonce, nonce, plain, nil)
attr.Bin = nil
attr.Val = base64.RawStdEncoding.EncodeToString(key.Salt) +
base64.RawStdEncoding.EncodeToString(cipher)
attr.Encrypted = true
return nil
}
// Do the reverse
func Decrypt(pass []byte, cipherb64 string) ([]byte, error) {
salt, err := base64.RawStdEncoding.Strict().DecodeString(cipherb64[0:B64SaltLen])
if err != nil {
return nil, err
}
key, err := DeriveKey(pass, salt)
if err != nil {
return nil, err
}
cipher, err := base64.RawStdEncoding.Strict().DecodeString(cipherb64[B64SaltLen:])
if err != nil {
return nil, err
}
aead, err := chacha20poly1305.New(key.Key)
if err != nil {
return nil, err
}
if len(cipher) < aead.NonceSize() {
return nil, errors.New("ciphertext too short")
}
nonce, ciphertext := cipher[:aead.NonceSize()], cipher[aead.NonceSize():]
return aead.Open(nil, nonce, ciphertext, nil)
}

View File

@@ -23,6 +23,7 @@ type DbEntry struct {
Id string `json:"id"` Id string `json:"id"`
Key string `json:"key"` Key string `json:"key"`
Value string `json:"value"` Value string `json:"value"`
Encrypted bool `json:"encrypted"`
Bin []byte `json:"bin"` Bin []byte `json:"bin"`
Tags []string `json:"tags"` Tags []string `json:"tags"`
Created time.Time `json:"created"` Created time.Time `json:"created"`
@@ -130,15 +131,12 @@ func (db *DB) Set(attr *DbAttr) error {
} }
defer db.Close() defer db.Close()
if err := attr.ParseKV(); err != nil {
return err
}
entry := DbEntry{ entry := DbEntry{
Key: attr.Key, Key: attr.Key,
Value: attr.Val, Value: attr.Val,
Bin: attr.Bin, Bin: attr.Bin,
Tags: attr.Tags, Tags: attr.Tags,
Encrypted: attr.Encrypted,
Created: time.Now(), Created: time.Now(),
} }

View File

@@ -9,6 +9,7 @@ type Config struct {
Dbfile string Dbfile string
Mode string // wide, table, yaml, json Mode string // wide, table, yaml, json
NoHeaders bool NoHeaders bool
Encrypt bool
DB *app.DB DB *app.DB
File string File string
Tags []string Tags []string

View File

@@ -7,6 +7,7 @@ import (
"os" "os"
"os/exec" "os/exec"
"strings" "strings"
"unicode/utf8"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/tlinden/anydb/app" "github.com/tlinden/anydb/app"
@@ -40,10 +41,29 @@ func Set(conf *cfg.Config) *cobra.Command {
attr.Tags = strings.Split(attr.Tags[0], ",") attr.Tags = strings.Split(attr.Tags[0], ",")
} }
// check if value given as file or via stdin and fill attr accordingly
if err := attr.ParseKV(); err != nil {
return err
}
// encrypt?
if conf.Encrypt {
pass, err := app.AskForPassword()
if err != nil {
return err
}
err = app.Encrypt(pass, &attr)
if err != nil {
return err
}
}
return conf.DB.Set(&attr) return conf.DB.Set(&attr)
}, },
} }
cmd.PersistentFlags().BoolVarP(&conf.Encrypt, "encrypt", "e", false, "encrypt value")
cmd.PersistentFlags().StringVarP(&attr.File, "file", "r", "", "Filename or - for STDIN") cmd.PersistentFlags().StringVarP(&attr.File, "file", "r", "", "Filename or - for STDIN")
cmd.PersistentFlags().StringArrayVarP(&attr.Tags, "tags", "t", nil, "tags, multiple allowed") cmd.PersistentFlags().StringArrayVarP(&attr.Tags, "tags", "t", nil, "tags, multiple allowed")
@@ -80,6 +100,26 @@ func Get(conf *cfg.Config) *cobra.Command {
return err return err
} }
if entry.Encrypted {
pass, err := app.AskForPassword()
if err != nil {
return err
}
clear, err := app.Decrypt(pass, entry.Value)
if err != nil {
return err
}
if utf8.ValidString(string(clear)) {
entry.Value = string(clear)
} else {
entry.Bin = clear
}
entry.Encrypted = false
}
return output.Print(os.Stdout, conf, &attr, entry) return output.Print(os.Stdout, conf, &attr, entry)
}, },
} }

1
go.mod
View File

@@ -12,6 +12,7 @@ require (
github.com/spf13/cobra v1.8.1 // indirect github.com/spf13/cobra v1.8.1 // indirect
github.com/spf13/pflag v1.0.5 // indirect github.com/spf13/pflag v1.0.5 // indirect
go.etcd.io/bbolt v1.3.11 // indirect go.etcd.io/bbolt v1.3.11 // indirect
golang.org/x/crypto v0.31.0 // indirect
golang.org/x/sys v0.28.0 // indirect golang.org/x/sys v0.28.0 // indirect
golang.org/x/term v0.27.0 // indirect golang.org/x/term v0.27.0 // indirect
golang.org/x/tools v0.22.0 // indirect golang.org/x/tools v0.22.0 // indirect

2
go.sum
View File

@@ -34,6 +34,8 @@ go.etcd.io/bbolt v1.3.4/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ=
go.etcd.io/bbolt v1.3.11 h1:yGEzV1wPz2yVCLsD8ZAiGHhHVlczyC9d1rP43/VCRJ0= go.etcd.io/bbolt v1.3.11 h1:yGEzV1wPz2yVCLsD8ZAiGHhHVlczyC9d1rP43/VCRJ0=
go.etcd.io/bbolt v1.3.11/go.mod h1:dksAq7YMXoljX0xu6VF5DMZGbhYYoLUalEiSySYAS4I= go.etcd.io/bbolt v1.3.11/go.mod h1:dksAq7YMXoljX0xu6VF5DMZGbhYYoLUalEiSySYAS4I=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20191105084925-a882066a44e0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191105084925-a882066a44e0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=

View File

@@ -54,8 +54,12 @@ func ListTable(writer io.Writer, conf *cfg.Config, entries app.DbEntries) error
for _, row := range entries { for _, row := range entries {
size := len(row.Value) size := len(row.Value)
if row.Encrypted {
row.Value = "<encrypted-content>"
}
if len(row.Bin) > 0 { if len(row.Bin) > 0 {
row.Value = "binary-content" row.Value = "<binary-content>"
size = len(row.Bin) size = len(row.Bin)
} }