/
crypt.c
2401 lines (2194 loc) · 79.7 KB
/
crypt.c
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* crypt.c
* (C) 2017, all rights reserved,
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* PROTOCOL SUMMARY:
*
* HANDSHAKE:
* (0) Server publishes the URL(RSACertificateHash), where
* - RSACertificateHash is a cryptographic hash function of an RSA
* certificate.
* (1) Client sends a GET_COOKIE request.
* (2) Server responds with a COOKIE(Cookie) reply.
* (3) [OPTIONAL] Client sends a GET_CERTIFICATE(Cookie) request, where:
* - Cookie is the same as message (2).
* - This is OPTIONAL if the client has a cached copy of the
* RSACertificate corresponding to RSACertificateHash from message (0).
* (4) [OPTIONAL] Server responds with a CERTIFICATE(RSACertificate) message.
* The client verifies that hash(RSACertificate) == RSACertificateHash
* (5) Client sends a GET_KEY(Cookie, ClientDHPublicKey) request, where:
* - Cookie is the same as message (2).
* - ClientDHPublicKey is the client's DH public key
* (6) Server responds with a
* KEY(ServerDHPublicKey, encrypt_DHSharedKey(
* sign_RSAPrivateKey(SessionKey, SessionKeyId)))
* reply, where:
* - ServerDHPublicKey is the server's DH public key.
* - DHSharedKey is the DH shared secret key.
* - RSAPrivateKey is the RSA private key corresponding to
* RSACertificate.
* - SessionKey is the private key to use for the rest of the tunneling
* session.
* - SessionKeyId is the key identifier associated to SessionKey.
* Note: SessionKey is secret, SessionKeyId may be public.
*
* Note: portions of messages (1) - (6) are additionally encrypted using
* RSACertificateHash as the key. This makes it necessary for an
* eavesdropper to know the URL in order to read some protocol fields.
* This is a cheap way of adding more work for any attacker.
*
* TUNNELING:
*
* All encryption is done using a block cipher is CTR mode.
*
* (*) Client prepends a CLIENT_HEADER(IV, SessionKeyId, MAC) header and
* encrypts the packet using SessionKey, where
* - IV is a randomly generated Initialisation Vector.
* - SessionKeyId is the same as message (4) from the handshake.
* - MAC is the Message Authentication Code.
* (*) Server prepends a SERVER_HEADER(IV, MAC) header and encrypts the packet
* using SessionKey, as per above.
*
* Note: The Client additionally encrypts the SessionKeyId with the same IV
* and RSACertificateHash as the key.
*
* NOTES:
* (1) The server is stateless. The server derives the SessionKey from the
* SessionKeyId using a cryptographically secure secret hash function.
*
* POSSIBLE (NON-STANDARD) ATTACKS:
* - A man-in-the-middle could modify message (0) to insert their own
* certificate hash and message (3) to insert their own matching
* certificate. Then a standard man-in-the-middle attack can be executed.
* To counter this message (0) may be sent using some other secure protocol
* (e.g. SSL), or simply published widely.
* - A man-in-the-middle could observe a protocol handshake, then send forged
* GET_KEY requests to the server. If the server returns the same
* (SessionKey, SessionKeyId) as the one returned to the client, the session
* is compromised. To counter this the SessionKeyId is at least 39 bits
* (effective), meaning an average of 2^38 forged GET_KEY requests are
* required. As each GET_KEY is 100+ bytes, this is attack requires
* multiple terabytes of GET_KEY messages to be sent. Hopefully this is
* impractical for some time. The SessionKeyId may be up to 63 bits long.
* - The protocol has no built-in protection against replay attacks. This is
* because (1) the server is stateless, and (2) the tunneled protocols such
* as CKTP, TCP, and UDP have their own sequence numbers.
*
* IMPLEMENTATION BUGS:
* - This code has not been scrutinised/tested nearly enough to be considered
* secure. Rely on it at your own risk.
*/
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cktp_encoding.h"
#include "cookie.h"
#include "encodings/aes.h"
#include "encodings/aes_hardware.h"
#include "encodings/crypt.h"
#ifdef CLIENT
#include "natural.h"
#endif
#ifdef SERVER
#include <gmp.h>
#include "quota.h"
#include "thread.h"
#endif
/*
* Parameters:
*/
#define CRYPT_PUBLIC_KEY_SIZE 128
#define CRYPT_KEY_SIZE 16
#define CRYPT_BLOCK_SIZE CRYPT_KEY_SIZE
#define CRYPT_HASH_SIZE CRYPT_KEY_SIZE
#define CRYPT_HASH_BASE64_SIZE ((CRYPT_HASH_SIZE * 8 - 1) / 6 + 1)
#define CRYPT_PUBLIC_KEY_BASE64_SIZE \
((CRYPT_PUBLIC_KEY_SIZE * 8 - 1) / 6 + 1)
#define CRYPT_DH_GENERATOR 2
#define CRYPT_RSA_EXPONENT 0x00010001
#define CRYPT_MIN_AKEY_SIZE 2
#define CRYPT_MIN_ID_SIZE 5
#define CRYPT_MIN_IV_SIZE 4
#define CRYPT_MIN_MAC_SIZE 2
#define CRYPT_MAX_AKEY_SIZE CRYPT_MIN_AKEY_SIZE
#define CRYPT_MAX_ID_SIZE sizeof(uint64_t)
#define CRYPT_MAX_IV_SIZE sizeof(uint64_t)
#define CRYPT_MAX_MAC_SIZE sizeof(uint64_t)
#define CRYPT_DEFAULT_AKEY_SIZE 2
#define CRYPT_DEFAULT_ID_SIZE 6
#define CRYPT_DEFAULT_IV_SIZE 5
#define CRYPT_DEFAULT_MAC_SIZE 3
#define CRYPT_HEADER_SEQ 0x243F6A88 // PI
#define CRYPT_GEN_IDX_MASK 0x0000000000000001ull
#define CRYPT_TIMEOUT (60*60*1000) // 60 minutes
#define CRYPT_TIMEOUT_BUFF (60*1000) // 60 seconds
#define CRYPT_MIN_TIMEOUT (5*60*1000) // 5 minutes
#define CRYPT_MAX_TIMEOUT (24*60*60*1000) // 1 day
#define CRYPT_KEYS_FILENAME PACKAGE_NAME ".crypt.keys"
#define CRYPT_QUOTA_RK_TIMEMIN 4000 // 4 seconds
#define CRYPT_QUOTA_RK_TIMEMAX 8000 // 8 seconds
#define CRYPT_QUOTA_RK_RATE 8 // 8 per second
#define CRYPT_QUOTA_RK_NUM_BUCKETS 256
/*
* Error codes.
*/
#define CRYPT_ERROR_BAD_NAME (-100)
#define CRYPT_ERROR_BAD_STATE (-101)
#define CRYPT_ERROR_BAD_LENGTH (-102)
#define CRYPT_ERROR_BAD_CERTIFICATE (-103)
#define CRYPT_ERROR_BAD_PARAMETER (-104)
#define CRYPT_ERROR_BAD_VERSION (-105)
#define CRYPT_ERROR_BAD_MAGIC_NUMBER (-106)
#define CRYPT_ERROR_BAD_TIMEOUT (-107)
#define CRYPT_ERROR_BAD_COOKIE (-108)
#define CRYPT_ERROR_BAD_SEQ (-109)
#define CRYPT_ERROR_BAD_MAC (-110)
#define CRYPT_ERROR_BAD_URL_PARAMETER (-111)
#define CRYPT_ERROR_MISSING_URL_PARAMETER (-112)
#define CRYPT_ERROR_REPEATED_URL_PARAMETER (-113)
#define CRYPT_ERROR_OUT_OF_MEMORY (-114)
#define CRYPT_ERROR_DOS (-115)
/*
* 1024-bit prime for DH key exchange (see RFC2412 Appendix E.2)
*/
static const uint8_t p0[CRYPT_PUBLIC_KEY_SIZE] =
{
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x81, 0x53, 0xE6, 0xEC,
0x51, 0x66, 0x28, 0x49, 0xE6, 0x1F, 0x4B, 0x7C, 0x11, 0x24, 0x9F, 0xAE,
0xA5, 0x9F, 0x89, 0x5A, 0xFB, 0x6B, 0x38, 0xEE, 0xED, 0xB7, 0x06, 0xF4,
0xB6, 0x5C, 0xFF, 0x0B, 0x6B, 0xED, 0x37, 0xA6, 0xE9, 0x42, 0x4C, 0xF4,
0xC6, 0x7E, 0x5E, 0x62, 0x76, 0xB5, 0x85, 0xE4, 0x45, 0xC2, 0x51, 0x6D,
0x6D, 0x35, 0xE1, 0x4F, 0x37, 0x14, 0x5F, 0xF2, 0x6D, 0x0A, 0x2B, 0x30,
0x1B, 0x43, 0x3A, 0xCD, 0xB3, 0x19, 0x95, 0xEF, 0xDD, 0x04, 0x34, 0x8E,
0x79, 0x08, 0x4A, 0x51, 0x22, 0x9B, 0x13, 0x3B, 0xA6, 0xBE, 0x0B, 0x02,
0x74, 0xCC, 0x67, 0x8A, 0x08, 0x4E, 0x02, 0x29, 0xD1, 0x1C, 0xDC, 0x80,
0x8B, 0x62, 0xC6, 0xC4, 0x34, 0xC2, 0x68, 0x21, 0xA2, 0xDA, 0x0F, 0xC9,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
/*****************************************************************************/
/*
* Protocol messages:
*/
#define CRYPT_ID_REQ_COOKIE 0
#define CRYPT_ID_REQ_CERTIFICATE 1
#define CRYPT_ID_REQ_KEY 2
#define CRYPT_ID_MAX_RESERVED 8
/*
* NOTE: for all of these structures 'seq' must be (a) uint32_t and (b)
* be the first field.
*/
struct crypt_req_cookie_s
{
uint32_t seq; // Sequence Number
uint64_t unused; // Unused
} __attribute__((__packed__));
struct crypt_rep_cookie_s
{
uint32_t seq; // Sequence Number
uint32_t cookie; // Cookie
} __attribute__((__packed__));
struct crypt_req_certificate_s
{
uint32_t seq; // Sequence Number
uint32_t cookie; // Cookie
} __attribute__((__packed__));
struct crypt_rep_certificate_s
{
uint32_t seq; // Sequence Number
uint8_t certificate[CRYPT_PUBLIC_KEY_SIZE]; // Certificate
} __attribute__((__packed__));
struct crypt_req_key_s
{
uint32_t seq; // Sequence Number
uint32_t cookie; // Cookie
uint8_t public_key[CRYPT_PUBLIC_KEY_SIZE]; // Public key
} __attribute__((__packed__));
#define CRYPT_VERSION 0
#define CRYPT_MAGIC 0xA1C3952A
struct crypt_rep_key_s
{
uint32_t seq; // Sequence number
uint8_t public_key[CRYPT_PUBLIC_KEY_SIZE]; // Public key
uint32_t seq2; // Sequence number (IV)
uint64_t iv; // Initialisation Vector
uint64_t mac; // MAC
struct
{
uint8_t version; // Protocol version
uint32_t magic; // Magic number
uint8_t signature[CRYPT_PUBLIC_KEY_SIZE]; // Signed data
} __attribute__((__packed__)) encrypted;
} __attribute__((__packed__));
#define CRYPT_SIGNED_MAGIC_1 0xA614BF722967C0D7ULL
#define CRYPT_SIGNED_MAGIC_2 0x843CD0BE88A8F703ULL
struct crypt_signed_data_s
{
uint64_t iv; // Initialisation Vector
uint64_t mac; // MAC
struct
{
uint64_t magic1; // Magic number (1)
uint64_t magic2; // Magic number (2)
uint8_t version; // Protocol version
uint32_t seq; // Sequence number
uint64_t id; // Session ID
uint8_t key[CRYPT_KEY_SIZE]; // Session key
uint32_t timeout; // Timeout (ms)
uint8_t reserved[16]; // Reserved
} __attribute__((__packed__)) encrypted;
} __attribute__((__packed__));
/*****************************************************************************/
/*
* Prototypes.
*/
static void xxtea_expandkey(const uint8_t *key, size_t keysize, uint8_t *ekey);
static void xxtea_encrypt(const uint32_t *v, const uint32_t *k, uint32_t *r);
#define CRYPT_STATE_HANDSHAKE_REQ_COOKIE 1
#define CRYPT_STATE_HANDSHAKE_REQ_CERTIFICATE 2
#define CRYPT_STATE_HANDSHAKE_REQ_KEY 3
typedef void (*expandkeyfunc_t)(const void *key, size_t keysize, void *ekey);
typedef void (*encryptfunc_t)(const void *block, const void *key,
void *result);
typedef bool (*testfunc_t)(void);
/*
* Cipher representation.
*/
struct cipher_s
{
const char *name; // Cipher name
size_t ekeysize; // Expanded key size
expandkeyfunc_t expandkey; // Optional expand key
encryptfunc_t encrypt; // Encrypt
testfunc_t test; // Hardware cipher supported?
};
/*
* List of available ciphers.
*/
struct cipher_s ciphers[] =
{
{ // AES128
"aes",
CRYPT_KEY_SIZE*(AES_ROUNDS+1),
(expandkeyfunc_t)aes_expandkey,
(encryptfunc_t)aes_encrypt,
NULL
},
{ // XXTEA (128 block size)
"xxtea",
CRYPT_KEY_SIZE,
(expandkeyfunc_t)xxtea_expandkey,
(encryptfunc_t)xxtea_encrypt,
NULL
}
};
/*
* List of hardware-accelerated ciphers.
*/
struct cipher_s hardware_ciphers[] =
{
{ // AES128
"aes",
CRYPT_KEY_SIZE*(AES_ROUNDS+1),
(expandkeyfunc_t)aes_hardware_expandkey,
(encryptfunc_t)aes_hardware_encrypt,
(testfunc_t)aes_hardware_test
}
};
/*
* Comparison function for struct cipher_s
*/
static int cipher_s_compare(const void *a, const void *b)
{
const struct cipher_s *a1 = (const struct cipher_s *)a;
const struct cipher_s *b1 = (const struct cipher_s *)b;
return strcmp(a1->name, b1->name);
}
#ifdef SERVER
struct crypt_global_state_s
{
uint8_t refcount; // Reference count
uint64_t seq_key; // Sequence key
uint32_t seq; // Sequence number
uint8_t gen_idx; // Current generator index
uint64_t gen_timeout; // Timeout for gen_idx
struct cookie_gen_s cookie_gen[2]; // Cookie generator
struct cookie_gen_s key_gen[2]; // Key generator
quota_t quota; // Request Key quota
mpz_t mp_certificate; // Certificate
mpz_t mp_sign_key; // Sign key
};
#endif /* SERVER */
struct crypt_state_s
{
cktp_enc_lib_t lib; // Encoding lib
cktp_enc_rng_t rng; // Random numbers
const struct cipher_s *cipher; // Selected cipher
uint64_t id; // Session ID
size_t id_size; // ID size
size_t iv_size; // IV size
size_t mac_size; // MAC size
bool pad; // Pad handshake packets?
uint8_t cert_hash[CRYPT_HASH_SIZE]; // Certificate hash
uint8_t certificate[CRYPT_PUBLIC_KEY_SIZE]; // Certificate
uint8_t *ekey; // Expanded key
#ifdef CLIENT
bool have_cert; // Have certificate?
bool save_cert; // Should save certificate?
uint8_t key[CRYPT_PUBLIC_KEY_SIZE]; // Key
uint8_t state; // Handshake state
uint64_t seq_key; // Sequence key
uint32_t seq; // Sequence number
uint64_t timeout; // Timeout before reconnect
#endif /* CLIENT */
#ifdef SERVER
uint8_t key[CRYPT_KEY_SIZE]; // Key
uint8_t sign_key[CRYPT_PUBLIC_KEY_SIZE]; // Signing key
struct crypt_global_state_s *gbl_state; // Global state
#endif /* SERVER */
};
#ifdef SERVER
/*
* Pre-computed GMP numbers for the server.
*/
static bool mp_init = false;
static mpz_t p; // DH prime (p0)
static mpz_t p1; // DH prime less 1 (p - 1)
static mpz_t g; // DH generator
#endif /* SERVER */
typedef struct crypt_state_s *crypt_state_t;
typedef crypt_state_t state_t;
/*
* Crypt user parameters:
*/
#define CRYPT_CERT 0
#define CRYPT_CIPHER 1
#define CRYPT_HANDSHAKEPAD 2
#define CRYPT_SEC 3
struct cktp_enc_param_s crypt_params[] =
{
{"cert", CRYPT_CERT, CKTP_ENCODING_TYPE_STRING},
{"cipher", CRYPT_CIPHER, CKTP_ENCODING_TYPE_STRING},
{"handshakepad", CRYPT_HANDSHAKEPAD, CKTP_ENCODING_TYPE_NIL},
{"sec", CRYPT_SEC, CKTP_ENCODING_TYPE_UINT}
};
/*
* Prototypes.
*/
static uint64_t encrypt(const struct cipher_s *cipher, const uint8_t *iv,
size_t ivsize, uint32_t seq, const uint8_t *ekey, uint8_t *data,
size_t datasize);
static uint64_t decrypt(const struct cipher_s *cipher, const uint8_t *iv,
size_t ivsize, uint32_t seq, const uint8_t *ekey, uint8_t *data,
size_t datasize);
static void crypt(const struct cipher_s *cipher, const uint8_t *iv,
size_t ivsize, const uint8_t *key, uint8_t *data, size_t datasize);
static void hash(const struct cipher_s *cipher, uint8_t *data, size_t datasize,
uint8_t *hashval);
static int crypt_init(const cktp_enc_lib_t lib, const char *protocol,
const char *options, size_t options_size, state_t *stateptr);
static struct cipher_s *crypt_cipher_search(const char *name);
static void crypt_free(state_t state);
static size_t crypt_overhead(state_t state);
static const char *crypt_error_string(state_t state, int err);
static size_t crypt_handshake_pad_length(state_t state, uint8_t *data,
size_t size);
static bool crypt_handshake_is_valid_length(state_t state, size_t basesize,
size_t extsize);
static uint32_t crypt_seq(uint32_t seq, uint64_t seq_key);
#ifdef CLIENT
static bool crypt_find_certificate(state_t state);
static void crypt_save_certificate(state_t state);
static uint64_t crypt_timeout(state_t state);
static int crypt_handshake_request(state_t state, uint8_t *data, size_t *size);
static int crypt_handshake_reply(state_t state, uint8_t *data, size_t size);
static int crypt_decode(state_t state, uint8_t **dataptr, size_t *sizeptr);
#endif /* CLIENT */
static int crypt_encode(state_t state, uint8_t **dataptr, size_t *sizeptr);
#ifdef SERVER
static inline uint32_t crypt_next_seq(state_t state);
static int crypt_activate(state_t state);
static int crypt_clone(state_t state, state_t *stateptr);
static int crypt_server_decode(state_t state, uint32_t *source_addr,
size_t source_size, uint8_t **dataptr, size_t *sizeptr,
uint8_t **replyptr, size_t *replysizeptr);
static bool crypt_server_init(state_t state, bool read_cert);
static void *crypt_timeout_manager(void *state_ptr);
static bool crypt_read_certificate(state_t state);
static uint32_t crypt_cookie(state_t state, uint32_t *source_addr,
size_t source_size);
static void crypt_key(state_t state, uint32_t *source_addr, size_t source_size,
uint32_t id, uint8_t *key);
#endif /* SERVER */
/*
* Crypt encoding protocol:
*/
struct cktp_enc_info_s crypt_encoding =
{
"crypt",
(encoding_init_t)crypt_init,
(encoding_free_t)crypt_free,
(encoding_overhead_t)crypt_overhead,
(encoding_error_string_t)crypt_error_string,
#ifdef CLIENT
(encoding_timeout_t)crypt_timeout,
(encoding_handshake_request_t)crypt_handshake_request,
(encoding_handshake_reply_t)crypt_handshake_reply,
(encoding_encode_t)crypt_encode,
(encoding_decode_t)crypt_decode
#endif /* CLIENT */
#ifdef SERVER
(encoding_activate_t)crypt_activate,
(encoding_clone_t)crypt_clone,
(encoding_encode_t)crypt_encode,
(encoding_server_decode_t)crypt_server_decode
#endif /* SERVER */
};
/*
* Initialise the state.
*/
static int crypt_init(const cktp_enc_lib_t lib, const char *protocol,
const char *options, size_t options_size, state_t *stateptr)
{
*stateptr = NULL;
if (strcmp(protocol, "crypt") != 0)
{
return CRYPT_ERROR_BAD_NAME;
}
bool seen_cipher = false, seen_cert = false, seen_pad = false,
seen_sec = false;
struct cipher_s *cipher = NULL;
uint8_t cert_hash[CRYPT_HASH_SIZE+1];
size_t id_size = CRYPT_DEFAULT_ID_SIZE,
iv_size = CRYPT_DEFAULT_IV_SIZE,
mac_size = CRYPT_DEFAULT_MAC_SIZE;
for (size_t i = 0; i < options_size; i++)
{
struct cktp_enc_val_s val;
int result = lib->parse_param(crypt_params,
sizeof(crypt_params) / sizeof(struct cktp_enc_param_s),
options, &val);
if (result < 0)
{
return CRYPT_ERROR_BAD_URL_PARAMETER;
}
switch (val.param->id)
{
case CRYPT_CERT:
{
if (seen_cert)
{
return CRYPT_ERROR_REPEATED_URL_PARAMETER;
}
if (strlen(val.val.str_val) != CRYPT_HASH_BASE64_SIZE)
{
return CRYPT_ERROR_BAD_URL_PARAMETER;
}
if (lib->base64_decode(val.val.str_val, CRYPT_HASH_BASE64_SIZE,
cert_hash) != CRYPT_HASH_SIZE+1)
{
return CRYPT_ERROR_BAD_URL_PARAMETER;
}
seen_cert = true;
break;
}
case CRYPT_CIPHER:
{
if (seen_cipher)
{
return CRYPT_ERROR_REPEATED_URL_PARAMETER;
}
cipher = crypt_cipher_search(val.val.str_val);
if (cipher == NULL)
{
return CRYPT_ERROR_BAD_URL_PARAMETER;
}
seen_cipher = true;
break;
}
case CRYPT_HANDSHAKEPAD:
{
if (seen_pad)
{
return CRYPT_ERROR_REPEATED_URL_PARAMETER;
}
seen_pad = true;
break;
}
case CRYPT_SEC:
{
if (seen_sec)
{
return CRYPT_ERROR_REPEATED_URL_PARAMETER;
}
unsigned sec = val.val.uint_val;
size_t akey_size = (sec / 1000) % 10;
id_size = (sec / 100) % 10;
iv_size = (sec / 10) % 10;
mac_size = sec % 10;
if (akey_size < CRYPT_MIN_AKEY_SIZE ||
akey_size > CRYPT_MAX_AKEY_SIZE ||
id_size < CRYPT_MIN_ID_SIZE ||
id_size > CRYPT_MAX_ID_SIZE ||
iv_size < CRYPT_MIN_IV_SIZE ||
iv_size > CRYPT_MAX_IV_SIZE ||
mac_size < CRYPT_MIN_MAC_SIZE ||
mac_size > CRYPT_MAX_MAC_SIZE)
{
return CRYPT_ERROR_BAD_URL_PARAMETER;
}
seen_sec = true;
break;
}
default:
return CRYPT_ERROR_BAD_URL_PARAMETER;
}
options += strlen(options) + 1;
}
state_t state = (state_t)malloc(sizeof(struct crypt_state_s));
if (state == NULL)
{
return CRYPT_ERROR_OUT_OF_MEMORY;
}
state->lib = lib;
state->cipher = cipher;
state->id_size = id_size;
state->iv_size = iv_size;
state->mac_size = mac_size;
state->pad = seen_pad;
memmove(state->cert_hash, cert_hash, CRYPT_HASH_SIZE);
state->rng = lib->random_init();
state->ekey = (uint8_t *)malloc(cipher->ekeysize);
if (state->ekey == NULL)
{
free(state);
return CRYPT_ERROR_OUT_OF_MEMORY;
}
#ifdef CLIENT
if (!seen_cert)
{
free(state->ekey);
free(state);
return CRYPT_ERROR_MISSING_URL_PARAMETER;
}
state->have_cert = crypt_find_certificate(state);
state->save_cert = false;
state->state = CRYPT_STATE_HANDSHAKE_REQ_COOKIE;
#endif
#ifdef SERVER
if (!crypt_server_init(state, seen_cert))
{
free(state->ekey);
free(state);
return CRYPT_ERROR_MISSING_URL_PARAMETER;
}
#endif
*stateptr = state;
return 0;
}
/*
* Search for a given cipher.
*/
static struct cipher_s *crypt_cipher_search(const char *name)
{
struct cipher_s key;
key.name = name;
struct cipher_s *cipher = bsearch(&key, hardware_ciphers,
sizeof(hardware_ciphers) / sizeof(struct cipher_s),
sizeof(struct cipher_s), cipher_s_compare);
if (cipher != NULL &&
(cipher->test == NULL || cipher->test()))
{
return cipher;
}
cipher = bsearch(&key, ciphers, sizeof(ciphers) / sizeof(struct cipher_s),
sizeof(struct cipher_s), cipher_s_compare);
return cipher;
}
/*
* Free state.
*/
static void crypt_free(state_t state)
{
state->lib->random_free(state->rng);
free(state->ekey);
#ifdef SERVER
state->gbl_state->refcount--;
if (state->gbl_state->refcount == 0)
{
quota_free(state->gbl_state->quota);
mpz_clear(state->gbl_state->mp_certificate);
mpz_clear(state->gbl_state->mp_sign_key);
free(state->gbl_state);
}
#endif
free(state);
}
/*
* Query crypt overhead.
*/
static size_t crypt_overhead(state_t state)
{
return state->iv_size + state->id_size + sizeof(uint32_t) +
state->mac_size;
}
/*
* Convert error codes to strings.
*/
static const char *crypt_error_string(state_t state, int err)
{
switch (err)
{
case CRYPT_ERROR_BAD_NAME:
return "bad encoding name";
case CRYPT_ERROR_BAD_STATE:
return "bad internal state";
case CRYPT_ERROR_BAD_LENGTH:
return "bad message length";
case CRYPT_ERROR_BAD_CERTIFICATE:
return "bad certificate";
case CRYPT_ERROR_BAD_PARAMETER:
return "bad cryptographic parameter";
case CRYPT_ERROR_BAD_VERSION:
return "bad protocol version";
case CRYPT_ERROR_BAD_MAGIC_NUMBER:
return "bad magic number";
case CRYPT_ERROR_BAD_TIMEOUT:
return "bad timeout value";
case CRYPT_ERROR_BAD_COOKIE:
return "bad cookie";
case CRYPT_ERROR_BAD_SEQ:
return "bad sequence number";
case CRYPT_ERROR_BAD_MAC:
return "bad message authentication code";
case CRYPT_ERROR_BAD_URL_PARAMETER:
return "bad URL parameter";
case CRYPT_ERROR_MISSING_URL_PARAMETER:
return "missing URL parameter";
case CRYPT_ERROR_REPEATED_URL_PARAMETER:
return "repeated URL parameter";
case CRYPT_ERROR_OUT_OF_MEMORY:
return "out of memory";
case CRYPT_ERROR_DOS:
return "dos packet";
default:
return "generic error";
}
}
/*
* Add a random extension to a handshake packet.
*/
static size_t crypt_handshake_pad_length(state_t state, uint8_t *data,
size_t size)
{
if (state->pad)
{
size_t extend;
state->lib->random(state->rng, &extend, sizeof(extend));
extend = extend % (size / 2);
state->lib->random(state->rng, data+size, extend);
return size + extend;
}
else
{
return size;
}
}
/*
* Returns 'true' iff extension is valid.
*/
static bool crypt_handshake_is_valid_length(state_t state, size_t basesize,
size_t extsize)
{
if (state->pad)
{
return (extsize >= basesize);
}
else
{
return (extsize == basesize);
}
}
/*
* Get a sequence number.
*/
static uint32_t crypt_seq(uint32_t seq, uint64_t seq_key)
{
// Micro encryption based on TEA:
register uint16_t v0 = (uint16_t)seq, v1 = (uint16_t)(seq >> 16), sum = 0;
register uint16_t k0 = (uint16_t)seq_key, k1 = (uint16_t)(seq_key >> 16),
k2 = (uint16_t)(seq_key >> 32), k3 = (uint16_t)(seq_key >> 48);
for (register unsigned i = 0; i < 8; i++)
{
sum += 0x9E37;
v0 += ((v1 << 2) + k0) ^ (v1 + sum) ^ ((v1 >> 3) + k1);
v1 += ((v0 << 2) + k2) ^ (v0 + sum) ^ ((v0 >> 3) + k3);
}
return ((uint32_t)v0 | (((uint32_t)v1) << 16));
}
#ifdef CLIENT
/*
* Find a certificate from the local cache.
*/
static bool crypt_find_certificate(state_t state)
{
FILE *file = fopen(CRYPT_CERT_CACHE_FILENAME, "r");
if (file == NULL)
{
return false;
}
while (true)
{
char c = getc(file);
switch (c)
{
case EOF:
fclose(file);
return false;
case '\n':
continue;
case '#':
while ((c = getc(file)) != '\n' && c != EOF)
;
continue;
default:
ungetc(c, file);
break;
}
bool cipher_match = true;
size_t i;
for (i = 0; (c = getc(file)) != '\t'; i++)
{
if (!isalpha(c))
{
fclose(file);
goto parse_error;
}
if (cipher_match)
{
cipher_match = (c == state->cipher->name[i]);
}
}
if (cipher_match && state->cipher->name[i] != '\0')
{
cipher_match = false;
}
char cert_hash_str[CRYPT_HASH_BASE64_SIZE + 1];
char cert_str[CRYPT_PUBLIC_KEY_BASE64_SIZE + 1];
if (getc(file) != '\t' ||
fgets(cert_hash_str, sizeof(cert_hash_str), file) == NULL ||
getc(file) != ' ' ||
fgets(cert_str, sizeof(cert_str), file) == NULL ||
getc(file) != '\n')
{
fclose(file);
goto parse_error;
}
if (!cipher_match)
{
continue;
}
uint8_t cert_hash[CRYPT_HASH_SIZE+1];
if (state->lib->base64_decode(cert_hash_str, sizeof(cert_hash_str)-1,
cert_hash) != sizeof(cert_hash))
{
fclose(file);
goto parse_error;
}
if (memcmp(cert_hash, state->cert_hash, sizeof(state->cert_hash)) == 0)
{
fclose(file);
uint8_t cert[CRYPT_PUBLIC_KEY_SIZE+1];
if (state->lib->base64_decode(cert_str, sizeof(cert_str)-1,
cert) != sizeof(cert))
{
goto parse_error;
}
memmove(state->certificate, cert, sizeof(state->certificate));
// Verify the certificate hash:
hash(state->cipher, state->certificate, sizeof(state->certificate),
cert_hash);
if (memcmp(cert_hash, state->cert_hash, sizeof(state->cert_hash))
!= 0)
{
goto parse_error;
}
return true;
}
}
parse_error:
// If there is a parse error we assume the file is corrupted. Delete it.
remove(CRYPT_CERT_CACHE_FILENAME);
return false;
}
/*
* Save a local copy of the given certificate.
*/
static void crypt_save_certificate(state_t state)
{
char cert_hash_str[CRYPT_HASH_BASE64_SIZE + 1];
size_t end = state->lib->base64_encode(state->cert_hash,
sizeof(state->cert_hash), cert_hash_str);
cert_hash_str[end] = '\0';
char cert_str[CRYPT_PUBLIC_KEY_BASE64_SIZE + 1];
end = state->lib->base64_encode(state->certificate,
sizeof(state->certificate), cert_str);
cert_str[end] = '\0';
FILE *file = fopen(CRYPT_CERT_CACHE_FILENAME, "a");
if (file == NULL)
{
return;
}
fprintf(file, "%s\t\t%s %s\n", state->cipher->name, cert_hash_str,
cert_str);
fclose(file);
}
/*
* Get the timeout.
*/
static uint64_t crypt_timeout(state_t state)
{
return state->timeout;
}
/*
* Handshake request.
*/
static int crypt_handshake_request(state_t state, uint8_t *data, size_t *size)
{
switch (state->state)
{
case 0:
return 0; // TODO: fix
case CRYPT_STATE_HANDSHAKE_REQ_COOKIE:
{
struct crypt_req_cookie_wrap_s
{
uint8_t iv[state->iv_size];
uint8_t id[state->id_size];
struct crypt_req_cookie_s request;
} __attribute__((packed));
typedef struct crypt_req_cookie_wrap_s *crypt_req_cookie_wrap_t;
crypt_req_cookie_wrap_t req = (crypt_req_cookie_wrap_t)data;
state->lib->random(state->rng, req->iv, sizeof(req->iv));
uint64_t id = CRYPT_ID_REQ_COOKIE;
memmove(req->id, &id, sizeof(req->id));
state->lib->random(state->rng, &state->seq, sizeof(state->seq));
req->request.seq = state->seq;
state->lib->random(state->rng, &req->request.unused,
sizeof(req->request.unused));
crypt(state->cipher, req->iv, sizeof(req->iv), state->cert_hash,
req->id, sizeof(req->id) + sizeof(req->request.seq));
*size = crypt_handshake_pad_length(state, data, sizeof(*req));
return CRYPT_STATE_HANDSHAKE_REQ_COOKIE;
}
case CRYPT_STATE_HANDSHAKE_REQ_CERTIFICATE:
{
struct crypt_req_certificate_wrap_s
{
uint8_t iv[state->iv_size];
uint8_t id[state->id_size];
struct crypt_req_certificate_s request;
} __attribute__((packed));
typedef struct crypt_req_certificate_wrap_s *
crypt_req_certificate_wrap_t;
crypt_req_certificate_wrap_t req =
(crypt_req_certificate_wrap_t)data;
state->lib->random(state->rng, req->iv, sizeof(req->iv));
uint64_t id = CRYPT_ID_REQ_CERTIFICATE;
memmove(req->id, &id, sizeof(req->id));
state->lib->random(state->rng, &state->seq, sizeof(state->seq));
req->request.seq = state->seq;
req->request.cookie = state->id;
crypt(state->cipher, req->iv, sizeof(req->iv), state->cert_hash,
req->id, sizeof(req->id) + sizeof(req->request));
*size = crypt_handshake_pad_length(state, data, sizeof(*req));
return CRYPT_STATE_HANDSHAKE_REQ_CERTIFICATE;
}
case CRYPT_STATE_HANDSHAKE_REQ_KEY: