| 1 |
// Copyright (c) 2020 Tulir Asokan |
| 2 |
// |
| 3 |
// This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
// file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 6 |
|
| 7 |
package ssss |
| 8 |
|
| 9 |
import ( |
| 10 |
"crypto/rand" |
| 11 |
"encoding/base64" |
| 12 |
"fmt" |
| 13 |
"strings" |
| 14 |
|
| 15 |
"maunium.net/go/mautrix/crypto/utils" |
| 16 |
) |
| 17 |
|
| 18 |
// Key represents a SSSS private key and related metadata. |
| 19 |
type Key struct { |
| 20 |
ID string `json:"-"` |
| 21 |
Key []byte `json:"-"` |
| 22 |
Metadata *KeyMetadata `json:"-"` |
| 23 |
} |
| 24 |
|
| 25 |
// NewKey generates a new SSSS key, optionally based on the given passphrase. |
| 26 |
// |
| 27 |
// Errors are only returned if crypto/rand runs out of randomness. |
| 28 |
func NewKey(passphrase string) (*Key, error) { |
| 29 |
// We don't support any other algorithms currently. |
| 30 |
keyData := KeyMetadata{Algorithm: AlgorithmAESHMACSHA2} |
| 31 |
|
| 32 |
var ssssKey []byte |
| 33 |
if len(passphrase) > 0 { |
| 34 |
// There's a passphrase. We need to generate a salt for it, set the metadata |
| 35 |
// and then compute the key using the passphrase and the metadata. |
| 36 |
saltBytes := make([]byte, 24) |
| 37 |
if _, err := rand.Read(saltBytes); err != nil { |
| 38 |
return nil, fmt.Errorf("failed to get random bytes for salt: %w", err) |
| 39 |
} |
| 40 |
keyData.Passphrase = &PassphraseMetadata{ |
| 41 |
Algorithm: PassphraseAlgorithmPBKDF2, |
| 42 |
Iterations: 500000, |
| 43 |
Salt: base64.StdEncoding.EncodeToString(saltBytes), |
| 44 |
Bits: 256, |
| 45 |
} |
| 46 |
var err error |
| 47 |
ssssKey, err = keyData.Passphrase.GetKey(passphrase) |
| 48 |
if err != nil { |
| 49 |
return nil, fmt.Errorf("failed to get key from passphrase: %w", err) |
| 50 |
} |
| 51 |
} else { |
| 52 |
// No passphrase, just generate a random key |
| 53 |
ssssKey = make([]byte, 32) |
| 54 |
if _, err := rand.Read(ssssKey); err != nil { |
| 55 |
return nil, fmt.Errorf("failed to get random bytes for key: %w", err) |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
// Generate a random ID for the key. It's what identifies the key in account data. |
| 60 |
keyIDBytes := make([]byte, 24) |
| 61 |
if _, err := rand.Read(keyIDBytes); err != nil { |
| 62 |
return nil, fmt.Errorf("failed to get random bytes for key ID: %w", err) |
| 63 |
} |
| 64 |
|
| 65 |
// We store a certain hash in the key metadata so that clients can check if the user entered the correct key. |
| 66 |
var ivBytes [utils.AESCTRIVLength]byte |
| 67 |
if _, err := rand.Read(ivBytes[:]); err != nil { |
| 68 |
return nil, fmt.Errorf("failed to get random bytes for IV: %w", err) |
| 69 |
} |
| 70 |
keyData.IV = base64.StdEncoding.EncodeToString(ivBytes[:]) |
| 71 |
keyData.MAC = keyData.calculateHash(ssssKey) |
| 72 |
|
| 73 |
return &Key{ |
| 74 |
Key: ssssKey, |
| 75 |
ID: base64.StdEncoding.EncodeToString(keyIDBytes), |
| 76 |
Metadata: &keyData, |
| 77 |
}, nil |
| 78 |
} |
| 79 |
|
| 80 |
// RecoveryKey gets the recovery key for this SSSS key. |
| 81 |
func (key *Key) RecoveryKey() string { |
| 82 |
return utils.EncodeBase58RecoveryKey(key.Key) |
| 83 |
} |
| 84 |
|
| 85 |
// Encrypt encrypts the given data with this key. |
| 86 |
func (key *Key) Encrypt(eventType string, data []byte) EncryptedKeyData { |
| 87 |
aesKey, hmacKey := utils.DeriveKeysSHA256(key.Key, eventType) |
| 88 |
|
| 89 |
iv := utils.GenA256CTRIV() |
| 90 |
payload := make([]byte, base64.StdEncoding.EncodedLen(len(data))) |
| 91 |
base64.StdEncoding.Encode(payload, data) |
| 92 |
utils.XorA256CTR(payload, aesKey, iv) |
| 93 |
|
| 94 |
return EncryptedKeyData{ |
| 95 |
Ciphertext: base64.StdEncoding.EncodeToString(payload), |
| 96 |
IV: base64.StdEncoding.EncodeToString(iv[:]), |
| 97 |
MAC: utils.HMACSHA256B64(payload, hmacKey), |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
// Decrypt decrypts the given encrypted data with this key. |
| 102 |
func (key *Key) Decrypt(eventType string, data EncryptedKeyData) ([]byte, error) { |
| 103 |
var ivBytes [utils.AESCTRIVLength]byte |
| 104 |
decodedIV, _ := base64.StdEncoding.DecodeString(data.IV) |
| 105 |
copy(ivBytes[:], decodedIV) |
| 106 |
|
| 107 |
payload, err := base64.StdEncoding.DecodeString(data.Ciphertext) |
| 108 |
if err != nil { |
| 109 |
return nil, err |
| 110 |
} |
| 111 |
|
| 112 |
// derive the AES and HMAC keys for the requested event type using the SSSS key |
| 113 |
aesKey, hmacKey := utils.DeriveKeysSHA256(key.Key, eventType) |
| 114 |
|
| 115 |
// compare the stored MAC with the one we calculated from the ciphertext |
| 116 |
calcMac := utils.HMACSHA256B64(payload, hmacKey) |
| 117 |
if strings.ReplaceAll(data.MAC, "=", "") != strings.ReplaceAll(calcMac, "=", "") { |
| 118 |
return nil, ErrKeyDataMACMismatch |
| 119 |
} |
| 120 |
|
| 121 |
utils.XorA256CTR(payload, aesKey, ivBytes) |
| 122 |
decryptedDecoded, err := base64.StdEncoding.DecodeString(string(payload)) |
| 123 |
return decryptedDecoded, err |
| 124 |
} |