Fix Windows device asynchronous write behavior.
[tinc] / src / protocol_key.c
1 /*
2     protocol_key.c -- handle the meta-protocol, key exchange
3     Copyright (C) 1999-2005 Ivo Timmermans,
4                   2000-2014 Guus Sliepen <guus@tinc-vpn.org>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License along
17     with this program; if not, write to the Free Software Foundation, Inc.,
18     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include "system.h"
22
23 #include "cipher.h"
24 #include "connection.h"
25 #include "crypto.h"
26 #include "logger.h"
27 #include "net.h"
28 #include "netutl.h"
29 #include "node.h"
30 #include "prf.h"
31 #include "protocol.h"
32 #include "sptps.h"
33 #include "utils.h"
34 #include "xalloc.h"
35
36 static bool mykeyused = false;
37
38 void send_key_changed(void) {
39         send_request(everyone, "%d %x %s", KEY_CHANGED, rand(), myself->name);
40
41         /* Immediately send new keys to directly connected nodes to keep UDP mappings alive */
42
43         for list_each(connection_t, c, connection_list)
44                 if(c->edge && c->node && c->node->status.reachable && !c->node->status.sptps)
45                         send_ans_key(c->node);
46
47         /* Force key exchange for connections using SPTPS */
48
49         if(experimental) {
50                 for splay_each(node_t, n, node_tree)
51                         if(n->status.reachable && n->status.validkey && n->status.sptps)
52                                 sptps_force_kex(&n->sptps);
53         }
54 }
55
56 bool key_changed_h(connection_t *c, const char *request) {
57         char name[MAX_STRING_SIZE];
58         node_t *n;
59
60         if(sscanf(request, "%*d %*x " MAX_STRING, name) != 1) {
61                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "KEY_CHANGED",
62                            c->name, c->hostname);
63                 return false;
64         }
65
66         if(seen_request(request))
67                 return true;
68
69         n = lookup_node(name);
70
71         if(!n) {
72                 logger(DEBUG_ALWAYS, LOG_ERR, "Got %s from %s (%s) origin %s which does not exist",
73                            "KEY_CHANGED", c->name, c->hostname, name);
74                 return true;
75         }
76
77         if(!n->status.sptps) {
78                 n->status.validkey = false;
79                 n->last_req_key = 0;
80         }
81
82         /* Tell the others */
83
84         if(!tunnelserver)
85                 forward_request(c, request);
86
87         return true;
88 }
89
90 static bool send_initial_sptps_data(void *handle, uint8_t type, const void *data, size_t len) {
91         node_t *to = handle;
92         to->sptps.send_data = send_sptps_data;
93         char buf[len * 4 / 3 + 5];
94         b64encode(data, buf, len);
95         return send_request(to->nexthop->connection, "%d %s %s %d %s", REQ_KEY, myself->name, to->name, REQ_KEY, buf);
96 }
97
98 bool send_req_key(node_t *to) {
99         if(to->status.sptps) {
100                 if(!node_read_ecdsa_public_key(to)) {
101                         logger(DEBUG_PROTOCOL, LOG_DEBUG, "No Ed25519 key known for %s (%s)", to->name, to->hostname);
102                         send_request(to->nexthop->connection, "%d %s %s %d", REQ_KEY, myself->name, to->name, REQ_PUBKEY);
103                         return true;
104                 }
105
106                 if(to->sptps.label)
107                         logger(DEBUG_ALWAYS, LOG_DEBUG, "send_req_key(%s) called while sptps->label != NULL!", to->name);
108
109                 char label[25 + strlen(myself->name) + strlen(to->name)];
110                 snprintf(label, sizeof label, "tinc UDP key expansion %s %s", myself->name, to->name);
111                 sptps_stop(&to->sptps);
112                 to->status.validkey = false;
113                 to->status.waitingforkey = true;
114                 to->last_req_key = now.tv_sec;
115                 to->incompression = myself->incompression;
116                 return sptps_start(&to->sptps, to, true, true, myself->connection->ecdsa, to->ecdsa, label, sizeof label, send_initial_sptps_data, receive_sptps_record);
117         }
118
119         return send_request(to->nexthop->connection, "%d %s %s", REQ_KEY, myself->name, to->name);
120 }
121
122 /* REQ_KEY is overloaded to allow arbitrary requests to be routed between two nodes. */
123
124 static bool req_key_ext_h(connection_t *c, const char *request, node_t *from, int reqno) {
125         switch(reqno) {
126                 case REQ_PUBKEY: {
127                         if(!node_read_ecdsa_public_key(from)) {
128                                 /* Request their key *before* we send our key back. Otherwise the first SPTPS packet from them will get dropped. */
129                                 logger(DEBUG_PROTOCOL, LOG_DEBUG, "Preemptively requesting Ed25519 key for %s (%s)", from->name, from->hostname);
130                                 send_request(from->nexthop->connection, "%d %s %s %d", REQ_KEY, myself->name, from->name, REQ_PUBKEY);
131                         }
132                         char *pubkey = ecdsa_get_base64_public_key(myself->connection->ecdsa);
133                         send_request(from->nexthop->connection, "%d %s %s %d %s", REQ_KEY, myself->name, from->name, ANS_PUBKEY, pubkey);
134                         free(pubkey);
135                         return true;
136                 }
137
138                 case ANS_PUBKEY: {
139                         if(node_read_ecdsa_public_key(from)) {
140                                 logger(DEBUG_PROTOCOL, LOG_WARNING, "Got ANS_PUBKEY from %s (%s) even though we already have his pubkey", from->name, from->hostname);
141                                 return true;
142                         }
143
144                         char pubkey[MAX_STRING_SIZE];
145                         if(sscanf(request, "%*d %*s %*s %*d " MAX_STRING, pubkey) != 1 || !(from->ecdsa = ecdsa_set_base64_public_key(pubkey))) {
146                                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "ANS_PUBKEY", from->name, from->hostname, "invalid pubkey");
147                                 return true;
148                         }
149
150                         logger(DEBUG_PROTOCOL, LOG_INFO, "Learned Ed25519 public key from %s (%s)", from->name, from->hostname);
151                         append_config_file(from->name, "Ed25519PublicKey", pubkey);
152                         return true;
153                 }
154
155                 case REQ_KEY: {
156                         if(!node_read_ecdsa_public_key(from)) {
157                                 logger(DEBUG_PROTOCOL, LOG_DEBUG, "No Ed25519 key known for %s (%s)", from->name, from->hostname);
158                                 send_request(from->nexthop->connection, "%d %s %s %d", REQ_KEY, myself->name, from->name, REQ_PUBKEY);
159                                 return true;
160                         }
161
162                         if(from->sptps.label)
163                                 logger(DEBUG_ALWAYS, LOG_DEBUG, "Got REQ_KEY from %s while we already started a SPTPS session!", from->name);
164
165                         char buf[MAX_STRING_SIZE];
166                         int len;
167
168                         if(sscanf(request, "%*d %*s %*s %*d " MAX_STRING, buf) != 1 || !(len = b64decode(buf, buf, strlen(buf)))) {
169                                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "REQ_SPTPS_START", from->name, from->hostname, "invalid SPTPS data");
170                                 return true;
171                         }
172
173                         char label[25 + strlen(from->name) + strlen(myself->name)];
174                         snprintf(label, sizeof label, "tinc UDP key expansion %s %s", from->name, myself->name);
175                         sptps_stop(&from->sptps);
176                         from->status.validkey = false;
177                         from->status.waitingforkey = true;
178                         from->last_req_key = now.tv_sec;
179                         sptps_start(&from->sptps, from, false, true, myself->connection->ecdsa, from->ecdsa, label, sizeof label, send_sptps_data, receive_sptps_record);
180                         sptps_receive_data(&from->sptps, buf, len);
181                         return true;
182                 }
183
184                 case REQ_SPTPS: {
185                         if(!from->status.validkey) {
186                                 logger(DEBUG_PROTOCOL, LOG_ERR, "Got REQ_SPTPS from %s (%s) but we don't have a valid key yet", from->name, from->hostname);
187                                 return true;
188                         }
189
190                         char buf[MAX_STRING_SIZE];
191                         int len;
192                         if(sscanf(request, "%*d %*s %*s %*d " MAX_STRING, buf) != 1 || !(len = b64decode(buf, buf, strlen(buf)))) {
193                                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "REQ_SPTPS", from->name, from->hostname, "invalid SPTPS data");
194                                 return true;
195                         }
196                         sptps_receive_data(&from->sptps, buf, len);
197                         return true;
198                 }
199
200                 default:
201                         logger(DEBUG_ALWAYS, LOG_ERR, "Unknown extended REQ_KEY request from %s (%s): %s", from->name, from->hostname, request);
202                         return true;
203         }
204 }
205
206 bool req_key_h(connection_t *c, const char *request) {
207         char from_name[MAX_STRING_SIZE];
208         char to_name[MAX_STRING_SIZE];
209         node_t *from, *to;
210         int reqno = 0;
211
212         if(sscanf(request, "%*d " MAX_STRING " " MAX_STRING " %d", from_name, to_name, &reqno) < 2) {
213                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "REQ_KEY", c->name,
214                            c->hostname);
215                 return false;
216         }
217
218         if(!check_id(from_name) || !check_id(to_name)) {
219                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "REQ_KEY", c->name, c->hostname, "invalid name");
220                 return false;
221         }
222
223         from = lookup_node(from_name);
224
225         if(!from) {
226                 logger(DEBUG_ALWAYS, LOG_ERR, "Got %s from %s (%s) origin %s which does not exist in our connection list",
227                            "REQ_KEY", c->name, c->hostname, from_name);
228                 return true;
229         }
230
231         to = lookup_node(to_name);
232
233         if(!to) {
234                 logger(DEBUG_ALWAYS, LOG_ERR, "Got %s from %s (%s) destination %s which does not exist in our connection list",
235                            "REQ_KEY", c->name, c->hostname, to_name);
236                 return true;
237         }
238
239         /* Check if this key request is for us */
240
241         if(to == myself) {                      /* Yes */
242                 /* Is this an extended REQ_KEY message? */
243                 if(experimental && reqno)
244                         return req_key_ext_h(c, request, from, reqno);
245
246                 /* No, just send our key back */
247                 send_ans_key(from);
248         } else {
249                 if(tunnelserver)
250                         return true;
251
252                 if(!to->status.reachable) {
253                         logger(DEBUG_PROTOCOL, LOG_WARNING, "Got %s from %s (%s) destination %s which is not reachable",
254                                 "REQ_KEY", c->name, c->hostname, to_name);
255                         return true;
256                 }
257
258                 /* TODO: forwarding SPTPS packets in this way is inefficient because we send them over TCP without checking for UDP connectivity */
259                 send_request(to->nexthop->connection, "%s", request);
260         }
261
262         return true;
263 }
264
265 bool send_ans_key(node_t *to) {
266         if(to->status.sptps)
267                 abort();
268
269 #ifdef DISABLE_LEGACY
270         return false;
271 #else
272         size_t keylen = myself->incipher ? cipher_keylength(myself->incipher) : 1;
273         char key[keylen * 2 + 1];
274
275         randomize(key, keylen);
276
277         cipher_close(to->incipher);
278         digest_close(to->indigest);
279
280         if(myself->incipher) {
281                 to->incipher = cipher_open_by_nid(cipher_get_nid(myself->incipher));
282                 if(!to->incipher)
283                         abort();
284                 if(!cipher_set_key(to->incipher, key, false))
285                         abort();
286         }
287
288         if(myself->indigest) {
289                 to->indigest = digest_open_by_nid(digest_get_nid(myself->indigest), digest_length(myself->indigest));
290                 if(!to->indigest)
291                         abort();
292                 if(!digest_set_key(to->indigest, key, keylen))
293                         abort();
294         }
295
296         to->incompression = myself->incompression;
297
298         bin2hex(key, key, keylen);
299
300         // Reset sequence number and late packet window
301         mykeyused = true;
302         to->received_seqno = 0;
303         to->received = 0;
304         if(replaywin) memset(to->late, 0, replaywin);
305
306         to->status.validkey_in = true;
307
308         return send_request(to->nexthop->connection, "%d %s %s %s %d %d %d %d", ANS_KEY,
309                                                 myself->name, to->name, key,
310                                                 cipher_get_nid(to->incipher),
311                                                 digest_get_nid(to->indigest),
312                                                 (int)digest_length(to->indigest),
313                                                 to->incompression);
314 #endif
315 }
316
317 bool ans_key_h(connection_t *c, const char *request) {
318         char from_name[MAX_STRING_SIZE];
319         char to_name[MAX_STRING_SIZE];
320         char key[MAX_STRING_SIZE];
321         char address[MAX_STRING_SIZE] = "";
322         char port[MAX_STRING_SIZE] = "";
323         int cipher, digest, maclength, compression, keylen;
324         node_t *from, *to;
325
326         if(sscanf(request, "%*d "MAX_STRING" "MAX_STRING" "MAX_STRING" %d %d %d %d "MAX_STRING" "MAX_STRING,
327                 from_name, to_name, key, &cipher, &digest, &maclength,
328                 &compression, address, port) < 7) {
329                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ANS_KEY", c->name,
330                            c->hostname);
331                 return false;
332         }
333
334         if(!check_id(from_name) || !check_id(to_name)) {
335                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "ANS_KEY", c->name, c->hostname, "invalid name");
336                 return false;
337         }
338
339         from = lookup_node(from_name);
340
341         if(!from) {
342                 logger(DEBUG_ALWAYS, LOG_ERR, "Got %s from %s (%s) origin %s which does not exist in our connection list",
343                            "ANS_KEY", c->name, c->hostname, from_name);
344                 return true;
345         }
346
347         to = lookup_node(to_name);
348
349         if(!to) {
350                 logger(DEBUG_ALWAYS, LOG_ERR, "Got %s from %s (%s) destination %s which does not exist in our connection list",
351                            "ANS_KEY", c->name, c->hostname, to_name);
352                 return true;
353         }
354
355         /* Forward it if necessary */
356
357         if(to != myself) {
358                 if(tunnelserver)
359                         return true;
360
361                 if(!to->status.reachable) {
362                         logger(DEBUG_ALWAYS, LOG_WARNING, "Got %s from %s (%s) destination %s which is not reachable",
363                                    "ANS_KEY", c->name, c->hostname, to_name);
364                         return true;
365                 }
366
367                 if(!*address && from->address.sa.sa_family != AF_UNSPEC) {
368                         char *address, *port;
369                         logger(DEBUG_PROTOCOL, LOG_DEBUG, "Appending reflexive UDP address to ANS_KEY from %s to %s", from->name, to->name);
370                         sockaddr2str(&from->address, &address, &port);
371                         send_request(to->nexthop->connection, "%s %s %s", request, address, port);
372                         free(address);
373                         free(port);
374                         return true;
375                 }
376
377                 return send_request(to->nexthop->connection, "%s", request);
378         }
379
380 #ifndef DISABLE_LEGACY
381         /* Don't use key material until every check has passed. */
382         cipher_close(from->outcipher);
383         digest_close(from->outdigest);
384 #endif
385         from->status.validkey = false;
386
387         if(compression < 0 || compression > 11) {
388                 logger(DEBUG_ALWAYS, LOG_ERR, "Node %s (%s) uses bogus compression level!", from->name, from->hostname);
389                 return true;
390         }
391
392         from->outcompression = compression;
393
394         /* SPTPS or old-style key exchange? */
395
396         if(from->status.sptps) {
397                 char buf[strlen(key)];
398                 int len = b64decode(key, buf, strlen(key));
399
400                 if(!len || !sptps_receive_data(&from->sptps, buf, len))
401                         logger(DEBUG_ALWAYS, LOG_ERR, "Error processing SPTPS data from %s (%s)", from->name, from->hostname);
402
403                 if(from->status.validkey) {
404                         if(*address && *port) {
405                                 logger(DEBUG_PROTOCOL, LOG_DEBUG, "Using reflexive UDP address from %s: %s port %s", from->name, address, port);
406                                 sockaddr_t sa = str2sockaddr(address, port);
407                                 update_node_udp(from, &sa);
408                         }
409                 }
410
411                 return true;
412         }
413
414 #ifdef DISABLE_LEGACY
415         logger(DEBUG_ALWAYS, LOG_ERR, "Node %s (%s) uses legacy protocol!", from->name, from->hostname);
416         return false;
417 #else
418         /* Check and lookup cipher and digest algorithms */
419
420         if(cipher) {
421                 if(!(from->outcipher = cipher_open_by_nid(cipher))) {
422                         logger(DEBUG_ALWAYS, LOG_ERR, "Node %s (%s) uses unknown cipher!", from->name, from->hostname);
423                         return false;
424                 }
425         } else {
426                 from->outcipher = NULL;
427         }
428
429         if(digest) {
430                 if(!(from->outdigest = digest_open_by_nid(digest, maclength))) {
431                         logger(DEBUG_ALWAYS, LOG_ERR, "Node %s (%s) uses unknown digest!", from->name, from->hostname);
432                         return false;
433                 }
434         } else {
435                 from->outdigest = NULL;
436         }
437
438         if(maclength != digest_length(from->outdigest)) {
439                 logger(DEBUG_ALWAYS, LOG_ERR, "Node %s (%s) uses bogus MAC length!", from->name, from->hostname);
440                 return false;
441         }
442
443         /* Process key */
444
445         keylen = hex2bin(key, key, sizeof key);
446
447         if(keylen != (from->outcipher ? cipher_keylength(from->outcipher) : 1)) {
448                 logger(DEBUG_ALWAYS, LOG_ERR, "Node %s (%s) uses wrong keylength!", from->name, from->hostname);
449                 return true;
450         }
451
452         /* Update our copy of the origin's packet key */
453
454         if(from->outcipher && !cipher_set_key(from->outcipher, key, true))
455                 return false;
456         if(from->outdigest && !digest_set_key(from->outdigest, key, keylen))
457                 return false;
458
459         from->status.validkey = true;
460         from->sent_seqno = 0;
461
462         if(*address && *port) {
463                 logger(DEBUG_PROTOCOL, LOG_DEBUG, "Using reflexive UDP address from %s: %s port %s", from->name, address, port);
464                 sockaddr_t sa = str2sockaddr(address, port);
465                 update_node_udp(from, &sa);
466         }
467
468         return true;
469 #endif
470 }