1 // TODO key loading, generating, saving
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];
21 #define PROTOCOL_D0_BLIND_ID FOURCC_D0PK
22 #define PROTOCOL_VLEN (('v' << 0) | ('l' << 8) | ('e' << 16) | ('n' << 24))
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))
34 static unsigned long Crypto_LittleLong(const char *data)
37 ((unsigned char) data[0]) |
38 (((unsigned char) data[1]) << 8) |
39 (((unsigned char) data[2]) << 16) |
40 (((unsigned char) data[3]) << 24);
43 static void Crypto_UnLittleLong(char *data, unsigned long l)
46 data[1] = (l >> 8) & 0xFF;
47 data[2] = (l >> 16) & 0xFF;
48 data[3] = (l >> 24) & 0xFF;
51 static size_t Crypto_ParsePack(const char *buf, size_t len, unsigned long header, const char **lumps, size_t *lumpsize, size_t nlumps)
60 if(Crypto_LittleLong(buf) != header)
64 for(i = 0; i < nlumps; ++i)
68 lumpsize[i] = Crypto_LittleLong(&buf[pos]);
70 if(pos + lumpsize[i] > len)
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)
87 Crypto_UnLittleLong(buf, header);
90 for(i = 0; i < nlumps; ++i)
92 if(pos + 4 + lumpsize[i] > len)
94 Crypto_UnLittleLong(&buf[pos], lumpsize[i]);
96 memcpy(&buf[pos], lumps[i], lumpsize[i]);
101 // END stuff shared with xonotic-keygen
107 #include <d0_blind_id/d0_blind_id.h>
109 #define d0_blind_id_dll 1
110 #define Crypto_OpenLibrary() true
111 #define Crypto_CloseLibrary()
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
153 // d0_blind_id interface
156 #define D0_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
158 #define D0_WARN_UNUSED_RESULT
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
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[] =
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},
249 // end of d0_blind_id interface
251 static dllhandle_t d0_blind_id_dll = NULL;
252 static qboolean Crypto_OpenLibrary (void)
254 const char* dllnames [] =
257 "libd0_blind_id-0.dll",
258 #elif defined(MACOSX)
259 "libd0_blind_id.0.dylib",
261 "libd0_blind_id.so.0",
262 "libd0_blind_id.so", // FreeBSD
272 return Sys_LoadLibrary (dllnames, &d0_blind_id_dll, d0_blind_id_funcs);
275 static void Crypto_CloseLibrary (void)
277 Sys_UnloadLibrary (&d0_blind_id_dll);
282 #ifdef CRYPTO_RIJNDAEL_STATIC
284 #include <d0_blind_id/d0_rijndael.h>
286 #define d0_rijndael_dll 1
287 #define Crypto_Rijndael_OpenLibrary() true
288 #define Crypto_Rijndael_CloseLibrary()
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
297 // no need to do the #define dance here, as the upper part declares out macros either way
299 D0_EXPORT int (*qd0_rijndael_setup_encrypt) (unsigned long *rk, const unsigned char *key,
301 D0_EXPORT int (*qd0_rijndael_setup_decrypt) (unsigned long *rk, const unsigned char *key,
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[] =
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},
318 // end of d0_blind_id interface
320 static dllhandle_t d0_rijndael_dll = NULL;
321 static qboolean Crypto_Rijndael_OpenLibrary (void)
323 const char* dllnames [] =
326 "libd0_rijndael-0.dll",
327 #elif defined(MACOSX)
328 "libd0_rijndael.0.dylib",
330 "libd0_rijndael.so.0",
331 "libd0_rijndael.so", // FreeBSD
341 return Sys_LoadLibrary (dllnames, &d0_rijndael_dll, d0_rijndael_funcs);
344 static void Crypto_Rijndael_CloseLibrary (void)
346 Sys_UnloadLibrary (&d0_rijndael_dll);
352 void sha256(unsigned char *out, const unsigned char *in, int n)
354 qd0_blind_id_util_sha256((char *) out, (const char *) in, n);
357 static size_t Crypto_LoadFile(const char *path, char *buf, size_t nmax, qboolean inuserdir)
363 f = FS_SysOpen(va(vabuf, sizeof(vabuf), "%s%s", *fs_userdir ? fs_userdir : fs_basedir, path), "rb", false);
365 f = FS_SysOpen(va(vabuf, sizeof(vabuf), "%s%s", fs_basedir, path), "rb", false);
368 n = FS_Read(f, buf, nmax);
375 static qboolean PutWithNul(char **data, size_t *len, const char *str)
377 // invariant: data points to insertion point
378 size_t l = strlen(str);
381 memcpy(*data, str, l+1);
387 static const char *GetUntilNul(const char **data, size_t *len)
389 // invariant: data points to next character to take
390 const char *data_save = *data;
403 p = (const char *) memchr(*data, 0, *len);
404 if(!p) // no terminating NUL
417 return (const char *) data_save;
424 static d0_blind_id_t *Crypto_ReadPublicKey(char *buf, size_t len)
426 d0_blind_id_t *pk = NULL;
429 if(Crypto_ParsePack(buf, len, FOURCC_D0PK, p, l, 2))
431 pk = qd0_blind_id_new();
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]))
438 qd0_blind_id_free(pk);
443 static qboolean Crypto_AddPrivateKey(d0_blind_id_t *pk, char *buf, size_t len)
447 if(Crypto_ParsePack(buf, len, FOURCC_D0SI, p, l, 1))
449 if(qd0_blind_id_read_private_id(pk, p[0], l[0]))
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;
463 static int keygen_i = -1;
464 static char keygen_buf[8192];
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
475 lhnetaddress_t address;
479 server_cryptoconnect_t;
480 static server_cryptoconnect_t cryptoconnects[MAX_CRYPTOCONNECTS];
482 static int cdata_id = 0;
488 char challenge[2048];
489 char wantserver_idfp[FP64_SIZE+1];
490 qboolean wantserver_aes;
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
500 static crypto_t *Crypto_ServerFindInstance(lhnetaddress_t *peeraddress, qboolean allow_create)
506 return NULL; // no support
508 for(i = 0; i < MAX_CRYPTOCONNECTS; ++i)
509 if(LHNETADDRESS_Compare(peeraddress, &cryptoconnects[i].address))
511 if(i < MAX_CRYPTOCONNECTS && (allow_create || cryptoconnects[i].crypto.data))
513 crypto = &cryptoconnects[i].crypto;
514 cryptoconnects[i].lasttime = realtime;
520 for(i = 1; i < MAX_CRYPTOCONNECTS; ++i)
521 if(cryptoconnects[i].lasttime < cryptoconnects[best].lasttime)
523 crypto = &cryptoconnects[best].crypto;
524 cryptoconnects[best].lasttime = realtime;
525 memcpy(&cryptoconnects[best].address, peeraddress, sizeof(cryptoconnects[best].address));
530 qboolean Crypto_ServerFinishInstance(crypto_t *out, crypto_t *crypto)
532 // no check needed here (returned pointers are only used in prefilled fields)
533 if(!crypto || !crypto->authenticated)
535 Con_Printf("Passed an invalid crypto connect instance\n");
536 memset(out, 0, sizeof(*out));
540 memcpy(out, crypto, sizeof(*out));
541 memset(crypto, 0, sizeof(crypto));
545 crypto_t *Crypto_ServerGetInstance(lhnetaddress_t *peeraddress)
547 // no check needed here (returned pointers are only used in prefilled fields)
548 return Crypto_ServerFindInstance(peeraddress, false);
551 typedef struct crypto_storedhostkey_s
553 struct crypto_storedhostkey_s *next;
556 char idfp[FP64_SIZE+1];
559 crypto_storedhostkey_t;
560 static crypto_storedhostkey_t *crypto_storedhostkey_hashtable[CRYPTO_HOSTKEY_HASHSIZE];
562 static void Crypto_InitHostKeys(void)
565 for(i = 0; i < CRYPTO_HOSTKEY_HASHSIZE; ++i)
566 crypto_storedhostkey_hashtable[i] = NULL;
569 static void Crypto_ClearHostKeys(void)
572 crypto_storedhostkey_t *hk, *hkn;
573 for(i = 0; i < CRYPTO_HOSTKEY_HASHSIZE; ++i)
575 for(hk = crypto_storedhostkey_hashtable[i]; hk; hk = hkn)
580 crypto_storedhostkey_hashtable[i] = NULL;
584 static qboolean Crypto_ClearHostKey(lhnetaddress_t *peeraddress)
588 crypto_storedhostkey_t **hkp;
589 qboolean found = false;
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));
597 crypto_storedhostkey_t *hk = *hkp;
606 static void Crypto_StoreHostKey(lhnetaddress_t *peeraddress, const char *keystring, qboolean complain)
610 crypto_storedhostkey_t *hk;
612 char idfp[FP64_SIZE+1];
618 // syntax of keystring:
619 // aeslevel id@key id@key ...
623 aeslevel = bound(0, *keystring - '0', 3);
624 while(*keystring && *keystring != ' ')
628 while(*keystring && keyid < 0)
631 const char *idstart, *idend, *keystart, *keyend;
632 ++keystring; // skip the space
634 while(*keystring && *keystring != ' ' && *keystring != '@')
640 keystart = keystring;
641 while(*keystring && *keystring != ' ')
645 if(idend - idstart == FP64_SIZE && keyend - keystart == FP64_SIZE)
647 for(keyid = 0; keyid < MAX_PUBKEYS; ++keyid)
649 if(!memcmp(pubkeys_fp64[keyid], keystart, FP64_SIZE))
651 memcpy(idfp, idstart, FP64_SIZE);
655 if(keyid >= MAX_PUBKEYS)
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);
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);
676 hk->aeslevel = max(aeslevel, hk->aeslevel);
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));
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;
690 qboolean Crypto_RetrieveHostKey(lhnetaddress_t *peeraddress, int *keyid, char *keyfp, size_t keyfplen, char *idfp, size_t idfplen, int *aeslevel)
694 crypto_storedhostkey_t *hk;
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);
709 strlcpy(keyfp, pubkeys_fp64[hk->keyid], keyfplen);
711 strlcpy(idfp, hk->idfp, idfplen);
713 *aeslevel = hk->aeslevel;
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
719 if(keyid < 0 || keyid >= MAX_PUBKEYS)
728 strlcpy(keyfp, pubkeys_fp64[keyid], keyfplen);
730 if(pubkeys_havepriv[keyid])
731 strlcpy(idfp, pubkeys_priv_fp64[keyid], keyfplen);
736 // init/shutdown code
737 static void Crypto_BuildChallengeAppend(void)
739 char *p, *lengthptr, *startptr;
742 p = challenge_append;
743 n = sizeof(challenge_append);
744 Crypto_UnLittleLong(p, PROTOCOL_VLEN);
748 Crypto_UnLittleLong(p, 0);
751 Crypto_UnLittleLong(p, PROTOCOL_D0_BLIND_ID);
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;
766 void Crypto_LoadKeys(void)
773 if(!d0_blind_id_dll) // don't if we can't
776 if(crypto_idstring) // already loaded? then not
779 Host_LockSession(); // we use the session ID here
782 // note: we are just a CLIENT
784 // PUBLIC KEYS to accept (including modulus)
785 // PRIVATE KEY of user
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)
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)))
798 if(qd0_blind_id_fingerprint64_public_key(pubkeys[i], pubkeys_fp64[i], &len2)) // keeps final NUL
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);
804 if(Crypto_AddPrivateKey(pubkeys[i], buf, len))
807 if(qd0_blind_id_fingerprint64_public_id(pubkeys[i], pubkeys_priv_fp64[i], &len2)) // keeps final NUL
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));
815 // can't really happen
816 // but nothing leaked here
823 // can't really happen
824 qd0_blind_id_free(pubkeys[i]);
829 crypto_idstring = crypto_idstring_buf;
832 Crypto_BuildChallengeAppend();
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)
840 for(i = 0; i < MAX_PUBKEYS; ++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]];
849 for(i = 0; i < MAX_PUBKEYS; ++i)
853 if(buf[(unsigned char) pubkeys_fp64[i][crypto_keyfp_recommended_length]] < 2)
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;
860 ++crypto_keyfp_recommended_length;
861 for(i = 0; i < MAX_PUBKEYS; ++i)
866 if(pubkeys_havepriv[i])
867 if(!buf[256 + MAX_PUBKEYS + i])
873 if(crypto_keyfp_recommended_length < 7)
874 crypto_keyfp_recommended_length = 7;
877 static void Crypto_UnloadKeys(void)
882 for(i = 0; i < MAX_PUBKEYS; ++i)
885 qd0_blind_id_free(pubkeys[i]);
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;
892 crypto_idstring = NULL;
895 static mempool_t *cryptomempool;
901 static void *Crypto_d0_malloc(size_t len)
903 return Mem_Alloc(cryptomempool, len);
906 static void Crypto_d0_free(void *p)
911 static void *Crypto_d0_createmutex(void)
913 return Thread_CreateMutex();
916 static void Crypto_d0_destroymutex(void *m)
918 Thread_DestroyMutex(m);
921 static int Crypto_d0_lockmutex(void *m)
923 return Thread_LockMutex(m);
926 static int Crypto_d0_unlockmutex(void *m)
928 return Thread_UnlockMutex(m);
934 void Crypto_Shutdown(void)
939 Crypto_Rijndael_CloseLibrary();
944 for(i = 0; i < MAX_CRYPTOCONNECTS; ++i)
946 crypto = &cryptoconnects[i].crypto;
949 memset(cryptoconnects, 0, sizeof(cryptoconnects));
950 crypto = &cls.crypto;
955 qd0_blind_id_SHUTDOWN();
957 Crypto_CloseLibrary();
960 Mem_FreePool(&cryptomempool);
963 void Crypto_Init(void)
965 cryptomempool = Mem_AllocPool("crypto", 0, NULL);
967 if(!Crypto_OpenLibrary())
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);
974 if(!qd0_blind_id_INITIALIZE())
976 Crypto_Rijndael_CloseLibrary();
977 Crypto_CloseLibrary();
978 Con_Printf("libd0_blind_id initialization FAILED, cryptography support has been disabled\n");
982 Crypto_Rijndael_OpenLibrary(); // if this fails, it's uncritical
984 Crypto_InitHostKeys();
988 qboolean Crypto_Available(void)
996 static void Crypto_KeyGen_Finished(int code, size_t length_received, unsigned char *buffer, void *cbdata)
1000 static char buf[8192];
1001 static char buf2[8192];
1002 size_t bufsize, buf2size;
1004 d0_blind_id_t *ctx, *ctx2;
1009 SV_LockThreadMutex();
1011 if(!d0_blind_id_dll)
1013 Con_Print("libd0_blind_id DLL not found, this command is inactive.\n");
1015 SV_UnlockThreadMutex();
1019 if(keygen_i >= MAX_PUBKEYS || !pubkeys[keygen_i])
1021 Con_Printf("overflow of keygen_i\n");
1023 SV_UnlockThreadMutex();
1028 Con_Printf("Unexpected response from keygen server:\n");
1029 Com_HexDumpToConsole(buffer, length_received);
1030 SV_UnlockThreadMutex();
1033 if(!Crypto_ParsePack((const char *) buffer, length_received, FOURCC_D0IR, p, l, 1))
1035 if(length_received >= 5 && Crypto_LittleLong((const char *) buffer) == FOURCC_D0ER)
1037 Con_Printf("Error response from keygen server: %.*s\n", (int)(length_received - 5), buffer + 5);
1041 Con_Printf("Invalid response from keygen server:\n");
1042 Com_HexDumpToConsole(buffer, length_received);
1045 SV_UnlockThreadMutex();
1048 if(!qd0_blind_id_finish_private_id_request(pubkeys[keygen_i], p[0], l[0]))
1050 Con_Printf("d0_blind_id_finish_private_id_request failed\n");
1052 SV_UnlockThreadMutex();
1056 // verify the key we just got (just in case)
1057 ctx = qd0_blind_id_new();
1060 Con_Printf("d0_blind_id_new failed\n");
1062 SV_UnlockThreadMutex();
1065 ctx2 = qd0_blind_id_new();
1068 Con_Printf("d0_blind_id_new failed\n");
1069 qd0_blind_id_free(ctx);
1071 SV_UnlockThreadMutex();
1074 if(!qd0_blind_id_copy(ctx, pubkeys[keygen_i]))
1076 Con_Printf("d0_blind_id_copy failed\n");
1077 qd0_blind_id_free(ctx);
1078 qd0_blind_id_free(ctx2);
1080 SV_UnlockThreadMutex();
1083 if(!qd0_blind_id_copy(ctx2, pubkeys[keygen_i]))
1085 Con_Printf("d0_blind_id_copy failed\n");
1086 qd0_blind_id_free(ctx);
1087 qd0_blind_id_free(ctx2);
1089 SV_UnlockThreadMutex();
1092 bufsize = sizeof(buf);
1093 if(!qd0_blind_id_authenticate_with_private_id_start(ctx, 1, 1, "hello world", 11, buf, &bufsize))
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);
1099 SV_UnlockThreadMutex();
1102 buf2size = sizeof(buf2);
1103 if(!qd0_blind_id_authenticate_with_private_id_challenge(ctx2, 1, 1, buf, bufsize, buf2, &buf2size, &status) || !status)
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);
1109 SV_UnlockThreadMutex();
1112 bufsize = sizeof(buf);
1113 if(!qd0_blind_id_authenticate_with_private_id_response(ctx, buf2, buf2size, buf, &bufsize))
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);
1119 SV_UnlockThreadMutex();
1122 buf2size = sizeof(buf2);
1123 if(!qd0_blind_id_authenticate_with_private_id_verify(ctx2, buf, bufsize, buf2, &buf2size, &status) || !status)
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);
1129 SV_UnlockThreadMutex();
1132 qd0_blind_id_free(ctx);
1133 qd0_blind_id_free(ctx2);
1135 // we have a valid key now!
1136 // make the rest of crypto.c know that
1138 if(qd0_blind_id_fingerprint64_public_id(pubkeys[keygen_i], pubkeys_priv_fp64[keygen_i], &len2)) // keeps final NUL
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();
1146 // write the key to disk
1149 if(!qd0_blind_id_write_private_id(pubkeys[keygen_i], buf, &l[0]))
1151 Con_Printf("d0_blind_id_write_private_id failed\n");
1153 SV_UnlockThreadMutex();
1156 if(!(buf2size = Crypto_UnParsePack(buf2, sizeof(buf2), FOURCC_D0SI, p, l, 1)))
1158 Con_Printf("Crypto_UnParsePack failed\n");
1160 SV_UnlockThreadMutex();
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);
1168 Con_Printf("Cannot open key_%d.d0si%s\n", keygen_i, sessionid.string);
1170 SV_UnlockThreadMutex();
1173 FS_Write(f, buf2, buf2size);
1176 Con_Printf("Saved to key_%d.d0si%s\n", keygen_i, sessionid.string);
1178 SV_UnlockThreadMutex();
1181 static void Crypto_KeyGen_f(void)
1186 static char buf[8192];
1187 static char buf2[8192];
1188 size_t buf2l, buf2pos;
1189 if(!d0_blind_id_dll)
1191 Con_Print("libd0_blind_id DLL not found, this command is inactive.\n");
1196 Con_Printf("usage:\n%s id url\n", Cmd_Argv(0));
1199 SV_LockThreadMutex();
1201 i = atoi(Cmd_Argv(1));
1204 Con_Printf("there is no public key %d\n", i);
1205 SV_UnlockThreadMutex();
1208 if(pubkeys_havepriv[i])
1210 Con_Printf("there is already a private key for %d\n", i);
1211 SV_UnlockThreadMutex();
1216 Con_Printf("there is already a keygen run on the way\n");
1217 SV_UnlockThreadMutex();
1221 if(!qd0_blind_id_generate_private_id_start(pubkeys[keygen_i]))
1223 Con_Printf("d0_blind_id_start failed\n");
1225 SV_UnlockThreadMutex();
1230 if(!qd0_blind_id_generate_private_id_request(pubkeys[keygen_i], buf, &l[0]))
1232 Con_Printf("d0_blind_id_generate_private_id_request failed\n");
1234 SV_UnlockThreadMutex();
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)))
1241 Con_Printf("Crypto_UnParsePack failed\n");
1243 SV_UnlockThreadMutex();
1246 if(!(buf2l = base64_encode((unsigned char *) (buf2 + buf2pos), buf2l, sizeof(buf2) - buf2pos - 1)))
1248 Con_Printf("base64_encode failed\n");
1250 SV_UnlockThreadMutex();
1255 if(!Curl_Begin_ToMemory(buf2, 0, (unsigned char *) keygen_buf, sizeof(keygen_buf), Crypto_KeyGen_Finished, NULL))
1257 Con_Printf("curl failed\n");
1259 SV_UnlockThreadMutex();
1262 Con_Printf("key generation in progress\n");
1263 SV_UnlockThreadMutex();
1268 static void Crypto_Reload_f(void)
1270 Crypto_ClearHostKeys();
1271 Crypto_UnloadKeys();
1275 static void Crypto_Keys_f(void)
1278 if(!d0_blind_id_dll)
1280 Con_Print("libd0_blind_id DLL not found, this command is inactive.\n");
1283 for(i = 0; i < MAX_PUBKEYS; ++i)
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]);
1294 static void Crypto_HostKeys_f(void)
1297 crypto_storedhostkey_t *hk;
1300 if(!d0_blind_id_dll)
1302 Con_Print("libd0_blind_id DLL not found, this command is inactive.\n");
1305 for(i = 0; i < CRYPTO_HOSTKEY_HASHSIZE; ++i)
1307 for(hk = crypto_storedhostkey_hashtable[i]; hk; hk = hk->next)
1309 LHNETADDRESS_ToString(&hk->addr, buf, sizeof(buf), 1);
1310 Con_Printf("%d %s@%.*s %s\n",
1313 crypto_keyfp_recommended_length, pubkeys_fp64[hk->keyid],
1319 static void Crypto_HostKey_Clear_f(void)
1321 lhnetaddress_t addr;
1324 if(!d0_blind_id_dll)
1326 Con_Print("libd0_blind_id DLL not found, this command is inactive.\n");
1330 for(i = 1; i < Cmd_Argc(); ++i)
1332 LHNETADDRESS_FromString(&addr, Cmd_Argv(i), 26000);
1333 if(Crypto_ClearHostKey(&addr))
1335 Con_Printf("cleared host key for %s\n", Cmd_Argv(i));
1340 void Crypto_Init_Commands(void)
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);
1351 Cvar_RegisterVariable(&crypto_aeslevel);
1353 crypto_aeslevel.integer = 0; // make sure
1354 Cvar_RegisterVariable(&crypto_servercpupercent);
1355 Cvar_RegisterVariable(&crypto_servercpumaxtime);
1356 Cvar_RegisterVariable(&crypto_servercpudebug);
1362 static void aescpy(unsigned char *key, const unsigned char *iv, unsigned char *dst, const unsigned char *src, size_t len)
1364 const unsigned char *xorpos = iv;
1365 unsigned char xorbuf[16];
1366 unsigned long rk[D0_RIJNDAEL_RKLENGTH(DHKEY_SIZE * 8)];
1368 qd0_rijndael_setup_encrypt(rk, key, DHKEY_SIZE * 8);
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);
1381 for(i = 0; i < len; ++i)
1382 xorbuf[i] = src[i] ^ xorpos[i];
1384 xorbuf[i] = xorpos[i];
1385 qd0_rijndael_encrypt(rk, D0_RIJNDAEL_NROUNDS(DHKEY_SIZE * 8), xorbuf, dst);
1388 static void seacpy(unsigned char *key, const unsigned char *iv, unsigned char *dst, const unsigned char *src, size_t len)
1390 const unsigned char *xorpos = iv;
1391 unsigned char xorbuf[16];
1392 unsigned long rk[D0_RIJNDAEL_RKLENGTH(DHKEY_SIZE * 8)];
1394 qd0_rijndael_setup_decrypt(rk, key, DHKEY_SIZE * 8);
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];
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];
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)
1419 unsigned char h[32];
1421 if(crypto->authenticated)
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)
1430 Con_Print("To be encrypted:\n");
1431 Com_HexDumpToConsole((const unsigned char *) data_src, len_src);
1433 if(len_src + 32 > len || !HMAC_SHA256_32BYTES(h, (const unsigned char *) data_src, len_src, crypto->dhkey, DHKEY_SIZE))
1435 Con_Printf("Crypto_EncryptPacket failed (not enough space: %d bytes in, %d bytes out)\n", (int) len_src, (int) len);
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);
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))
1449 Con_Printf("Crypto_EncryptPacket failed (not enough space: %d bytes in, %d bytes out)\n", (int) len_src, (int) len);
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);
1456 // handle the "avoid" conditions:
1457 i = BuffBigLong((unsigned char *) data_dst);
1459 (i == (int)0xFFFFFFFF) // avoid QW control packet
1461 (i == (int)0x80000000 + (int)*len_dst) // avoid NQ control packet
1463 *(unsigned char *)data_dst ^= 0x80; // this will ALWAYS fix it
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)
1476 unsigned char h[32];
1479 // silently handle non-crypto packets
1480 i = BuffBigLong((unsigned char *) data_src);
1482 (i == (int)0xFFFFFFFF) // avoid QW control packet
1484 (i == (int)0x80000000 + (int)len_src) // avoid NQ control packet
1488 if(crypto->authenticated)
1492 if(len_src < 16 || ((len_src - 16) % 16))
1494 Con_Printf("Crypto_DecryptPacket failed (not enough space: %d bytes in, %d bytes out)\n", (int) len_src, (int) len);
1497 *len_dst = len_src - ((unsigned char *) data_src)[0];
1498 if(len < *len_dst || *len_dst > len_src - 16)
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);
1503 seacpy(crypto->dhkey, (unsigned char *) data_src, (unsigned char *) data_dst, ((const unsigned char *) data_src) + 16, *len_dst);
1505 if(!HMAC_SHA256_32BYTES(h, (const unsigned char *) data_dst, *len_dst, crypto->dhkey, DHKEY_SIZE))
1507 Con_Printf("HMAC fail\n");
1510 if(memcmp(((const unsigned char *) data_src)+1, h, 15)) // ignore first byte, used for length
1512 Con_Printf("HMAC mismatch\n");
1515 if(developer_networking.integer)
1517 Con_Print("Decrypted:\n");
1518 Com_HexDumpToConsole((const unsigned char *) data_dst, *len_dst);
1520 return data_dst; // no need to copy
1526 Con_Printf("Crypto_DecryptPacket failed (not enough space: %d bytes in, %d bytes out)\n", (int) len_src, (int) len);
1529 *len_dst = len_src - 16;
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);
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))
1538 Con_Printf("HMAC fail\n");
1539 Com_HexDumpToConsole((const unsigned char *) data_src, len_src);
1543 if(memcmp((const unsigned char *) data_src, h, 16)) // ignore first byte, used for length
1545 // undo the "avoid conditions"
1547 (i == (int)0x7FFFFFFF) // avoided QW control packet
1549 (i == (int)0x00000000 + (int)len_src) // avoided NQ control packet
1552 // do the avoidance on the hash too
1554 if(memcmp((const unsigned char *) data_src, h, 16)) // ignore first byte, used for length
1556 Con_Printf("HMAC mismatch\n");
1557 Com_HexDumpToConsole((const unsigned char *) data_src, len_src);
1563 Con_Printf("HMAC mismatch\n");
1564 Com_HexDumpToConsole((const unsigned char *) data_src, len_src);
1568 return ((const unsigned char *) data_src) + 16; // no need to copy, so data_dst is not used
1579 const char *Crypto_GetInfoResponseDataString(void)
1581 crypto_idstring_buf[0] = '0' + crypto_aeslevel.integer;
1582 return crypto_idstring;
1586 qboolean Crypto_ServerAppendToChallenge(const char *data_in, size_t len_in, char *data_out, size_t *len_out, size_t maxlen_out)
1588 // cheap op, all is precomputed
1589 if(!d0_blind_id_dll)
1590 return false; // no support
1592 if(maxlen_out <= *len_out + challenge_append_length)
1594 memcpy(data_out + *len_out, challenge_append, challenge_append_length);
1595 *len_out += challenge_append_length;
1599 static int Crypto_ServerError(char *data_out, size_t *len_out, const char *msg, const char *msg_client)
1603 Con_DPrintf("rejecting client: %s\n", msg);
1605 dpsnprintf(data_out, *len_out, "reject %s", msg_client);
1606 *len_out = strlen(data_out);
1607 return CRYPTO_DISCARD;
1610 static int Crypto_SoftServerError(char *data_out, size_t *len_out, const char *msg)
1613 Con_DPrintf("%s\n", msg);
1614 return CRYPTO_DISCARD;
1617 static int Crypto_ServerParsePacket_Internal(const char *data_in, size_t len_in, char *data_out, size_t *len_out, lhnetaddress_t *peeraddress)
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;
1626 char infostringvalue[MAX_INPUTLINE];
1629 if(!d0_blind_id_dll)
1630 return CRYPTO_NOMATCH; // no support
1632 if (len_in > 8 && !memcmp(string, "connect\\", 8) && d0_rijndael_dll && crypto_aeslevel.integer >= 3)
1636 // sorry, we have to verify the challenge here to not reflect network spam
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))
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
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);
1653 else if(len_in > 5 && !memcmp(string, "d0pk\\", 5) && ((LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP) || sv_public.integer > -3))
1655 const char *cnt, *s, *p;
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));
1662 return CRYPTO_DISCARD; // pre-challenge: rather be silent
1663 GetUntilNul(&data_in, &len_in);
1665 return CRYPTO_DISCARD; // pre-challenge: rather be silent
1666 if(!strcmp(cnt, "0"))
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))
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
1680 if (!(s = InfoString_GetValue(string + 4, "aeslevel", infostringvalue, sizeof(infostringvalue))))
1681 aeslevel = 0; // not supported
1683 aeslevel = bound(0, atoi(s), 3);
1684 switch(bound(0, d0_rijndael_dll ? crypto_aeslevel.integer : 0, 3))
1686 default: // dummy, never happens, but to make gcc happy...
1689 return Crypto_ServerError(data_out, len_out, "This server requires encryption to be not required (crypto_aeslevel <= 2)", NULL);
1693 aes = (aeslevel >= 2);
1696 aes = (aeslevel >= 1);
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);
1705 p = GetUntilNul(&data_in, &len_in);
1708 for(i = 0; i < MAX_PUBKEYS; ++i)
1711 if(!strcmp(p, pubkeys_fp64[i]))
1712 if(pubkeys_havepriv[i])
1717 return Crypto_ServerError(data_out, len_out, "Invalid server key", NULL);
1719 p = GetUntilNul(&data_in, &len_in);
1722 for(i = 0; i < MAX_PUBKEYS; ++i)
1725 if(!strcmp(p, pubkeys_fp64[i]))
1730 return Crypto_ServerError(data_out, len_out, "Invalid client key", NULL);
1733 crypto = Crypto_ServerFindInstance(peeraddress, true);
1735 return Crypto_ServerError(data_out, len_out, "Could not create a crypto connect instance", NULL);
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;
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));
1755 CDATA->id = qd0_blind_id_new();
1759 return Crypto_ServerError(data_out, len_out, "d0_blind_id_new failed", "Internal error");
1761 if(!qd0_blind_id_copy(CDATA->id, pubkeys[CDATA->s]))
1764 return Crypto_ServerError(data_out, len_out, "d0_blind_id_copy failed", "Internal error");
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
1770 return Crypto_ServerError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_start failed", "Internal error");
1772 CDATA->next_step = 2;
1773 data_out_p += *len_out;
1774 *len_out = data_out_p - data_out;
1775 return CRYPTO_DISCARD;
1777 else if(CDATA->c >= 0)
1780 CDATA->id = qd0_blind_id_new();
1784 return Crypto_ServerError(data_out, len_out, "d0_blind_id_new failed", "Internal error");
1786 if(!qd0_blind_id_copy(CDATA->id, pubkeys[CDATA->c]))
1789 return Crypto_ServerError(data_out, len_out, "d0_blind_id_copy failed", "Internal error");
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))
1795 return Crypto_ServerError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_challenge failed", "Internal error");
1797 CDATA->next_step = 6;
1798 data_out_p += *len_out;
1799 *len_out = data_out_p - data_out;
1800 return CRYPTO_DISCARD;
1805 return Crypto_ServerError(data_out, len_out, "Missing client and server key", NULL);
1808 else if(!strcmp(cnt, "2"))
1811 crypto = Crypto_ServerFindInstance(peeraddress, false);
1813 return CRYPTO_NOMATCH; // pre-challenge, rather be silent
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));
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))
1824 return Crypto_ServerError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_response failed", "Internal error");
1826 fpbuflen = DHKEY_SIZE;
1827 if(!qd0_blind_id_sessionkey_public_id(CDATA->id, (char *) crypto->dhkey, &fpbuflen))
1830 return Crypto_ServerError(data_out, len_out, "d0_blind_id_sessionkey_public_id failed", "Internal error");
1834 if(!qd0_blind_id_copy(CDATA->id, pubkeys[CDATA->c]))
1837 return Crypto_ServerError(data_out, len_out, "d0_blind_id_copy failed", "Internal error");
1839 CDATA->next_step = 4;
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;
1847 data_out_p += *len_out;
1848 *len_out = data_out_p - data_out;
1849 return CRYPTO_DISCARD;
1851 else if(!strcmp(cnt, "4"))
1853 crypto = Crypto_ServerFindInstance(peeraddress, false);
1855 return CRYPTO_NOMATCH; // pre-challenge, rather be silent
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))
1865 return Crypto_ServerError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_challenge failed", "Internal error");
1867 CDATA->next_step = 6;
1868 data_out_p += *len_out;
1869 *len_out = data_out_p - data_out;
1870 return CRYPTO_DISCARD;
1872 else if(!strcmp(cnt, "6"))
1874 static char msgbuf[32];
1875 size_t msgbuflen = sizeof(msgbuf);
1878 unsigned char dhkey[DHKEY_SIZE];
1879 crypto = Crypto_ServerFindInstance(peeraddress, false);
1881 return CRYPTO_NOMATCH; // pre-challenge, rather be silent
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));
1888 if(!qd0_blind_id_authenticate_with_private_id_verify(CDATA->id, data_in, len_in, msgbuf, &msgbuflen, &status))
1891 return Crypto_ServerError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_verify failed (authentication error)", "Authentication error");
1894 strlcpy(crypto->client_keyfp, pubkeys_fp64[CDATA->c], sizeof(crypto->client_keyfp));
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))
1902 return Crypto_ServerError(data_out, len_out, "d0_blind_id_fingerprint64_public_id failed", "Internal error");
1904 fpbuflen = DHKEY_SIZE;
1905 if(!qd0_blind_id_sessionkey_public_id(CDATA->id, (char *) dhkey, &fpbuflen))
1908 return Crypto_ServerError(data_out, len_out, "d0_blind_id_sessionkey_public_id failed", "Internal error");
1910 // XOR the two DH keys together to make one
1911 for(i = 0; i < DHKEY_SIZE; ++i)
1912 crypto->dhkey[i] ^= dhkey[i];
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;
1923 return CRYPTO_NOMATCH; // pre-challenge, rather be silent
1925 return CRYPTO_NOMATCH;
1928 int Crypto_ServerParsePacket(const char *data_in, size_t len_in, char *data_out, size_t *len_out, lhnetaddress_t *peeraddress)
1932 static double complain_time = 0;
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))
1941 cnt = InfoString_GetValue(data_in + 4, "cnt", infostringvalue, sizeof(infostringvalue));
1943 if(!strcmp(cnt, "0"))
1948 // check if we may perform crypto...
1949 if(crypto_servercpupercent.value > 0)
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;
1958 if(crypto_servercpumaxtime.value > 0)
1959 if(realtime != crypto_servercpu_lastrealtime)
1960 crypto_servercpu_accumulator = crypto_servercpumaxtime.value;
1962 crypto_servercpu_lastrealtime = realtime;
1963 if(do_reject && crypto_servercpu_accumulator < 0)
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");
1968 return CRYPTO_DISCARD;
1970 t = Sys_DirtyTime();
1972 ret = Crypto_ServerParsePacket_Internal(data_in, len_in, data_out, len_out, peeraddress);
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);
1985 static int Crypto_ClientError(char *data_out, size_t *len_out, const char *msg)
1987 dpsnprintf(data_out, *len_out, "reject %s", msg);
1988 *len_out = strlen(data_out);
1989 return CRYPTO_REPLACE;
1992 static int Crypto_SoftClientError(char *data_out, size_t *len_out, const char *msg)
1995 Con_Printf("%s\n", msg);
1996 return CRYPTO_DISCARD;
1999 int Crypto_ClientParsePacket(const char *data_in, size_t len_in, char *data_out, size_t *len_out, lhnetaddress_t *peeraddress)
2001 crypto_t *crypto = &cls.crypto;
2002 const char *string = data_in;
2005 char *data_out_p = data_out;
2007 char infostringvalue[MAX_INPUTLINE];
2010 if(!d0_blind_id_dll)
2011 return CRYPTO_NOMATCH; // no support
2013 // if "challenge": verify challenge, and discard message, send next crypto protocol message instead
2014 // otherwise, just handle actual protocol messages
2016 if (len_in == 6 && !memcmp(string, "accept", 6) && cls.connect_trying && d0_rijndael_dll)
2018 int wantserverid = -1;
2019 Crypto_RetrieveHostKey(&cls.connect_address, &wantserverid, NULL, 0, NULL, 0, NULL);
2020 if(!crypto || !crypto->authenticated)
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)");
2027 return CRYPTO_NOMATCH;
2029 else if (len_in >= 1 && string[0] == 'j' && cls.connect_trying && d0_rijndael_dll && crypto_aeslevel.integer >= 3)
2031 int wantserverid = -1;
2032 Crypto_RetrieveHostKey(&cls.connect_address, &wantserverid, NULL, 0, NULL, 0, NULL);
2033 if(!crypto || !crypto->authenticated)
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)");
2040 return CRYPTO_NOMATCH;
2042 else if (len_in >= 13 && !memcmp(string, "infoResponse\x0A", 13))
2044 s = InfoString_GetValue(string + 13, "d0_blind_id", infostringvalue, sizeof(infostringvalue));
2046 Crypto_StoreHostKey(peeraddress, s, true);
2047 return CRYPTO_NOMATCH;
2049 else if (len_in >= 15 && !memcmp(string, "statusResponse\x0A", 15))
2053 p = strchr(string + 15, '\n');
2057 * (char *) p = 0; // cut off the string there
2059 s = InfoString_GetValue(string + 15, "d0_blind_id", infostringvalue, sizeof(infostringvalue));
2061 Crypto_StoreHostKey(peeraddress, s, true);
2064 * (char *) p = save;
2065 // invoking those nasal demons again (do not run this on the DS9k)
2067 return CRYPTO_NOMATCH;
2069 else if(len_in > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
2071 const char *vlen_blind_id_ptr = NULL;
2072 size_t len_blind_id_ptr = 0;
2074 const char *challenge = data_in + 10;
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;
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
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;
2095 GetUntilNul(&data_in, &len_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) :
2101 // FTEQW extension protocol
2104 k = Crypto_LittleLong(data_in);
2105 v = Crypto_LittleLong(data_in + 4);
2113 k = Crypto_LittleLong(data_in);
2118 case PROTOCOL_D0_BLIND_ID:
2119 vlen_blind_id_ptr = data_in;
2120 len_blind_id_ptr = v;
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) :
2137 data_in = vlen_blind_id_ptr;
2138 len_in = len_blind_id_ptr;
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
2146 p = GetUntilNul(&data_in, &len_in);
2151 if(!server_can_auth)
2152 break; // other protocol message may follow
2153 server_can_auth = false;
2158 for(i = 0; i < MAX_PUBKEYS; ++i)
2161 if(!strcmp(p, pubkeys_fp64[i]))
2163 if(pubkeys_havepriv[i])
2168 if(wantserverid < 0 || i == wantserverid)
2172 if(clientid >= 0 && serverid >= 0)
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");
2180 if(serverid >= 0 || clientid >= 0)
2182 // TODO at this point, fill clientside crypto struct!
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));
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))
2198 default: // dummy, never happens, but to make gcc happy...
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;
2205 CDATA->wantserver_aes = (wantserver_aeslevel >= 2);
2208 CDATA->wantserver_aes = (wantserver_aeslevel >= 1);
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;
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] : "");
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));
2233 CDATA->id = qd0_blind_id_new();
2237 return Crypto_ClientError(data_out, len_out, "d0_blind_id_new failed");
2239 if(!qd0_blind_id_copy(CDATA->id, pubkeys[CDATA->s]))
2242 return Crypto_ClientError(data_out, len_out, "d0_blind_id_copy failed");
2244 CDATA->next_step = 1;
2245 *len_out = data_out_p - data_out;
2247 else if(clientid >= 0)
2249 // skip over server auth, perform client auth only
2251 CDATA->id = qd0_blind_id_new();
2255 return Crypto_ClientError(data_out, len_out, "d0_blind_id_new failed");
2257 if(!qd0_blind_id_copy(CDATA->id, pubkeys[CDATA->c]))
2260 return Crypto_ClientError(data_out, len_out, "d0_blind_id_copy failed");
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
2265 return Crypto_ClientError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_start failed");
2267 CDATA->next_step = 5;
2268 data_out_p += *len_out;
2269 *len_out = data_out_p - data_out;
2272 *len_out = data_out_p - data_out;
2274 return CRYPTO_DISCARD;
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) :
2285 else if(len_in > 5 && !memcmp(string, "d0pk\\", 5) && cls.connect_trying)
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));
2293 return Crypto_ClientError(data_out, len_out, "d0pk\\ message without cnt");
2294 GetUntilNul(&data_in, &len_in);
2296 return Crypto_ClientError(data_out, len_out, "d0pk\\ message without attachment");
2298 if(!strcmp(cnt, "1"))
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));
2306 cls.connect_nextsendtime = max(cls.connect_nextsendtime, realtime + 1); // prevent "hammering"
2308 if((s = InfoString_GetValue(string + 4, "aes", infostringvalue, sizeof(infostringvalue))))
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)
2318 return Crypto_ClientError(data_out, len_out, "Stored host key requires encryption, but server did not enable encryption");
2320 if(aes && (!d0_rijndael_dll || crypto_aeslevel.integer <= 0))
2323 return Crypto_ClientError(data_out, len_out, "Server insists on encryption too hard");
2325 if(!aes && (d0_rijndael_dll && crypto_aeslevel.integer >= 3))
2328 return Crypto_ClientError(data_out, len_out, "Server insists on plaintext too hard");
2330 crypto->use_aes = aes != 0;
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))
2336 return Crypto_ClientError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_challenge failed");
2338 CDATA->next_step = 3;
2339 data_out_p += *len_out;
2340 *len_out = data_out_p - data_out;
2341 return CRYPTO_DISCARD;
2343 else if(!strcmp(cnt, "3"))
2345 static char msgbuf[32];
2346 size_t msgbuflen = sizeof(msgbuf);
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));
2355 cls.connect_nextsendtime = max(cls.connect_nextsendtime, realtime + 1); // prevent "hammering"
2357 if(!qd0_blind_id_authenticate_with_private_id_verify(CDATA->id, data_in, len_in, msgbuf, &msgbuflen, &status))
2360 return Crypto_ClientError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_verify failed (server authentication error)");
2363 strlcpy(crypto->server_keyfp, pubkeys_fp64[CDATA->s], sizeof(crypto->server_keyfp));
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))
2371 return Crypto_ClientError(data_out, len_out, "d0_blind_id_fingerprint64_public_id failed");
2373 if(CDATA->wantserver_idfp[0])
2374 if(memcmp(CDATA->wantserver_idfp, crypto->server_idfp, sizeof(crypto->server_idfp)))
2377 return Crypto_ClientError(data_out, len_out, "Server ID does not match stored host key, refusing to connect");
2379 fpbuflen = DHKEY_SIZE;
2380 if(!qd0_blind_id_sessionkey_public_id(CDATA->id, (char *) crypto->dhkey, &fpbuflen))
2383 return Crypto_ClientError(data_out, len_out, "d0_blind_id_sessionkey_public_id failed");
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);
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]))
2396 return Crypto_ClientError(data_out, len_out, "d0_blind_id_copy failed");
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
2401 return Crypto_ClientError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_start failed");
2403 CDATA->next_step = 5;
2404 data_out_p += *len_out;
2405 *len_out = data_out_p - data_out;
2406 return CRYPTO_DISCARD;
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;
2420 else if(!strcmp(cnt, "5"))
2423 unsigned char dhkey[DHKEY_SIZE];
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));
2432 cls.connect_nextsendtime = max(cls.connect_nextsendtime, realtime + 1); // prevent "hammering"
2434 if(CDATA->s < 0) // only if server didn't auth
2436 if((s = InfoString_GetValue(string + 4, "aes", infostringvalue, sizeof(infostringvalue))))
2440 if(CDATA->wantserver_idfp[0]) // if we know a host key, honor its encryption setting
2441 if(!aes && CDATA->wantserver_aes)
2444 return Crypto_ClientError(data_out, len_out, "Stored host key requires encryption, but server did not enable encryption");
2446 if(aes && (!d0_rijndael_dll || crypto_aeslevel.integer <= 0))
2449 return Crypto_ClientError(data_out, len_out, "Server insists on encryption too hard");
2451 if(!aes && (d0_rijndael_dll && crypto_aeslevel.integer >= 3))
2454 return Crypto_ClientError(data_out, len_out, "Server insists on plaintext too hard");
2456 crypto->use_aes = aes != 0;
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))
2463 return Crypto_ClientError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_response failed");
2465 fpbuflen = DHKEY_SIZE;
2466 if(!qd0_blind_id_sessionkey_public_id(CDATA->id, (char *) dhkey, &fpbuflen))
2469 return Crypto_ClientError(data_out, len_out, "d0_blind_id_sessionkey_public_id failed");
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;
2481 return Crypto_SoftClientError(data_out, len_out, "Got unknown d0_blind_id message from server");
2484 return CRYPTO_NOMATCH;
2487 size_t Crypto_SignData(const void *data, size_t datasize, int keyid, void *signed_data, size_t signed_size)
2489 if(keyid < 0 || keyid >= MAX_PUBKEYS)
2491 if(!pubkeys_havepriv[keyid])
2493 if(qd0_blind_id_sign_with_private_id_sign(pubkeys[keyid], true, false, (const char *)data, datasize, (char *)signed_data, &signed_size))
2498 size_t Crypto_SignDataDetached(const void *data, size_t datasize, int keyid, void *signed_data, size_t signed_size)
2500 if(keyid < 0 || keyid >= MAX_PUBKEYS)
2502 if(!pubkeys_havepriv[keyid])
2504 if(qd0_blind_id_sign_with_private_id_sign_detached(pubkeys[keyid], true, false, (const char *)data, datasize, (char *)signed_data, &signed_size))