/
device_keystore_wrapper.go
259 lines (210 loc) · 8.25 KB
/
device_keystore_wrapper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package secretstore
import (
"crypto/ed25519"
crand "crypto/rand"
"encoding/hex"
"fmt"
"strings"
"sync"
"github.com/aead/ecdh"
keystore "github.com/ipfs/go-ipfs-keystore"
"github.com/libp2p/go-libp2p/core/crypto"
"go.uber.org/zap"
"berty.tech/weshnet/pkg/cryptoutil"
"berty.tech/weshnet/pkg/errcode"
"berty.tech/weshnet/pkg/protocoltypes"
)
const (
keyAccount = "accountSK"
keyAccountProof = "accountProofSK"
keyDevice = "deviceSK"
keyMemberDevice = "memberDeviceSK"
keyMember = "memberSK"
keyContactGroup = "contactGroupSK"
)
// deviceKeystore is a wrapper around a keystore.Keystore object.
// It contains methods to manipulate member and device keys.
type deviceKeystore struct {
keystore keystore.Keystore
mu sync.Mutex
logger *zap.Logger
}
// newDeviceKeystore instantiate a new device keystore
func newDeviceKeystore(ks keystore.Keystore, logger *zap.Logger) *deviceKeystore {
if logger == nil {
logger = zap.NewNop()
}
return &deviceKeystore{
keystore: ks,
logger: logger,
}
}
// getAccountPrivateKey returns the private key of the current account
func (a *deviceKeystore) getAccountPrivateKey() (crypto.PrivKey, error) {
a.mu.Lock()
defer a.mu.Unlock()
return a.getOrGenerateNamedKey(keyAccount)
}
// getAccountProofPrivateKey returns the private proof key of
// the current account
func (a *deviceKeystore) getAccountProofPrivateKey() (crypto.PrivKey, error) {
a.mu.Lock()
defer a.mu.Unlock()
return a.getOrGenerateNamedKey(keyAccountProof)
}
// devicePrivateKey returns the current private key of the current device for
// the account and one-to-one conversations
func (a *deviceKeystore) devicePrivateKey() (crypto.PrivKey, error) {
a.mu.Lock()
defer a.mu.Unlock()
return a.getOrGenerateNamedKey(keyDevice)
}
// contactGroupPrivateKey retrieves the key for the contact group
// shared with the supplied contact's public key, this key will be derived to
// form the contact group keys
func (a *deviceKeystore) contactGroupPrivateKey(contactPublicKey crypto.PubKey) (crypto.PrivKey, error) {
accountPrivateKey, err := a.getAccountPrivateKey()
if err != nil {
return nil, errcode.ErrInternal.Wrap(err)
}
return a.getOrComputeECDH(keyContactGroup, contactPublicKey, accountPrivateKey)
}
// memberDeviceForMultiMemberGroup retrieves the device private key for the
// supplied group
func (a *deviceKeystore) memberDeviceForMultiMemberGroup(groupPublicKey crypto.PubKey) (*ownMemberDevice, error) {
memberPrivateKey, err := a.computeMemberKeyForMultiMemberGroup(groupPublicKey)
if err != nil {
return nil, errcode.ErrInternal.Wrap(fmt.Errorf("unable to get or generate a device key for group member: %w", err))
}
devicePrivateKey, err := a.getOrGenerateDeviceKeyForMultiMemberGroup(groupPublicKey)
if err != nil {
return nil, errcode.ErrInternal.Wrap(err)
}
return newOwnMemberDevice(memberPrivateKey, devicePrivateKey), nil
}
// memberDeviceForGroup computes or retrieves the member and device key for the
// supplied group
func (a *deviceKeystore) memberDeviceForGroup(group *protocoltypes.Group) (*ownMemberDevice, error) {
publicKey, err := group.GetPubKey()
if err != nil {
return nil, errcode.ErrInvalidInput.Wrap(fmt.Errorf("unable to get public key for group: %w", err))
}
switch group.GetGroupType() {
case protocoltypes.GroupTypeAccount, protocoltypes.GroupTypeContact:
memberPrivateKey, err := a.getAccountPrivateKey()
if err != nil {
return nil, errcode.ErrInternal.Wrap(err)
}
devicePrivateKey, err := a.devicePrivateKey()
if err != nil {
return nil, errcode.ErrInternal.Wrap(err)
}
return newOwnMemberDevice(memberPrivateKey, devicePrivateKey), nil
case protocoltypes.GroupTypeMultiMember:
return a.memberDeviceForMultiMemberGroup(publicKey)
}
return nil, errcode.ErrInvalidInput.Wrap(fmt.Errorf("unknown group type"))
}
// getOrGenerateNamedKey retrieves a private key by its name, or generate it
// if missing
func (a *deviceKeystore) getOrGenerateNamedKey(name string) (crypto.PrivKey, error) {
privateKey, err := a.keystore.Get(name)
if err == nil {
return privateKey, nil
} else if err.Error() != keystore.ErrNoSuchKey.Error() {
return nil, errcode.ErrDBRead.Wrap(fmt.Errorf("unable to perform get operation on keystore: %w", err))
}
privateKey, _, err = crypto.GenerateEd25519Key(crand.Reader)
if err != nil {
return nil, errcode.ErrCryptoKeyGeneration.Wrap(fmt.Errorf("unable to generate an ed25519 key: %w", err))
}
if err := a.keystore.Put(name, privateKey); err != nil {
return nil, errcode.ErrDBWrite.Wrap(fmt.Errorf("unable to perform put operation on keystore: %w", err))
}
return privateKey, nil
}
// getOrGenerateDeviceKeyForMultiMemberGroup fetches or generate a new device
// key for a multi-member group. The results do not need to be deterministic
// as it will only be used on the current device.
func (a *deviceKeystore) getOrGenerateDeviceKeyForMultiMemberGroup(groupPublicKey crypto.PubKey) (crypto.PrivKey, error) {
a.mu.Lock()
defer a.mu.Unlock()
groupPublicKeyRaw, err := groupPublicKey.Raw()
if err != nil {
return nil, errcode.ErrSerialization.Wrap(err)
}
name := strings.Join([]string{keyMemberDevice, hex.EncodeToString(groupPublicKeyRaw)}, "_")
return a.getOrGenerateNamedKey(name)
}
// getOrComputeECDH fetches a named private key or computes one via an
// elliptic-curve Diffie-Hellman key agreement if not cached
func (a *deviceKeystore) getOrComputeECDH(nameSpace string, publicKey crypto.PubKey, ownPrivateKey crypto.PrivKey) (crypto.PrivKey, error) {
a.mu.Lock()
defer a.mu.Unlock()
publicKeyRaw, err := publicKey.Raw()
if err != nil {
return nil, errcode.ErrSerialization.Wrap(err)
}
name := strings.Join([]string{nameSpace, hex.EncodeToString(publicKeyRaw)}, "_")
privateKey, err := a.keystore.Get(name)
if err == nil {
return privateKey, nil
} else if err.Error() != keystore.ErrNoSuchKey.Error() {
return nil, errcode.ErrDBRead.Wrap(fmt.Errorf("unable to perform get operation on keystore: %w", err))
}
privateKeyBytes, publicKeyBytes, err := cryptoutil.EdwardsToMontgomery(ownPrivateKey, publicKey)
if err != nil {
return nil, errcode.ErrCryptoKeyConversion.Wrap(err)
}
secret := ecdh.X25519().ComputeSecret(privateKeyBytes, publicKeyBytes)
groupSecretPrivateKey := ed25519.NewKeyFromSeed(secret)
privateKey, _, err = crypto.KeyPairFromStdKey(&groupSecretPrivateKey)
if err != nil {
return nil, errcode.ErrCryptoKeyConversion.Wrap(err)
}
if err := a.keystore.Put(name, privateKey); err != nil {
return nil, errcode.ErrDBWrite.Wrap(err)
}
return privateKey, nil
}
// computeMemberKeyForMultiMemberGroup returns a deterministic private key
// for a multi member group, this allows a group to be joined from two
// different devices simultaneously without requiring a consensus.
func (a *deviceKeystore) computeMemberKeyForMultiMemberGroup(groupPublicKey crypto.PubKey) (crypto.PrivKey, error) {
accountProofPrivateKey, err := a.getAccountProofPrivateKey()
if err != nil {
return nil, errcode.ErrInternal.Wrap(err)
}
return a.getOrComputeECDH(keyMember, groupPublicKey, accountProofPrivateKey)
}
// restoreAccountKeys restores exported LibP2P keys into the deviceKeystore, it
// will fail if accounts keys are already created or imported into the keystore
func (a *deviceKeystore) restoreAccountKeys(accountPrivateKeyBytes []byte, accountProofPrivateKeyBytes []byte) error {
privateKeys := map[string]crypto.PrivKey{}
for keyName, keyBytes := range map[string][]byte{
keyAccount: accountPrivateKeyBytes,
keyAccountProof: accountProofPrivateKeyBytes,
} {
var err error
privateKeys[keyName], err = getEd25519PrivateKeyFromLibP2PFormattedBytes(keyBytes)
if err != nil {
return errcode.ErrDeserialization.Wrap(err)
}
}
if privateKeys[keyAccount].Equals(privateKeys[keyAccountProof]) {
return errcode.ErrInvalidInput.Wrap(fmt.Errorf("the account key cannot be the same value as the account proof key"))
}
for keyName := range privateKeys {
if exists, err := a.keystore.Has(keyName); err != nil {
return errcode.ErrDBRead.Wrap(err)
} else if exists {
return errcode.ErrInvalidInput.Wrap(fmt.Errorf("an account is already set in this keystore"))
}
}
for keyName, privateKey := range privateKeys {
if err := a.keystore.Put(keyName, privateKey); err != nil {
return errcode.ErrDBWrite.Wrap(err)
}
}
return nil
}