Skip to content
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
62 changes: 46 additions & 16 deletions pkg/enpass/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,45 +10,75 @@ import (
"github.com/pkg/errors"
)

// NewItemKey returns a fresh 44-byte item key: a 32-byte AES-256 key followed
// by a 12-byte GCM nonce. Enpass stores this blob in item.key and uses it for
// every sensitive field of that item.
func NewItemKey() ([]byte, error) {
itemKey := make([]byte, 44)
if _, err := rand.Read(itemKey); err != nil {
return nil, errors.Wrap(err, "could not generate random item key")
}

return itemKey, nil
}

// EncryptValue encrypts a plaintext value using AES-256-GCM.
// Returns the hex-encoded ciphertext and the 44-byte key (32-byte AES key + 12-byte nonce).
// The uuid (without dashes) is used as Additional Authenticated Data (AAD).
func EncryptValue(plaintext string, uuid string) (encryptedValue string, itemKey []byte, err error) {
// Generate random 32-byte AES key
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
return "", nil, errors.Wrap(err, "could not generate random key")
itemKey, err = NewItemKey()
if err != nil {
return "", nil, err
}

encryptedValue, err = EncryptValueWithKey(plaintext, uuid, itemKey)
if err != nil {
return "", nil, err
}

// Generate random 12-byte nonce for GCM
nonce := make([]byte, 12)
if _, err := rand.Read(nonce); err != nil {
return "", nil, errors.Wrap(err, "could not generate random nonce")
return encryptedValue, itemKey, nil
}

// EncryptValueWithKey encrypts plaintext with an existing item key.
//
// Enpass keeps one key per item, not one per field: every sensitive row of an
// item is encrypted with the same 32-byte key and 12-byte nonce, which is why
// two fields holding the same value have byte-identical ciphertext. Reusing the
// existing key on update therefore keeps every other sensitive field of the
// item decryptable; generating a new key and storing only the updated field
// would leave the remaining fields encrypted under the old, discarded key.
//
// itemKey must be exactly 44 bytes. The uuid (without dashes) is used as AAD,
// so the ciphertext is bound to the item.
//
// Example: EncryptValueWithKey("hunter2", uuid, existingKey)
func EncryptValueWithKey(plaintext string, uuid string, itemKey []byte) (encryptedValue string, err error) {
if len(itemKey) != 44 {
return "", errors.Errorf("item key must be 44 bytes (32 key + 12 nonce), got %d", len(itemKey))
}

key := itemKey[:32]
nonce := itemKey[32:]

// Create cipher
block, err := aes.NewCipher(key)
if err != nil {
return "", nil, errors.Wrap(err, "could not create cipher")
return "", errors.Wrap(err, "could not create cipher")
}

aesgcm, err := cipher.NewGCM(block)
if err != nil {
return "", nil, errors.Wrap(err, "could not create GCM")
return "", errors.Wrap(err, "could not create GCM")
}

// AAD is the UUID without dashes
aad, err := hex.DecodeString(strings.ReplaceAll(uuid, "-", ""))
if err != nil {
return "", nil, errors.Wrap(err, "could not decode UUID for AAD")
return "", errors.Wrap(err, "could not decode UUID for AAD")
}

// Encrypt (output includes authentication tag)
ciphertextAndTag := aesgcm.Seal(nil, nonce, []byte(plaintext), aad)

// Return hex-encoded ciphertext and key+nonce
encryptedValue = hex.EncodeToString(ciphertextAndTag)
itemKey = append(key, nonce...)

return encryptedValue, itemKey, nil
return hex.EncodeToString(ciphertextAndTag), nil
}
148 changes: 148 additions & 0 deletions pkg/enpass/template.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
package enpass

import (
"crypto/sha1"
"encoding/hex"
"encoding/json"
"net/url"
"strings"
)

const (
// loginCategory is the value Enpass stores in item.category for login items.
// The app writes it in lower case; the previous writer used "Login", which the
// app does not recognise as a built-in category.
loginCategory = "login"

// loginTemplate is the value Enpass stores in item.template for login items.
// It must not be NULL: the macOS app passes this column to strlen() while
// rendering and crashes on a NULL template.
loginTemplate = "login.default"
)

// templateField describes one field slot of the stock login.default template.
//
// The desktop app does not store template definitions in the vault: the
// template/category tables are empty for stock vaults and the definitions ship
// inside the app bundle (templates.json). The app resolves a field's label and
// section grouping by looking up (item.template, itemfield.item_field_uid), so
// a field written with an invented uid has no label to render.
//
// These uids and their order were taken from items written by Enpass 6.12 on
// macOS; they are stable across the 6.x releases we inspected. Fields with a
// high uid (5xxx/6xxx/9xxx) are user-created custom fields: those carry their
// label in itemfield.label and are not part of this list.
//
// A note on the hard-coded layout: the stock template is deliberately kept as a
// constant here rather than looked up, because stock vaults ship an empty
// template/category table — the definitions live in the app bundle, so there is
// nothing in the vault to read at write time. The more future-proof approach is
// to copy the skeleton from an existing item of the same template in the same
// vault (its template-provided slots are exactly the fields with an empty
// label), falling back to this constant only when the vault has no such item.
// That needs a fallback path and a policy for custom fields, so it is left as a
// follow-up rather than folded into this fix.
type templateField struct {
// uid is Enpass's item_field_uid for this slot.
uid int
// fieldType is the itemfield.type value ("username", "password", ...).
fieldType string
// orde is the display order inside the item, starting at 1.
orde int
// sensitive marks fields whose value is AES-GCM encrypted with item.key.
sensitive bool
}

// loginFields is the stock login.default layout, in display order.
var loginFields = []templateField{
{uid: 10, fieldType: "username", orde: 1},
{uid: 12, fieldType: "email", orde: 2},
{uid: 11, fieldType: "password", orde: 3, sensitive: true},
{uid: 13, fieldType: "url", orde: 4},
{uid: 101, fieldType: "section", orde: 5},
{uid: 14, fieldType: "phone", orde: 6},
{uid: 102, fieldType: "totp", orde: 7},
{uid: 15, fieldType: "text", orde: 8},
{uid: 16, fieldType: "text", orde: 9, sensitive: true},
}

// loginFieldByType returns the first stock slot of the given type.
//
// Username, password and url have exactly one slot each, so "first" is
// unambiguous. It returns false for types the login template does not have.
//
// Example: loginFieldByType("password") == templateField{uid: 11, orde: 3, ...}, true
//
// loginFieldByType("nope") == templateField{}, false
func loginFieldByType(fieldType string) (templateField, bool) {
for _, field := range loginFields {
if field.fieldType == fieldType {
return field, true
}
}

return templateField{}, false
}

// loginIcon builds the JSON blob Enpass expects in item.icon for a login item.
//
// The app stores a JSON object, not a plain icon name. A plain string such as
// "card_password" (what the previous writer stored) makes the item render with
// a blank/default icon.
//
// The favicon domain is derived from the item URL so the app can show the site's
// icon; when the URL is empty or unparseable the favicon domain is left empty
// and the generic login icon is used.
//
// Example: loginIcon("https://www.example.com/login")
//
// == `{"fav":"example.com","image":{"file":"misc/login"},"type":1,"uuid":""}`
func loginIcon(rawURL string) string {
favicon := ""
if parsed, err := url.Parse(rawURL); err == nil {
favicon = strings.TrimPrefix(parsed.Hostname(), "www.")
}

icon, err := json.Marshal(map[string]interface{}{
"fav": favicon,
"image": map[string]string{"file": "misc/login"},
"type": 1,
"uuid": "",
})
if err != nil {
// json.Marshal of a map of strings and ints cannot fail; return the
// generic icon rather than panicking if that ever changes.
return `{"fav":"","image":{"file":"misc/login"},"type":1,"uuid":""}`
}

return string(icon)
}

// valueHash returns the SHA-1 hex digest Enpass stores in itemfield.hash.
//
// The app keeps a digest of the plaintext value (passwords included) and uses
// it to detect duplicate/identical passwords. It is empty for empty values.
//
// Example: valueHash("noIdeaata11") == "a3f1...".
func valueHash(value string) string {
if value == "" {
return ""
}

sum := sha1.Sum([]byte(value))

return hex.EncodeToString(sum[:])
}

// valueInitial returns the two leading characters Enpass displays for a
// password field in the item list. It is only used for passwords.
//
// Example: valueInitial("agentpass") == "ag"; valueInitial("") == "".
func valueInitial(value string) string {
runes := []rune(value)
if len(runes) > 2 {
return string(runes[:2])
}

return string(runes)
}
97 changes: 97 additions & 0 deletions pkg/enpass/vaultinfo.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ package enpass
import (
"encoding/json"
"os"
"path/filepath"
"strconv"
"time"

"github.com/pkg/errors"
)
Expand Down Expand Up @@ -36,3 +39,97 @@ func (v *Vault) loadVaultInfo() (VaultInfo, error) {

return vaultInfo, nil
}

// syncVaultInfo keeps vault.json in step with the database after a write.
//
// The desktop app uses vault_items_count and last_modified_time for its own
// bookkeeping and for sync conflict detection. Leaving them stale made an entry
// created by this tool invisible to that accounting. Device and user fields
// describe whoever last wrote the vault and are left untouched.
//
// Failures are logged rather than returned: the database write is already
// committed by the time this runs, so returning an error would suggest the
// entry was not created while it actually exists.
func (v *Vault) syncVaultInfo() {
var count int
if err := v.db.QueryRow("SELECT count(*) FROM item WHERE deleted = 0").Scan(&count); err != nil {
v.logger.WithError(err).Warn("could not count vault items")
return
}

now := time.Now().Unix()
err := v.patchVaultInfo(map[string]json.RawMessage{
"vault_items_count": json.RawMessage(strconv.Itoa(count)),
"last_modified_time": json.RawMessage(strconv.FormatInt(now, 10)),
})
if err != nil {
v.logger.WithError(err).Warn("could not update vault info")
return
}

v.vaultInfo.VaultNumItems = count
}

// patchVaultInfo replaces the given keys in vault.json, leaving every other
// key byte-identical.
//
// vault.json is shared with the desktop app and the sync engine, so it carries
// fields this tool does not interpret (device names, sync watermarks, the
// encryption parameters). It is therefore decoded as raw JSON, patched, and
// written back atomically: a temporary file in the same directory followed by
// a rename, so a crash can never leave the vault described by a truncated file.
//
// Example: patchVaultInfo(map[string]json.RawMessage{"vault_items_count": json.RawMessage("2")})
func (v *Vault) patchVaultInfo(patch map[string]json.RawMessage) error {
infoBytes, err := os.ReadFile(v.vaultInfoFilename)
if err != nil {
return errors.Wrap(err, "could not read vault info")
}

info := make(map[string]json.RawMessage)
if err := json.Unmarshal(infoBytes, &info); err != nil {
return errors.Wrap(err, "could not parse vault info")
}

for key, value := range patch {
info[key] = value
}

patched, err := json.MarshalIndent(info, "", " ")
if err != nil {
return errors.Wrap(err, "could not serialize vault info")
}
patched = append(patched, '\n')

mode := os.FileMode(0o600)
if stat, err := os.Stat(v.vaultInfoFilename); err == nil {
mode = stat.Mode().Perm()
}

tmp, err := os.CreateTemp(filepath.Dir(v.vaultInfoFilename), ".vault.json.*")
if err != nil {
return errors.Wrap(err, "could not create temporary vault info")
}
tmpName := tmp.Name()

if _, err := tmp.Write(patched); err != nil {
tmp.Close()
os.Remove(tmpName)
return errors.Wrap(err, "could not write vault info")
}
if err := tmp.Chmod(mode); err != nil {
tmp.Close()
os.Remove(tmpName)
return errors.Wrap(err, "could not set vault info permissions")
}
if err := tmp.Close(); err != nil {
os.Remove(tmpName)
return errors.Wrap(err, "could not close vault info")
}
if err := os.Rename(tmpName, v.vaultInfoFilename); err != nil {
os.Remove(tmpName)
return errors.Wrap(err, "could not replace vault info")
}

return nil
}
Loading
Loading