-
Notifications
You must be signed in to change notification settings - Fork 12
/
kx.go
159 lines (143 loc) · 4.2 KB
/
kx.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
// Copyright (c) 2016,2017 Company 0, LLC.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package session
import (
"crypto/rand"
"encoding/binary"
"errors"
"fmt"
"io"
"github.com/companyzero/bisonrelay/zkidentity"
"github.com/companyzero/sntrup4591761"
"golang.org/x/crypto/nacl/secretbox"
)
var (
ErrEncrypt = errors.New("encrypt failure")
ErrDecrypt = errors.New("decrypt failure")
ErrOverflow = errors.New("message too large")
ErrInvalidKx = errors.New("invalid kx")
ErrMarshal = errors.New("could not marshal")
ErrUnmarshal = errors.New("could not unmarshal")
ErrNilTheirPubKey = errors.New("nil TheirPublicKey")
)
// KX allows two peers to derive a pair of shared keys. One peer must trigger
// Initiate (the client) while the other (the server) should call Init once
// followed by Respond for each connection.
type KX struct {
Conn io.ReadWriter
MaxMessageSize uint
OurPrivateKey *zkidentity.FixedSizeSntrupPrivateKey
OurPublicKey *zkidentity.FixedSizeSntrupPublicKey
TheirPublicKey *zkidentity.FixedSizeSntrupPublicKey
writeKey *[32]byte
readKey *[32]byte
writeSeq *sequence
readSeq *sequence
}
// Initiate performs a key exchange on behalf of a connecting client. A key
// exchange involves the following variables:
// k1, k2, k3, k4: NTRU Prime shared keys.
// c1, c2, c3, c4: NTRU Prime ciphertexts corresponding to k1, k2, k3, k4.
// From the perspective of the initiator, the process unfolds as follows:
func (kx *KX) Initiate() error {
if kx.TheirPublicKey == nil {
return ErrNilTheirPubKey
}
// Step 1: Generate k1, send c1.
c, k1, err := sntrup4591761.Encapsulate(rand.Reader, (*sntrup4591761.PublicKey)(kx.TheirPublicKey))
if err != nil {
return ErrEncrypt
}
var lenBytes [4]byte
binary.LittleEndian.PutUint32(lenBytes[:], uint32(len(c)))
_, err = kx.Conn.Write(lenBytes[:])
if err != nil {
return err
}
_, err = kx.Conn.Write(c[:])
if err != nil {
return err
}
kx.writeKey = k1
kx.readKey = k1
cn := newSequence(halfForClient)
sn := newSequence(halfForServer)
kx.writeSeq = cn
kx.readSeq = sn
return nil
}
// Respond performs a key exchange on behalf of a responding server. A key
// exchange involves the following variables:
// k1, k2, k3, k4: NTRU Prime shared keys.
// c1, c2, c3, c4: NTRU Prime ciphertexts corresponding to k1, k2, k3, k4.
// From the perspective of the responder, the process unfolds as follows:
func (kx *KX) Respond() error {
// Step 1: Receive c1, obtain k1.
var lenBytes [4]byte
_, err := kx.Conn.Read(lenBytes[:])
if err != nil {
return err
}
l := binary.LittleEndian.Uint32(lenBytes[:])
if l != sntrup4591761.CiphertextSize {
return fmt.Errorf("invalid ciphertext size received")
}
c := new(sntrup4591761.Ciphertext)
_, err = kx.Conn.Read(c[:])
if err != nil {
return err
}
k1, ok := sntrup4591761.Decapsulate(c, (*sntrup4591761.PrivateKey)(kx.OurPrivateKey))
if ok != 1 {
return ErrInvalidKx
}
kx.writeKey = k1
kx.readKey = k1
cn := newSequence(halfForClient)
sn := newSequence(halfForServer)
kx.writeSeq = sn
kx.readSeq = cn
return nil
}
func (kx *KX) Read() ([]byte, error) {
var lenBytes [4]byte
_, err := io.ReadFull(kx.Conn, lenBytes[:])
if err != nil {
return nil, err
}
l := binary.LittleEndian.Uint32(lenBytes[:])
if l > uint32(kx.MaxMessageSize) {
return nil, fmt.Errorf("len > max message size: %d > %d", l, kx.MaxMessageSize)
}
payload := make([]byte, l)
_, err = io.ReadFull(kx.Conn, payload)
if err != nil {
return nil, err
}
data, ok := secretbox.Open(nil, payload, kx.readSeq.Nonce(), kx.readKey)
kx.readSeq.Decrease()
if !ok {
return payload, ErrDecrypt
}
return data, nil
}
// Write encrypts and marshals data to the underlying writer.
func (kx *KX) Write(data []byte) error {
payload := secretbox.Seal(nil, data, kx.writeSeq.Nonce(), kx.writeKey)
kx.writeSeq.Decrease()
if uint(len(payload)) > kx.MaxMessageSize {
return ErrOverflow
}
var lenBytes [4]byte
binary.LittleEndian.PutUint32(lenBytes[:], uint32(len(payload)))
_, err := kx.Conn.Write(lenBytes[:])
if err != nil {
return err
}
_, err = kx.Conn.Write(payload)
if err != nil {
return err
}
return nil
}