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