-
Notifications
You must be signed in to change notification settings - Fork 143
/
session.go
280 lines (239 loc) · 7.77 KB
/
session.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package session
/*
#cgo LDFLAGS: -lthemis -lsoter
#include "session.h"
extern const int GOTHEMIS_INVALID_PARAMETER;
extern const int GOTHEMIS_BUFFER_TOO_SMALL;
extern const int GOTHEMIS_SUCCESS;
extern const int GOTHEMIS_SSESSION_GET_PUB_FOR_ID_ERROR;
extern const int GOTHEMIS_SSESSION_SEND_OUTPUT_TO_PEER;
*/
import "C"
import (
"reflect"
"runtime"
"unsafe"
"github.com/cossacklabs/themis/gothemis/errors"
"github.com/cossacklabs/themis/gothemis/keys"
)
// Secure Session states.
const (
StateIdle = iota
StateNegotiating
StateEstablished
)
// Secure Session states.
//
// Deprecated: Since 0.11. Use "session.State..." constants instead.
const (
STATE_IDLE = StateIdle
STATE_NEGOTIATING = StateNegotiating
STATE_ESTABLISHED = StateEstablished
)
// Errors returned by Secure Session.
var (
ErrCreateSession = errors.New("failed to create secure session object")
ErrDestroySession = errors.New("failed to destroy secure session object")
ErrMessageSize = errors.New("failed to get message size")
ErrMessageData = errors.New("failed to process message data")
ErrNoPublicKey = errors.NewCallbackError("failed to get public key (get_public_key_by_id callback error)")
ErrBadRemoteIDLength = errors.NewCallbackError("incorrect remote id length (0)")
ErrGetRemoteID = errors.NewCallbackError("failed to get session remote id")
ErrMissingClientID = errors.NewWithCode(errors.InvalidParameter, "empty client ID for Secure Session")
ErrMissingPrivateKey = errors.NewWithCode(errors.InvalidParameter, "empty client private key for Secure Session")
ErrMissingMessage = errors.NewWithCode(errors.InvalidParameter, "empty message for Secure Session")
ErrOutOfMemory = errors.NewWithCode(errors.NoMemory, "Secure Session cannot allocate enough memory")
// Deprecated: Since 0.14. Use ErrOutOfMemory instead.
ErrOverflow = ErrOutOfMemory
)
// SessionCallbacks implements a delegate for SecureSession.
type SessionCallbacks interface {
GetPublicKeyForId(ss *SecureSession, id []byte) *keys.PublicKey
StateChanged(ss *SecureSession, state int)
}
// SecureSession is a lightweight mechanism for securing any kind of network communication
// (both private and public networks, including the Internet). It is protocol-agnostic and
// operates on the 5th layer of the network OSI model (the session layer).
type SecureSession struct {
ctx *C.struct_session_with_callbacks_type
clb SessionCallbacks
state int
}
func finalize(ss *SecureSession) {
ss.Close()
}
// C returns sizes as size_t but Go expresses buffer lengths as int.
// Make sure that all sizes are representable in Go and there is no overflows.
func sizeOverflow(n C.size_t) bool {
const maxInt = int(^uint(0) >> 1)
return n > C.size_t(maxInt)
}
// New makes a new Secure Session with provided peer ID, private key, and callbacks.
func New(id []byte, signKey *keys.PrivateKey, callbacks SessionCallbacks) (*SecureSession, error) {
ss := &SecureSession{clb: callbacks}
if nil == id || 0 == len(id) {
return nil, ErrMissingClientID
}
if nil == signKey || 0 == len(signKey.Value) {
return nil, ErrMissingPrivateKey
}
ss.ctx = C.session_init(unsafe.Pointer(&id[0]),
C.size_t(len(id)),
unsafe.Pointer(&signKey.Value[0]),
C.size_t(len(signKey.Value)))
if ss.ctx == nil {
return nil, ErrCreateSession
}
runtime.SetFinalizer(ss, finalize)
return ss, nil
}
// Close destroys a Secure Session.
func (ss *SecureSession) Close() error {
if nil != ss.ctx {
if bool(C.session_destroy(ss.ctx)) {
ss.ctx = nil
} else {
return ErrDestroySession
}
}
return nil
}
//export onPublicKeyForId
func onPublicKeyForId(ssCtx unsafe.Pointer, idPtr unsafe.Pointer, idLen C.size_t, keyPtr unsafe.Pointer, keyLen C.size_t) int {
var ss *SecureSession
if sizeOverflow(idLen) {
return int(C.THEMIS_NO_MEMORY)
}
id := C.GoBytes(idPtr, C.int(idLen))
ss = (*SecureSession)(unsafe.Pointer(uintptr(ssCtx) - unsafe.Offsetof(ss.ctx)))
pub := ss.clb.GetPublicKeyForId(ss, id)
if nil == pub {
return int(C.GOTHEMIS_INVALID_PARAMETER)
}
if len(pub.Value) > int(keyLen) {
return int(C.GOTHEMIS_BUFFER_TOO_SMALL)
}
sliceHeader := reflect.SliceHeader{Data: uintptr(keyPtr), Len: int(keyLen), Cap: int(keyLen)}
key := *(*[]byte)(unsafe.Pointer(&sliceHeader))
copy(key, pub.Value)
return int(C.GOTHEMIS_SUCCESS)
}
//export onStateChanged
func onStateChanged(ssCtx unsafe.Pointer, event int) {
var ss *SecureSession
ss = (*SecureSession)(unsafe.Pointer(uintptr(ssCtx) - unsafe.Offsetof(ss.ctx)))
ss.state = event
ss.clb.StateChanged(ss, event)
}
// GetState returns current state of Secure Session.
func (ss *SecureSession) GetState() int {
return ss.state
}
// ConnectRequest generates a connection request that must be sent to the remote peer.
func (ss *SecureSession) ConnectRequest() ([]byte, error) {
var reqLen C.size_t
if !bool(C.session_connect_size(ss.ctx,
&reqLen)) {
return nil, ErrMessageSize
}
if sizeOverflow(reqLen) {
return nil, ErrOutOfMemory
}
req := make([]byte, reqLen)
if !bool(C.session_connect(&ss.ctx,
unsafe.Pointer(&req[0]),
reqLen)) {
return nil, ErrMessageData
}
return req, nil
}
// Wrap encrypts the provided data for the peer.
func (ss *SecureSession) Wrap(data []byte) ([]byte, error) {
var outLen C.size_t
if nil == data || 0 == len(data) {
return nil, ErrMissingMessage
}
if !bool(C.session_wrap_size(&ss.ctx,
unsafe.Pointer(&data[0]),
C.size_t(len(data)),
&outLen)) {
return nil, ErrMessageSize
}
if sizeOverflow(outLen) {
return nil, ErrOutOfMemory
}
out := make([]byte, outLen)
if !bool(C.session_wrap(&ss.ctx,
unsafe.Pointer(&data[0]),
C.size_t(len(data)),
unsafe.Pointer(&out[0]),
outLen)) {
return nil, ErrMessageData
}
return out, nil
}
// Unwrap decrypts the encrypted data from the peer.
// It is also used for connection negotiation.
func (ss *SecureSession) Unwrap(data []byte) ([]byte, bool, error) {
var outLen C.size_t
if nil == data || 0 == len(data) {
return nil, false, ErrMissingMessage
}
res := C.session_unwrap_size(&ss.ctx,
unsafe.Pointer(&data[0]),
C.size_t(len(data)),
&outLen)
switch {
case (C.GOTHEMIS_SUCCESS == res) && (0 == outLen):
return nil, false, nil
case (C.GOTHEMIS_SSESSION_GET_PUB_FOR_ID_ERROR == res):
return nil, false, ErrNoPublicKey
case (C.GOTHEMIS_BUFFER_TOO_SMALL != res):
return nil, false, ErrMessageSize
}
if sizeOverflow(outLen) {
return nil, false, ErrOutOfMemory
}
out := make([]byte, outLen)
res = C.session_unwrap(&ss.ctx,
unsafe.Pointer(&data[0]),
C.size_t(len(data)),
unsafe.Pointer(&out[0]),
outLen)
switch {
case (C.GOTHEMIS_SUCCESS == res) && (0 == outLen):
return nil, false, nil
case (C.GOTHEMIS_SSESSION_SEND_OUTPUT_TO_PEER == res) && (0 < outLen):
return out, true, nil
case (C.GOTHEMIS_SUCCESS == res) && (0 < outLen):
return out, false, nil
case (C.GOTHEMIS_SSESSION_GET_PUB_FOR_ID_ERROR == res):
return nil, false, ErrNoPublicKey
}
return nil, false, ErrMessageData
}
// GetRemoteID returns ID of the remote peer.
func (ss *SecureSession) GetRemoteID() ([]byte, error) {
// secure_session_get_remote_id
var outLength C.size_t
if C.secure_session_get_remote_id(ss.ctx.session, nil, &outLength) != C.THEMIS_BUFFER_TOO_SMALL {
return nil, ErrGetRemoteID
}
if outLength == 0 {
return nil, ErrBadRemoteIDLength
}
if sizeOverflow(outLength) {
return nil, ErrOutOfMemory
}
out := make([]byte, int(outLength))
if C.secure_session_get_remote_id(ss.ctx.session, (*C.uint8_t)(&out[0]), &outLength) != C.THEMIS_SUCCESS {
return nil, ErrGetRemoteID
}
return out, nil
}
// GetRemoteId returns ID of the remote peer.
//
// Deprecated: Since 0.11. Use GetRemoteID() instead.
func (ss *SecureSession) GetRemoteId() ([]byte, error) {
return ss.GetRemoteID()
}