-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmessage.go
173 lines (140 loc) · 3.97 KB
/
message.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
package session
import (
"crypto/rand"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"io"
"regexp"
"time"
"github.com/nknorg/nkngomobile"
"github.com/nknorg/nkn/v2/crypto/ed25519"
"golang.org/x/crypto/nacl/box"
)
const (
nonceSize = 24
sharedKeySize = 32
maxAddrSize = 512
maxSessionMetadataSize = 1024
maxSessionMsgOverhead = 1024
ActionGetPubAddr = "getPubAddr"
)
type Request struct {
Action string `json:"action"`
SessionID []byte `json:"sessionID"`
}
type PubAddr struct {
IP string `json:"ip"`
Port uint32 `json:"port"`
InPrice string `json:"inPrice,omitempty"`
OutPrice string `json:"outPrice,omitempty"`
}
func (pa *PubAddr) String() string {
return fmt.Sprintf("%v:%v", pa.IP, pa.Port)
}
type PubAddrs struct {
Addrs []*PubAddr `json:"addrs"`
SessionClosed bool `json:"sessionClosed"`
}
func (c *TunaSessionClient) getOrComputeSharedKey(remotePublicKey []byte) (*[sharedKeySize]byte, error) {
k := hex.EncodeToString(remotePublicKey)
c.RLock()
sharedKey, ok := c.sharedKeys[k]
c.RUnlock()
if ok && sharedKey != nil {
return sharedKey, nil
}
if len(remotePublicKey) != ed25519.PublicKeySize {
return nil, fmt.Errorf("public key length is %d, expecting %d", len(remotePublicKey), ed25519.PublicKeySize)
}
var pk [ed25519.PublicKeySize]byte
copy(pk[:], remotePublicKey)
curve25519PublicKey, ok := ed25519.PublicKeyToCurve25519PublicKey(&pk)
if !ok {
return nil, fmt.Errorf("converting public key %x to curve25519 public key failed", remotePublicKey)
}
var sk [ed25519.PrivateKeySize]byte
copy(sk[:], c.clientAccount.PrivKey())
curveSecretKey := ed25519.PrivateKeyToCurve25519PrivateKey(&sk)
sharedKey = new([sharedKeySize]byte)
box.Precompute(sharedKey, curve25519PublicKey, curveSecretKey)
c.Lock()
c.sharedKeys[k] = sharedKey
c.Unlock()
return sharedKey, nil
}
func encrypt(message []byte, sharedKey *[sharedKeySize]byte) ([]byte, []byte, error) {
encrypted := make([]byte, len(message)+box.Overhead)
var nonce [nonceSize]byte
if _, err := rand.Read(nonce[:]); err != nil {
return nil, nil, err
}
box.SealAfterPrecomputation(encrypted[:0], message, &nonce, sharedKey)
return encrypted, nonce[:], nil
}
func decrypt(message []byte, nonce [nonceSize]byte, sharedKey *[sharedKeySize]byte) ([]byte, error) {
decrypted := make([]byte, len(message)-box.Overhead)
_, ok := box.OpenAfterPrecomputation(decrypted[:0], message, &nonce, sharedKey)
if !ok {
return nil, errors.New("decrypt message failed")
}
return decrypted, nil
}
func writeMessage(conn *Conn, buf []byte, writeTimeout time.Duration) error {
conn.WriteLock.Lock()
defer conn.WriteLock.Unlock()
msgSizeBuf := make([]byte, 4)
binary.LittleEndian.PutUint32(msgSizeBuf, uint32(len(buf)))
if writeTimeout > 0 {
conn.SetWriteDeadline(time.Now().Add(writeTimeout))
}
_, err := conn.Write(msgSizeBuf)
if err != nil {
return err
}
_, err = conn.Write(buf)
if err != nil {
return err
}
if writeTimeout > 0 {
conn.SetWriteDeadline(zeroTime)
}
return nil
}
func readMessage(conn *Conn, maxMsgSize uint32) ([]byte, error) {
conn.ReadLock.Lock()
defer conn.ReadLock.Unlock()
msgSizeBuf := make([]byte, 4)
_, err := io.ReadFull(conn, msgSizeBuf)
if err != nil {
return nil, err
}
msgSize := binary.LittleEndian.Uint32(msgSizeBuf)
if msgSize > maxMsgSize {
return nil, fmt.Errorf("invalid message size %d, should be no greater than %d", msgSize, maxMsgSize)
}
buf := make([]byte, msgSize)
_, err = io.ReadFull(conn, buf)
if err != nil {
return nil, err
}
return buf, nil
}
func getAcceptAddrs(addrsRe *nkngomobile.StringArray) ([]*regexp.Regexp, error) {
var addrs []string
if addrsRe == nil {
addrs = []string{DefaultSessionAllowAddr}
} else {
addrs = addrsRe.Elems()
}
var err error
acceptAddrs := make([]*regexp.Regexp, len(addrs))
for i := 0; i < len(acceptAddrs); i++ {
acceptAddrs[i], err = regexp.Compile(addrs[i])
if err != nil {
return nil, err
}
}
return acceptAddrs, nil
}