]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - crypto.c
fix a compile error in my last edit for OSX
[xonotic/darkplaces.git] / crypto.c
1 // TODO key loading, generating, saving
2 #include "quakedef.h"
3 #include "crypto.h"
4 #include "common.h"
5
6 #include "hmac.h"
7 #include "libcurl.h"
8
9 cvar_t crypto_developer = {CVAR_SAVE, "crypto_developer", "0", "print extra info about crypto handshake"};
10 cvar_t crypto_servercpupercent = {CVAR_SAVE, "crypto_servercpupercent", "10", "allowed crypto CPU load in percent for server operation (0 = no limit, faster)"};
11 cvar_t crypto_servercpumaxtime = {CVAR_SAVE, "crypto_servercpumaxtime", "0.01", "maximum allowed crypto CPU time per frame (0 = no limit)"};
12 cvar_t crypto_servercpudebug = {CVAR_SAVE, "crypto_servercpudebug", "0", "print statistics about time usage by crypto"};
13 static double crypto_servercpu_accumulator = 0;
14 static double crypto_servercpu_lastrealtime = 0;
15 cvar_t crypto_aeslevel = {CVAR_SAVE, "crypto_aeslevel", "1", "whether to support AES encryption in authenticated connections (0 = no, 1 = supported, 2 = requested, 3 = required)"};
16 int crypto_keyfp_recommended_length;
17 static const char *crypto_idstring = NULL;
18 static char crypto_idstring_buf[512];
19
20 #define PROTOCOL_D0_BLIND_ID FOURCC_D0PK
21 #define PROTOCOL_VLEN (('v' << 0) | ('l' << 8) | ('e' << 16) | ('n' << 24))
22
23 // BEGIN stuff shared with crypto-keygen-standalone
24 #define FOURCC_D0PK (('d' << 0) | ('0' << 8) | ('p' << 16) | ('k' << 24))
25 #define FOURCC_D0SK (('d' << 0) | ('0' << 8) | ('s' << 16) | ('k' << 24))
26 #define FOURCC_D0PI (('d' << 0) | ('0' << 8) | ('p' << 16) | ('i' << 24))
27 #define FOURCC_D0SI (('d' << 0) | ('0' << 8) | ('s' << 16) | ('i' << 24))
28 #define FOURCC_D0IQ (('d' << 0) | ('0' << 8) | ('i' << 16) | ('q' << 24))
29 #define FOURCC_D0IR (('d' << 0) | ('0' << 8) | ('i' << 16) | ('r' << 24))
30 #define FOURCC_D0ER (('d' << 0) | ('0' << 8) | ('e' << 16) | ('r' << 24))
31 #define FOURCC_D0IC (('d' << 0) | ('0' << 8) | ('i' << 16) | ('c' << 24))
32
33 static unsigned long Crypto_LittleLong(const char *data)
34 {
35         return
36                 ((unsigned char) data[0]) |
37                 (((unsigned char) data[1]) << 8) |
38                 (((unsigned char) data[2]) << 16) |
39                 (((unsigned char) data[3]) << 24);
40 }
41
42 static void Crypto_UnLittleLong(char *data, unsigned long l)
43 {
44         data[0] = l & 0xFF;
45         data[1] = (l >> 8) & 0xFF;
46         data[2] = (l >> 16) & 0xFF;
47         data[3] = (l >> 24) & 0xFF;
48 }
49
50 static size_t Crypto_ParsePack(const char *buf, size_t len, unsigned long header, const char **lumps, size_t *lumpsize, size_t nlumps)
51 {
52         size_t i;
53         size_t pos;
54         pos = 0;
55         if(header)
56         {
57                 if(len < 4)
58                         return 0;
59                 if(Crypto_LittleLong(buf) != header)
60                         return 0;
61                 pos += 4;
62         }
63         for(i = 0; i < nlumps; ++i)
64         {
65                 if(pos + 4 > len)
66                         return 0;
67                 lumpsize[i] = Crypto_LittleLong(&buf[pos]);
68                 pos += 4;
69                 if(pos + lumpsize[i] > len)
70                         return 0;
71                 lumps[i] = &buf[pos];
72                 pos += lumpsize[i];
73         }
74         return pos;
75 }
76
77 static size_t Crypto_UnParsePack(char *buf, size_t len, unsigned long header, const char *const *lumps, const size_t *lumpsize, size_t nlumps)
78 {
79         size_t i;
80         size_t pos;
81         pos = 0;
82         if(header)
83         {
84                 if(len < 4)
85                         return 0;
86                 Crypto_UnLittleLong(buf, header);
87                 pos += 4;
88         }
89         for(i = 0; i < nlumps; ++i)
90         {
91                 if(pos + 4 + lumpsize[i] > len)
92                         return 0;
93                 Crypto_UnLittleLong(&buf[pos], lumpsize[i]);
94                 pos += 4;
95                 memcpy(&buf[pos], lumps[i], lumpsize[i]);
96                 pos += lumpsize[i];
97         }
98         return pos;
99 }
100 // END stuff shared with xonotic-keygen
101
102 #define USE_AES
103
104 #ifdef CRYPTO_STATIC
105
106 #include <d0_blind_id/d0_blind_id.h>
107
108 #define d0_blind_id_dll 1
109 #define Crypto_OpenLibrary() true
110 #define Crypto_CloseLibrary()
111
112 #define qd0_blind_id_new d0_blind_id_new
113 #define qd0_blind_id_free d0_blind_id_free
114 //#define qd0_blind_id_clear d0_blind_id_clear
115 #define qd0_blind_id_copy d0_blind_id_copy
116 //#define qd0_blind_id_generate_private_key d0_blind_id_generate_private_key
117 //#define qd0_blind_id_generate_private_key_fastreject d0_blind_id_generate_private_key_fastreject
118 //#define qd0_blind_id_read_private_key d0_blind_id_read_private_key
119 #define qd0_blind_id_read_public_key d0_blind_id_read_public_key
120 //#define qd0_blind_id_write_private_key d0_blind_id_write_private_key
121 //#define qd0_blind_id_write_public_key d0_blind_id_write_public_key
122 #define qd0_blind_id_fingerprint64_public_key d0_blind_id_fingerprint64_public_key
123 //#define qd0_blind_id_generate_private_id_modulus d0_blind_id_generate_private_id_modulus
124 #define qd0_blind_id_read_private_id_modulus d0_blind_id_read_private_id_modulus
125 //#define qd0_blind_id_write_private_id_modulus d0_blind_id_write_private_id_modulus
126 #define qd0_blind_id_generate_private_id_start d0_blind_id_generate_private_id_start
127 #define qd0_blind_id_generate_private_id_request d0_blind_id_generate_private_id_request
128 //#define qd0_blind_id_answer_private_id_request d0_blind_id_answer_private_id_request
129 #define qd0_blind_id_finish_private_id_request d0_blind_id_finish_private_id_request
130 //#define qd0_blind_id_read_private_id_request_camouflage d0_blind_id_read_private_id_request_camouflage
131 //#define qd0_blind_id_write_private_id_request_camouflage d0_blind_id_write_private_id_request_camouflage
132 #define qd0_blind_id_read_private_id d0_blind_id_read_private_id
133 //#define qd0_blind_id_read_public_id d0_blind_id_read_public_id
134 #define qd0_blind_id_write_private_id d0_blind_id_write_private_id
135 //#define qd0_blind_id_write_public_id d0_blind_id_write_public_id
136 #define qd0_blind_id_authenticate_with_private_id_start d0_blind_id_authenticate_with_private_id_start
137 #define qd0_blind_id_authenticate_with_private_id_challenge d0_blind_id_authenticate_with_private_id_challenge
138 #define qd0_blind_id_authenticate_with_private_id_response d0_blind_id_authenticate_with_private_id_response
139 #define qd0_blind_id_authenticate_with_private_id_verify d0_blind_id_authenticate_with_private_id_verify
140 #define qd0_blind_id_fingerprint64_public_id d0_blind_id_fingerprint64_public_id
141 #define qd0_blind_id_sessionkey_public_id d0_blind_id_sessionkey_public_id
142 #define qd0_blind_id_INITIALIZE d0_blind_id_INITIALIZE
143 #define qd0_blind_id_SHUTDOWN d0_blind_id_SHUTDOWN
144 #define qd0_blind_id_util_sha256 d0_blind_id_util_sha256
145 #define qd0_blind_id_sign_with_private_id_sign d0_blind_id_sign_with_private_id_sign
146 #define qd0_blind_id_sign_with_private_id_sign_detached d0_blind_id_sign_with_private_id_sign_detached
147
148 #else
149
150 // d0_blind_id interface
151 #define D0_EXPORT
152 #ifdef __GNUC__
153 #define D0_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
154 #else
155 #define D0_WARN_UNUSED_RESULT
156 #endif
157 #define D0_BOOL int
158
159 typedef struct d0_blind_id_s d0_blind_id_t;
160 typedef D0_BOOL (*d0_fastreject_function) (const d0_blind_id_t *ctx, void *pass);
161 static D0_EXPORT D0_WARN_UNUSED_RESULT d0_blind_id_t *(*qd0_blind_id_new) (void);
162 static D0_EXPORT void (*qd0_blind_id_free) (d0_blind_id_t *a);
163 //static D0_EXPORT void (*qd0_blind_id_clear) (d0_blind_id_t *ctx);
164 static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_copy) (d0_blind_id_t *ctx, const d0_blind_id_t *src);
165 //static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_generate_private_key) (d0_blind_id_t *ctx, int k);
166 //static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_generate_private_key_fastreject) (d0_blind_id_t *ctx, int k, d0_fastreject_function reject, void *pass);
167 //static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_read_private_key) (d0_blind_id_t *ctx, const char *inbuf, size_t inbuflen);
168 static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_read_public_key) (d0_blind_id_t *ctx, const char *inbuf, size_t inbuflen);
169 //static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_write_private_key) (const d0_blind_id_t *ctx, char *outbuf, size_t *outbuflen);
170 //static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_write_public_key) (const d0_blind_id_t *ctx, char *outbuf, size_t *outbuflen);
171 static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_fingerprint64_public_key) (const d0_blind_id_t *ctx, char *outbuf, size_t *outbuflen);
172 //static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_generate_private_id_modulus) (d0_blind_id_t *ctx);
173 static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_read_private_id_modulus) (d0_blind_id_t *ctx, const char *inbuf, size_t inbuflen);
174 //static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_write_private_id_modulus) (const d0_blind_id_t *ctx, char *outbuf, size_t *outbuflen);
175 static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_generate_private_id_start) (d0_blind_id_t *ctx);
176 static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_generate_private_id_request) (d0_blind_id_t *ctx, char *outbuf, size_t *outbuflen);
177 //static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_answer_private_id_request) (const d0_blind_id_t *ctx, const char *inbuf, size_t inbuflen, char *outbuf, size_t *outbuflen);
178 static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_finish_private_id_request) (d0_blind_id_t *ctx, const char *inbuf, size_t inbuflen);
179 //static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_read_private_id_request_camouflage) (d0_blind_id_t *ctx, const char *inbuf, size_t inbuflen);
180 //static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_write_private_id_request_camouflage) (const d0_blind_id_t *ctx, char *outbuf, size_t *outbuflen);
181 static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_read_private_id) (d0_blind_id_t *ctx, const char *inbuf, size_t inbuflen);
182 //static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_read_public_id) (d0_blind_id_t *ctx, const char *inbuf, size_t inbuflen);
183 static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_write_private_id) (const d0_blind_id_t *ctx, char *outbuf, size_t *outbuflen);
184 //static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_write_public_id) (const d0_blind_id_t *ctx, char *outbuf, size_t *outbuflen);
185 static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_authenticate_with_private_id_start) (d0_blind_id_t *ctx, D0_BOOL is_first, D0_BOOL send_modulus, const char *message, size_t msglen, char *outbuf, size_t *outbuflen);
186 static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_authenticate_with_private_id_challenge) (d0_blind_id_t *ctx, D0_BOOL is_first, D0_BOOL recv_modulus, const char *inbuf, size_t inbuflen, char *outbuf, size_t *outbuflen, D0_BOOL *status);
187 static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_authenticate_with_private_id_response) (d0_blind_id_t *ctx, const char *inbuf, size_t inbuflen, char *outbuf, size_t *outbuflen);
188 static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_authenticate_with_private_id_verify) (d0_blind_id_t *ctx, const char *inbuf, size_t inbuflen, char *msg, size_t *msglen, D0_BOOL *status);
189 static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_fingerprint64_public_id) (const d0_blind_id_t *ctx, char *outbuf, size_t *outbuflen);
190 static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_sessionkey_public_id) (const d0_blind_id_t *ctx, char *outbuf, size_t *outbuflen); // can only be done after successful key exchange, this performs a modpow; key length is limited by SHA_DIGESTSIZE for now; also ONLY valid after successful d0_blind_id_authenticate_with_private_id_verify/d0_blind_id_fingerprint64_public_id
191 static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_INITIALIZE) (void);
192 static D0_EXPORT void (*qd0_blind_id_SHUTDOWN) (void);
193 static D0_EXPORT void (*qd0_blind_id_util_sha256) (char *out, const char *in, size_t n);
194 static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_sign_with_private_id_sign) (d0_blind_id_t *ctx, D0_BOOL is_first, D0_BOOL send_modulus, const char *message, size_t msglen, char *outbuf, size_t *outbuflen);
195 static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_sign_with_private_id_sign_detached) (d0_blind_id_t *ctx, D0_BOOL is_first, D0_BOOL send_modulus, const char *message, size_t msglen, char *outbuf, size_t *outbuflen);
196 static dllfunction_t d0_blind_id_funcs[] =
197 {
198         {"d0_blind_id_new", (void **) &qd0_blind_id_new},
199         {"d0_blind_id_free", (void **) &qd0_blind_id_free},
200         //{"d0_blind_id_clear", (void **) &qd0_blind_id_clear},
201         {"d0_blind_id_copy", (void **) &qd0_blind_id_copy},
202         //{"d0_blind_id_generate_private_key", (void **) &qd0_blind_id_generate_private_key},
203         //{"d0_blind_id_generate_private_key_fastreject", (void **) &qd0_blind_id_generate_private_key_fastreject},
204         //{"d0_blind_id_read_private_key", (void **) &qd0_blind_id_read_private_key},
205         {"d0_blind_id_read_public_key", (void **) &qd0_blind_id_read_public_key},
206         //{"d0_blind_id_write_private_key", (void **) &qd0_blind_id_write_private_key},
207         //{"d0_blind_id_write_public_key", (void **) &qd0_blind_id_write_public_key},
208         {"d0_blind_id_fingerprint64_public_key", (void **) &qd0_blind_id_fingerprint64_public_key},
209         //{"d0_blind_id_generate_private_id_modulus", (void **) &qd0_blind_id_generate_private_id_modulus},
210         {"d0_blind_id_read_private_id_modulus", (void **) &qd0_blind_id_read_private_id_modulus},
211         //{"d0_blind_id_write_private_id_modulus", (void **) &qd0_blind_id_write_private_id_modulus},
212         {"d0_blind_id_generate_private_id_start", (void **) &qd0_blind_id_generate_private_id_start},
213         {"d0_blind_id_generate_private_id_request", (void **) &qd0_blind_id_generate_private_id_request},
214         //{"d0_blind_id_answer_private_id_request", (void **) &qd0_blind_id_answer_private_id_request},
215         {"d0_blind_id_finish_private_id_request", (void **) &qd0_blind_id_finish_private_id_request},
216         //{"d0_blind_id_read_private_id_request_camouflage", (void **) &qd0_blind_id_read_private_id_request_camouflage},
217         //{"d0_blind_id_write_private_id_request_camouflage", (void **) &qd0_blind_id_write_private_id_request_camouflage},
218         {"d0_blind_id_read_private_id", (void **) &qd0_blind_id_read_private_id},
219         //{"d0_blind_id_read_public_id", (void **) &qd0_blind_id_read_public_id},
220         {"d0_blind_id_write_private_id", (void **) &qd0_blind_id_write_private_id},
221         //{"d0_blind_id_write_public_id", (void **) &qd0_blind_id_write_public_id},
222         {"d0_blind_id_authenticate_with_private_id_start", (void **) &qd0_blind_id_authenticate_with_private_id_start},
223         {"d0_blind_id_authenticate_with_private_id_challenge", (void **) &qd0_blind_id_authenticate_with_private_id_challenge},
224         {"d0_blind_id_authenticate_with_private_id_response", (void **) &qd0_blind_id_authenticate_with_private_id_response},
225         {"d0_blind_id_authenticate_with_private_id_verify", (void **) &qd0_blind_id_authenticate_with_private_id_verify},
226         {"d0_blind_id_fingerprint64_public_id", (void **) &qd0_blind_id_fingerprint64_public_id},
227         {"d0_blind_id_sessionkey_public_id", (void **) &qd0_blind_id_sessionkey_public_id},
228         {"d0_blind_id_INITIALIZE", (void **) &qd0_blind_id_INITIALIZE},
229         {"d0_blind_id_SHUTDOWN", (void **) &qd0_blind_id_SHUTDOWN},
230         {"d0_blind_id_util_sha256", (void **) &qd0_blind_id_util_sha256},
231         {"d0_blind_id_sign_with_private_id_sign", (void **) &qd0_blind_id_sign_with_private_id_sign},
232         {"d0_blind_id_sign_with_private_id_sign_detached", (void **) &qd0_blind_id_sign_with_private_id_sign_detached},
233         {NULL, NULL}
234 };
235 // end of d0_blind_id interface
236
237 static dllhandle_t d0_blind_id_dll = NULL;
238 static qboolean Crypto_OpenLibrary (void)
239 {
240         const char* dllnames [] =
241         {
242 #if defined(WIN32)
243                 "libd0_blind_id-0.dll",
244 #elif defined(MACOSX)
245                 "libd0_blind_id.0.dylib",
246 #else
247                 "libd0_blind_id.so.0",
248                 "libd0_blind_id.so", // FreeBSD
249 #endif
250                 NULL
251         };
252
253         // Already loaded?
254         if (d0_blind_id_dll)
255                 return true;
256
257         // Load the DLL
258         return Sys_LoadLibrary (dllnames, &d0_blind_id_dll, d0_blind_id_funcs);
259 }
260
261 static void Crypto_CloseLibrary (void)
262 {
263         Sys_UnloadLibrary (&d0_blind_id_dll);
264 }
265
266 #endif
267
268 #ifdef CRYPTO_RIJNDAEL_STATIC
269
270 #include <d0_blind_id/d0_rijndael.h>
271
272 #define d0_rijndael_dll 1
273 #define Crypto_Rijndael_OpenLibrary() true
274 #define Crypto_Rijndael_CloseLibrary()
275
276 #define qd0_rijndael_setup_encrypt d0_rijndael_setup_encrypt
277 #define qd0_rijndael_setup_decrypt d0_rijndael_setup_decrypt
278 #define qd0_rijndael_encrypt d0_rijndael_encrypt
279 #define qd0_rijndael_decrypt d0_rijndael_decrypt
280
281 #else
282
283 // no need to do the #define dance here, as the upper part declares out macros either way
284
285 D0_EXPORT int (*qd0_rijndael_setup_encrypt) (unsigned long *rk, const unsigned char *key,
286   int keybits);
287 D0_EXPORT int (*qd0_rijndael_setup_decrypt) (unsigned long *rk, const unsigned char *key,
288   int keybits);
289 D0_EXPORT void (*qd0_rijndael_encrypt) (const unsigned long *rk, int nrounds,
290   const unsigned char plaintext[16], unsigned char ciphertext[16]);
291 D0_EXPORT void (*qd0_rijndael_decrypt) (const unsigned long *rk, int nrounds,
292   const unsigned char ciphertext[16], unsigned char plaintext[16]);
293 #define D0_RIJNDAEL_KEYLENGTH(keybits) ((keybits)/8)
294 #define D0_RIJNDAEL_RKLENGTH(keybits)  ((keybits)/8+28)
295 #define D0_RIJNDAEL_NROUNDS(keybits)   ((keybits)/32+6)
296 static dllfunction_t d0_rijndael_funcs[] =
297 {
298         {"d0_rijndael_setup_decrypt", (void **) &qd0_rijndael_setup_decrypt},
299         {"d0_rijndael_setup_encrypt", (void **) &qd0_rijndael_setup_encrypt},
300         {"d0_rijndael_decrypt", (void **) &qd0_rijndael_decrypt},
301         {"d0_rijndael_encrypt", (void **) &qd0_rijndael_encrypt},
302         {NULL, NULL}
303 };
304 // end of d0_blind_id interface
305
306 static dllhandle_t d0_rijndael_dll = NULL;
307 static qboolean Crypto_Rijndael_OpenLibrary (void)
308 {
309         const char* dllnames [] =
310         {
311 #if defined(WIN32)
312                 "libd0_rijndael-0.dll",
313 #elif defined(MACOSX)
314                 "libd0_rijndael.0.dylib",
315 #else
316                 "libd0_rijndael.so.0",
317                 "libd0_rijndael.so", // FreeBSD
318 #endif
319                 NULL
320         };
321
322         // Already loaded?
323         if (d0_rijndael_dll)
324                 return true;
325
326         // Load the DLL
327         return Sys_LoadLibrary (dllnames, &d0_rijndael_dll, d0_rijndael_funcs);
328 }
329
330 static void Crypto_Rijndael_CloseLibrary (void)
331 {
332         Sys_UnloadLibrary (&d0_rijndael_dll);
333 }
334
335 #endif
336
337 // various helpers
338 void sha256(unsigned char *out, const unsigned char *in, int n)
339 {
340         qd0_blind_id_util_sha256((char *) out, (const char *) in, n);
341 }
342
343 static size_t Crypto_LoadFile(const char *path, char *buf, size_t nmax)
344 {
345         qfile_t *f = NULL;
346         fs_offset_t n;
347         if(*fs_userdir)
348                 f = FS_SysOpen(va("%s%s", fs_userdir, path), "rb", false);
349         if(!f)
350                 f = FS_SysOpen(va("%s%s", fs_basedir, path), "rb", false);
351         if(!f)
352                 return 0;
353         n = FS_Read(f, buf, nmax);
354         if(n < 0)
355                 n = 0;
356         FS_Close(f);
357         return (size_t) n;
358 }
359
360 static qboolean PutWithNul(char **data, size_t *len, const char *str)
361 {
362         // invariant: data points to insertion point
363         size_t l = strlen(str);
364         if(l >= *len)
365                 return false;
366         memcpy(*data, str, l+1);
367         *data += l+1;
368         *len -= l+1;
369         return true;
370 }
371
372 static const char *GetUntilNul(const char **data, size_t *len)
373 {
374         // invariant: data points to next character to take
375         const char *data_save = *data;
376         size_t n;
377         const char *p;
378
379         if(!*data)
380                 return NULL;
381
382         if(!*len)
383         {
384                 *data = NULL;
385                 return NULL;
386         }
387
388         p = (const char *) memchr(*data, 0, *len);
389         if(!p) // no terminating NUL
390         {
391                 *data = NULL;
392                 *len = 0;
393                 return NULL;
394         }
395         else
396         {
397                 n = (p - *data) + 1;
398                 *len -= n;
399                 *data += n;
400                 if(*len == 0)
401                         *data = NULL;
402                 return (const char *) data_save;
403         }
404         *data = NULL;
405         return NULL;
406 }
407
408 // d0pk reading
409 static d0_blind_id_t *Crypto_ReadPublicKey(char *buf, size_t len)
410 {
411         d0_blind_id_t *pk = NULL;
412         const char *p[2];
413         size_t l[2];
414         if(Crypto_ParsePack(buf, len, FOURCC_D0PK, p, l, 2))
415         {
416                 pk = qd0_blind_id_new();
417                 if(pk)
418                         if(qd0_blind_id_read_public_key(pk, p[0], l[0]))
419                                 if(qd0_blind_id_read_private_id_modulus(pk, p[1], l[1]))
420                                         return pk;
421         }
422         if(pk)
423                 qd0_blind_id_free(pk);
424         return NULL;
425 }
426
427 // d0si reading
428 static qboolean Crypto_AddPrivateKey(d0_blind_id_t *pk, char *buf, size_t len)
429 {
430         const char *p[1];
431         size_t l[1];
432         if(Crypto_ParsePack(buf, len, FOURCC_D0SI, p, l, 1))
433         {
434                 if(qd0_blind_id_read_private_id(pk, p[0], l[0]))
435                         return true;
436         }
437         return false;
438 }
439
440 #define MAX_PUBKEYS 16
441 static d0_blind_id_t *pubkeys[MAX_PUBKEYS];
442 static char pubkeys_fp64[MAX_PUBKEYS][FP64_SIZE+1];
443 static qboolean pubkeys_havepriv[MAX_PUBKEYS];
444 static char pubkeys_priv_fp64[MAX_PUBKEYS][FP64_SIZE+1];
445 static char challenge_append[1400];
446 static size_t challenge_append_length;
447
448 static int keygen_i = -1;
449 static char keygen_buf[8192];
450
451 #define MAX_CRYPTOCONNECTS 16
452 #define CRYPTOCONNECT_NONE 0
453 #define CRYPTOCONNECT_PRECONNECT 1
454 #define CRYPTOCONNECT_CONNECT 2
455 #define CRYPTOCONNECT_RECONNECT 3
456 #define CRYPTOCONNECT_DUPLICATE 4
457 typedef struct server_cryptoconnect_s
458 {
459         double lasttime;
460         lhnetaddress_t address;
461         crypto_t crypto;
462         int next_step;
463 }
464 server_cryptoconnect_t;
465 static server_cryptoconnect_t cryptoconnects[MAX_CRYPTOCONNECTS];
466
467 static int cdata_id = 0;
468 typedef struct
469 {
470         d0_blind_id_t *id;
471         int s, c;
472         int next_step;
473         char challenge[2048];
474         char wantserver_idfp[FP64_SIZE+1];
475         qboolean wantserver_aes;
476         int cdata_id;
477 }
478 crypto_data_t;
479
480 // crypto specific helpers
481 #define CDATA ((crypto_data_t *) crypto->data)
482 #define MAKE_CDATA if(!crypto->data) crypto->data = Z_Malloc(sizeof(crypto_data_t))
483 #define CLEAR_CDATA if(crypto->data) { if(CDATA->id) qd0_blind_id_free(CDATA->id); Z_Free(crypto->data); } crypto->data = NULL
484
485 static crypto_t *Crypto_ServerFindInstance(lhnetaddress_t *peeraddress, qboolean allow_create)
486 {
487         crypto_t *crypto; 
488         int i, best;
489
490         if(!d0_blind_id_dll)
491                 return NULL; // no support
492
493         for(i = 0; i < MAX_CRYPTOCONNECTS; ++i)
494                 if(LHNETADDRESS_Compare(peeraddress, &cryptoconnects[i].address))
495                         break;
496         if(i < MAX_CRYPTOCONNECTS && (allow_create || cryptoconnects[i].crypto.data))
497         {
498                 crypto = &cryptoconnects[i].crypto;
499                 cryptoconnects[i].lasttime = realtime;
500                 return crypto;
501         }
502         if(!allow_create)
503                 return NULL;
504         best = 0;
505         for(i = 1; i < MAX_CRYPTOCONNECTS; ++i)
506                 if(cryptoconnects[i].lasttime < cryptoconnects[best].lasttime)
507                         best = i;
508         crypto = &cryptoconnects[best].crypto;
509         cryptoconnects[best].lasttime = realtime;
510         memcpy(&cryptoconnects[best].address, peeraddress, sizeof(cryptoconnects[best].address));
511         CLEAR_CDATA;
512         return crypto;
513 }
514
515 qboolean Crypto_ServerFinishInstance(crypto_t *out, crypto_t *crypto)
516 {
517         // no check needed here (returned pointers are only used in prefilled fields)
518         if(!crypto || !crypto->authenticated)
519         {
520                 Con_Printf("Passed an invalid crypto connect instance\n");
521                 memset(out, 0, sizeof(*out));
522                 return false;
523         }
524         CLEAR_CDATA;
525         memcpy(out, crypto, sizeof(*out));
526         memset(crypto, 0, sizeof(crypto));
527         return true;
528 }
529
530 crypto_t *Crypto_ServerGetInstance(lhnetaddress_t *peeraddress)
531 {
532         // no check needed here (returned pointers are only used in prefilled fields)
533         return Crypto_ServerFindInstance(peeraddress, false);
534 }
535
536 typedef struct crypto_storedhostkey_s
537 {
538         struct crypto_storedhostkey_s *next;
539         lhnetaddress_t addr;
540         int keyid;
541         char idfp[FP64_SIZE+1];
542         int aeslevel;
543 }
544 crypto_storedhostkey_t;
545 static crypto_storedhostkey_t *crypto_storedhostkey_hashtable[CRYPTO_HOSTKEY_HASHSIZE];
546
547 static void Crypto_InitHostKeys(void)
548 {
549         int i;
550         for(i = 0; i < CRYPTO_HOSTKEY_HASHSIZE; ++i)
551                 crypto_storedhostkey_hashtable[i] = NULL;
552 }
553
554 static void Crypto_ClearHostKeys(void)
555 {
556         int i;
557         crypto_storedhostkey_t *hk, *hkn;
558         for(i = 0; i < CRYPTO_HOSTKEY_HASHSIZE; ++i)
559         {
560                 for(hk = crypto_storedhostkey_hashtable[i]; hk; hk = hkn)
561                 {
562                         hkn = hk->next;
563                         Z_Free(hk);
564                 }
565                 crypto_storedhostkey_hashtable[i] = NULL;
566         }
567 }
568
569 static qboolean Crypto_ClearHostKey(lhnetaddress_t *peeraddress)
570 {
571         char buf[128];
572         int hashindex;
573         crypto_storedhostkey_t **hkp;
574         qboolean found = false;
575
576         LHNETADDRESS_ToString(peeraddress, buf, sizeof(buf), 1);
577         hashindex = CRC_Block((const unsigned char *) buf, strlen(buf)) % CRYPTO_HOSTKEY_HASHSIZE;
578         for(hkp = &crypto_storedhostkey_hashtable[hashindex]; *hkp && LHNETADDRESS_Compare(&((*hkp)->addr), peeraddress); hkp = &((*hkp)->next));
579
580         if(*hkp)
581         {
582                 crypto_storedhostkey_t *hk = *hkp;
583                 *hkp = hk->next;
584                 Z_Free(hk);
585                 found = true;
586         }
587
588         return found;
589 }
590
591 static void Crypto_StoreHostKey(lhnetaddress_t *peeraddress, const char *keystring, qboolean complain)
592 {
593         char buf[128];
594         int hashindex;
595         crypto_storedhostkey_t *hk;
596         int keyid;
597         char idfp[FP64_SIZE+1];
598         int aeslevel;
599
600         if(!d0_blind_id_dll)
601                 return;
602         
603         // syntax of keystring:
604         // aeslevel id@key id@key ...
605
606         if(!*keystring)
607                 return;
608         aeslevel = bound(0, *keystring - '0', 3);
609         while(*keystring && *keystring != ' ')
610                 ++keystring;
611
612         keyid = -1;
613         while(*keystring && keyid < 0)
614         {
615                 // id@key
616                 const char *idstart, *idend, *keystart, *keyend;
617                 ++keystring; // skip the space
618                 idstart = keystring;
619                 while(*keystring && *keystring != ' ' && *keystring != '@')
620                         ++keystring;
621                 idend = keystring;
622                 if(!*keystring)
623                         break;
624                 ++keystring;
625                 keystart = keystring;
626                 while(*keystring && *keystring != ' ')
627                         ++keystring;
628                 keyend = keystring;
629
630                 if(idend - idstart == FP64_SIZE && keyend - keystart == FP64_SIZE)
631                 {
632                         for(keyid = 0; keyid < MAX_PUBKEYS; ++keyid)
633                                 if(pubkeys[keyid])
634                                         if(!memcmp(pubkeys_fp64[keyid], keystart, FP64_SIZE))
635                                         {
636                                                 memcpy(idfp, idstart, FP64_SIZE);
637                                                 idfp[FP64_SIZE] = 0;
638                                                 break;
639                                         }
640                         if(keyid >= MAX_PUBKEYS)
641                                 keyid = -1;
642                 }
643         }
644
645         if(keyid < 0)
646                 return;
647
648         LHNETADDRESS_ToString(peeraddress, buf, sizeof(buf), 1);
649         hashindex = CRC_Block((const unsigned char *) buf, strlen(buf)) % CRYPTO_HOSTKEY_HASHSIZE;
650         for(hk = crypto_storedhostkey_hashtable[hashindex]; hk && LHNETADDRESS_Compare(&hk->addr, peeraddress); hk = hk->next);
651
652         if(hk)
653         {
654                 if(complain)
655                 {
656                         if(hk->keyid != keyid || memcmp(hk->idfp, idfp, FP64_SIZE+1))
657                                 Con_Printf("Server %s tried to change the host key to a value not in the host cache. Connecting to it will fail. To accept the new host key, do crypto_hostkey_clear %s\n", buf, buf);
658                         if(hk->aeslevel > aeslevel)
659                                 Con_Printf("Server %s tried to reduce encryption status, not accepted. Connecting to it will fail. To accept, do crypto_hostkey_clear %s\n", buf, buf);
660                 }
661                 hk->aeslevel = max(aeslevel, hk->aeslevel);
662                 return;
663         }
664
665         // great, we did NOT have it yet
666         hk = (crypto_storedhostkey_t *) Z_Malloc(sizeof(*hk));
667         memcpy(&hk->addr, peeraddress, sizeof(hk->addr));
668         hk->keyid = keyid;
669         memcpy(hk->idfp, idfp, FP64_SIZE+1);
670         hk->next = crypto_storedhostkey_hashtable[hashindex];
671         hk->aeslevel = aeslevel;
672         crypto_storedhostkey_hashtable[hashindex] = hk;
673 }
674
675 qboolean Crypto_RetrieveHostKey(lhnetaddress_t *peeraddress, int *keyid, char *keyfp, size_t keyfplen, char *idfp, size_t idfplen, int *aeslevel)
676 {
677         char buf[128];
678         int hashindex;
679         crypto_storedhostkey_t *hk;
680
681         if(!d0_blind_id_dll)
682                 return false;
683
684         LHNETADDRESS_ToString(peeraddress, buf, sizeof(buf), 1);
685         hashindex = CRC_Block((const unsigned char *) buf, strlen(buf)) % CRYPTO_HOSTKEY_HASHSIZE;
686         for(hk = crypto_storedhostkey_hashtable[hashindex]; hk && LHNETADDRESS_Compare(&hk->addr, peeraddress); hk = hk->next);
687
688         if(!hk)
689                 return false;
690
691         if(keyid)
692                 *keyid = hk->keyid;
693         if(keyfp)
694                 strlcpy(keyfp, pubkeys_fp64[hk->keyid], keyfplen);
695         if(idfp)
696                 strlcpy(idfp, hk->idfp, idfplen);
697         if(aeslevel)
698                 *aeslevel = hk->aeslevel;
699
700         return true;
701 }
702 int Crypto_RetrieveLocalKey(int keyid, char *keyfp, size_t keyfplen, char *idfp, size_t idfplen) // return value: -1 if more to come, +1 if valid, 0 if end of list
703 {
704         if(keyid < 0 || keyid >= MAX_PUBKEYS)
705                 return 0;
706         if(keyfp)
707                 *keyfp = 0;
708         if(idfp)
709                 *idfp = 0;
710         if(!pubkeys[keyid])
711                 return -1;
712         if(keyfp)
713                 strlcpy(keyfp, pubkeys_fp64[keyid], keyfplen);
714         if(idfp)
715                 if(pubkeys_havepriv[keyid])
716                         strlcpy(idfp, pubkeys_priv_fp64[keyid], keyfplen);
717         return 1;
718 }
719 // end
720
721 // init/shutdown code
722 static void Crypto_BuildChallengeAppend(void)
723 {
724         char *p, *lengthptr, *startptr;
725         size_t n;
726         int i;
727         p = challenge_append;
728         n = sizeof(challenge_append);
729         Crypto_UnLittleLong(p, PROTOCOL_VLEN);
730         p += 4;
731         n -= 4;
732         lengthptr = p;
733         Crypto_UnLittleLong(p, 0);
734         p += 4;
735         n -= 4;
736         Crypto_UnLittleLong(p, PROTOCOL_D0_BLIND_ID);
737         p += 4;
738         n -= 4;
739         startptr = p;
740         for(i = 0; i < MAX_PUBKEYS; ++i)
741                 if(pubkeys_havepriv[i])
742                         PutWithNul(&p, &n, pubkeys_fp64[i]);
743         PutWithNul(&p, &n, "");
744         for(i = 0; i < MAX_PUBKEYS; ++i)
745                 if(!pubkeys_havepriv[i] && pubkeys[i])
746                         PutWithNul(&p, &n, pubkeys_fp64[i]);
747         Crypto_UnLittleLong(lengthptr, p - startptr);
748         challenge_append_length = p - challenge_append;
749 }
750
751 static void Crypto_LoadKeys(void)
752 {
753         char buf[8192];
754         size_t len, len2;
755         int i;
756
757         // load keys
758         // note: we are just a CLIENT
759         // so we load:
760         //   PUBLIC KEYS to accept (including modulus)
761         //   PRIVATE KEY of user
762
763         crypto_idstring = NULL;
764         dpsnprintf(crypto_idstring_buf, sizeof(crypto_idstring_buf), "%d", d0_rijndael_dll ? crypto_aeslevel.integer : 0);
765         for(i = 0; i < MAX_PUBKEYS; ++i)
766         {
767                 memset(pubkeys_fp64[i], 0, sizeof(pubkeys_fp64[i]));
768                 memset(pubkeys_priv_fp64[i], 0, sizeof(pubkeys_fp64[i]));
769                 pubkeys_havepriv[i] = false;
770                 len = Crypto_LoadFile(va("key_%d.d0pk", i), buf, sizeof(buf));
771                 if((pubkeys[i] = Crypto_ReadPublicKey(buf, len)))
772                 {
773                         len2 = FP64_SIZE;
774                         if(qd0_blind_id_fingerprint64_public_key(pubkeys[i], pubkeys_fp64[i], &len2)) // keeps final NUL
775                         {
776                                 Con_Printf("Loaded public key key_%d.d0pk (fingerprint: %s)\n", i, pubkeys_fp64[i]);
777                                 len = Crypto_LoadFile(va("key_%d.d0si", i), buf, sizeof(buf));
778                                 if(len)
779                                 {
780                                         if(Crypto_AddPrivateKey(pubkeys[i], buf, len))
781                                         {
782                                                 len2 = FP64_SIZE;
783                                                 if(qd0_blind_id_fingerprint64_public_id(pubkeys[i], pubkeys_priv_fp64[i], &len2)) // keeps final NUL
784                                                 {
785                                                         Con_Printf("Loaded private ID key_%d.d0si for key_%d.d0pk (fingerprint: %s)\n", i, i, pubkeys_priv_fp64[i]);
786                                                         pubkeys_havepriv[i] = true;
787                                                         strlcat(crypto_idstring_buf, va(" %s@%s", pubkeys_priv_fp64[i], pubkeys_fp64[i]), sizeof(crypto_idstring_buf));
788                                                 }
789                                                 else
790                                                 {
791                                                         // can't really happen
792                                                         // but nothing leaked here
793                                                 }
794                                         }
795                                 }
796                         }
797                         else
798                         {
799                                 // can't really happen
800                                 qd0_blind_id_free(pubkeys[i]);
801                                 pubkeys[i] = NULL;
802                         }
803                 }
804         }
805         crypto_idstring = crypto_idstring_buf;
806
807         keygen_i = -1;
808         Crypto_BuildChallengeAppend();
809
810         // find a good prefix length for all the keys we know (yes, algorithm is not perfect yet, may yield too long prefix length)
811         crypto_keyfp_recommended_length = 0;
812         memset(buf+256, 0, MAX_PUBKEYS + MAX_PUBKEYS);
813         while(crypto_keyfp_recommended_length < FP64_SIZE)
814         {
815                 memset(buf, 0, 256);
816                 for(i = 0; i < MAX_PUBKEYS; ++i)
817                         if(pubkeys[i])
818                         {
819                                 if(!buf[256 + i])
820                                         ++buf[(unsigned char) pubkeys_fp64[i][crypto_keyfp_recommended_length]];
821                                 if(pubkeys_havepriv[i])
822                                         if(!buf[256 + MAX_PUBKEYS + i])
823                                                 ++buf[(unsigned char) pubkeys_priv_fp64[i][crypto_keyfp_recommended_length]];
824                         }
825                 for(i = 0; i < MAX_PUBKEYS; ++i)
826                         if(pubkeys[i])
827                         {
828                                 if(!buf[256 + i])
829                                         if(buf[(unsigned char) pubkeys_fp64[i][crypto_keyfp_recommended_length]] < 2)
830                                                 buf[256 + i] = 1;
831                                 if(pubkeys_havepriv[i])
832                                         if(!buf[256 + MAX_PUBKEYS + i])
833                                                 if(buf[(unsigned char) pubkeys_priv_fp64[i][crypto_keyfp_recommended_length]] < 2)
834                                                         buf[256 + MAX_PUBKEYS + i] = 1;
835                         }
836                 ++crypto_keyfp_recommended_length;
837                 for(i = 0; i < MAX_PUBKEYS; ++i)
838                         if(pubkeys[i])
839                         {
840                                 if(!buf[256 + i])
841                                         break;
842                                 if(pubkeys_havepriv[i])
843                                         if(!buf[256 + MAX_PUBKEYS + i])
844                                                 break;
845                         }
846                 if(i >= MAX_PUBKEYS)
847                         break;
848         }
849         if(crypto_keyfp_recommended_length < 7)
850                 crypto_keyfp_recommended_length = 7;
851 }
852
853 static void Crypto_UnloadKeys(void)
854 {
855         int i;
856         keygen_i = -1;
857         for(i = 0; i < MAX_PUBKEYS; ++i)
858         {
859                 if(pubkeys[i])
860                         qd0_blind_id_free(pubkeys[i]);
861                 pubkeys[i] = NULL;
862                 pubkeys_havepriv[i] = false;
863                 memset(pubkeys_fp64[i], 0, sizeof(pubkeys_fp64[i]));
864                 memset(pubkeys_priv_fp64[i], 0, sizeof(pubkeys_fp64[i]));
865                 challenge_append_length = 0;
866         }
867         crypto_idstring = NULL;
868 }
869
870 void Crypto_Shutdown(void)
871 {
872         crypto_t *crypto;
873         int i;
874
875         Crypto_Rijndael_CloseLibrary();
876
877         if(d0_blind_id_dll)
878         {
879                 // free memory
880                 for(i = 0; i < MAX_CRYPTOCONNECTS; ++i)
881                 {
882                         crypto = &cryptoconnects[i].crypto;
883                         CLEAR_CDATA;
884                 }
885                 memset(cryptoconnects, 0, sizeof(cryptoconnects));
886                 crypto = &cls.crypto;
887                 CLEAR_CDATA;
888
889                 Crypto_UnloadKeys();
890
891                 qd0_blind_id_SHUTDOWN();
892
893                 Crypto_CloseLibrary();
894         }
895 }
896
897 void Crypto_Init(void)
898 {
899         if(!Crypto_OpenLibrary())
900                 return;
901
902         if(!qd0_blind_id_INITIALIZE())
903         {
904                 Crypto_Rijndael_CloseLibrary();
905                 Crypto_CloseLibrary();
906                 Con_Printf("libd0_blind_id initialization FAILED, cryptography support has been disabled\n");
907                 return;
908         }
909
910         Crypto_Rijndael_OpenLibrary(); // if this fails, it's uncritical
911
912         Crypto_InitHostKeys();
913         Crypto_LoadKeys();
914 }
915 // end
916
917 // keygen code
918 static void Crypto_KeyGen_Finished(int code, size_t length_received, unsigned char *buffer, void *cbdata)
919 {
920         const char *p[1];
921         size_t l[1];
922         static char buf[8192];
923         static char buf2[8192];
924         size_t bufsize, buf2size;
925         qfile_t *f = NULL;
926         d0_blind_id_t *ctx, *ctx2;
927         D0_BOOL status;
928         size_t len2;
929
930         if(!d0_blind_id_dll)
931         {
932                 Con_Print("libd0_blind_id DLL not found, this command is inactive.\n");
933                 keygen_i = -1;
934                 return;
935         }
936
937         if(keygen_i >= MAX_PUBKEYS || !pubkeys[keygen_i])
938         {
939                 Con_Printf("overflow of keygen_i\n");
940                 keygen_i = -1;
941                 return;
942         }
943         if(keygen_i < 0)
944         {
945                 Con_Printf("Unexpected response from keygen server:\n");
946                 Com_HexDumpToConsole(buffer, length_received);
947                 return;
948         }
949         if(!Crypto_ParsePack((const char *) buffer, length_received, FOURCC_D0IR, p, l, 1))
950         {
951                 if(length_received >= 5 && Crypto_LittleLong((const char *) buffer) == FOURCC_D0ER)
952                 {
953                         Con_Printf("Error response from keygen server: %.*s\n", (int)(length_received - 5), buffer + 5);
954                 }
955                 else
956                 {
957                         Con_Printf("Invalid response from keygen server:\n");
958                         Com_HexDumpToConsole(buffer, length_received);
959                 }
960                 keygen_i = -1;
961                 return;
962         }
963         if(!qd0_blind_id_finish_private_id_request(pubkeys[keygen_i], p[0], l[0]))
964         {
965                 Con_Printf("d0_blind_id_finish_private_id_request failed\n");
966                 keygen_i = -1;
967                 return;
968         }
969
970         // verify the key we just got (just in case)
971         ctx = qd0_blind_id_new();
972         if(!ctx)
973         {
974                 Con_Printf("d0_blind_id_new failed\n");
975                 keygen_i = -1;
976                 return;
977         }
978         ctx2 = qd0_blind_id_new();
979         if(!ctx2)
980         {
981                 Con_Printf("d0_blind_id_new failed\n");
982                 qd0_blind_id_free(ctx);
983                 keygen_i = -1;
984                 return;
985         }
986         if(!qd0_blind_id_copy(ctx, pubkeys[keygen_i]))
987         {
988                 Con_Printf("d0_blind_id_copy failed\n");
989                 qd0_blind_id_free(ctx);
990                 qd0_blind_id_free(ctx2);
991                 keygen_i = -1;
992                 return;
993         }
994         if(!qd0_blind_id_copy(ctx2, pubkeys[keygen_i]))
995         {
996                 Con_Printf("d0_blind_id_copy failed\n");
997                 qd0_blind_id_free(ctx);
998                 qd0_blind_id_free(ctx2);
999                 keygen_i = -1;
1000                 return;
1001         }
1002         bufsize = sizeof(buf);
1003         if(!qd0_blind_id_authenticate_with_private_id_start(ctx, 1, 1, "hello world", 11, buf, &bufsize))
1004         {
1005                 Con_Printf("d0_blind_id_authenticate_with_private_id_start failed\n");
1006                 qd0_blind_id_free(ctx);
1007                 qd0_blind_id_free(ctx2);
1008                 keygen_i = -1;
1009                 return;
1010         }
1011         buf2size = sizeof(buf2);
1012         if(!qd0_blind_id_authenticate_with_private_id_challenge(ctx2, 1, 1, buf, bufsize, buf2, &buf2size, &status) || !status)
1013         {
1014                 Con_Printf("d0_blind_id_authenticate_with_private_id_challenge failed (server does not have the requested private key)\n");
1015                 qd0_blind_id_free(ctx);
1016                 qd0_blind_id_free(ctx2);
1017                 keygen_i = -1;
1018                 return;
1019         }
1020         bufsize = sizeof(buf);
1021         if(!qd0_blind_id_authenticate_with_private_id_response(ctx, buf2, buf2size, buf, &bufsize))
1022         {
1023                 Con_Printf("d0_blind_id_authenticate_with_private_id_response failed\n");
1024                 qd0_blind_id_free(ctx);
1025                 qd0_blind_id_free(ctx2);
1026                 keygen_i = -1;
1027                 return;
1028         }
1029         buf2size = sizeof(buf2);
1030         if(!qd0_blind_id_authenticate_with_private_id_verify(ctx2, buf, bufsize, buf2, &buf2size, &status) || !status)
1031         {
1032                 Con_Printf("d0_blind_id_authenticate_with_private_id_verify failed (server does not have the requested private key)\n");
1033                 qd0_blind_id_free(ctx);
1034                 qd0_blind_id_free(ctx2);
1035                 keygen_i = -1;
1036                 return;
1037         }
1038         qd0_blind_id_free(ctx);
1039         qd0_blind_id_free(ctx2);
1040
1041         // we have a valid key now!
1042         // make the rest of crypto.c know that
1043         len2 = FP64_SIZE;
1044         if(qd0_blind_id_fingerprint64_public_id(pubkeys[keygen_i], pubkeys_priv_fp64[keygen_i], &len2)) // keeps final NUL
1045         {
1046                 Con_Printf("Received private ID key_%d.d0pk (fingerprint: %s)\n", keygen_i, pubkeys_priv_fp64[keygen_i]);
1047                 pubkeys_havepriv[keygen_i] = true;
1048                 strlcat(crypto_idstring_buf, va(" %s@%s", pubkeys_priv_fp64[keygen_i], pubkeys_fp64[keygen_i]), sizeof(crypto_idstring_buf));
1049                 crypto_idstring = crypto_idstring_buf;
1050                 Crypto_BuildChallengeAppend();
1051         }
1052         // write the key to disk
1053         p[0] = buf;
1054         l[0] = sizeof(buf);
1055         if(!qd0_blind_id_write_private_id(pubkeys[keygen_i], buf, &l[0]))
1056         {
1057                 Con_Printf("d0_blind_id_write_private_id failed\n");
1058                 keygen_i = -1;
1059                 return;
1060         }
1061         if(!(buf2size = Crypto_UnParsePack(buf2, sizeof(buf2), FOURCC_D0SI, p, l, 1)))
1062         {
1063                 Con_Printf("Crypto_UnParsePack failed\n");
1064                 keygen_i = -1;
1065                 return;
1066         }
1067
1068         if(*fs_userdir)
1069         {
1070                 FS_CreatePath(va("%skey_%d.d0si", fs_userdir, keygen_i));
1071                 f = FS_SysOpen(va("%skey_%d.d0si", fs_userdir, keygen_i), "wb", false);
1072         }
1073         if(!f)
1074         {
1075                 FS_CreatePath(va("%skey_%d.d0si", fs_basedir, keygen_i));
1076                 f = FS_SysOpen(va("%skey_%d.d0si", fs_basedir, keygen_i), "wb", false);
1077         }
1078         if(!f)
1079         {
1080                 Con_Printf("Cannot open key_%d.d0si\n", keygen_i);
1081                 keygen_i = -1;
1082                 return;
1083         }
1084         FS_Write(f, buf2, buf2size);
1085         FS_Close(f);
1086
1087         Con_Printf("Saved to key_%d.d0si\n", keygen_i);
1088         keygen_i = -1;
1089 }
1090
1091 static void Crypto_KeyGen_f(void)
1092 {
1093         int i;
1094         const char *p[1];
1095         size_t l[1];
1096         static char buf[8192];
1097         static char buf2[8192];
1098         size_t buf2l, buf2pos;
1099         if(!d0_blind_id_dll)
1100         {
1101                 Con_Print("libd0_blind_id DLL not found, this command is inactive.\n");
1102                 return;
1103         }
1104         if(Cmd_Argc() != 3)
1105         {
1106                 Con_Printf("usage:\n%s id url\n", Cmd_Argv(0));
1107                 return;
1108         }
1109         i = atoi(Cmd_Argv(1));
1110         if(!pubkeys[i])
1111         {
1112                 Con_Printf("there is no public key %d\n", i);
1113                 return;
1114         }
1115         if(pubkeys_havepriv[i])
1116         {
1117                 Con_Printf("there is already a private key for %d\n", i);
1118                 return;
1119         }
1120         if(keygen_i >= 0)
1121         {
1122                 Con_Printf("there is already a keygen run on the way\n");
1123                 return;
1124         }
1125         keygen_i = i;
1126         if(!qd0_blind_id_generate_private_id_start(pubkeys[keygen_i]))
1127         {
1128                 Con_Printf("d0_blind_id_start failed\n");
1129                 keygen_i = -1;
1130                 return;
1131         }
1132         p[0] = buf;
1133         l[0] = sizeof(buf);
1134         if(!qd0_blind_id_generate_private_id_request(pubkeys[keygen_i], buf, &l[0]))
1135         {
1136                 Con_Printf("d0_blind_id_generate_private_id_request failed\n");
1137                 keygen_i = -1;
1138                 return;
1139         }
1140         buf2pos = strlen(Cmd_Argv(2));
1141         memcpy(buf2, Cmd_Argv(2), buf2pos);
1142         if(!(buf2l = Crypto_UnParsePack(buf2 + buf2pos, sizeof(buf2) - buf2pos - 1, FOURCC_D0IQ, p, l, 1)))
1143         {
1144                 Con_Printf("Crypto_UnParsePack failed\n");
1145                 keygen_i = -1;
1146                 return;
1147         }
1148         if(!(buf2l = base64_encode((unsigned char *) (buf2 + buf2pos), buf2l, sizeof(buf2) - buf2pos - 1)))
1149         {
1150                 Con_Printf("base64_encode failed\n");
1151                 keygen_i = -1;
1152                 return;
1153         }
1154         buf2l += buf2pos;
1155         buf[buf2l] = 0;
1156         if(!Curl_Begin_ToMemory(buf2, 0, (unsigned char *) keygen_buf, sizeof(keygen_buf), Crypto_KeyGen_Finished, NULL))
1157         {
1158                 Con_Printf("curl failed\n");
1159                 keygen_i = -1;
1160                 return;
1161         }
1162         Con_Printf("key generation in progress\n");
1163 }
1164 // end
1165
1166 // console commands
1167 static void Crypto_Reload_f(void)
1168 {
1169         Crypto_ClearHostKeys();
1170         Crypto_UnloadKeys();
1171         Crypto_LoadKeys();
1172 }
1173
1174 static void Crypto_Keys_f(void)
1175 {
1176         int i;
1177         if(!d0_blind_id_dll)
1178         {
1179                 Con_Print("libd0_blind_id DLL not found, this command is inactive.\n");
1180                 return;
1181         }
1182         for(i = 0; i < MAX_PUBKEYS; ++i)
1183         {
1184                 if(pubkeys[i])
1185                 {
1186                         Con_Printf("%2d: public key key_%d.d0pk (fingerprint: %s)\n", i, i, pubkeys_fp64[i]);
1187                         if(pubkeys_havepriv[i])
1188                                 Con_Printf("    private ID key_%d.d0si (fingerprint: %s)\n", i, pubkeys_priv_fp64[i]);
1189                 }
1190         }
1191 }
1192
1193 static void Crypto_HostKeys_f(void)
1194 {
1195         int i;
1196         crypto_storedhostkey_t *hk;
1197         char buf[128];
1198
1199         if(!d0_blind_id_dll)
1200         {
1201                 Con_Print("libd0_blind_id DLL not found, this command is inactive.\n");
1202                 return;
1203         }
1204         for(i = 0; i < CRYPTO_HOSTKEY_HASHSIZE; ++i)
1205         {
1206                 for(hk = crypto_storedhostkey_hashtable[i]; hk; hk = hk->next)
1207                 {
1208                         LHNETADDRESS_ToString(&hk->addr, buf, sizeof(buf), 1);
1209                         Con_Printf("%d %s@%.*s %s\n",
1210                                         hk->aeslevel,
1211                                         hk->idfp,
1212                                         crypto_keyfp_recommended_length, pubkeys_fp64[hk->keyid],
1213                                         buf);
1214                 }
1215         }
1216 }
1217
1218 static void Crypto_HostKey_Clear_f(void)
1219 {
1220         lhnetaddress_t addr;
1221         int i;
1222
1223         if(!d0_blind_id_dll)
1224         {
1225                 Con_Print("libd0_blind_id DLL not found, this command is inactive.\n");
1226                 return;
1227         }
1228
1229         for(i = 1; i < Cmd_Argc(); ++i)
1230         {
1231                 LHNETADDRESS_FromString(&addr, Cmd_Argv(i), 26000);
1232                 if(Crypto_ClearHostKey(&addr))
1233                 {
1234                         Con_Printf("cleared host key for %s\n", Cmd_Argv(i));
1235                 }
1236         }
1237 }
1238
1239 void Crypto_Init_Commands(void)
1240 {
1241         if(d0_blind_id_dll)
1242         {
1243                 Cmd_AddCommand("crypto_reload", Crypto_Reload_f, "reloads cryptographic keys");
1244                 Cmd_AddCommand("crypto_keygen", Crypto_KeyGen_f, "generates and saves a cryptographic key");
1245                 Cmd_AddCommand("crypto_keys", Crypto_Keys_f, "lists the loaded keys");
1246                 Cmd_AddCommand("crypto_hostkeys", Crypto_HostKeys_f, "lists the cached host keys");
1247                 Cmd_AddCommand("crypto_hostkey_clear", Crypto_HostKey_Clear_f, "clears a cached host key");
1248                 Cvar_RegisterVariable(&crypto_developer);
1249                 if(d0_rijndael_dll)
1250                         Cvar_RegisterVariable(&crypto_aeslevel);
1251                 else
1252                         crypto_aeslevel.integer = 0; // make sure
1253                 Cvar_RegisterVariable(&crypto_servercpupercent);
1254                 Cvar_RegisterVariable(&crypto_servercpumaxtime);
1255                 Cvar_RegisterVariable(&crypto_servercpudebug);
1256         }
1257 }
1258 // end
1259
1260 // AES encryption
1261 static void aescpy(unsigned char *key, const unsigned char *iv, unsigned char *dst, const unsigned char *src, size_t len)
1262 {
1263         const unsigned char *xorpos = iv;
1264         unsigned char xorbuf[16];
1265         unsigned long rk[D0_RIJNDAEL_RKLENGTH(DHKEY_SIZE * 8)];
1266         size_t i;
1267         qd0_rijndael_setup_encrypt(rk, key, DHKEY_SIZE * 8);
1268         while(len > 16)
1269         {
1270                 for(i = 0; i < 16; ++i)
1271                         xorbuf[i] = src[i] ^ xorpos[i];
1272                 qd0_rijndael_encrypt(rk, D0_RIJNDAEL_NROUNDS(DHKEY_SIZE * 8), xorbuf, dst);
1273                 xorpos = dst;
1274                 len -= 16;
1275                 src += 16;
1276                 dst += 16;
1277         }
1278         if(len > 0)
1279         {
1280                 for(i = 0; i < len; ++i)
1281                         xorbuf[i] = src[i] ^ xorpos[i];
1282                 for(; i < 16; ++i)
1283                         xorbuf[i] = xorpos[i];
1284                 qd0_rijndael_encrypt(rk, D0_RIJNDAEL_NROUNDS(DHKEY_SIZE * 8), xorbuf, dst);
1285         }
1286 }
1287 static void seacpy(unsigned char *key, const unsigned char *iv, unsigned char *dst, const unsigned char *src, size_t len)
1288 {
1289         const unsigned char *xorpos = iv;
1290         unsigned char xorbuf[16];
1291         unsigned long rk[D0_RIJNDAEL_RKLENGTH(DHKEY_SIZE * 8)];
1292         size_t i;
1293         qd0_rijndael_setup_decrypt(rk, key, DHKEY_SIZE * 8);
1294         while(len > 16)
1295         {
1296                 qd0_rijndael_decrypt(rk, D0_RIJNDAEL_NROUNDS(DHKEY_SIZE * 8), src, xorbuf);
1297                 for(i = 0; i < 16; ++i)
1298                         dst[i] = xorbuf[i] ^ xorpos[i];
1299                 xorpos = src;
1300                 len -= 16;
1301                 src += 16;
1302                 dst += 16;
1303         }
1304         if(len > 0)
1305         {
1306                 qd0_rijndael_decrypt(rk, D0_RIJNDAEL_NROUNDS(DHKEY_SIZE * 8), src, xorbuf);
1307                 for(i = 0; i < len; ++i)
1308                         dst[i] = xorbuf[i] ^ xorpos[i];
1309         }
1310 }
1311
1312 // NOTE: we MUST avoid the following begins of the packet:
1313 //   1. 0xFF, 0xFF, 0xFF, 0xFF
1314 //   2. 0x80, 0x00, length/256, length%256
1315 // this luckily does NOT affect AES mode, where the first byte always is in the range from 0x00 to 0x0F
1316 const void *Crypto_EncryptPacket(crypto_t *crypto, const void *data_src, size_t len_src, void *data_dst, size_t *len_dst, size_t len)
1317 {
1318         unsigned char h[32];
1319         int i;
1320         if(crypto->authenticated)
1321         {
1322                 if(crypto->use_aes)
1323                 {
1324                         // AES packet = 1 byte length overhead, 15 bytes from HMAC-SHA-256, data, 0..15 bytes padding
1325                         // 15 bytes HMAC-SHA-256 (112bit) suffice as the attacker can't do more than forge a random-looking packet
1326                         // HMAC is needed to not leak information about packet content
1327                         if(developer_networking.integer)
1328                         {
1329                                 Con_Print("To be encrypted:\n");
1330                                 Com_HexDumpToConsole((const unsigned char *) data_src, len_src);
1331                         }
1332                         if(len_src + 32 > len || !HMAC_SHA256_32BYTES(h, (const unsigned char *) data_src, len_src, crypto->dhkey, DHKEY_SIZE))
1333                         {
1334                                 Con_Printf("Crypto_EncryptPacket failed (not enough space: %d bytes in, %d bytes out)\n", (int) len_src, (int) len);
1335                                 return NULL;
1336                         }
1337                         *len_dst = ((len_src + 15) / 16) * 16 + 16; // add 16 for HMAC, then round to 16-size for AES
1338                         ((unsigned char *) data_dst)[0] = *len_dst - len_src;
1339                         memcpy(((unsigned char *) data_dst)+1, h, 15);
1340                         aescpy(crypto->dhkey, (const unsigned char *) data_dst, ((unsigned char *) data_dst) + 16, (const unsigned char *) data_src, len_src);
1341                         //                    IV                                dst                                src                               len
1342                 }
1343                 else
1344                 {
1345                         // HMAC packet = 16 bytes HMAC-SHA-256 (truncated to 128 bits), data
1346                         if(len_src + 16 > len || !HMAC_SHA256_32BYTES(h, (const unsigned char *) data_src, len_src, crypto->dhkey, DHKEY_SIZE))
1347                         {
1348                                 Con_Printf("Crypto_EncryptPacket failed (not enough space: %d bytes in, %d bytes out)\n", (int) len_src, (int) len);
1349                                 return NULL;
1350                         }
1351                         *len_dst = len_src + 16;
1352                         memcpy(data_dst, h, 16);
1353                         memcpy(((unsigned char *) data_dst) + 16, (unsigned char *) data_src, len_src);
1354
1355                         // handle the "avoid" conditions:
1356                         i = BuffBigLong((unsigned char *) data_dst);
1357                         if(
1358                                 (i == (int)0xFFFFFFFF) // avoid QW control packet
1359                                 ||
1360                                 (i == (int)0x80000000 + (int)*len_dst) // avoid NQ control packet
1361                         )
1362                                 *(unsigned char *)data_dst ^= 0x80; // this will ALWAYS fix it
1363                 }
1364                 return data_dst;
1365         }
1366         else
1367         {
1368                 *len_dst = len_src;
1369                 return data_src;
1370         }
1371 }
1372
1373 const void *Crypto_DecryptPacket(crypto_t *crypto, const void *data_src, size_t len_src, void *data_dst, size_t *len_dst, size_t len)
1374 {
1375         unsigned char h[32];
1376         int i;
1377
1378         // silently handle non-crypto packets
1379         i = BuffBigLong((unsigned char *) data_src);
1380         if(
1381                 (i == (int)0xFFFFFFFF) // avoid QW control packet
1382                 ||
1383                 (i == (int)0x80000000 + (int)len_src) // avoid NQ control packet
1384         )
1385                 return NULL;
1386
1387         if(crypto->authenticated)
1388         {
1389                 if(crypto->use_aes)
1390                 {
1391                         if(len_src < 16 || ((len_src - 16) % 16))
1392                         {
1393                                 Con_Printf("Crypto_DecryptPacket failed (not enough space: %d bytes in, %d bytes out)\n", (int) len_src, (int) len);
1394                                 return NULL;
1395                         }
1396                         *len_dst = len_src - ((unsigned char *) data_src)[0];
1397                         if(len < *len_dst || *len_dst > len_src - 16)
1398                         {
1399                                 Con_Printf("Crypto_DecryptPacket failed (not enough space: %d bytes in, %d->%d bytes out)\n", (int) len_src, (int) *len_dst, (int) len);
1400                                 return NULL;
1401                         }
1402                         seacpy(crypto->dhkey, (unsigned char *) data_src, (unsigned char *) data_dst, ((const unsigned char *) data_src) + 16, *len_dst);
1403                         //                    IV                          dst                         src                                      len
1404                         if(!HMAC_SHA256_32BYTES(h, (const unsigned char *) data_dst, *len_dst, crypto->dhkey, DHKEY_SIZE))
1405                         {
1406                                 Con_Printf("HMAC fail\n");
1407                                 return NULL;
1408                         }
1409                         if(memcmp(((const unsigned char *) data_src)+1, h, 15)) // ignore first byte, used for length
1410                         {
1411                                 Con_Printf("HMAC mismatch\n");
1412                                 return NULL;
1413                         }
1414                         if(developer_networking.integer)
1415                         {
1416                                 Con_Print("Decrypted:\n");
1417                                 Com_HexDumpToConsole((const unsigned char *) data_dst, *len_dst);
1418                         }
1419                         return data_dst; // no need to copy
1420                 }
1421                 else
1422                 {
1423                         if(len_src < 16)
1424                         {
1425                                 Con_Printf("Crypto_DecryptPacket failed (not enough space: %d bytes in, %d bytes out)\n", (int) len_src, (int) len);
1426                                 return NULL;
1427                         }
1428                         *len_dst = len_src - 16;
1429                         if(len < *len_dst)
1430                         {
1431                                 Con_Printf("Crypto_DecryptPacket failed (not enough space: %d bytes in, %d->%d bytes out)\n", (int) len_src, (int) *len_dst, (int) len);
1432                                 return NULL;
1433                         }
1434                         //memcpy(data_dst, data_src + 16, *len_dst);
1435                         if(!HMAC_SHA256_32BYTES(h, ((const unsigned char *) data_src) + 16, *len_dst, crypto->dhkey, DHKEY_SIZE))
1436                         {
1437                                 Con_Printf("HMAC fail\n");
1438                                 Com_HexDumpToConsole((const unsigned char *) data_src, len_src);
1439                                 return NULL;
1440                         }
1441
1442                         if(memcmp((const unsigned char *) data_src, h, 16)) // ignore first byte, used for length
1443                         {
1444                                 // undo the "avoid conditions"
1445                                 if(
1446                                                 (i == (int)0x7FFFFFFF) // avoided QW control packet
1447                                                 ||
1448                                                 (i == (int)0x00000000 + (int)len_src) // avoided NQ control packet
1449                                   )
1450                                 {
1451                                         // do the avoidance on the hash too
1452                                         h[0] ^= 0x80;
1453                                         if(memcmp((const unsigned char *) data_src, h, 16)) // ignore first byte, used for length
1454                                         {
1455                                                 Con_Printf("HMAC mismatch\n");
1456                                                 Com_HexDumpToConsole((const unsigned char *) data_src, len_src);
1457                                                 return NULL;
1458                                         }
1459                                 }
1460                                 else
1461                                 {
1462                                         Con_Printf("HMAC mismatch\n");
1463                                         Com_HexDumpToConsole((const unsigned char *) data_src, len_src);
1464                                         return NULL;
1465                                 }
1466                         }
1467                         return ((const unsigned char *) data_src) + 16; // no need to copy, so data_dst is not used
1468                 }
1469         }
1470         else
1471         {
1472                 *len_dst = len_src;
1473                 return data_src;
1474         }
1475 }
1476 // end
1477
1478 const char *Crypto_GetInfoResponseDataString(void)
1479 {
1480         crypto_idstring_buf[0] = '0' + crypto_aeslevel.integer;
1481         return crypto_idstring;
1482 }
1483
1484 // network protocol
1485 qboolean Crypto_ServerAppendToChallenge(const char *data_in, size_t len_in, char *data_out, size_t *len_out, size_t maxlen_out)
1486 {
1487         // cheap op, all is precomputed
1488         if(!d0_blind_id_dll)
1489                 return false; // no support
1490         // append challenge
1491         if(maxlen_out <= *len_out + challenge_append_length)
1492                 return false;
1493         memcpy(data_out + *len_out, challenge_append, challenge_append_length);
1494         *len_out += challenge_append_length;
1495         return false;
1496 }
1497
1498 static int Crypto_ServerError(char *data_out, size_t *len_out, const char *msg, const char *msg_client)
1499 {
1500         if(!msg_client)
1501                 msg_client = msg;
1502         Con_DPrintf("rejecting client: %s\n", msg);
1503         if(*msg_client)
1504                 dpsnprintf(data_out, *len_out, "reject %s", msg_client);
1505         *len_out = strlen(data_out);
1506         return CRYPTO_DISCARD;
1507 }
1508
1509 static int Crypto_SoftServerError(char *data_out, size_t *len_out, const char *msg)
1510 {
1511         *len_out = 0;
1512         Con_DPrintf("%s\n", msg);
1513         return CRYPTO_DISCARD;
1514 }
1515
1516 static int Crypto_ServerParsePacket_Internal(const char *data_in, size_t len_in, char *data_out, size_t *len_out, lhnetaddress_t *peeraddress)
1517 {
1518         // if "connect": reject if in the middle of crypto handshake
1519         crypto_t *crypto = NULL;
1520         char *data_out_p = data_out;
1521         const char *string = data_in;
1522         int aeslevel;
1523         D0_BOOL aes;
1524         D0_BOOL status;
1525
1526         if(!d0_blind_id_dll)
1527                 return CRYPTO_NOMATCH; // no support
1528
1529         if (len_in > 8 && !memcmp(string, "connect\\", 8) && d0_rijndael_dll && crypto_aeslevel.integer >= 3)
1530         {
1531                 const char *s;
1532                 int i;
1533                 // sorry, we have to verify the challenge here to not reflect network spam
1534
1535                 if (!(s = SearchInfostring(string + 4, "challenge")))
1536                         return CRYPTO_NOMATCH; // will be later accepted if encryption was set up
1537                 // validate the challenge
1538                 for (i = 0;i < MAX_CHALLENGES;i++)
1539                         if(challenge[i].time > 0)
1540                                 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1541                                         break;
1542                 // if the challenge is not recognized, drop the packet
1543                 if (i == MAX_CHALLENGES) // challenge mismatch is silent
1544                         return CRYPTO_DISCARD; // pre-challenge: rather be silent
1545
1546                 crypto = Crypto_ServerFindInstance(peeraddress, false);
1547                 if(!crypto || !crypto->authenticated)
1548                         return Crypto_ServerError(data_out, len_out, "This server requires authentication and encryption to be supported by your client", NULL);
1549         }
1550         else if(len_in > 5 && !memcmp(string, "d0pk\\", 5) && ((LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP) || sv_public.integer > -3))
1551         {
1552                 const char *cnt, *s, *p;
1553                 int id;
1554                 int clientid = -1, serverid = -1;
1555                 cnt = SearchInfostring(string + 4, "id");
1556                 id = (cnt ? atoi(cnt) : -1);
1557                 cnt = SearchInfostring(string + 4, "cnt");
1558                 if(!cnt)
1559                         return CRYPTO_DISCARD; // pre-challenge: rather be silent
1560                 GetUntilNul(&data_in, &len_in);
1561                 if(!data_in)
1562                         return CRYPTO_DISCARD; // pre-challenge: rather be silent
1563                 if(!strcmp(cnt, "0"))
1564                 {
1565                         int i;
1566                         if (!(s = SearchInfostring(string + 4, "challenge")))
1567                                 return CRYPTO_DISCARD; // pre-challenge: rather be silent
1568                         // validate the challenge
1569                         for (i = 0;i < MAX_CHALLENGES;i++)
1570                                 if(challenge[i].time > 0)
1571                                         if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1572                                                 break;
1573                         // if the challenge is not recognized, drop the packet
1574                         if (i == MAX_CHALLENGES) // challenge mismatch is silent
1575                                 return CRYPTO_DISCARD; // pre-challenge: rather be silent
1576
1577                         if (!(s = SearchInfostring(string + 4, "aeslevel")))
1578                                 aeslevel = 0; // not supported
1579                         else
1580                                 aeslevel = bound(0, atoi(s), 3);
1581                         switch(bound(0, d0_rijndael_dll ? crypto_aeslevel.integer : 0, 3))
1582                         {
1583                                 default: // dummy, never happens, but to make gcc happy...
1584                                 case 0:
1585                                         if(aeslevel >= 3)
1586                                                 return Crypto_ServerError(data_out, len_out, "This server requires encryption to be not required (crypto_aeslevel <= 2)", NULL);
1587                                         aes = false;
1588                                         break;
1589                                 case 1:
1590                                         aes = (aeslevel >= 2);
1591                                         break;
1592                                 case 2:
1593                                         aes = (aeslevel >= 1);
1594                                         break;
1595                                 case 3:
1596                                         if(aeslevel <= 0)
1597                                                 return Crypto_ServerError(data_out, len_out, "This server requires encryption to be supported (crypto_aeslevel >= 1, and d0_rijndael library must be present)", NULL);
1598                                         aes = true;
1599                                         break;
1600                         }
1601
1602                         p = GetUntilNul(&data_in, &len_in);
1603                         if(p && *p)
1604                         {
1605                                 for(i = 0; i < MAX_PUBKEYS; ++i)
1606                                 {
1607                                         if(pubkeys[i])
1608                                                 if(!strcmp(p, pubkeys_fp64[i]))
1609                                                         if(pubkeys_havepriv[i])
1610                                                                 if(serverid < 0)
1611                                                                         serverid = i;
1612                                 }
1613                                 if(serverid < 0)
1614                                         return Crypto_ServerError(data_out, len_out, "Invalid server key", NULL);
1615                         }
1616                         p = GetUntilNul(&data_in, &len_in);
1617                         if(p && *p)
1618                         {
1619                                 for(i = 0; i < MAX_PUBKEYS; ++i)
1620                                 {
1621                                         if(pubkeys[i])
1622                                                 if(!strcmp(p, pubkeys_fp64[i]))
1623                                                         if(clientid < 0)
1624                                                                 clientid = i;
1625                                 }
1626                                 if(clientid < 0)
1627                                         return Crypto_ServerError(data_out, len_out, "Invalid client key", NULL);
1628                         }
1629
1630                         crypto = Crypto_ServerFindInstance(peeraddress, true);
1631                         if(!crypto)
1632                                 return Crypto_ServerError(data_out, len_out, "Could not create a crypto connect instance", NULL);
1633                         MAKE_CDATA;
1634                         CDATA->cdata_id = id;
1635                         CDATA->s = serverid;
1636                         CDATA->c = clientid;
1637                         memset(crypto->dhkey, 0, sizeof(crypto->dhkey));
1638                         CDATA->challenge[0] = 0;
1639                         crypto->client_keyfp[0] = 0;
1640                         crypto->client_idfp[0] = 0;
1641                         crypto->server_keyfp[0] = 0;
1642                         crypto->server_idfp[0] = 0;
1643                         crypto->use_aes = aes != 0;
1644
1645                         if(CDATA->s >= 0)
1646                         {
1647                                 // I am the server, and my key is ok... so let's set server_keyfp and server_idfp
1648                                 strlcpy(crypto->server_keyfp, pubkeys_fp64[CDATA->s], sizeof(crypto->server_keyfp));
1649                                 strlcpy(crypto->server_idfp, pubkeys_priv_fp64[CDATA->s], sizeof(crypto->server_idfp));
1650
1651                                 if(!CDATA->id)
1652                                         CDATA->id = qd0_blind_id_new();
1653                                 if(!CDATA->id)
1654                                 {
1655                                         CLEAR_CDATA;
1656                                         return Crypto_ServerError(data_out, len_out, "d0_blind_id_new failed", "Internal error");
1657                                 }
1658                                 if(!qd0_blind_id_copy(CDATA->id, pubkeys[CDATA->s]))
1659                                 {
1660                                         CLEAR_CDATA;
1661                                         return Crypto_ServerError(data_out, len_out, "d0_blind_id_copy failed", "Internal error");
1662                                 }
1663                                 PutWithNul(&data_out_p, len_out, va("d0pk\\cnt\\1\\id\\%d\\aes\\%d", CDATA->cdata_id, crypto->use_aes));
1664                                 if(!qd0_blind_id_authenticate_with_private_id_start(CDATA->id, true, false, "XONOTIC", 8, data_out_p, len_out)) // len_out receives used size by this op
1665                                 {
1666                                         CLEAR_CDATA;
1667                                         return Crypto_ServerError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_start failed", "Internal error");
1668                                 }
1669                                 CDATA->next_step = 2;
1670                                 data_out_p += *len_out;
1671                                 *len_out = data_out_p - data_out;
1672                                 return CRYPTO_DISCARD;
1673                         }
1674                         else if(CDATA->c >= 0)
1675                         {
1676                                 if(!CDATA->id)
1677                                         CDATA->id = qd0_blind_id_new();
1678                                 if(!CDATA->id)
1679                                 {
1680                                         CLEAR_CDATA;
1681                                         return Crypto_ServerError(data_out, len_out, "d0_blind_id_new failed", "Internal error");
1682                                 }
1683                                 if(!qd0_blind_id_copy(CDATA->id, pubkeys[CDATA->c]))
1684                                 {
1685                                         CLEAR_CDATA;
1686                                         return Crypto_ServerError(data_out, len_out, "d0_blind_id_copy failed", "Internal error");
1687                                 }
1688                                 PutWithNul(&data_out_p, len_out, va("d0pk\\cnt\\5\\id\\%d\\aes\\%d", CDATA->cdata_id, crypto->use_aes));
1689                                 if(!qd0_blind_id_authenticate_with_private_id_challenge(CDATA->id, true, false, data_in, len_in, data_out_p, len_out, &status))
1690                                 {
1691                                         CLEAR_CDATA;
1692                                         return Crypto_ServerError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_challenge failed", "Internal error");
1693                                 }
1694                                 CDATA->next_step = 6;
1695                                 data_out_p += *len_out;
1696                                 *len_out = data_out_p - data_out;
1697                                 return CRYPTO_DISCARD;
1698                         }
1699                         else
1700                         {
1701                                 CLEAR_CDATA;
1702                                 return Crypto_ServerError(data_out, len_out, "Missing client and server key", NULL);
1703                         }
1704                 }
1705                 else if(!strcmp(cnt, "2"))
1706                 {
1707                         size_t fpbuflen;
1708                         crypto = Crypto_ServerFindInstance(peeraddress, false);
1709                         if(!crypto)
1710                                 return CRYPTO_NOMATCH; // pre-challenge, rather be silent
1711                         if(id >= 0)
1712                                 if(CDATA->cdata_id != id)
1713                                         return Crypto_SoftServerError(data_out, len_out, va("Got d0pk\\id\\%d when expecting %d", id, CDATA->cdata_id));
1714                         if(CDATA->next_step != 2)
1715                                 return Crypto_SoftServerError(data_out, len_out, va("Got d0pk\\cnt\\%s when expecting %d", cnt, CDATA->next_step));
1716
1717                         PutWithNul(&data_out_p, len_out, va("d0pk\\cnt\\3\\id\\%d", CDATA->cdata_id));
1718                         if(!qd0_blind_id_authenticate_with_private_id_response(CDATA->id, data_in, len_in, data_out_p, len_out))
1719                         {
1720                                 CLEAR_CDATA;
1721                                 return Crypto_ServerError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_response failed", "Internal error");
1722                         }
1723                         fpbuflen = DHKEY_SIZE;
1724                         if(!qd0_blind_id_sessionkey_public_id(CDATA->id, (char *) crypto->dhkey, &fpbuflen))
1725                         {
1726                                 CLEAR_CDATA;
1727                                 return Crypto_ServerError(data_out, len_out, "d0_blind_id_sessionkey_public_id failed", "Internal error");
1728                         }
1729                         if(CDATA->c >= 0)
1730                         {
1731                                 if(!qd0_blind_id_copy(CDATA->id, pubkeys[CDATA->c]))
1732                                 {
1733                                         CLEAR_CDATA;
1734                                         return Crypto_ServerError(data_out, len_out, "d0_blind_id_copy failed", "Internal error");
1735                                 }
1736                                 CDATA->next_step = 4;
1737                         }
1738                         else
1739                         {
1740                                 // session key is FINISHED (no server part is to be expected)! By this, all keys are set up
1741                                 crypto->authenticated = true;
1742                                 CDATA->next_step = 0;
1743                         }
1744                         data_out_p += *len_out;
1745                         *len_out = data_out_p - data_out;
1746                         return CRYPTO_DISCARD;
1747                 }
1748                 else if(!strcmp(cnt, "4"))
1749                 {
1750                         crypto = Crypto_ServerFindInstance(peeraddress, false);
1751                         if(!crypto)
1752                                 return CRYPTO_NOMATCH; // pre-challenge, rather be silent
1753                         if(id >= 0)
1754                                 if(CDATA->cdata_id != id)
1755                                         return Crypto_SoftServerError(data_out, len_out, va("Got d0pk\\id\\%d when expecting %d", id, CDATA->cdata_id));
1756                         if(CDATA->next_step != 4)
1757                                 return Crypto_SoftServerError(data_out, len_out, va("Got d0pk\\cnt\\%s when expecting %d", cnt, CDATA->next_step));
1758                         PutWithNul(&data_out_p, len_out, va("d0pk\\cnt\\5\\id\\%d", CDATA->cdata_id));
1759                         if(!qd0_blind_id_authenticate_with_private_id_challenge(CDATA->id, true, false, data_in, len_in, data_out_p, len_out, &status))
1760                         {
1761                                 CLEAR_CDATA;
1762                                 return Crypto_ServerError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_challenge failed", "Internal error");
1763                         }
1764                         CDATA->next_step = 6;
1765                         data_out_p += *len_out;
1766                         *len_out = data_out_p - data_out;
1767                         return CRYPTO_DISCARD;
1768                 }
1769                 else if(!strcmp(cnt, "6"))
1770                 {
1771                         static char msgbuf[32];
1772                         size_t msgbuflen = sizeof(msgbuf);
1773                         size_t fpbuflen;
1774                         int i;
1775                         unsigned char dhkey[DHKEY_SIZE];
1776                         crypto = Crypto_ServerFindInstance(peeraddress, false);
1777                         if(!crypto)
1778                                 return CRYPTO_NOMATCH; // pre-challenge, rather be silent
1779                         if(id >= 0)
1780                                 if(CDATA->cdata_id != id)
1781                                         return Crypto_SoftServerError(data_out, len_out, va("Got d0pk\\id\\%d when expecting %d", id, CDATA->cdata_id));
1782                         if(CDATA->next_step != 6)
1783                                 return Crypto_SoftServerError(data_out, len_out, va("Got d0pk\\cnt\\%s when expecting %d", cnt, CDATA->next_step));
1784
1785                         if(!qd0_blind_id_authenticate_with_private_id_verify(CDATA->id, data_in, len_in, msgbuf, &msgbuflen, &status))
1786                         {
1787                                 CLEAR_CDATA;
1788                                 return Crypto_ServerError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_verify failed (authentication error)", "Authentication error");
1789                         }
1790                         if(status)
1791                                 strlcpy(crypto->client_keyfp, pubkeys_fp64[CDATA->c], sizeof(crypto->client_keyfp));
1792                         else
1793                                 crypto->client_keyfp[0] = 0;
1794                         memset(crypto->client_idfp, 0, sizeof(crypto->client_idfp));
1795                         fpbuflen = FP64_SIZE;
1796                         if(!qd0_blind_id_fingerprint64_public_id(CDATA->id, crypto->client_idfp, &fpbuflen))
1797                         {
1798                                 CLEAR_CDATA;
1799                                 return Crypto_ServerError(data_out, len_out, "d0_blind_id_fingerprint64_public_id failed", "Internal error");
1800                         }
1801                         fpbuflen = DHKEY_SIZE;
1802                         if(!qd0_blind_id_sessionkey_public_id(CDATA->id, (char *) dhkey, &fpbuflen))
1803                         {
1804                                 CLEAR_CDATA;
1805                                 return Crypto_ServerError(data_out, len_out, "d0_blind_id_sessionkey_public_id failed", "Internal error");
1806                         }
1807                         // XOR the two DH keys together to make one
1808                         for(i = 0; i < DHKEY_SIZE; ++i)
1809                                 crypto->dhkey[i] ^= dhkey[i];
1810
1811                         // session key is FINISHED (no server part is to be expected)! By this, all keys are set up
1812                         crypto->authenticated = true;
1813                         CDATA->next_step = 0;
1814                         // send a challenge-less challenge
1815                         PutWithNul(&data_out_p, len_out, "challenge ");
1816                         *len_out = data_out_p - data_out;
1817                         --*len_out; // remove NUL terminator
1818                         return CRYPTO_MATCH;
1819                 }
1820                 return CRYPTO_NOMATCH; // pre-challenge, rather be silent
1821         }
1822         return CRYPTO_NOMATCH;
1823 }
1824
1825 int Crypto_ServerParsePacket(const char *data_in, size_t len_in, char *data_out, size_t *len_out, lhnetaddress_t *peeraddress)
1826 {
1827         int ret;
1828         double t = 0;
1829         static double complain_time = 0;
1830         const char *cnt;
1831         qboolean do_time = false;
1832         qboolean do_reject = false;
1833         if(crypto_servercpupercent.value > 0 || crypto_servercpumaxtime.value > 0)
1834                 if(len_in > 5 && !memcmp(data_in, "d0pk\\", 5))
1835                 {
1836                         do_time = true;
1837                         cnt = SearchInfostring(data_in + 4, "cnt");
1838                         if(cnt)
1839                                 if(!strcmp(cnt, "0"))
1840                                         do_reject = true;
1841                 }
1842         if(do_time)
1843         {
1844                 // check if we may perform crypto...
1845                 if(crypto_servercpupercent.value > 0)
1846                 {
1847                         crypto_servercpu_accumulator += (realtime - crypto_servercpu_lastrealtime) * crypto_servercpupercent.value * 0.01;
1848                         if(crypto_servercpumaxtime.value)
1849                                 if(crypto_servercpu_accumulator > crypto_servercpumaxtime.value)
1850                                         crypto_servercpu_accumulator = crypto_servercpumaxtime.value;
1851                 }
1852                 else
1853                 {
1854                         if(crypto_servercpumaxtime.value > 0)
1855                                 if(realtime != crypto_servercpu_lastrealtime)
1856                                         crypto_servercpu_accumulator = crypto_servercpumaxtime.value;
1857                 }
1858                 crypto_servercpu_lastrealtime = realtime;
1859                 if(do_reject && crypto_servercpu_accumulator < 0)
1860                 {
1861                         if(realtime > complain_time + 5)
1862                                 Con_Printf("crypto: cannot perform requested crypto operations; denial service attack or crypto_servercpupercent/crypto_servercpumaxtime are too low\n");
1863                         *len_out = 0;
1864                         return CRYPTO_DISCARD;
1865                 }
1866                 t = Sys_DoubleTime();
1867         }
1868         ret = Crypto_ServerParsePacket_Internal(data_in, len_in, data_out, len_out, peeraddress);
1869         if(do_time)
1870         {
1871                 t = Sys_DoubleTime() - t;
1872                 if(crypto_servercpudebug.integer)
1873                         Con_Printf("crypto: accumulator was %.1f ms, used %.1f ms for crypto, ", crypto_servercpu_accumulator * 1000, t * 1000);
1874                 crypto_servercpu_accumulator -= t;
1875                 if(crypto_servercpudebug.integer)
1876                         Con_Printf("is %.1f ms\n", crypto_servercpu_accumulator * 1000);
1877         }
1878         return ret;
1879 }
1880
1881 static int Crypto_ClientError(char *data_out, size_t *len_out, const char *msg)
1882 {
1883         dpsnprintf(data_out, *len_out, "reject %s", msg);
1884         *len_out = strlen(data_out);
1885         return CRYPTO_REPLACE;
1886 }
1887
1888 static int Crypto_SoftClientError(char *data_out, size_t *len_out, const char *msg)
1889 {
1890         *len_out = 0;
1891         Con_Printf("%s\n", msg);
1892         return CRYPTO_DISCARD;
1893 }
1894
1895 int Crypto_ClientParsePacket(const char *data_in, size_t len_in, char *data_out, size_t *len_out, lhnetaddress_t *peeraddress)
1896 {
1897         crypto_t *crypto = &cls.crypto;
1898         const char *string = data_in;
1899         const char *s;
1900         D0_BOOL aes;
1901         char *data_out_p = data_out;
1902         D0_BOOL status;
1903
1904         if(!d0_blind_id_dll)
1905                 return CRYPTO_NOMATCH; // no support
1906
1907         // if "challenge": verify challenge, and discard message, send next crypto protocol message instead
1908         // otherwise, just handle actual protocol messages
1909
1910         if (len_in == 6 && !memcmp(string, "accept", 6) && cls.connect_trying && d0_rijndael_dll)
1911         {
1912                 int wantserverid = -1;
1913                 Crypto_RetrieveHostKey(&cls.connect_address, &wantserverid, NULL, 0, NULL, 0, NULL);
1914                 if(!crypto || !crypto->authenticated)
1915                 {
1916                         if(wantserverid >= 0)
1917                                 return Crypto_ClientError(data_out, len_out, "Server tried an unauthenticated connection even though a host key is present");
1918                         if(crypto_aeslevel.integer >= 3)
1919                                 return Crypto_ClientError(data_out, len_out, "This server requires encryption to be not required (crypto_aeslevel <= 2)");
1920                 }
1921                 return CRYPTO_NOMATCH;
1922         }
1923         else if (len_in >= 1 && string[0] == 'j' && cls.connect_trying && d0_rijndael_dll && crypto_aeslevel.integer >= 3)
1924         {
1925                 int wantserverid = -1;
1926                 Crypto_RetrieveHostKey(&cls.connect_address, &wantserverid, NULL, 0, NULL, 0, NULL);
1927                 if(!crypto || !crypto->authenticated)
1928                 {
1929                         if(wantserverid >= 0)
1930                                 return Crypto_ClientError(data_out, len_out, "Server tried an unauthenticated connection even though a host key is present");
1931                         if(crypto_aeslevel.integer >= 3)
1932                                 return Crypto_ClientError(data_out, len_out, "This server requires encryption to be not required (crypto_aeslevel <= 2)");
1933                 }
1934                 return CRYPTO_NOMATCH;
1935         }
1936         else if (len_in >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1937         {
1938                 s = SearchInfostring(string + 13, "d0_blind_id");
1939                 if(s)
1940                         Crypto_StoreHostKey(peeraddress, s, true);
1941                 return CRYPTO_NOMATCH;
1942         }
1943         else if (len_in >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1944         {
1945                 char save = 0;
1946                 const char *p;
1947                 p = strchr(string + 15, '\n');
1948                 if(p)
1949                 {
1950                         save = *p;
1951                         * (char *) p = 0; // cut off the string there
1952                 }
1953                 s = SearchInfostring(string + 15, "d0_blind_id");
1954                 if(s)
1955                         Crypto_StoreHostKey(peeraddress, s, true);
1956                 if(p)
1957                 {
1958                         * (char *) p = save;
1959                         // invoking those nasal demons again (do not run this on the DS9k)
1960                 }
1961                 return CRYPTO_NOMATCH;
1962         }
1963         else if(len_in > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1964         {
1965                 const char *vlen_blind_id_ptr = NULL;
1966                 size_t len_blind_id_ptr = 0;
1967                 unsigned long k, v;
1968                 const char *challenge = data_in + 10;
1969                 const char *p;
1970                 int i;
1971                 int clientid = -1, serverid = -1, wantserverid = -1;
1972                 qboolean server_can_auth = true;
1973                 char wantserver_idfp[FP64_SIZE+1];
1974                 int wantserver_aeslevel;
1975
1976                 // if we have a stored host key for the server, assume serverid to already be selected!
1977                 // (the loop will refuse to overwrite this one then)
1978                 wantserver_idfp[0] = 0;
1979                 Crypto_RetrieveHostKey(&cls.connect_address, &wantserverid, NULL, 0, wantserver_idfp, sizeof(wantserver_idfp), &wantserver_aeslevel);
1980                 // requirement: wantserver_idfp is a full ID if wantserverid set
1981
1982                 // if we leave, we have to consider the connection
1983                 // unauthenticated; NOTE: this may be faked by a clever
1984                 // attacker to force an unauthenticated connection; so we have
1985                 // a safeguard check in place when encryption is required too
1986                 // in place, or when authentication is required by the server
1987                 crypto->authenticated = false;
1988
1989                 GetUntilNul(&data_in, &len_in);
1990                 if(!data_in)
1991                         return (wantserverid >= 0) ? Crypto_ClientError(data_out, len_out, "Server tried an unauthenticated connection even though a host key is present") :
1992                                 (d0_rijndael_dll && crypto_aeslevel.integer >= 3) ? Crypto_ServerError(data_out, len_out, "This server requires encryption to be not required (crypto_aeslevel <= 2)", NULL) :
1993                                 CRYPTO_NOMATCH;
1994
1995                 // FTEQW extension protocol
1996                 while(len_in >= 8)
1997                 {
1998                         k = Crypto_LittleLong(data_in);
1999                         v = Crypto_LittleLong(data_in + 4);
2000                         data_in += 8;
2001                         len_in -= 8;
2002                         switch(k)
2003                         {
2004                                 case PROTOCOL_VLEN:
2005                                         if(len_in >= 4 + v)
2006                                         {
2007                                                 k = Crypto_LittleLong(data_in);
2008                                                 data_in += 4;
2009                                                 len_in -= 4;
2010                                                 switch(k)
2011                                                 {
2012                                                         case PROTOCOL_D0_BLIND_ID:
2013                                                                 vlen_blind_id_ptr = data_in;
2014                                                                 len_blind_id_ptr = v;
2015                                                                 break;
2016                                                 }
2017                                                 data_in += v;
2018                                                 len_in -= v;
2019                                         }
2020                                         break;
2021                                 default:
2022                                         break;
2023                         }
2024                 }
2025
2026                 if(!vlen_blind_id_ptr)
2027                         return (wantserverid >= 0) ? Crypto_ClientError(data_out, len_out, "Server tried an unauthenticated connection even though authentication is required") :
2028                                 (d0_rijndael_dll && crypto_aeslevel.integer >= 3) ? Crypto_ServerError(data_out, len_out, "This server requires encryption to be not required (crypto_aeslevel <= 2)", NULL) :
2029                                 CRYPTO_NOMATCH;
2030
2031                 data_in = vlen_blind_id_ptr;
2032                 len_in = len_blind_id_ptr;
2033
2034                 // parse fingerprints
2035                 //   once we found a fingerprint we can auth to (ANY), select it as clientfp
2036                 //   once we found a fingerprint in the first list that we know, select it as serverfp
2037
2038                 for(;;)
2039                 {
2040                         p = GetUntilNul(&data_in, &len_in);
2041                         if(!p)
2042                                 break;
2043                         if(!*p)
2044                         {
2045                                 if(!server_can_auth)
2046                                         break; // other protocol message may follow
2047                                 server_can_auth = false;
2048                                 if(clientid >= 0)
2049                                         break;
2050                                 continue;
2051                         }
2052                         for(i = 0; i < MAX_PUBKEYS; ++i)
2053                         {
2054                                 if(pubkeys[i])
2055                                 if(!strcmp(p, pubkeys_fp64[i]))
2056                                 {
2057                                         if(pubkeys_havepriv[i])
2058                                                 if(clientid < 0)
2059                                                         clientid = i;
2060                                         if(server_can_auth)
2061                                                 if(serverid < 0)
2062                                                         if(wantserverid < 0 || i == wantserverid)
2063                                                                 serverid = i;
2064                                 }
2065                         }
2066                         if(clientid >= 0 && serverid >= 0)
2067                                 break;
2068                 }
2069
2070                 // if stored host key is not found:
2071                 if(wantserverid >= 0 && serverid < 0)
2072                         return Crypto_ClientError(data_out, len_out, "Server CA does not match stored host key, refusing to connect");
2073
2074                 if(serverid >= 0 || clientid >= 0)
2075                 {
2076                         // TODO at this point, fill clientside crypto struct!
2077                         MAKE_CDATA;
2078                         CDATA->cdata_id = ++cdata_id;
2079                         CDATA->s = serverid;
2080                         CDATA->c = clientid;
2081                         memset(crypto->dhkey, 0, sizeof(crypto->dhkey));
2082                         strlcpy(CDATA->challenge, challenge, sizeof(CDATA->challenge));
2083                         crypto->client_keyfp[0] = 0;
2084                         crypto->client_idfp[0] = 0;
2085                         crypto->server_keyfp[0] = 0;
2086                         crypto->server_idfp[0] = 0;
2087                         memcpy(CDATA->wantserver_idfp, wantserver_idfp, sizeof(crypto->server_idfp));
2088
2089                         if(CDATA->wantserver_idfp[0]) // if we know a host key, honor its encryption setting
2090                         switch(bound(0, d0_rijndael_dll ? crypto_aeslevel.integer : 0, 3))
2091                         {
2092                                 default: // dummy, never happens, but to make gcc happy...
2093                                 case 0:
2094                                         if(wantserver_aeslevel >= 3)
2095                                                 return Crypto_ServerError(data_out, len_out, "This server requires encryption to be not required (crypto_aeslevel <= 2)", NULL);
2096                                         CDATA->wantserver_aes = false;
2097                                         break;
2098                                 case 1:
2099                                         CDATA->wantserver_aes = (wantserver_aeslevel >= 2);
2100                                         break;
2101                                 case 2:
2102                                         CDATA->wantserver_aes = (wantserver_aeslevel >= 1);
2103                                         break;
2104                                 case 3:
2105                                         if(wantserver_aeslevel <= 0)
2106                                                 return Crypto_ServerError(data_out, len_out, "This server requires encryption to be supported (crypto_aeslevel >= 1, and d0_rijndael library must be present)", NULL);
2107                                         CDATA->wantserver_aes = true;
2108                                         break;
2109                         }
2110
2111                         // build outgoing message
2112                         // append regular stuff
2113                         PutWithNul(&data_out_p, len_out, va("d0pk\\cnt\\0\\id\\%d\\aeslevel\\%d\\challenge\\%s", CDATA->cdata_id, d0_rijndael_dll ? crypto_aeslevel.integer : 0, challenge));
2114                         PutWithNul(&data_out_p, len_out, serverid >= 0 ? pubkeys_fp64[serverid] : "");
2115                         PutWithNul(&data_out_p, len_out, clientid >= 0 ? pubkeys_fp64[clientid] : "");
2116
2117                         if(clientid >= 0)
2118                         {
2119                                 // I am the client, and my key is ok... so let's set client_keyfp and client_idfp
2120                                 strlcpy(crypto->client_keyfp, pubkeys_fp64[CDATA->c], sizeof(crypto->client_keyfp));
2121                                 strlcpy(crypto->client_idfp, pubkeys_priv_fp64[CDATA->c], sizeof(crypto->client_idfp));
2122                         }
2123
2124                         if(serverid >= 0)
2125                         {
2126                                 if(!CDATA->id)
2127                                         CDATA->id = qd0_blind_id_new();
2128                                 if(!CDATA->id)
2129                                 {
2130                                         CLEAR_CDATA;
2131                                         return Crypto_ClientError(data_out, len_out, "d0_blind_id_new failed");
2132                                 }
2133                                 if(!qd0_blind_id_copy(CDATA->id, pubkeys[CDATA->s]))
2134                                 {
2135                                         CLEAR_CDATA;
2136                                         return Crypto_ClientError(data_out, len_out, "d0_blind_id_copy failed");
2137                                 }
2138                                 CDATA->next_step = 1;
2139                                 *len_out = data_out_p - data_out;
2140                         }
2141                         else if(clientid >= 0)
2142                         {
2143                                 // skip over server auth, perform client auth only
2144                                 if(!CDATA->id)
2145                                         CDATA->id = qd0_blind_id_new();
2146                                 if(!CDATA->id)
2147                                 {
2148                                         CLEAR_CDATA;
2149                                         return Crypto_ClientError(data_out, len_out, "d0_blind_id_new failed");
2150                                 }
2151                                 if(!qd0_blind_id_copy(CDATA->id, pubkeys[CDATA->c]))
2152                                 {
2153                                         CLEAR_CDATA;
2154                                         return Crypto_ClientError(data_out, len_out, "d0_blind_id_copy failed");
2155                                 }
2156                                 if(!qd0_blind_id_authenticate_with_private_id_start(CDATA->id, true, false, "XONOTIC", 8, data_out_p, len_out)) // len_out receives used size by this op
2157                                 {
2158                                         CLEAR_CDATA;
2159                                         return Crypto_ClientError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_start failed");
2160                                 }
2161                                 CDATA->next_step = 5;
2162                                 data_out_p += *len_out;
2163                                 *len_out = data_out_p - data_out;
2164                         }
2165                         else
2166                                 *len_out = data_out_p - data_out;
2167
2168                         return CRYPTO_DISCARD;
2169                 }
2170                 else
2171                 {
2172                         if(wantserver_idfp[0]) // if we know a host key, honor its encryption setting
2173                         if(wantserver_aeslevel >= 3)
2174                                 return Crypto_ClientError(data_out, len_out, "Server insists on encryption, but neither can authenticate to the other");
2175                         return (d0_rijndael_dll && crypto_aeslevel.integer >= 3) ? Crypto_ServerError(data_out, len_out, "This server requires encryption to be not required (crypto_aeslevel <= 2)", NULL) :
2176                                 CRYPTO_NOMATCH;
2177                 }
2178         }
2179         else if(len_in > 5 && !memcmp(string, "d0pk\\", 5) && cls.connect_trying)
2180         {
2181                 const char *cnt;
2182                 int id;
2183                 cnt = SearchInfostring(string + 4, "id");
2184                 id = (cnt ? atoi(cnt) : -1);
2185                 cnt = SearchInfostring(string + 4, "cnt");
2186                 if(!cnt)
2187                         return Crypto_ClientError(data_out, len_out, "d0pk\\ message without cnt");
2188                 GetUntilNul(&data_in, &len_in);
2189                 if(!data_in)
2190                         return Crypto_ClientError(data_out, len_out, "d0pk\\ message without attachment");
2191
2192                 if(!strcmp(cnt, "1"))
2193                 {
2194                         if(id >= 0)
2195                                 if(CDATA->cdata_id != id)
2196                                         return Crypto_SoftServerError(data_out, len_out, va("Got d0pk\\id\\%d when expecting %d", id, CDATA->cdata_id));
2197                         if(CDATA->next_step != 1)
2198                                 return Crypto_SoftClientError(data_out, len_out, va("Got d0pk\\cnt\\%s when expecting %d", cnt, CDATA->next_step));
2199
2200                         cls.connect_nextsendtime = max(cls.connect_nextsendtime, realtime + 1); // prevent "hammering"
2201
2202                         if((s = SearchInfostring(string + 4, "aes")))
2203                                 aes = atoi(s);
2204                         else
2205                                 aes = false;
2206                         // we CANNOT toggle the AES status any more!
2207                         // as the server already decided
2208                         if(CDATA->wantserver_idfp[0]) // if we know a host key, honor its encryption setting
2209                         if(!aes && CDATA->wantserver_aes)
2210                         {
2211                                 CLEAR_CDATA;
2212                                 return Crypto_ClientError(data_out, len_out, "Stored host key requires encryption, but server did not enable encryption");
2213                         }
2214                         if(aes && (!d0_rijndael_dll || crypto_aeslevel.integer <= 0))
2215                         {
2216                                 CLEAR_CDATA;
2217                                 return Crypto_ClientError(data_out, len_out, "Server insists on encryption too hard");
2218                         }
2219                         if(!aes && (d0_rijndael_dll && crypto_aeslevel.integer >= 3))
2220                         {
2221                                 CLEAR_CDATA;
2222                                 return Crypto_ClientError(data_out, len_out, "Server insists on plaintext too hard");
2223                         }
2224                         crypto->use_aes = aes != 0;
2225
2226                         PutWithNul(&data_out_p, len_out, va("d0pk\\cnt\\2\\id\\%d", CDATA->cdata_id));
2227                         if(!qd0_blind_id_authenticate_with_private_id_challenge(CDATA->id, true, false, data_in, len_in, data_out_p, len_out, &status))
2228                         {
2229                                 CLEAR_CDATA;
2230                                 return Crypto_ClientError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_challenge failed");
2231                         }
2232                         CDATA->next_step = 3;
2233                         data_out_p += *len_out;
2234                         *len_out = data_out_p - data_out;
2235                         return CRYPTO_DISCARD;
2236                 }
2237                 else if(!strcmp(cnt, "3"))
2238                 {
2239                         static char msgbuf[32];
2240                         size_t msgbuflen = sizeof(msgbuf);
2241                         size_t fpbuflen;
2242
2243                         if(id >= 0)
2244                                 if(CDATA->cdata_id != id)
2245                                         return Crypto_SoftServerError(data_out, len_out, va("Got d0pk\\id\\%d when expecting %d", id, CDATA->cdata_id));
2246                         if(CDATA->next_step != 3)
2247                                 return Crypto_SoftClientError(data_out, len_out, va("Got d0pk\\cnt\\%s when expecting %d", cnt, CDATA->next_step));
2248
2249                         cls.connect_nextsendtime = max(cls.connect_nextsendtime, realtime + 1); // prevent "hammering"
2250
2251                         if(!qd0_blind_id_authenticate_with_private_id_verify(CDATA->id, data_in, len_in, msgbuf, &msgbuflen, &status))
2252                         {
2253                                 CLEAR_CDATA;
2254                                 return Crypto_ClientError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_verify failed (server authentication error)");
2255                         }
2256                         if(status)
2257                                 strlcpy(crypto->server_keyfp, pubkeys_fp64[CDATA->s], sizeof(crypto->server_keyfp));
2258                         else
2259                                 crypto->server_keyfp[0] = 0;
2260                         memset(crypto->server_idfp, 0, sizeof(crypto->server_idfp));
2261                         fpbuflen = FP64_SIZE;
2262                         if(!qd0_blind_id_fingerprint64_public_id(CDATA->id, crypto->server_idfp, &fpbuflen))
2263                         {
2264                                 CLEAR_CDATA;
2265                                 return Crypto_ClientError(data_out, len_out, "d0_blind_id_fingerprint64_public_id failed");
2266                         }
2267                         if(CDATA->wantserver_idfp[0])
2268                         if(memcmp(CDATA->wantserver_idfp, crypto->server_idfp, sizeof(crypto->server_idfp)))
2269                         {
2270                                 CLEAR_CDATA;
2271                                 return Crypto_ClientError(data_out, len_out, "Server ID does not match stored host key, refusing to connect");
2272                         }
2273                         fpbuflen = DHKEY_SIZE;
2274                         if(!qd0_blind_id_sessionkey_public_id(CDATA->id, (char *) crypto->dhkey, &fpbuflen))
2275                         {
2276                                 CLEAR_CDATA;
2277                                 return Crypto_ClientError(data_out, len_out, "d0_blind_id_sessionkey_public_id failed");
2278                         }
2279
2280                         // cache the server key
2281                         Crypto_StoreHostKey(&cls.connect_address, va("%d %s@%s", crypto->use_aes ? 1 : 0, crypto->server_idfp, pubkeys_fp64[CDATA->s]), false);
2282
2283                         if(CDATA->c >= 0)
2284                         {
2285                                 // client will auth next
2286                                 PutWithNul(&data_out_p, len_out, va("d0pk\\cnt\\4\\id\\%d", CDATA->cdata_id));
2287                                 if(!qd0_blind_id_copy(CDATA->id, pubkeys[CDATA->c]))
2288                                 {
2289                                         CLEAR_CDATA;
2290                                         return Crypto_ClientError(data_out, len_out, "d0_blind_id_copy failed");
2291                                 }
2292                                 if(!qd0_blind_id_authenticate_with_private_id_start(CDATA->id, true, false, "XONOTIC", 8, data_out_p, len_out)) // len_out receives used size by this op
2293                                 {
2294                                         CLEAR_CDATA;
2295                                         return Crypto_ClientError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_start failed");
2296                                 }
2297                                 CDATA->next_step = 5;
2298                                 data_out_p += *len_out;
2299                                 *len_out = data_out_p - data_out;
2300                                 return CRYPTO_DISCARD;
2301                         }
2302                         else
2303                         {
2304                                 // session key is FINISHED (no server part is to be expected)! By this, all keys are set up
2305                                 crypto->authenticated = true;
2306                                 CDATA->next_step = 0;
2307                                 // assume we got the empty challenge to finish the protocol
2308                                 PutWithNul(&data_out_p, len_out, "challenge ");
2309                                 *len_out = data_out_p - data_out;
2310                                 --*len_out; // remove NUL terminator
2311                                 return CRYPTO_REPLACE;
2312                         }
2313                 }
2314                 else if(!strcmp(cnt, "5"))
2315                 {
2316                         size_t fpbuflen;
2317                         unsigned char dhkey[DHKEY_SIZE];
2318                         int i;
2319
2320                         if(id >= 0)
2321                                 if(CDATA->cdata_id != id)
2322                                         return Crypto_SoftServerError(data_out, len_out, va("Got d0pk\\id\\%d when expecting %d", id, CDATA->cdata_id));
2323                         if(CDATA->next_step != 5)
2324                                 return Crypto_SoftClientError(data_out, len_out, va("Got d0pk\\cnt\\%s when expecting %d", cnt, CDATA->next_step));
2325
2326                         cls.connect_nextsendtime = max(cls.connect_nextsendtime, realtime + 1); // prevent "hammering"
2327
2328                         if(CDATA->s < 0) // only if server didn't auth
2329                         {
2330                                 if((s = SearchInfostring(string + 4, "aes")))
2331                                         aes = atoi(s);
2332                                 else
2333                                         aes = false;
2334                                 if(CDATA->wantserver_idfp[0]) // if we know a host key, honor its encryption setting
2335                                 if(!aes && CDATA->wantserver_aes)
2336                                 {
2337                                         CLEAR_CDATA;
2338                                         return Crypto_ClientError(data_out, len_out, "Stored host key requires encryption, but server did not enable encryption");
2339                                 }
2340                                 if(aes && (!d0_rijndael_dll || crypto_aeslevel.integer <= 0))
2341                                 {
2342                                         CLEAR_CDATA;
2343                                         return Crypto_ClientError(data_out, len_out, "Server insists on encryption too hard");
2344                                 }
2345                                 if(!aes && (d0_rijndael_dll && crypto_aeslevel.integer >= 3))
2346                                 {
2347                                         CLEAR_CDATA;
2348                                         return Crypto_ClientError(data_out, len_out, "Server insists on plaintext too hard");
2349                                 }
2350                                 crypto->use_aes = aes != 0;
2351                         }
2352
2353                         PutWithNul(&data_out_p, len_out, va("d0pk\\cnt\\6\\id\\%d", CDATA->cdata_id));
2354                         if(!qd0_blind_id_authenticate_with_private_id_response(CDATA->id, data_in, len_in, data_out_p, len_out))
2355                         {
2356                                 CLEAR_CDATA;
2357                                 return Crypto_ClientError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_response failed");
2358                         }
2359                         fpbuflen = DHKEY_SIZE;
2360                         if(!qd0_blind_id_sessionkey_public_id(CDATA->id, (char *) dhkey, &fpbuflen))
2361                         {
2362                                 CLEAR_CDATA;
2363                                 return Crypto_ClientError(data_out, len_out, "d0_blind_id_sessionkey_public_id failed");
2364                         }
2365                         // XOR the two DH keys together to make one
2366                         for(i = 0; i < DHKEY_SIZE; ++i)
2367                                 crypto->dhkey[i] ^= dhkey[i];
2368                         // session key is FINISHED! By this, all keys are set up
2369                         crypto->authenticated = true;
2370                         CDATA->next_step = 0;
2371                         data_out_p += *len_out;
2372                         *len_out = data_out_p - data_out;
2373                         return CRYPTO_DISCARD;
2374                 }
2375                 return Crypto_SoftClientError(data_out, len_out, "Got unknown d0_blind_id message from server");
2376         }
2377
2378         return CRYPTO_NOMATCH;
2379 }
2380
2381 size_t Crypto_SignData(const void *data, size_t datasize, int keyid, void *signed_data, size_t signed_size)
2382 {
2383         if(keyid < 0 || keyid >= MAX_PUBKEYS)
2384                 return 0;
2385         if(!pubkeys_havepriv[keyid])
2386                 return 0;
2387         if(qd0_blind_id_sign_with_private_id_sign(pubkeys[keyid], true, false, (const char *)data, datasize, (char *)signed_data, &signed_size))
2388                 return signed_size;
2389         return 0;
2390 }
2391
2392 size_t Crypto_SignDataDetached(const void *data, size_t datasize, int keyid, void *signed_data, size_t signed_size)
2393 {
2394         if(keyid < 0 || keyid >= MAX_PUBKEYS)
2395                 return 0;
2396         if(!pubkeys_havepriv[keyid])
2397                 return 0;
2398         if(qd0_blind_id_sign_with_private_id_sign_detached(pubkeys[keyid], true, false, (const char *)data, datasize, (char *)signed_data, &signed_size))
2399                 return signed_size;
2400         return 0;
2401 }