Files
rclone/backend/protondrive/crypto.go
StereotypicalCatandClaude Opus 5.5 c0bdbcde6b
build / windows (push) Skipped
build / other_os (push) Skipped
build / mac_amd64 (push) Skipped
build / mac_arm64 (push) Skipped
build / linux (push) Skipped
build / go1.26 (push) Skipped
build / linux_386 (push) Skipped
build / lint (push) Skipped
build / android-all (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/386 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/amd64 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm/v6 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm/v7 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm64 (push) Skipped
Build & Push Docker Images / Merge & Push Final Docker Image (push) Waiting for needed jobs
protondrive: rewrite the backend as a native Go client of the Proton Drive API
Replace Proton-API-Bridge and go-proton-api with a client in
backend/protondrive written against Proton's current Drive API, following
the behaviour of Proton's official Drive SDK:

- volume-based and v2 routes only
- upload block verification, signed manifests and extended attributes
- current content encryption (v4 node keys, v6 PKESK, SEIPDv2)
- browser (session fork) sign-in, with username and password still
  supported
- the volume's change events, used to keep the metadata cache current and
  for ChangeNotify, polled at most every 30 s
- an in-memory fake Proton server (protontest) so the tests run without
  an account

Uses ProtonMail/gopenpgp/v3 and ProtonMail/go-srp directly; no cgo.

Written with heavy AI assistance (Claude Code).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 23:22:46 +01:00

1025 lines
34 KiB
Go

package protondrive
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"time"
"unicode/utf16"
"unicode/utf8"
"github.com/ProtonMail/go-crypto/openpgp/packet"
"github.com/ProtonMail/go-crypto/openpgp/s2k"
"github.com/ProtonMail/go-srp"
"github.com/ProtonMail/gopenpgp/v3/armor"
"github.com/ProtonMail/gopenpgp/v3/constants"
"github.com/ProtonMail/gopenpgp/v3/crypto"
"github.com/ProtonMail/gopenpgp/v3/profile"
)
// computeKeyPassword returns the key password which unlocks the user
// keys, derived from the mailbox password and the base64 key salt of
// the user key.
func computeKeyPassword(password []byte, salt string) ([]byte, error) {
if salt == "" {
return nil, errors.New("compute key password: no key salt")
}
rawSalt, err := base64.StdEncoding.DecodeString(salt)
if err != nil {
return nil, fmt.Errorf("compute key password: decode salt: %w", err)
}
hashed, err := srp.MailboxPassword(password, rawSalt)
if err != nil {
return nil, fmt.Errorf("compute key password: %w", err)
}
// The key password is the bcrypt hash without its "$2y$10$" prefix
// and salt: the last 31 characters.
const keyPasswordLen = 31
if len(hashed) < keyPasswordLen {
return nil, errors.New("compute key password: bcrypt output too short")
}
return hashed[len(hashed)-keyPasswordLen:], nil
}
// forkPayloadAAD is the additional data authenticating a fork payload.
const forkPayloadAAD = "fork"
// decryptForkPayload returns the key password from the base64 payload
// of a session fork, encrypted with AES-256-GCM by Proton's sign-in
// page using key.
func decryptForkPayload(payloadB64 string, key []byte) (keyPassword string, err error) {
blob, err := base64.StdEncoding.DecodeString(payloadB64)
if err != nil {
return "", fmt.Errorf("decrypt fork payload: %w", err)
}
block, err := aes.NewCipher(key)
if err != nil {
return "", fmt.Errorf("decrypt fork payload: %w", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", fmt.Errorf("decrypt fork payload: %w", err)
}
if len(blob) < gcm.NonceSize()+gcm.Overhead() {
return "", errors.New("decrypt fork payload: payload too short")
}
nonce, sealed := blob[:gcm.NonceSize()], blob[gcm.NonceSize():]
plain, err := gcm.Open(nil, nonce, sealed, []byte(forkPayloadAAD))
if err != nil {
return "", fmt.Errorf("decrypt fork payload: %w", err)
}
var payload struct {
KeyPassword *string `json:"keyPassword"`
}
if err := json.Unmarshal(plain, &payload); err != nil || payload.KeyPassword == nil {
return "", errors.New("decrypt fork payload: no key password in payload")
}
return *payload.KeyPassword, nil
}
// Node cryptography follows the reference SDK (driveCrypto.ts): file
// content (content key packet and blocks) uses AEAD when the node key
// accepts it, and everything else - passphrases, names, hash keys,
// extended attributes - never does, whatever the keys accept, because
// not every official client reads AEAD there.
//
// Every function takes now, the server time, for key creation, signing
// and verification; the zero time means the local clock.
// nodeKeyUserID is the user ID of every node key.
const nodeKeyUserID = "Drive key"
// errSignatureMissing is the verification error of a value which has
// no signature.
var errSignatureMissing = errors.New("signature is missing")
// aeadPGP returns a handle which writes SEIPDv2 data with AES-256-GCM,
// the AEAD mode Proton Drive uses, and generates v4 keys which accept
// it.
func aeadPGP() *crypto.PGPHandle {
p := profile.Default()
p.AeadEncryption = &packet.AEADConfig{DefaultMode: packet.AEADModeGCM}
return crypto.PGPWithProfile(p)
}
// pgpFor returns the handle which writes data in the format of sk.
func pgpFor(sk *crypto.SessionKey) *crypto.PGPHandle {
if sk.IsV6() {
return aeadPGP()
}
return crypto.PGP()
}
// generatePassphrase returns 32 random bytes as base64 text.
func generatePassphrase() ([]byte, error) {
raw := make([]byte, 32)
if _, err := rand.Read(raw); err != nil {
return nil, err
}
passphrase := make([]byte, base64.StdEncoding.EncodedLen(len(raw)))
base64.StdEncoding.Encode(passphrase, raw)
clear(raw)
return passphrase, nil
}
// encryptWithSessionKey returns sk encrypted to encKR followed by plain
// encrypted with sk, signed inside the encryption by signKR unless it
// is nil, and compressed if compress is set.
//
// The format follows sk alone, whatever the keys in encKR accept: a v6
// PKESK and SEIPDv2 for a v6 session key, otherwise a v3 PKESK and
// SEIPDv1.
func encryptWithSessionKey(plain []byte, sk *crypto.SessionKey, encKR, signKR *crypto.KeyRing, compress bool, now time.Time) ([]byte, error) {
pgp := pgpFor(sk)
kb := pgp.Encryption().Recipients(encKR)
db := pgp.Encryption().SessionKey(sk)
if signKR != nil {
db = db.SigningKeys(signKR)
}
if compress {
db = db.Compress()
}
if !now.IsZero() {
// The clock of the key packet handle selects the recipients'
// encryption keys, which may be newer than the local clock.
kb = kb.SignTime(now.Unix())
db = db.SignTime(now.Unix())
}
kh, err := kb.New()
if err != nil {
return nil, err
}
keyPacket, err := kh.EncryptSessionKey(sk)
if err != nil {
return nil, err
}
dh, err := db.New()
if err != nil {
return nil, err
}
data, err := dh.Encrypt(plain)
if err != nil {
return nil, err
}
return append(keyPacket, data.Bytes()...), nil
}
// armorMessage armors msg, encrypted with sk. As RFC 9580 asks, the
// armor of v6 packets has no checksum.
func armorMessage(msg []byte, sk *crypto.SessionKey) (string, error) {
return armor.ArmorPGPMessageChecksum(msg, !sk.IsV6())
}
// encryptArmored returns plain encrypted to encKR with a new non-AEAD
// session key, or with sk if not nil, signed by signKR, and armored.
func encryptArmored(plain []byte, sk *crypto.SessionKey, encKR, signKR *crypto.KeyRing, compress bool, now time.Time) (string, error) {
if sk == nil {
var err error
sk, err = crypto.GenerateSessionKeyAlgo(constants.AES256)
if err != nil {
return "", err
}
}
msg, err := encryptWithSessionKey(plain, sk, encKR, signKR, compress, now)
if err != nil {
return "", err
}
return armorMessage(msg, sk)
}
// Limits of decrypted metadata, which decryptMessage enforces: a
// compressed message can expand a thousandfold or more, and anyone
// holding the public key can write one.
const (
// maxSmallMessageSize bounds a name, passphrase or hash key. A name
// is at most 255 UTF-16 code units, so 1020 bytes of UTF-8.
maxSmallMessageSize = 64 << 10
// maxXAttrsSize bounds extended attributes, whose block sizes take
// about 2 MiB for a 1 TiB file.
maxXAttrsSize = 16 << 20
)
// decryptMessage decrypts the armored message with decKR and returns
// it with its session key. Its embedded signature is checked against
// verifyKR alone, and any failure returned as verifyErr; a nil verifyKR
// checks it against no key, so verifyErr is set. A compressed message
// which expands to more than maxSize bytes, counting the packet headers
// and signatures inside it, is an error, and so is an armored message
// too large to hold at most maxSize bytes uncompressed.
func decryptMessage(armored string, decKR, verifyKR *crypto.KeyRing, now time.Time, maxSize int64) (res *crypto.VerifiedDataResult, sk *crypto.SessionKey, verifyErr, err error) {
// Armor takes 4/3 of the binary size and line breaks; the rest is
// room for the key packets.
if maxArmored := 2*maxSize + 64<<10; int64(len(armored)) > maxArmored {
return nil, nil, nil, fmt.Errorf("message is larger than %d bytes", maxArmored)
}
msg, err := crypto.NewPGPMessageFromArmored(armored)
if err != nil {
return nil, nil, nil, err
}
kh, err := crypto.PGP().Decryption().DecryptionKeys(decKR).New()
if err != nil {
return nil, nil, nil, err
}
sk, err = kh.DecryptSessionKey(msg.BinaryKeyPacket())
if err != nil {
return nil, nil, nil, err
}
if verifyKR == nil {
if verifyKR, err = crypto.NewKeyRing(nil); err != nil {
return nil, nil, nil, err
}
}
// gopenpgp looks signers up in the decryption keys too, so the data
// is decrypted with the session key alone: otherwise a signature by
// any holder of decKR would verify. gopenpgp can then not check the
// intended recipients a signature lists, so that is done below.
b := crypto.PGP().Decryption().SessionKey(sk).VerificationKeys(verifyKR).DisableIntendedRecipients().MaxDecompressedMessageSize(maxSize)
if !now.IsZero() {
b = b.VerifyTime(now.Unix())
}
dh, err := b.New()
if err != nil {
return nil, nil, nil, err
}
res, err = dh.Decrypt(msg.BinaryDataPacket(), crypto.Bytes)
if err != nil {
return nil, nil, nil, err
}
return res, sk, intendedRecipientsError(res, decKR), nil
}
// intendedRecipientsError returns the signature error of res, or an
// error if each valid signature lists intended recipients (as gopenpgp
// writes when it encrypts and signs at once) and none of them is a key
// of decKR.
func intendedRecipientsError(res *crypto.VerifiedDataResult, decKR *crypto.KeyRing) error {
if err := res.SignatureError(); err != nil {
return err
}
for _, sig := range res.Signatures {
if sig.SignatureError != nil || sig.Signature == nil {
continue
}
if len(sig.Signature.IntendedRecipients) == 0 {
return nil
}
for _, recipient := range sig.Signature.IntendedRecipients {
for _, key := range decKR.GetKeys() {
if bytes.Equal(recipient.Fingerprint, key.GetEntity().PrimaryKey.Fingerprint) {
return nil
}
}
}
}
return errors.New("signature is intended for another recipient")
}
// signDetached returns the armored detached signature of data by signKR.
func signDetached(data []byte, signKR *crypto.KeyRing, now time.Time) (string, error) {
sig, err := signDetachedEncoded(data, signKR, crypto.Armor, now)
return string(sig), err
}
// signDetachedEncoded returns the detached signature of data by signKR,
// encoded as crypto.Armor or crypto.Bytes.
func signDetachedEncoded(data []byte, signKR *crypto.KeyRing, encoding int8, now time.Time) ([]byte, error) {
b := crypto.PGP().Sign().SigningKeys(signKR).Detached()
if !now.IsZero() {
b = b.SignTime(now.Unix())
}
sh, err := b.New()
if err != nil {
return nil, err
}
return sh.Sign(data, encoding)
}
// verifyDetached checks the armored detached signature of data against
// verifyKR. It returns errSignatureMissing if armoredSig is empty.
func verifyDetached(data []byte, armoredSig string, verifyKR *crypto.KeyRing, now time.Time) error {
if armoredSig == "" {
return errSignatureMissing
}
b := crypto.PGP().Verify().VerificationKeys(verifyKR)
if !now.IsZero() {
b = b.VerifyTime(now.Unix())
}
vh, err := b.New()
if err != nil {
return err
}
res, err := vh.VerifyDetached(data, []byte(armoredSig), crypto.Armor)
if err != nil {
return err
}
return res.SignatureError()
}
// joinKeyRings returns a key ring of the keys of all of krs, skipping
// nil ones.
func joinKeyRings(krs ...*crypto.KeyRing) (*crypto.KeyRing, error) {
joined, err := crypto.NewKeyRing(nil)
if err != nil {
return nil, err
}
for _, kr := range krs {
if kr == nil {
continue
}
for _, key := range kr.GetKeys() {
if err := joined.AddKey(key); err != nil {
return nil, err
}
}
}
return joined, nil
}
// nodeKeys is the unlocked key of a node with the passphrase which
// locks it.
type nodeKeys struct {
keyRing *crypto.KeyRing
passphrase []byte // base64 text locking the key
passphraseSessionKey *crypto.SessionKey // session key of the encrypted passphrase
unverified error // why the key may not be its owner's; nil if its signature verified
}
// generateNodeKeys returns a new node key, armored and locked with a
// new passphrase, the passphrase encrypted to parentKR, its detached
// signature by signerKR, and the unlocked keys.
//
// The key is a v4 EdDSA key with an ECDH Curve25519 subkey, locked with
// an ordinary (not Argon2, not AEAD) S2K. If aead is set, as for a file,
// the key accepts AEAD data (SEIPDv2 with AES-256-GCM).
func generateNodeKeys(parentKR, signerKR *crypto.KeyRing, aead bool, now time.Time) (armoredKey, encPassphrase, passphraseSig string, keys *nodeKeys, err error) {
passphrase, err := generatePassphrase()
if err != nil {
return "", "", "", nil, fmt.Errorf("generate node keys: %w", err)
}
pgp := crypto.PGP()
if aead {
pgp = aeadPGP()
}
kb := pgp.KeyGeneration().AddUserId(nodeKeyUserID, "")
if !now.IsZero() {
kb = kb.GenerationTime(now.Unix())
}
key, err := kb.New().GenerateKey()
if err != nil {
return "", "", "", nil, fmt.Errorf("generate node keys: %w", err)
}
// The default profile locks with CFB and an iterated and salted
// S2K. Argon2 or AEAD locked node keys break the official web app.
locked, err := crypto.PGP().LockKey(key, passphrase)
if err == nil {
armoredKey, err = locked.Armor()
locked.ClearPrivateParams()
}
if err != nil {
key.ClearPrivateParams()
return "", "", "", nil, fmt.Errorf("generate node keys: lock key: %w", err)
}
kr, err := crypto.NewKeyRing(key)
if err != nil {
key.ClearPrivateParams()
return "", "", "", nil, fmt.Errorf("generate node keys: %w", err)
}
sk, err := crypto.GenerateSessionKeyAlgo(constants.AES256)
if err != nil {
kr.ClearPrivateParams()
return "", "", "", nil, fmt.Errorf("generate node keys: %w", err)
}
keys = &nodeKeys{keyRing: kr, passphrase: passphrase, passphraseSessionKey: sk}
encPassphrase, passphraseSig, err = encryptPassphrase(keys, parentKR, signerKR, now)
if err != nil {
kr.ClearPrivateParams()
return "", "", "", nil, fmt.Errorf("generate node keys: %w", err)
}
return armoredKey, encPassphrase, passphraseSig, keys, nil
}
// encryptPassphrase returns the passphrase of keys encrypted with its
// session key to parentKR, and its detached signature by signerKR.
func encryptPassphrase(keys *nodeKeys, parentKR, signerKR *crypto.KeyRing, now time.Time) (encPassphrase, passphraseSig string, err error) {
encPassphrase, err = encryptArmored(keys.passphrase, keys.passphraseSessionKey, parentKR, nil, false, now)
if err != nil {
return "", "", fmt.Errorf("encrypt passphrase: %w", err)
}
passphraseSig, err = signDetached(keys.passphrase, signerKR, now)
if err != nil {
return "", "", fmt.Errorf("sign passphrase: %w", err)
}
return encPassphrase, passphraseSig, nil
}
// decryptNodeKeys decrypts the passphrase with parentKR, checks its
// detached signature against verifyKR and unlocks the armored node key
// with it.
//
// A signature which doesn't verify, or is missing, is returned as
// verifyErr with the keys; err is set only if the keys can't be had.
func decryptNodeKeys(parentKR, verifyKR *crypto.KeyRing, armoredKey, encPassphrase, passphraseSig string, now time.Time) (keys *nodeKeys, verifyErr, err error) {
res, sk, _, err := decryptMessage(encPassphrase, parentKR, nil, now, maxSmallMessageSize)
if err != nil {
return nil, nil, fmt.Errorf("decrypt node passphrase: %w", err)
}
passphrase := res.Bytes()
verifyErr = verifyDetached(passphrase, passphraseSig, verifyKR, now)
key, err := unlockForeignKey(armoredKey, passphrase)
if err != nil {
clear(passphrase)
return nil, nil, fmt.Errorf("unlock node key: %w", err)
}
kr, err := crypto.NewKeyRing(key)
if err != nil {
clear(passphrase)
key.ClearPrivateParams()
return nil, nil, fmt.Errorf("unlock node key: %w", err)
}
return &nodeKeys{keyRing: kr, passphrase: passphrase, passphraseSessionKey: sk}, verifyErr, nil
}
// Limits of an Argon2 S2K locking a key from the server or another
// user, checked before the KDF runs, which go-crypto lets use up to
// 2 TiB of memory and 255 passes. gopenpgp and OpenPGP.js write 3
// passes, parallelism 4 and 64 MiB by default; the node keys Proton's
// clients write use an iterated and salted S2K instead, whose one byte
// count encoding bounds its cost to 65011712 bytes hashed, 4 times the
// default.
const (
maxArgon2MemoryExp = 17 // 128 MiB
maxArgon2Passes = 4
maxArgon2Parallelism = 8
)
// unlockForeignKey is unlockKey for a key from the server or another
// user. It returns an error wrapping errIntegrity, without running the
// S2K, if the key is locked with an Argon2 S2K beyond the limits.
func unlockForeignKey(armored string, passphrase []byte) (*crypto.Key, error) {
data, err := armor.Unarmor(armored)
if err != nil {
return nil, err
}
if err := checkKeyS2K(data); err != nil {
return nil, err
}
locked, err := crypto.NewKey(data)
if err != nil {
return nil, err
}
return locked.Unlock(passphrase)
}
// checkKeyS2K returns an error wrapping errIntegrity if a secret key or
// subkey packet of the binary key data is locked with an Argon2 S2K
// beyond the limits.
func checkKeyS2K(data []byte) error {
r := packet.NewOpaqueReader(bytes.NewReader(data))
for {
op, err := r.Next()
if err == io.EOF {
return nil
}
if err != nil {
return fmt.Errorf("read key: %w", err)
}
// 5 and 7 are the secret key and secret subkey packets.
if op.Tag != 5 && op.Tag != 7 {
continue
}
spec, err := s2kSpecifier(op)
if err != nil {
return err
}
if len(spec) < 20 || spec[0] != byte(s2k.Argon2S2K) {
continue
}
passes, parallelism, memExp := spec[17], spec[18], spec[19]
if passes > maxArgon2Passes || parallelism > maxArgon2Parallelism || memExp > maxArgon2MemoryExp {
return fmt.Errorf("%w: the key is locked with Argon2 of %d passes, parallelism %d and 2^%d KiB, more than rclone accepts", errIntegrity, passes, parallelism, memExp)
}
}
}
// s2kSpecifier returns the bytes of the secret key or subkey packet op
// from its S2K specifier on, or nil if it isn't locked with one.
func s2kSpecifier(op *packet.OpaquePacket) ([]byte, error) {
var buf bytes.Buffer
if err := op.Serialize(&buf); err != nil {
return nil, fmt.Errorf("read key: %w", err)
}
p, err := packet.Read(&buf)
if err != nil {
return nil, fmt.Errorf("read key: %w", err)
}
pk, ok := p.(*packet.PrivateKey)
if !ok {
return nil, fmt.Errorf("read key: packet is %T", p)
}
// The secret packet's body starts with the public key's.
buf.Reset()
if err := pk.PublicKey.Serialize(&buf); err != nil {
return nil, fmt.Errorf("read key: %w", err)
}
pub, err := packet.NewOpaqueReader(&buf).Next()
if err != nil {
return nil, fmt.Errorf("read key: %w", err)
}
if !bytes.HasPrefix(op.Contents, pub.Contents) {
return nil, errors.New("read key: secret key packet doesn't start with its public key")
}
// RFC 9580 section 5.5.3: the S2K usage octet, a count octet in
// v5 and v6, the cipher, an AEAD mode for usage 253, and an S2K
// specifier length octet in v6, as go-crypto parses them.
rest := op.Contents[len(pub.Contents):]
if len(rest) == 0 {
return nil, errors.New("read key: secret key packet is truncated")
}
usage, i := rest[0], 1
if usage != 253 && usage != 254 && usage != 255 {
return nil, nil
}
if pk.Version == 5 || pk.Version == 6 {
i++
}
i++
if usage == 253 {
i++
}
if pk.Version == 6 {
i++
}
if i >= len(rest) {
return nil, errors.New("read key: secret key packet is truncated")
}
return rest[i:], nil
}
// encryptName returns name encrypted to parentKR and signed by
// signerKR, without AEAD, with the session key sk, or a new one if sk
// is nil.
func encryptName(name string, sk *crypto.SessionKey, parentKR, signerKR *crypto.KeyRing, now time.Time) (string, error) {
enc, err := encryptArmored([]byte(name), sk, parentKR, signerKR, false, now)
if err != nil {
return "", fmt.Errorf("encrypt name: %w", err)
}
return enc, nil
}
// decryptName decrypts encName with parentKR and checks its signature
// against verifyKR. A signature which doesn't verify is returned as
// verifyErr with the name.
func decryptName(encName string, parentKR, verifyKR *crypto.KeyRing, now time.Time) (name string, verifyErr, err error) {
res, _, verifyErr, err := decryptMessage(encName, parentKR, verifyKR, now, maxSmallMessageSize)
if err != nil {
return "", nil, fmt.Errorf("decrypt name: %w", err)
}
if !utf8.Valid(res.Bytes()) {
return "", nil, errors.New("decrypt name: name is not valid UTF-8")
}
return string(res.Bytes()), verifyErr, nil
}
// nameSessionKey returns the session key of encName, decrypted with
// parentKR.
func nameSessionKey(encName string, parentKR *crypto.KeyRing) (*crypto.SessionKey, error) {
msg, err := crypto.NewPGPMessageFromArmored(encName)
if err != nil {
return nil, fmt.Errorf("name session key: %w", err)
}
dh, err := crypto.PGP().Decryption().DecryptionKeys(parentKR).New()
if err != nil {
return nil, fmt.Errorf("name session key: %w", err)
}
sk, err := dh.DecryptSessionKey(msg.BinaryKeyPacket())
if err != nil {
return nil, fmt.Errorf("name session key: %w", err)
}
return sk, nil
}
// maxNameLength is the longest name in UTF-16 code units, which is how
// the SDK counts.
const maxNameLength = 255
// validateName returns an error if name can't be the name of a node.
func validateName(name string) error {
switch {
case name == "":
return errors.New("name must not be empty")
case name == "." || name == "..":
return fmt.Errorf("name must not be %q", name)
case strings.ContainsAny(name, "/\x00"):
return errors.New("name must not contain / or NUL")
case !utf8.ValidString(name):
return errors.New("name must be valid UTF-8")
}
n := 0
for _, r := range name {
n += utf16.RuneLen(r)
}
if n > maxNameLength {
return fmt.Errorf("name must be at most %d characters long", maxNameLength)
}
return nil
}
// generateHashKey returns a new hash key of a folder, encrypted to and
// signed by its node key nodeKR, without AEAD.
//
// The hash key is the base64 text of 32 random bytes; the text itself,
// not the bytes it encodes, is the HMAC key of nameHash.
func generateHashKey(nodeKR *crypto.KeyRing, now time.Time) (encHashKey string, hashKey []byte, err error) {
hashKey, err = generatePassphrase()
if err != nil {
return "", nil, fmt.Errorf("generate hash key: %w", err)
}
encHashKey, err = encryptArmored(hashKey, nil, nodeKR, nodeKR, false, now)
if err != nil {
return "", nil, fmt.Errorf("generate hash key: %w", err)
}
return encHashKey, hashKey, nil
}
// decryptHashKey decrypts encHashKey with nodeKR and checks its
// signature against nodeKR and extraVerifyKR (which may be nil): some
// clients signed hash keys with the address key. A signature which
// doesn't verify is returned as verifyErr with the hash key.
func decryptHashKey(encHashKey string, nodeKR, extraVerifyKR *crypto.KeyRing, now time.Time) (hashKey []byte, verifyErr, err error) {
verifyKR, err := joinKeyRings(nodeKR, extraVerifyKR)
if err != nil {
return nil, nil, fmt.Errorf("decrypt hash key: %w", err)
}
res, _, verifyErr, err := decryptMessage(encHashKey, nodeKR, verifyKR, now, maxSmallMessageSize)
if err != nil {
return nil, nil, fmt.Errorf("decrypt hash key: %w", err)
}
return res.Bytes(), verifyErr, nil
}
// nameHash returns the lookup hash of name in a folder with hashKey:
// the lower-case hex HMAC-SHA256 of the name's UTF-8 bytes, as given,
// without Unicode normalisation.
func nameHash(name string, hashKey []byte) string {
mac := hmac.New(sha256.New, hashKey)
mac.Write([]byte(name))
return hex.EncodeToString(mac.Sum(nil))
}
// generateContentKey returns a new content session key of a file, its
// key packet encrypted to the file's node key nodeKR in base64, and its
// armored detached signature by nodeKR.
//
// As in the SDK the format follows the node key: a v6 session key and
// PKESK if the node key accepts AEAD, as new file keys do, otherwise
// v3.
func generateContentKey(nodeKR *crypto.KeyRing, now time.Time) (contentKeyPacketB64, contentKeyPacketSig string, sk *crypto.SessionKey, err error) {
b := aeadPGP().Encryption().Recipients(nodeKR)
if !now.IsZero() {
b = b.SignTime(now.Unix())
}
eh, err := b.New()
if err != nil {
return "", "", nil, fmt.Errorf("generate content key: %w", err)
}
sk, err = eh.GenerateSessionKey()
if err != nil {
return "", "", nil, fmt.Errorf("generate content key: %w", err)
}
keyPacket, err := eh.EncryptSessionKey(sk)
if err != nil {
return "", "", nil, fmt.Errorf("generate content key: %w", err)
}
contentKeyPacketSig, err = signDetached(sk.Key, nodeKR, now)
if err != nil {
return "", "", nil, fmt.Errorf("generate content key: sign: %w", err)
}
return base64.StdEncoding.EncodeToString(keyPacket), contentKeyPacketSig, sk, nil
}
// decryptContentKey returns the content session key from the base64
// key packet (v3 or v6 PKESK), decrypted with the node key nodeKR.
//
// contentKeyPacketSig is checked against nodeKR and extraVerifyKR
// (which may be nil): some clients signed with the address key. A
// signature which doesn't verify, or is missing, is returned as
// verifyErr with the session key.
func decryptContentKey(contentKeyPacketB64, contentKeyPacketSig string, nodeKR, extraVerifyKR *crypto.KeyRing, now time.Time) (sk *crypto.SessionKey, verifyErr, err error) {
keyPacket, err := base64.StdEncoding.DecodeString(contentKeyPacketB64)
if err != nil {
return nil, nil, fmt.Errorf("decrypt content key: %w", err)
}
dh, err := crypto.PGP().Decryption().DecryptionKeys(nodeKR).New()
if err != nil {
return nil, nil, fmt.Errorf("decrypt content key: %w", err)
}
sk, err = dh.DecryptSessionKey(keyPacket)
if err != nil {
return nil, nil, fmt.Errorf("decrypt content key: %w", err)
}
verifyKR, err := joinKeyRings(nodeKR, extraVerifyKR)
if err != nil {
return nil, nil, fmt.Errorf("decrypt content key: %w", err)
}
return sk, verifyDetached(sk.Key, contentKeyPacketSig, verifyKR, now), nil
}
// encryptBlock returns the block plain encrypted with the content
// session key sk, the armored detached signature of plain by signerKR
// encrypted to the node key nodeKR, and the SHA-256 of the encrypted
// block.
//
// The block is a data packet alone: SEIPDv2 with AES-256-GCM for a v6
// session key, SEIPDv1 otherwise. As in the SDK the signature is
// encrypted with sk too, so it takes the same format.
func encryptBlock(plain []byte, sk *crypto.SessionKey, nodeKR, signerKR *crypto.KeyRing, now time.Time) (enc []byte, encSignature string, hash [32]byte, err error) {
var buf bytes.Buffer
encSignature, err = encryptBlockTo(&buf, bytes.NewReader(plain), sk, nodeKR, signerKR, now)
if err != nil {
return nil, "", hash, err
}
return buf.Bytes(), encSignature, sha256.Sum256(buf.Bytes()), nil
}
// encryptBlockTo is encryptBlock reading the block from plain and
// writing it encrypted to enc as it goes, so neither is held in memory.
func encryptBlockTo(enc io.Writer, plain io.Reader, sk *crypto.SessionKey, nodeKR, signerKR *crypto.KeyRing, now time.Time) (encSignature string, err error) {
eh, err := pgpFor(sk).Encryption().SessionKey(sk).New()
if err != nil {
return "", fmt.Errorf("encrypt block: %w", err)
}
sb := crypto.PGP().Sign().SigningKeys(signerKR).Detached()
if !now.IsZero() {
sb = sb.SignTime(now.Unix())
}
sh, err := sb.New()
if err != nil {
return "", fmt.Errorf("encrypt block: sign: %w", err)
}
ew, err := eh.EncryptingWriter(enc, crypto.Bytes)
if err != nil {
return "", fmt.Errorf("encrypt block: %w", err)
}
var sig bytes.Buffer
sw, err := sh.SigningWriter(&sig, crypto.Bytes)
if err != nil {
return "", fmt.Errorf("encrypt block: sign: %w", err)
}
if _, err = io.Copy(io.MultiWriter(ew, sw), plain); err != nil {
return "", fmt.Errorf("encrypt block: %w", err)
}
if err = ew.Close(); err != nil {
return "", fmt.Errorf("encrypt block: %w", err)
}
if err = sw.Close(); err != nil {
return "", fmt.Errorf("encrypt block: sign: %w", err)
}
encSig, err := encryptWithSessionKey(sig.Bytes(), sk, nodeKR, nil, false, now)
if err != nil {
return "", fmt.Errorf("encrypt block: encrypt signature: %w", err)
}
if encSignature, err = armorMessage(encSig, sk); err != nil {
return "", fmt.Errorf("encrypt block: %w", err)
}
return encSignature, nil
}
// blockDecrypter returns a reader of the encrypted block enc (SEIPDv1
// or v2) decrypted with the content session key sk.
//
// The block's integrity is checked only as the reader reaches its end:
// what it returns before io.EOF must not be used if a Read fails.
func blockDecrypter(enc io.Reader, sk *crypto.SessionKey) (io.Reader, error) {
dh, err := crypto.PGP().Decryption().SessionKey(sk).New()
if err != nil {
return nil, fmt.Errorf("decrypt block: %w", err)
}
r, err := dh.DecryptingReader(enc, crypto.Bytes)
if err != nil {
return nil, fmt.Errorf("decrypt block: %w", err)
}
return r, nil
}
// verifierToken returns the token proving that encBlock was encrypted
// with the right key: verificationCode XOR the start of encBlock, padded
// with zeros if shorter.
func verifierToken(verificationCode, encBlock []byte) []byte {
token := make([]byte, len(verificationCode))
for i, c := range verificationCode {
if i < len(encBlock) {
c ^= encBlock[i]
}
token[i] = c
}
return token
}
// signManifest returns the armored detached signature by signerKR of
// the manifest: the concatenated blockHashes, in order.
func signManifest(blockHashes [][]byte, signerKR *crypto.KeyRing, now time.Time) (armoredSig string, err error) {
sig, err := signDetached(bytes.Join(blockHashes, nil), signerKR, now)
if err != nil {
return "", fmt.Errorf("sign manifest: %w", err)
}
return sig, nil
}
// verifyManifest checks the armored manifest signature of blockHashes
// against verifyKR.
func verifyManifest(blockHashes [][]byte, armoredSig string, verifyKR *crypto.KeyRing, now time.Time) error {
if err := verifyDetached(bytes.Join(blockHashes, nil), armoredSig, verifyKR, now); err != nil {
return fmt.Errorf("verify manifest: %w", err)
}
return nil
}
// xattrs are the extended attributes of a revision or folder.
type xattrs struct {
ModTime time.Time // in UTC; zero if unknown
Size int64
BlockSizes []int64
SHA1 string // hex; empty for a folder
Extra map[string]json.RawMessage // top level members other than Common
NoSize bool // set if read attributes record no usable size
}
// blockSizesOnly returns x with only its block sizes, which reads
// check, and the size they add up to.
func (x *xattrs) blockSizesOnly() *xattrs {
out := &xattrs{NoSize: true}
if x == nil {
return out
}
var total int64
for _, size := range x.BlockSizes {
if size > maxBlockSize {
return out
}
total += size
}
if x.BlockSizes != nil {
out.BlockSizes, out.Size, out.NoSize = x.BlockSizes, total, false
}
return out
}
// xattrsTimeLayout is the layout of ModificationTime, as JavaScript's
// Date.toISOString writes it.
const xattrsTimeLayout = "2006-01-02T15:04:05.000Z07:00"
// xattrsTimeLayouts are the layouts of ModificationTime accepted on
// reading. Old rclone versions wrote a numeric zone without a colon.
var xattrsTimeLayouts = []string{time.RFC3339Nano, "2006-01-02T15:04:05.999999999Z0700"}
// xattrsCommon is the Common member written for a file; a folder has
// only ModificationTime.
type xattrsCommon struct {
ModificationTime string `json:"ModificationTime,omitempty"`
Size *int64 `json:"Size,omitempty"`
BlockSizes *[]int64 `json:"BlockSizes,omitempty"`
Digests *xattrsDigests `json:"Digests,omitempty"`
}
type xattrsDigests struct {
SHA1 string `json:"SHA1"`
}
// marshal returns the JSON of x. Size, BlockSizes and the SHA1 digest
// are written when SHA1 is set, as for a file.
func (x *xattrs) marshal() ([]byte, error) {
if _, ok := x.Extra["Common"]; ok {
return nil, errors.New("common attributes are not allowed in extra attributes")
}
var common xattrsCommon
if !x.ModTime.IsZero() {
common.ModificationTime = x.ModTime.UTC().Format(xattrsTimeLayout)
}
if x.SHA1 != "" {
blockSizes := x.BlockSizes
if blockSizes == nil {
blockSizes = []int64{}
}
common.Size = &x.Size
common.BlockSizes = &blockSizes
common.Digests = &xattrsDigests{SHA1: x.SHA1}
}
members := make(map[string]any, len(x.Extra)+1)
for k, v := range x.Extra {
members[k] = v
}
if common != (xattrsCommon{}) {
members["Common"] = common
}
return json.Marshal(members)
}
// parseXAttrs returns the extended attributes in data. As in the SDK,
// members which are missing or malformed are left zero.
func parseXAttrs(data []byte) *xattrs {
x := &xattrs{}
var members map[string]json.RawMessage
if json.Unmarshal(data, &members) != nil {
x.NoSize = true
return x
}
var common struct {
ModificationTime *string
Size json.RawMessage
BlockSizes json.RawMessage
Digests *struct{ SHA1 json.RawMessage }
}
if raw, ok := members["Common"]; ok {
_ = json.Unmarshal(raw, &common)
delete(members, "Common")
}
if len(members) > 0 {
x.Extra = members
}
if common.ModificationTime != nil {
for _, layout := range xattrsTimeLayouts {
if t, err := time.Parse(layout, *common.ModificationTime); err == nil {
x.ModTime = t.UTC()
break
}
}
}
var blockSizes []int64
if json.Unmarshal(common.BlockSizes, &blockSizes) == nil && len(blockSizes) > 0 {
x.BlockSizes = blockSizes
for _, size := range blockSizes {
if size <= 0 {
x.BlockSizes = nil
break
}
}
}
var size *int64
if json.Unmarshal(common.Size, &size) != nil {
size = nil
}
if size != nil {
x.Size = *size
}
if size == nil || x.Size < 0 {
// Without a valid size, block sizes no larger than a block
// add up to it.
x.Size = 0
x.NoSize = x.BlockSizes == nil
for _, size := range x.BlockSizes {
if size > maxBlockSize {
x.Size, x.NoSize = 0, true
break
}
x.Size += size
}
}
if common.Digests != nil {
_ = json.Unmarshal(common.Digests.SHA1, &x.SHA1)
}
return x
}
// encryptXAttrs returns x as JSON, compressed, encrypted to the node
// key nodeKR and signed by signerKR, without AEAD. The members of Extra
// are written beside Common; Extra must not hold Common.
func encryptXAttrs(x *xattrs, nodeKR, signerKR *crypto.KeyRing, now time.Time) (string, error) {
data, err := x.marshal()
if err != nil {
return "", fmt.Errorf("encrypt extended attributes: %w", err)
}
enc, err := encryptArmored(data, nil, nodeKR, signerKR, true, now)
if err != nil {
return "", fmt.Errorf("encrypt extended attributes: %w", err)
}
return enc, nil
}
// decryptXAttrs decrypts enc with the node key nodeKR and checks its
// signature against verifyKR. A signature which doesn't verify is
// returned as verifyErr with the attributes. An empty enc has no
// attributes.
func decryptXAttrs(enc string, nodeKR, verifyKR *crypto.KeyRing, now time.Time) (x *xattrs, verifyErr, err error) {
if enc == "" {
return &xattrs{}, nil, nil
}
res, _, verifyErr, err := decryptMessage(enc, nodeKR, verifyKR, now, maxXAttrsSize)
if err != nil {
return nil, nil, fmt.Errorf("decrypt extended attributes: %w", err)
}
if !utf8.Valid(res.Bytes()) {
return nil, nil, errors.New("decrypt extended attributes: not valid UTF-8")
}
return parseXAttrs(res.Bytes()), verifyErr, nil
}