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