]> git.meshlink.io Git - meshlink/blob - src/protocol_auth.c
persistence of DeviceClass
[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 "ecdsa.h"
25 #include "edge.h"
26 #include "graph.h"
27 #include "logger.h"
28 #include "meshlink_internal.h"
29 #include "meta.h"
30 #include "net.h"
31 #include "netutl.h"
32 #include "node.h"
33 #include "prf.h"
34 #include "protocol.h"
35 #include "sptps.h"
36 #include "utils.h"
37 #include "xalloc.h"
38 #include "ed25519/sha512.h"
39
40 static bool send_proxyrequest(meshlink_handle_t *mesh, connection_t *c) {
41         switch(mesh->proxytype) {
42                 case PROXY_HTTP: {
43                         char *host;
44                         char *port;
45
46                         sockaddr2str(&c->address, &host, &port);
47                         send_request(mesh, c, "CONNECT %s:%s HTTP/1.1\r\n\r", host, port);
48                         free(host);
49                         free(port);
50                         return true;
51                 }
52                 case PROXY_SOCKS4: {
53                         if(c->address.sa.sa_family != AF_INET) {
54                                 logger(mesh, MESHLINK_ERROR, "Cannot connect to an IPv6 host through a SOCKS 4 proxy!");
55                                 return false;
56                         }
57                         char s4req[9 + (mesh->proxyuser ? strlen(mesh->proxyuser) : 0)];
58                         s4req[0] = 4;
59                         s4req[1] = 1;
60                         memcpy(s4req + 2, &c->address.in.sin_port, 2);
61                         memcpy(s4req + 4, &c->address.in.sin_addr, 4);
62                         if(mesh->proxyuser)
63                                 memcpy(s4req + 8, mesh->proxyuser, strlen(mesh->proxyuser));
64                         s4req[sizeof s4req - 1] = 0;
65                         c->tcplen = 8;
66                         return send_meta(mesh, c, s4req, sizeof s4req);
67                 }
68                 case PROXY_SOCKS5: {
69                         int len = 3 + 6 + (c->address.sa.sa_family == AF_INET ? 4 : 16);
70                         c->tcplen = 2;
71                         if(mesh->proxypass)
72                                 len += 3 + strlen(mesh->proxyuser) + strlen(mesh->proxypass);
73                         char s5req[len];
74                         int i = 0;
75                         s5req[i++] = 5;
76                         s5req[i++] = 1;
77                         if(mesh->proxypass) {
78                                 s5req[i++] = 2;
79                                 s5req[i++] = 1;
80                                 s5req[i++] = strlen(mesh->proxyuser);
81                                 memcpy(s5req + i, mesh->proxyuser, strlen(mesh->proxyuser));
82                                 i += strlen(mesh->proxyuser);
83                                 s5req[i++] = strlen(mesh->proxypass);
84                                 memcpy(s5req + i, mesh->proxypass, strlen(mesh->proxypass));
85                                 i += strlen(mesh->proxypass);
86                                 c->tcplen += 2;
87                         } else {
88                                 s5req[i++] = 0;
89                         }
90                         s5req[i++] = 5;
91                         s5req[i++] = 1;
92                         s5req[i++] = 0;
93                         if(c->address.sa.sa_family == AF_INET) {
94                                 s5req[i++] = 1;
95                                 memcpy(s5req + i, &c->address.in.sin_addr, 4);
96                                 i += 4;
97                                 memcpy(s5req + i, &c->address.in.sin_port, 2);
98                                 i += 2;
99                                 c->tcplen += 10;
100                         } else if(c->address.sa.sa_family == AF_INET6) {
101                                 s5req[i++] = 3;
102                                 memcpy(s5req + i, &c->address.in6.sin6_addr, 16);
103                                 i += 16;
104                                 memcpy(s5req + i, &c->address.in6.sin6_port, 2);
105                                 i += 2;
106                                 c->tcplen += 22;
107                         } else {
108                                 logger(mesh, MESHLINK_ERROR, "Address family %hx not supported for SOCKS 5 proxies!", c->address.sa.sa_family);
109                                 return false;
110                         }
111                         if(i > len)
112                                 abort();
113                         return send_meta(mesh, c, s5req, sizeof s5req);
114                 }
115                 case PROXY_SOCKS4A:
116                         logger(mesh, MESHLINK_ERROR, "Proxy type not implemented yet");
117                         return false;
118                 case PROXY_EXEC:
119                         return true;
120                 default:
121                         logger(mesh, MESHLINK_ERROR, "Unknown proxy type");
122                         return false;
123         }
124 }
125
126 bool send_id(meshlink_handle_t *mesh, connection_t *c) {
127         
128         int minor = mesh->self->connection->protocol_minor;
129
130         if(mesh->proxytype && c->outgoing)
131                 if(!send_proxyrequest(mesh, c))
132                         return false;
133
134         return send_request(mesh, c, "%d %s %d.%d", ID, mesh->self->connection->name, mesh->self->connection->protocol_major, minor);
135 }
136
137 static bool finalize_invitation(meshlink_handle_t *mesh, connection_t *c, const void *data, uint16_t len) {
138         if(strchr(data, '\n')) {
139                 logger(mesh, MESHLINK_ERROR, "Received invalid key from invited node %s (%s)!\n", c->name, c->hostname);
140                 return false;
141         }
142
143         // Create a new host config file
144         char filename[PATH_MAX];
145         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, c->name);
146         if(!access(filename, F_OK)) {
147                 logger(mesh, MESHLINK_ERROR, "Host config file for %s (%s) already exists!\n", c->name, c->hostname);
148                 return false;
149         }
150
151         FILE *f = fopen(filename, "w");
152         if(!f) {
153                 logger(mesh, MESHLINK_ERROR, "Error trying to create %s: %s\n", filename, strerror(errno));
154                 return false;
155         }
156
157         fprintf(f, "ECDSAPublicKey = %s\n", (const char *)data);
158         fclose(f);
159
160         logger(mesh, MESHLINK_INFO, "Key succesfully received from %s (%s)", c->name, c->hostname);
161
162         //TODO: callback to application to inform of an accepted invitation
163
164         sptps_send_record(&c->sptps, 2, data, 0);
165
166         load_all_nodes(mesh);
167
168         return true;
169 }
170
171 static bool receive_invitation_sptps(void *handle, uint8_t type, const void *data, uint16_t len) {
172         connection_t *c = handle;
173         meshlink_handle_t *mesh = c->mesh;
174
175         if(type == 128)
176                 return true;
177
178         if(type == 1 && c->status.invitation_used)
179                 return finalize_invitation(mesh, 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(mesh, MESHLINK_ERROR, "Peer %s tried to use non-existing invitation %s\n", c->hostname, cookie);
203                 else
204                         logger(mesh, MESHLINK_ERROR, "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(mesh, MESHLINK_ERROR, "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(mesh, MESHLINK_ERROR, "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(mesh, MESHLINK_INFO, "Invitation %s succesfully sent to %s (%s)", cookie, c->name, c->hostname);
251         return true;
252 }
253
254 bool id_h(meshlink_handle_t *mesh, 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(mesh, MESHLINK_ERROR, "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(mesh, MESHLINK_ERROR, "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(mesh, MESHLINK_ERROR, "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(mesh, c, "%d %s", ACK, mykey))
282                         return false;
283                 free(mykey);
284
285                 c->protocol_minor = 2;
286                 c->allow_request = 1;
287
288                 return sptps_start(&c->sptps, c, false, false, mesh->invitation_key, c->ecdsa, "meshlink 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(mesh, MESHLINK_ERROR, "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(mesh, MESHLINK_ERROR, "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 != mesh->self->connection->protocol_major) {
316                 logger(mesh, MESHLINK_ERROR, "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(!c->config_tree) {
322                 init_configuration(&c->config_tree);
323
324                 if(!read_host_config(mesh, c->config_tree, c->name)) {
325                         logger(mesh, MESHLINK_ERROR, "Peer %s had unknown identity (%s)", c->hostname, c->name);
326                         return false;
327                 }
328
329                 read_ecdsa_public_key(mesh, c);
330         } else {
331                 if(c->protocol_minor && !ecdsa_active(c->ecdsa))
332                         c->protocol_minor = 1;
333         }
334
335         /* Forbid version rollback for nodes whose ECDSA key we know */
336
337         if(ecdsa_active(c->ecdsa) && c->protocol_minor < 2) {
338                 logger(mesh, MESHLINK_ERROR, "Peer %s (%s) tries to roll back protocol version to %d.%d",
339                         c->name, c->hostname, c->protocol_major, c->protocol_minor);
340                 return false;
341         }
342
343         c->allow_request = ACK;
344         char label[25 + strlen(mesh->self->name) + strlen(c->name)];
345
346         if(c->outgoing)
347                 snprintf(label, sizeof label, "meshlink TCP key expansion %s %s", mesh->self->name, c->name);
348         else
349                 snprintf(label, sizeof label, "meshlink TCP key expansion %s %s", c->name, mesh->self->name);
350
351         return sptps_start(&c->sptps, c, c->outgoing, false, mesh->self->connection->ecdsa, c->ecdsa, label, sizeof label, send_meta_sptps, receive_meta_sptps);
352 }
353
354 bool send_ack(meshlink_handle_t *mesh, connection_t *c) {
355
356         /* Check some options */
357
358         if(mesh->self->options & OPTION_PMTU_DISCOVERY)
359                 c->options |= OPTION_PMTU_DISCOVERY;
360
361         return send_request(mesh, c, "%d %s %d %x", ACK, mesh->myport, mesh->dclass, (c->options & 0xffffff) | (PROT_MINOR << 24));
362 }
363
364 static void send_everything(meshlink_handle_t *mesh, connection_t *c) {
365         /* Send all known subnets and edges */
366
367         for splay_each(node_t, n, mesh->nodes) {
368                 for splay_each(edge_t, e, n->edge_tree)
369                         send_add_edge(mesh, c, e);
370         }
371 }
372
373 bool ack_h(meshlink_handle_t *mesh, connection_t *c, const char *request) {
374         char hisport[MAX_STRING_SIZE];
375         char *hisaddress;
376         int dclass;
377         uint32_t options;
378         node_t *n;
379
380         if(sscanf(request, "%*d " MAX_STRING " %d %x", hisport, &dclass, &options) != 3) {
381                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s (%s)", "ACK", c->name,
382                            c->hostname);
383                 return false;
384         }
385
386         /* Check if we already have a node_t for him */
387
388         n = lookup_node(mesh, c->name);
389
390         if(!n) {
391                 n = new_node();
392                 n->name = xstrdup(c->name);
393                 node_add(mesh, n);
394         } else {
395                 if(n->connection) {
396                         /* Oh dear, we already have a connection to this node. */
397                         logger(mesh, MESHLINK_DEBUG, "Established a second connection with %s (%s), closing old connection", n->connection->name, n->connection->hostname);
398
399                         if(n->connection->outgoing) {
400                                 if(c->outgoing)
401                                         logger(mesh, MESHLINK_WARNING, "Two outgoing connections to the same node!");
402                                 else
403                                         c->outgoing = n->connection->outgoing;
404
405                                 n->connection->outgoing = NULL;
406                         }
407
408                         terminate_connection(mesh, n->connection, false);
409                         /* Run graph algorithm to keep things in sync */
410                         graph(mesh);
411                 }
412         }
413
414         n->dclass = dclass;
415         node_write_dclass(mesh, n);
416
417         n->connection = c;
418         c->node = n;
419         if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
420                 c->options &= ~OPTION_PMTU_DISCOVERY;
421                 options &= ~OPTION_PMTU_DISCOVERY;
422         }
423         c->options |= options;
424
425         /* Activate this connection */
426
427         c->allow_request = ALL;
428         c->status.active = true;
429
430         logger(mesh, MESHLINK_INFO, "Connection with %s (%s) activated", c->name,
431                            c->hostname);
432
433         /* Send him everything we know */
434
435         send_everything(mesh, c);
436
437         /* Create an edge_t for this connection */
438
439         c->edge = new_edge();
440         c->edge->from = mesh->self;
441         c->edge->to = n;
442         sockaddr2str(&c->address, &hisaddress, NULL);
443         c->edge->address = str2sockaddr(hisaddress, hisport);
444         free(hisaddress);
445         c->edge->weight = weight_from_dclass(dclass);
446         c->edge->connection = c;
447         c->edge->options = c->options;
448
449         edge_add(mesh, c->edge);
450
451         /* Notify everyone of the new edge */
452
453         send_add_edge(mesh, mesh->everyone, c->edge);
454
455         /* Run MST and SSSP algorithms */
456
457         graph(mesh);
458
459         return true;
460 }