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