forked from berty/berty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeystore_message_utils.go
172 lines (136 loc) · 4.67 KB
/
keystore_message_utils.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
package bertyprotocol
import (
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"github.com/gogo/protobuf/proto"
"github.com/ipfs/go-cid"
"github.com/ipfs/go-datastore"
"github.com/libp2p/go-libp2p-core/crypto"
"golang.org/x/crypto/hkdf"
"golang.org/x/crypto/nacl/secretbox"
"berty.tech/berty/v2/go/internal/cryptoutil"
"berty.tech/berty/v2/go/internal/tracer"
"berty.tech/berty/v2/go/pkg/errcode"
"berty.tech/berty/v2/go/pkg/protocoltypes"
)
func sealPayload(payload []byte, ds *protocoltypes.DeviceSecret, deviceSK crypto.PrivKey, g *protocoltypes.Group) ([]byte, []byte, error) {
var (
msgKey [32]byte
err error
)
sig, err := deviceSK.Sign(payload)
if err != nil {
return nil, nil, errcode.ErrCryptoSignature.Wrap(err)
}
if _, msgKey, err = deriveNextKeys(ds.ChainKey, nil, g.GetPublicKey()); err != nil {
return nil, nil, errcode.ErrCryptoKeyGeneration.Wrap(err)
}
return secretbox.Seal(nil, payload, uint64AsNonce(ds.Counter+1), &msgKey), sig, nil
}
func sealEnvelopeInternal(ctx context.Context, payload []byte, ds *protocoltypes.DeviceSecret, deviceSK crypto.PrivKey, g *protocoltypes.Group, attachmentsCIDs [][]byte) ([]byte, error) {
encryptedPayload, sig, err := sealPayload(payload, ds, deviceSK, g)
if err != nil {
return nil, errcode.ErrCryptoEncrypt.Wrap(err)
}
devicePKRaw, err := deviceSK.GetPublic().Raw()
if err != nil {
return nil, errcode.ErrSerialization.Wrap(err)
}
h := &protocoltypes.MessageHeaders{
Counter: ds.Counter + 1,
DevicePK: devicePKRaw,
Sig: sig,
}
tracer.InjectSpanContextToMessageHeaders(ctx, h)
headers, err := proto.Marshal(h)
if err != nil {
return nil, errcode.ErrSerialization.Wrap(err)
}
nonce, err := cryptoutil.GenerateNonce()
if err != nil {
return nil, errcode.ErrCryptoNonceGeneration.Wrap(err)
}
encryptedHeaders := secretbox.Seal(nil, headers, nonce, g.GetSharedSecret())
encryptedAttachmentsCIDs, err := attachmentCIDSliceEncrypt(g, attachmentsCIDs)
if err != nil {
return nil, errcode.ErrCryptoEncrypt.Wrap(err)
}
env, err := proto.Marshal(&protocoltypes.MessageEnvelope{
MessageHeaders: encryptedHeaders,
Message: encryptedPayload,
Nonce: nonce[:],
EncryptedAttachmentCIDs: encryptedAttachmentsCIDs,
})
if err != nil {
return nil, errcode.ErrSerialization.Wrap(err)
}
return env, nil
}
func openEnvelopeHeaders(data []byte, g *protocoltypes.Group) (*protocoltypes.MessageEnvelope, *protocoltypes.MessageHeaders, error) {
env := &protocoltypes.MessageEnvelope{}
err := env.Unmarshal(data)
if err != nil {
return nil, nil, errcode.ErrDeserialization.Wrap(err)
}
nonce, err := cryptoutil.NonceSliceToArray(env.Nonce)
if err != nil {
return nil, nil, errcode.ErrSerialization.Wrap(err)
}
headersBytes, ok := secretbox.Open(nil, env.MessageHeaders, nonce, g.GetSharedSecret())
if !ok {
return nil, nil, errcode.ErrCryptoDecrypt.Wrap(fmt.Errorf("secretbox failed to open headers"))
}
headers := &protocoltypes.MessageHeaders{}
if err := headers.Unmarshal(headersBytes); err != nil {
return nil, nil, errcode.ErrDeserialization.Wrap(err)
}
return env, headers, nil
}
func deriveNextKeys(ck []byte, salt []byte, groupID []byte) ([]byte, [32]byte, error) {
var (
nextMsg [32]byte
err error
)
// Salt length must be equal to hash length (64 bytes for sha256)
hash := sha256.New
// Generate Pseudo Random Key using ck as IKM and salt
prk := hkdf.Extract(hash, ck, salt)
if len(prk) == 0 {
return nil, nextMsg, errcode.ErrInternal
}
// Expand using extracted prk and groupID as info (kind of namespace)
kdf := hkdf.Expand(hash, prk, groupID)
// Generate next KDF and message keys
nextCK, err := ioutil.ReadAll(io.LimitReader(kdf, 32))
if err != nil {
return nil, nextMsg, errcode.ErrCryptoKeyGeneration.Wrap(err)
}
nextMsgSlice, err := ioutil.ReadAll(io.LimitReader(kdf, 32))
if err != nil {
return nil, nextMsg, errcode.ErrCryptoKeyGeneration.Wrap(err)
}
for i, b := range nextMsgSlice {
nextMsg[i] = b
}
return nextCK, nextMsg, nil
}
func idForCachedKey(groupPK, pk []byte, counter uint64) datastore.Key {
return datastore.KeyWithNamespaces([]string{"cachedCKs", hex.EncodeToString(groupPK), hex.EncodeToString(pk), fmt.Sprintf("%d", counter)})
}
func idForCurrentCK(groupPK, pk []byte) datastore.Key {
return datastore.KeyWithNamespaces([]string{"currentCKs", hex.EncodeToString(groupPK), hex.EncodeToString(pk)})
}
func idForCID(id cid.Cid) datastore.Key {
// TODO: specify the id
return datastore.KeyWithNamespaces([]string{"cid", id.String()})
}
func uint64AsNonce(val uint64) *[24]byte {
var nonce [24]byte
binary.BigEndian.PutUint64(nonce[:], val)
return &nonce
}