beaconcrypt 0.4.0

Cryptographic transport for C2 channels
Documentation
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// SPDX-License-Identifier: 0BSD

package beaconcrypt

/*
#cgo windows LDFLAGS: -L${SRCDIR}/target/x86_64-pc-windows-gnu/release -l:libbeaconcrypt.a -lbcrypt -lws2_32 -luserenv -ldbghelp -lntdll
#cgo linux LDFLAGS: -L${SRCDIR}/target/release -l:libbeaconcrypt.a
#cgo darwin LDFLAGS: ${SRCDIR}/target/release/libbeaconcrypt.a
#include <stdint.h>
#include <stdlib.h>

typedef struct {
	uint8_t *ptr;
	uintptr_t len;
	uintptr_t cap;
} beaconcrypt_buffer;

typedef struct {
	beaconcrypt_buffer response;
	beaconcrypt_buffer beacon_pk;
	uint64_t key_id;
} beaconcrypt_registration_response;

typedef struct {
	beaconcrypt_buffer data;
	beaconcrypt_buffer key;
	beaconcrypt_buffer state;
	uint64_t key_id;
	uint64_t seq;
} beaconcrypt_encrypt_state;

void beaconcrypt_free_buffer(beaconcrypt_buffer buffer);
void *beaconcrypt_server_new(uint64_t server_kid);
void *beaconcrypt_server_new_from_seed(uint64_t server_kid, const uint8_t *seed_ptr, uintptr_t seed_len);
void *beaconcrypt_server_new_from_state(uint64_t server_kid, const uint8_t *seed_ptr, uintptr_t seed_len, const uint8_t *state_ptr, uintptr_t state_len);
void *beaconcrypt_beacon_new(uint64_t server_kid, const uint8_t *server_pk_ptr, uintptr_t server_pk_len);
void beaconcrypt_free(void *handle);
beaconcrypt_buffer beaconcrypt_identity_pk(const void *handle);
beaconcrypt_buffer beaconcrypt_generate_registration(void *handle);
beaconcrypt_registration_response beaconcrypt_register_beacon(void *handle, const uint8_t *reg_ptr, uintptr_t reg_len, const uint8_t *msg_ptr, uintptr_t msg_len);
beaconcrypt_buffer beaconcrypt_process_initial_message(void *handle, const uint8_t *ptr, uintptr_t len);
beaconcrypt_buffer beaconcrypt_encrypt_to_beacon(void *handle, uint64_t key_id, const uint8_t *ptr, uintptr_t len);
beaconcrypt_buffer beaconcrypt_decrypt_beacon_message(void *handle, const uint8_t *ptr, uintptr_t len);
beaconcrypt_encrypt_state beaconcrypt_encrypt_and_update(void *handle, uint64_t key_id, const uint8_t *ptr, uintptr_t len);
beaconcrypt_buffer beaconcrypt_encrypt_and_update_json(void *handle, uint64_t key_id, const uint8_t *ptr, uintptr_t len);
beaconcrypt_encrypt_state beaconcrypt_decrypt_and_update(void *handle, const uint8_t *ptr, uintptr_t len);
beaconcrypt_buffer beaconcrypt_decrypt_and_update_json(void *handle, const uint8_t *ptr, uintptr_t len);
beaconcrypt_buffer beaconcrypt_export_state(const void *handle);
beaconcrypt_buffer beaconcrypt_encrypt_to_server(void *handle, const uint8_t *ptr, uintptr_t len);
beaconcrypt_buffer beaconcrypt_decrypt_server_message(void *handle, const uint8_t *ptr, uintptr_t len);
*/
import "C"

import (
	"errors"
	"runtime"
	"sync"
	"unsafe"
)

var (
	ErrClosed    = errors.New("beaconcrypt: handle is closed")
	ErrCrypto    = errors.New("beaconcrypt: cryptographic operation failed")
	ErrSeedSize  = errors.New("beaconcrypt: server seed must be 32 bytes")
	ErrEmptyData = errors.New("beaconcrypt: input must not be empty")
)

type nativeHandle struct {
	mu     sync.Mutex
	handle unsafe.Pointer
}

// Server is safe for concurrent use. Calls on one Server are serialized because
// they mutate shared native ratchet state.
type Server struct {
	native *nativeHandle
}

// Beacon is safe for concurrent use. Calls on one Beacon are serialized because
// they mutate shared native ratchet state.
type Beacon struct {
	native *nativeHandle
}

type RegistrationResponse struct {
	Serialized []byte
	BeaconPK   []byte
	KeyID      uint64
}

type EncryptState struct {
	Data []byte
	// Key is the current directional KDF state.
	Key []byte
	// State is the complete ratchet state serialized as JSON.
	State string
	KeyID uint64
	Seq   uint64
}

func NewServer(serverKID uint64) (*Server, error) {
	handle := C.beaconcrypt_server_new(C.uint64_t(serverKID))
	if handle == nil {
		return nil, ErrCrypto
	}
	server := &Server{native: newNativeHandle(handle)}
	return server, nil
}

func NewServerFromSeed(serverKID uint64, seed []byte) (*Server, error) {
	if len(seed) != 32 {
		return nil, ErrSeedSize
	}
	ptr, free := cBytes(seed)
	defer free()
	handle := C.beaconcrypt_server_new_from_seed(C.uint64_t(serverKID), ptr, C.uintptr_t(len(seed)))
	if handle == nil {
		return nil, ErrCrypto
	}
	server := &Server{native: newNativeHandle(handle)}
	return server, nil
}

func NewServerFromState(serverKID uint64, seed []byte, state string) (*Server, error) {
	if len(seed) != 0 && len(seed) != 32 {
		return nil, ErrSeedSize
	}
	if len(state) == 0 {
		return nil, ErrEmptyData
	}
	seedPtr, seedFree := cBytes(seed)
	defer seedFree()
	stateBytes := []byte(state)
	statePtr, stateFree := cBytes(stateBytes)
	defer stateFree()
	handle := C.beaconcrypt_server_new_from_state(
		C.uint64_t(serverKID),
		seedPtr,
		C.uintptr_t(len(seed)),
		statePtr,
		C.uintptr_t(len(stateBytes)),
	)
	if handle == nil {
		return nil, ErrCrypto
	}
	server := &Server{native: newNativeHandle(handle)}
	return server, nil
}

func NewBeacon(serverKID uint64, serverPK []byte) (*Beacon, error) {
	ptr, free := cBytes(serverPK)
	defer free()
	handle := C.beaconcrypt_beacon_new(C.uint64_t(serverKID), ptr, C.uintptr_t(len(serverPK)))
	if handle == nil {
		return nil, ErrCrypto
	}
	beacon := &Beacon{native: newNativeHandle(handle)}
	return beacon, nil
}

func (s *Server) Close() {
	if s == nil {
		return
	}
	s.native.close()
}

func (b *Beacon) Close() {
	if b == nil {
		return
	}
	b.native.close()
}

func (s *Server) IdentityPK() ([]byte, error) {
	if s == nil {
		return nil, ErrClosed
	}
	return withNativeHandle(s.native, func(handle unsafe.Pointer) ([]byte, error) {
		return copyBuffer(C.beaconcrypt_identity_pk(handle))
	})
}

func (b *Beacon) GenerateRegistration() ([]byte, error) {
	if b == nil {
		return nil, ErrClosed
	}
	return withNativeHandle(b.native, func(handle unsafe.Pointer) ([]byte, error) {
		return copyBuffer(C.beaconcrypt_generate_registration(handle))
	})
}

func (s *Server) RegisterBeacon(registration, initialMessage []byte) (*RegistrationResponse, error) {
	if s == nil {
		return nil, ErrClosed
	}
	return withNativeHandle(s.native, func(handle unsafe.Pointer) (*RegistrationResponse, error) {
		if len(registration) == 0 {
			return nil, ErrEmptyData
		}
		regPtr, regFree := cBytes(registration)
		defer regFree()
		msgPtr, msgFree := cBytes(initialMessage)
		defer msgFree()
		response := C.beaconcrypt_register_beacon(
			handle,
			regPtr,
			C.uintptr_t(len(registration)),
			msgPtr,
			C.uintptr_t(len(initialMessage)),
		)
		serialized, err := copyBuffer(response.response)
		if err != nil {
			C.beaconcrypt_free_buffer(response.beacon_pk)
			return nil, err
		}
		beaconPK, err := copyBuffer(response.beacon_pk)
		if err != nil {
			return nil, err
		}
		return &RegistrationResponse{
			Serialized: serialized,
			BeaconPK:   beaconPK,
			KeyID:      uint64(response.key_id),
		}, nil
	})
}

func (b *Beacon) ProcessInitialMessage(data []byte) ([]byte, error) {
	if b == nil {
		return nil, ErrClosed
	}
	return withNativeHandle(b.native, func(handle unsafe.Pointer) ([]byte, error) {
		return callUnary(data, func(ptr *C.uint8_t, len C.uintptr_t) C.beaconcrypt_buffer {
			return C.beaconcrypt_process_initial_message(handle, ptr, len)
		})
	})
}

func (s *Server) EncryptToBeacon(keyID uint64, plaintext []byte) ([]byte, error) {
	if s == nil {
		return nil, ErrClosed
	}
	return withNativeHandle(s.native, func(handle unsafe.Pointer) ([]byte, error) {
		return callUnary(plaintext, func(ptr *C.uint8_t, len C.uintptr_t) C.beaconcrypt_buffer {
			return C.beaconcrypt_encrypt_to_beacon(handle, C.uint64_t(keyID), ptr, len)
		})
	})
}

func (s *Server) DecryptBeaconMessage(ciphertext []byte) ([]byte, error) {
	if s == nil {
		return nil, ErrClosed
	}
	return withNativeHandle(s.native, func(handle unsafe.Pointer) ([]byte, error) {
		return callUnary(ciphertext, func(ptr *C.uint8_t, len C.uintptr_t) C.beaconcrypt_buffer {
			return C.beaconcrypt_decrypt_beacon_message(handle, ptr, len)
		})
	})
}

func (s *Server) EncryptAndUpdate(keyID uint64, plaintext []byte) (*EncryptState, error) {
	if s == nil {
		return nil, ErrClosed
	}
	return withNativeHandle(s.native, func(handle unsafe.Pointer) (*EncryptState, error) {
		return callStateUpdate(plaintext, func(ptr *C.uint8_t, len C.uintptr_t) C.beaconcrypt_encrypt_state {
			return C.beaconcrypt_encrypt_and_update(handle, C.uint64_t(keyID), ptr, len)
		})
	})
}

func (s *Server) EncryptAndUpdateJSON(keyID uint64, plaintext []byte) (string, error) {
	if s == nil {
		return "", ErrClosed
	}
	return withNativeHandle(s.native, func(handle unsafe.Pointer) (string, error) {
		data, err := callUnary(plaintext, func(ptr *C.uint8_t, len C.uintptr_t) C.beaconcrypt_buffer {
			return C.beaconcrypt_encrypt_and_update_json(handle, C.uint64_t(keyID), ptr, len)
		})
		if err != nil {
			return "", err
		}
		return string(data), nil
	})
}

func (s *Server) DecryptAndUpdate(ciphertext []byte) (*EncryptState, error) {
	if s == nil {
		return nil, ErrClosed
	}
	return withNativeHandle(s.native, func(handle unsafe.Pointer) (*EncryptState, error) {
		return callStateUpdate(ciphertext, func(ptr *C.uint8_t, len C.uintptr_t) C.beaconcrypt_encrypt_state {
			return C.beaconcrypt_decrypt_and_update(handle, ptr, len)
		})
	})
}

func (s *Server) DecryptAndUpdateJSON(ciphertext []byte) (string, error) {
	if s == nil {
		return "", ErrClosed
	}
	return withNativeHandle(s.native, func(handle unsafe.Pointer) (string, error) {
		data, err := callUnary(ciphertext, func(ptr *C.uint8_t, len C.uintptr_t) C.beaconcrypt_buffer {
			return C.beaconcrypt_decrypt_and_update_json(handle, ptr, len)
		})
		if err != nil {
			return "", err
		}
		return string(data), nil
	})
}

func (s *Server) ExportState() (string, error) {
	if s == nil {
		return "", ErrClosed
	}
	return withNativeHandle(s.native, func(handle unsafe.Pointer) (string, error) {
		data, err := copyBuffer(C.beaconcrypt_export_state(handle))
		if err != nil {
			return "", err
		}
		return string(data), nil
	})
}

func (b *Beacon) EncryptToServer(plaintext []byte) ([]byte, error) {
	if b == nil {
		return nil, ErrClosed
	}
	return withNativeHandle(b.native, func(handle unsafe.Pointer) ([]byte, error) {
		return callUnary(plaintext, func(ptr *C.uint8_t, len C.uintptr_t) C.beaconcrypt_buffer {
			return C.beaconcrypt_encrypt_to_server(handle, ptr, len)
		})
	})
}

func (b *Beacon) DecryptServerMessage(ciphertext []byte) ([]byte, error) {
	if b == nil {
		return nil, ErrClosed
	}
	return withNativeHandle(b.native, func(handle unsafe.Pointer) ([]byte, error) {
		return callUnary(ciphertext, func(ptr *C.uint8_t, len C.uintptr_t) C.beaconcrypt_buffer {
			return C.beaconcrypt_decrypt_server_message(handle, ptr, len)
		})
	})
}

func withNativeHandle[T any](
	native *nativeHandle,
	call func(unsafe.Pointer) (T, error),
) (T, error) {
	var zero T
	if native == nil {
		return zero, ErrClosed
	}
	native.mu.Lock()
	defer native.mu.Unlock()
	defer runtime.KeepAlive(native)
	if native.handle == nil {
		return zero, ErrClosed
	}
	return call(native.handle)
}

func newNativeHandle(handle unsafe.Pointer) *nativeHandle {
	native := &nativeHandle{handle: handle}
	runtime.SetFinalizer(native, (*nativeHandle).close)
	return native
}

func (native *nativeHandle) close() {
	if native == nil {
		return
	}
	native.mu.Lock()
	defer native.mu.Unlock()
	defer runtime.KeepAlive(native)
	runtime.SetFinalizer(native, nil)
	if native.handle != nil {
		C.beaconcrypt_free(native.handle)
		native.handle = nil
	}
}

func callUnary(data []byte, call func(*C.uint8_t, C.uintptr_t) C.beaconcrypt_buffer) ([]byte, error) {
	if len(data) == 0 {
		return nil, ErrEmptyData
	}
	ptr, free := cBytes(data)
	defer free()
	return copyBuffer(call(ptr, C.uintptr_t(len(data))))
}

func callStateUpdate(data []byte, call func(*C.uint8_t, C.uintptr_t) C.beaconcrypt_encrypt_state) (*EncryptState, error) {
	if len(data) == 0 {
		return nil, ErrEmptyData
	}
	ptr, free := cBytes(data)
	defer free()
	state := call(ptr, C.uintptr_t(len(data)))
	output, err := copyBuffer(state.data)
	if err != nil {
		C.beaconcrypt_free_buffer(state.key)
		C.beaconcrypt_free_buffer(state.state)
		return nil, err
	}
	key, err := copyBuffer(state.key)
	if err != nil {
		C.beaconcrypt_free_buffer(state.state)
		return nil, err
	}
	serializedState, err := copyBuffer(state.state)
	if err != nil {
		return nil, err
	}
	return &EncryptState{
		Data:  output,
		Key:   key,
		State: string(serializedState),
		KeyID: uint64(state.key_id),
		Seq:   uint64(state.seq),
	}, nil
}

func copyBuffer(buffer C.beaconcrypt_buffer) ([]byte, error) {
	if buffer.ptr == nil {
		return nil, ErrCrypto
	}
	defer C.beaconcrypt_free_buffer(buffer)
	if buffer.len == 0 {
		return []byte{}, nil
	}
	return C.GoBytes(unsafe.Pointer(buffer.ptr), C.int(buffer.len)), nil
}

func cBytes(data []byte) (*C.uint8_t, func()) {
	if len(data) == 0 {
		return nil, func() {}
	}
	ptr := C.CBytes(data)
	return (*C.uint8_t)(ptr), func() { C.free(ptr) }
}