]> git.meshlink.io Git - meshlink/blob - src/protocol_auth.c
Move node_udp_cache, everyone and invitation_key to mesh.
[meshlink] / src / protocol_auth.c
1 /*
2     protocol_auth.c -- handle the meta-protocol, authentication
3     Copyright (C) 2014 Guus Sliepen <guus@meshlink.io>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "system.h"
21
22 #include "conf.h"
23 #include "connection.h"
24 #include "cipher.h"
25 #include "crypto.h"
26 #include "digest.h"
27 #include "ecdsa.h"
28 #include "edge.h"
29 #include "graph.h"
30 #include "logger.h"
31 #include "meshlink_internal.h"
32 #include "meta.h"
33 #include "net.h"
34 #include "netutl.h"
35 #include "node.h"
36 #include "prf.h"
37 #include "protocol.h"
38 #include "sptps.h"
39 #include "utils.h"
40 #include "xalloc.h"
41 #include "ed25519/sha512.h"
42
43 static bool send_proxyrequest(connection_t *c) {
44         switch(mesh->proxytype) {
45                 case PROXY_HTTP: {
46                         char *host;
47                         char *port;
48
49                         sockaddr2str(&c->address, &host, &port);
50                         send_request(c, "CONNECT %s:%s HTTP/1.1\r\n\r", host, port);
51                         free(host);
52                         free(port);
53                         return true;
54                 }
55                 case PROXY_SOCKS4: {
56                         if(c->address.sa.sa_family != AF_INET) {
57                                 logger(DEBUG_ALWAYS, LOG_ERR, "Cannot connect to an IPv6 host through a SOCKS 4 proxy!");
58                                 return false;
59                         }
60                         char s4req[9 + (mesh->proxyuser ? strlen(mesh->proxyuser) : 0)];
61                         s4req[0] = 4;
62                         s4req[1] = 1;
63                         memcpy(s4req + 2, &c->address.in.sin_port, 2);
64                         memcpy(s4req + 4, &c->address.in.sin_addr, 4);
65                         if(mesh->proxyuser)
66                                 memcpy(s4req + 8, mesh->proxyuser, strlen(mesh->proxyuser));
67                         s4req[sizeof s4req - 1] = 0;
68                         c->tcplen = 8;
69                         return send_meta(c, s4req, sizeof s4req);
70                 }
71                 case PROXY_SOCKS5: {
72                         int len = 3 + 6 + (c->address.sa.sa_family == AF_INET ? 4 : 16);
73                         c->tcplen = 2;
74                         if(mesh->proxypass)
75                                 len += 3 + strlen(mesh->proxyuser) + strlen(mesh->proxypass);
76                         char s5req[len];
77                         int i = 0;
78                         s5req[i++] = 5;
79                         s5req[i++] = 1;
80                         if(mesh->proxypass) {
81                                 s5req[i++] = 2;
82                                 s5req[i++] = 1;
83                                 s5req[i++] = strlen(mesh->proxyuser);
84                                 memcpy(s5req + i, mesh->proxyuser, strlen(mesh->proxyuser));
85                                 i += strlen(mesh->proxyuser);
86                                 s5req[i++] = strlen(mesh->proxypass);
87                                 memcpy(s5req + i, mesh->proxypass, strlen(mesh->proxypass));
88                                 i += strlen(mesh->proxypass);
89                                 c->tcplen += 2;
90                         } else {
91                                 s5req[i++] = 0;
92                         }
93                         s5req[i++] = 5;
94                         s5req[i++] = 1;
95                         s5req[i++] = 0;
96                         if(c->address.sa.sa_family == AF_INET) {
97                                 s5req[i++] = 1;
98                                 memcpy(s5req + i, &c->address.in.sin_addr, 4);
99                                 i += 4;
100                                 memcpy(s5req + i, &c->address.in.sin_port, 2);
101                                 i += 2;
102                                 c->tcplen += 10;
103                         } else if(c->address.sa.sa_family == AF_INET6) {
104                                 s5req[i++] = 3;
105                                 memcpy(s5req + i, &c->address.in6.sin6_addr, 16);
106                                 i += 16;
107                                 memcpy(s5req + i, &c->address.in6.sin6_port, 2);
108                                 i += 2;
109                                 c->tcplen += 22;
110                         } else {
111                                 logger(DEBUG_ALWAYS, LOG_ERR, "Address family %hx not supported for SOCKS 5 proxies!", c->address.sa.sa_family);
112                                 return false;
113                         }
114                         if(i > len)
115                                 abort();
116                         return send_meta(c, s5req, sizeof s5req);
117                 }
118                 case PROXY_SOCKS4A:
119                         logger(DEBUG_ALWAYS, LOG_ERR, "Proxy type not implemented yet");
120                         return false;
121                 case PROXY_EXEC:
122                         return true;
123                 default:
124                         logger(DEBUG_ALWAYS, LOG_ERR, "Unknown proxy type");
125                         return false;
126         }
127 }
128
129 bool send_id(connection_t *c) {
130         gettimeofday(&c->start, NULL);
131
132         int minor = mesh->self->connection->protocol_minor;
133
134         if(mesh->proxytype && c->outgoing)
135                 if(!send_proxyrequest(c))
136                         return false;
137
138         return send_request(c, "%d %s %d.%d", ID, mesh->self->connection->name, mesh->self->connection->protocol_major, minor);
139 }
140
141 static bool finalize_invitation(connection_t *c, const char *data, uint16_t len) {
142         if(strchr(data, '\n')) {
143                 logger(DEBUG_ALWAYS, LOG_ERR, "Received invalid key from invited node %s (%s)!\n", c->name, c->hostname);
144                 return false;
145         }
146
147         // Create a new host config file
148         char filename[PATH_MAX];
149         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, c->name);
150         if(!access(filename, F_OK)) {
151                 logger(DEBUG_ALWAYS, LOG_ERR, "Host config file for %s (%s) already exists!\n", c->name, c->hostname);
152                 return false;
153         }
154
155         FILE *f = fopen(filename, "w");
156         if(!f) {
157                 logger(DEBUG_ALWAYS, LOG_ERR, "Error trying to create %s: %s\n", filename, strerror(errno));
158                 return false;
159         }
160
161         fprintf(f, "ECDSAPublicKey = %s\n", data);
162         fclose(f);
163
164         logger(DEBUG_CONNECTIONS, LOG_INFO, "Key succesfully received from %s (%s)", c->name, c->hostname);
165
166         //TODO: callback to application to inform of an accepted invitation
167
168         sptps_send_record(&c->sptps, 2, data, 0);
169         return true;
170 }
171
172 static bool receive_invitation_sptps(void *handle, uint8_t type, const char *data, uint16_t len) {
173         connection_t *c = handle;
174
175         if(type == 128)
176                 return true;
177
178         if(type == 1 && c->status.invitation_used)
179                 return finalize_invitation(c, data, len);
180
181         if(type != 0 || len != 18 || c->status.invitation_used)
182                 return false;
183
184         // Recover the filename from the cookie and the key
185         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
186         char hash[64];
187         char hashbuf[18 + strlen(fingerprint)];
188         char cookie[25];
189         memcpy(hashbuf, data, 18);
190         memcpy(hashbuf + 18, fingerprint, sizeof hashbuf - 18);
191         sha512(hashbuf, sizeof hashbuf, hash);
192         b64encode_urlsafe(hash, cookie, 18);
193         free(fingerprint);
194
195         char filename[PATH_MAX], usedname[PATH_MAX];
196         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookie);
197         snprintf(usedname, sizeof usedname, "%s" SLASH "invitations" SLASH "%s.used", mesh->confbase, cookie);
198
199         // Atomically rename the invitation file
200         if(rename(filename, usedname)) {
201                 if(errno == ENOENT)
202                         logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s tried to use non-existing invitation %s\n", c->hostname, cookie);
203                 else
204                         logger(DEBUG_ALWAYS, LOG_ERR, "Error trying to rename invitation %s\n", cookie);
205                 return false;
206         }
207
208         // Open the renamed file
209         FILE *f = fopen(usedname, "r");
210         if(!f) {
211                 logger(DEBUG_ALWAYS, LOG_ERR, "Error trying to open invitation %s\n", cookie);
212                 return false;
213         }
214
215         // Read the new node's Name from the file
216         char buf[1024];
217         fgets(buf, sizeof buf, f);
218         if(*buf)
219                 buf[strlen(buf) - 1] = 0;
220
221         len = strcspn(buf, " \t=");
222         char *name = buf + len;
223         name += strspn(name, " \t");
224         if(*name == '=') {
225                 name++;
226                 name += strspn(name, " \t");
227         }
228         buf[len] = 0;
229
230         if(!*buf || !*name || strcasecmp(buf, "Name") || !check_id(name)) {
231                 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid invitation file %s\n", cookie);
232                 fclose(f);
233                 return false;
234         }
235
236         free(c->name);
237         c->name = xstrdup(name);
238
239         // Send the node the contents of the invitation file
240         rewind(f);
241         size_t result;
242         while((result = fread(buf, 1, sizeof buf, f)))
243                 sptps_send_record(&c->sptps, 0, buf, result);
244         sptps_send_record(&c->sptps, 1, buf, 0);
245         fclose(f);
246         unlink(usedname);
247
248         c->status.invitation_used = true;
249
250         logger(DEBUG_CONNECTIONS, LOG_INFO, "Invitation %s succesfully sent to %s (%s)", cookie, c->name, c->hostname);
251         return true;
252 }
253
254 bool id_h(connection_t *c, const char *request) {
255         char name[MAX_STRING_SIZE];
256
257         if(sscanf(request, "%*d " MAX_STRING " %d.%d", name, &c->protocol_major, &c->protocol_minor) < 2) {
258                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ID", c->name,
259                            c->hostname);
260                 return false;
261         }
262
263         /* Check if this is an invitation  */
264
265         if(name[0] == '?') {
266                 if(!mesh->invitation_key) {
267                         logger(DEBUG_ALWAYS, LOG_ERR, "Got invitation from %s but we don't have an invitation key", c->hostname);
268                         return false;
269                 }
270
271                 c->ecdsa = ecdsa_set_base64_public_key(name + 1);
272                 if(!c->ecdsa) {
273                         logger(DEBUG_ALWAYS, LOG_ERR, "Got bad invitation from %s", c->hostname);
274                         return false;
275                 }
276
277                 c->status.invitation = true;
278                 char *mykey = ecdsa_get_base64_public_key(mesh->invitation_key);
279                 if(!mykey)
280                         return false;
281                 if(!send_request(c, "%d %s", ACK, mykey))
282                         return false;
283                 free(mykey);
284
285                 c->protocol_minor = 2;
286
287                 return sptps_start(&c->sptps, c, false, false, mesh->invitation_key, c->ecdsa, "tinc invitation", 15, send_meta_sptps, receive_invitation_sptps);
288         }
289
290         /* Check if identity is a valid name */
291
292         if(!check_id(name)) {
293                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "ID", c->name,
294                            c->hostname, "invalid name");
295                 return false;
296         }
297
298         /* If this is an outgoing connection, make sure we are connected to the right host */
299
300         if(c->outgoing) {
301                 if(strcmp(c->name, name)) {
302                         logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s is %s instead of %s", c->hostname, name,
303                                    c->name);
304                         return false;
305                 }
306         } else {
307                 if(c->name)
308                         free(c->name);
309                 c->name = xstrdup(name);
310         }
311
312         /* Check if version matches */
313
314         if(c->protocol_major != mesh->self->connection->protocol_major) {
315                 logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s (%s) uses incompatible version %d.%d",
316                         c->name, c->hostname, c->protocol_major, c->protocol_minor);
317                 return false;
318         }
319
320         if(bypass_security) {
321                 if(!c->config_tree)
322                         init_configuration(&c->config_tree);
323                 c->allow_request = ACK;
324                 return send_ack(c);
325         }
326
327         if(!c->config_tree) {
328                 init_configuration(&c->config_tree);
329
330                 if(!read_host_config(c->config_tree, c->name)) {
331                         logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s had unknown identity (%s)", c->hostname, c->name);
332                         return false;
333                 }
334
335                 read_ecdsa_public_key(c);
336         } else {
337                 if(c->protocol_minor && !ecdsa_active(c->ecdsa))
338                         c->protocol_minor = 1;
339         }
340
341         /* Forbid version rollback for nodes whose ECDSA key we know */
342
343         if(ecdsa_active(c->ecdsa) && c->protocol_minor < 2) {
344                 logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s (%s) tries to roll back protocol version to %d.%d",
345                         c->name, c->hostname, c->protocol_major, c->protocol_minor);
346                 return false;
347         }
348
349         c->allow_request = ACK;
350         char label[25 + strlen(mesh->self->name) + strlen(c->name)];
351
352         if(c->outgoing)
353                 snprintf(label, sizeof label, "tinc TCP key expansion %s %s", mesh->self->name, c->name);
354         else
355                 snprintf(label, sizeof label, "tinc TCP key expansion %s %s", c->name, mesh->self->name);
356
357         return sptps_start(&c->sptps, c, c->outgoing, false, mesh->self->connection->ecdsa, c->ecdsa, label, sizeof label, send_meta_sptps, receive_meta_sptps);
358 }
359
360 bool send_ack(connection_t *c) {
361         /* ACK message contains rest of the information the other end needs
362            to create node_t and edge_t structures. */
363
364         struct timeval now;
365         bool choice;
366
367         /* Estimate weight */
368
369         gettimeofday(&now, NULL);
370         c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
371
372         /* Check some options */
373
374         if(mesh->self->options & OPTION_PMTU_DISCOVERY)
375                 c->options |= OPTION_PMTU_DISCOVERY;
376
377         return send_request(c, "%d %s %d %x", ACK, mesh->myport, c->estimated_weight, (c->options & 0xffffff) | (PROT_MINOR << 24));
378 }
379
380 static void send_everything(connection_t *c) {
381         /* Send all known subnets and edges */
382
383         for splay_each(node_t, n, mesh->nodes) {
384                 for splay_each(edge_t, e, n->edge_tree)
385                         send_add_edge(c, e);
386         }
387 }
388
389 bool ack_h(connection_t *c, const char *request) {
390         char hisport[MAX_STRING_SIZE];
391         char *hisaddress;
392         int weight, mtu;
393         uint32_t options;
394         node_t *n;
395         bool choice;
396
397         if(sscanf(request, "%*d " MAX_STRING " %d %x", hisport, &weight, &options) != 3) {
398                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name,
399                            c->hostname);
400                 return false;
401         }
402
403         /* Check if we already have a node_t for him */
404
405         n = lookup_node(c->name);
406
407         if(!n) {
408                 n = new_node();
409                 n->name = xstrdup(c->name);
410                 node_add(n);
411         } else {
412                 if(n->connection) {
413                         /* Oh dear, we already have a connection to this node. */
414                         logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Established a second connection with %s (%s), closing old connection", n->connection->name, n->connection->hostname);
415
416                         if(n->connection->outgoing) {
417                                 if(c->outgoing)
418                                         logger(DEBUG_ALWAYS, LOG_WARNING, "Two outgoing connections to the same node!");
419                                 else
420                                         c->outgoing = n->connection->outgoing;
421
422                                 n->connection->outgoing = NULL;
423                         }
424
425                         terminate_connection(n->connection, false);
426                         /* Run graph algorithm to keep things in sync */
427                         graph();
428                 }
429         }
430
431         n->connection = c;
432         c->node = n;
433         if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
434                 c->options &= ~OPTION_PMTU_DISCOVERY;
435                 options &= ~OPTION_PMTU_DISCOVERY;
436         }
437         c->options |= options;
438
439         /* Activate this connection */
440
441         c->allow_request = ALL;
442         c->status.active = true;
443
444         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection with %s (%s) activated", c->name,
445                            c->hostname);
446
447         /* Send him everything we know */
448
449         send_everything(c);
450
451         /* Create an edge_t for this connection */
452
453         c->edge = new_edge();
454         c->edge->from = mesh->self;
455         c->edge->to = n;
456         sockaddr2str(&c->address, &hisaddress, NULL);
457         c->edge->address = str2sockaddr(hisaddress, hisport);
458         free(hisaddress);
459         c->edge->weight = (weight + c->estimated_weight) / 2;
460         c->edge->connection = c;
461         c->edge->options = c->options;
462
463         edge_add(c->edge);
464
465         /* Notify everyone of the new edge */
466
467         send_add_edge(mesh->everyone, c->edge);
468
469         /* Run MST and SSSP algorithms */
470
471         graph();
472
473         return true;
474 }