]> git.meshlink.io Git - meshlink/blob - src/libmeshlink.c
fd7426cace616e9e48e2e2a377689ad7d81169ef
[meshlink] / src / libmeshlink.c
1 /*
2     libmeshlink.h -- Tincd Library
3     Copyright (C) 2014 Guus Sliepen <guus@meshlink.io> Saverio Proto <zioproto@gmail.com>
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 <pthread.h>
23
24 #include "connection.h"
25 #include "crypto.h"
26 #include "ecdsagen.h"
27 #include "edge.h"
28 #include "libmeshlink.h"
29 #include "net.h"
30 #include "node.h"
31 #include "protocol.h"
32
33 char *hosts_dir = NULL;
34 static char *name = NULL;
35 char *tinc_conf = NULL;
36 static bool tty = false;
37
38 #ifdef HAVE_MLOCKALL
39 /* If nonzero, disable swapping for this process. */
40 static bool do_mlock = false;
41 #endif
42
43 /* Open a file with the desired permissions, minus the umask.
44    Also, if we want to create an executable file, we call fchmod()
45    to set the executable bits. */
46
47 FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
48         mode_t mask = umask(0);
49         perms &= ~mask;
50         umask(~perms);
51         FILE *f = fopen(filename, mode);
52 #ifdef HAVE_FCHMOD
53         if((perms & 0444) && f)
54                 fchmod(fileno(f), perms);
55 #endif
56         umask(mask);
57         return f;
58 }
59
60 static void disable_old_keys(const char *filename, const char *what) {
61         char tmpfile[PATH_MAX] = "";
62         char buf[1024];
63         bool disabled = false;
64         bool block = false;
65         bool error = false;
66         FILE *r, *w;
67
68         r = fopen(filename, "r");
69         if(!r)
70                 return;
71
72         snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
73
74         struct stat st = {.st_mode = 0600};
75         fstat(fileno(r), &st);
76         w = fopenmask(tmpfile, "w", st.st_mode);
77
78         while(fgets(buf, sizeof buf, r)) {
79                 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
80                         if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
81                                 disabled = true;
82                                 block = true;
83                         }
84                 }
85
86                 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
87
88                 if(ecdsapubkey)
89                         disabled = true;
90
91                 if(w) {
92                         if(block || ecdsapubkey)
93                                 fputc('#', w);
94                         if(fputs(buf, w) < 0) {
95                                 error = true;
96                                 break;
97                         }
98                 }
99
100                 if(block && !strncmp(buf, "-----END ", 9))
101                         block = false;
102         }
103
104         if(w)
105                 if(fclose(w) < 0)
106                         error = true;
107         if(ferror(r) || fclose(r) < 0)
108                 error = true;
109
110         if(disabled) {
111                 if(!w || error) {
112                         fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
113                         if(w)
114                                 unlink(tmpfile);
115                         return;
116                 }
117
118 #ifdef HAVE_MINGW
119                 // We cannot atomically replace files on Windows.
120                 char bakfile[PATH_MAX] = "";
121                 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
122                 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
123                         rename(bakfile, filename);
124 #else
125                 if(rename(tmpfile, filename)) {
126 #endif
127                         fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
128                 } else  {
129 #ifdef HAVE_MINGW
130                         unlink(bakfile);
131 #endif
132                         fprintf(stderr, "Warning: old key(s) found and disabled.\n");
133                 }
134         }
135
136         unlink(tmpfile);
137 }
138
139 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask, mode_t perms) {
140         FILE *r;
141         char *directory;
142         char buf[PATH_MAX];
143         char buf2[PATH_MAX];
144
145         /* Check stdin and stdout */
146         if(ask && tty) {
147                 /* Ask for a file and/or directory name. */
148                 fprintf(stderr, "Please enter a file to save %s to [%s]: ", what, filename);
149
150                 if(fgets(buf, sizeof buf, stdin) == NULL) {
151                         fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
152                         return NULL;
153                 }
154
155                 size_t len = strlen(buf);
156                 if(len)
157                         buf[--len] = 0;
158
159                 if(len)
160                         filename = buf;
161         }
162
163 #ifdef HAVE_MINGW
164         if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
165 #else
166         if(filename[0] != '/') {
167 #endif
168                 /* The directory is a relative path or a filename. */
169                 directory = get_current_dir_name();
170                 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
171                 filename = buf2;
172         }
173
174         disable_old_keys(filename, what);
175
176         /* Open it first to keep the inode busy */
177
178         r = fopenmask(filename, mode, perms);
179
180         if(!r) {
181                 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
182                 return NULL;
183         }
184
185         return r;
186 }
187
188 /*
189   Generate a public/private ECDSA keypair, and ask for a file to store
190   them in.
191 */
192 bool ecdsa_keygen(bool ask) {
193         ecdsa_t *key;
194         FILE *f;
195         char *pubname, *privname;
196
197         fprintf(stderr, "Generating ECDSA keypair:\n");
198
199         if(!(key = ecdsa_generate())) {
200                 fprintf(stderr, "Error during key generation!\n");
201                 return false;
202         } else
203                 fprintf(stderr, "Done.\n");
204
205         xasprintf(&privname, "%s" SLASH "ecdsa_key.priv", confbase);
206         f = ask_and_open(privname, "private ECDSA key", "a", ask, 0600);
207         free(privname);
208
209         if(!f)
210                 return false;
211
212         if(!ecdsa_write_pem_private_key(key, f)) {
213                 fprintf(stderr, "Error writing private key!\n");
214                 ecdsa_free(key);
215                 fclose(f);
216                 return false;
217         }
218
219         fclose(f);
220
221         if(name)
222                 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
223         else
224                 xasprintf(&pubname, "%s" SLASH "ecdsa_key.pub", confbase);
225
226         f = ask_and_open(pubname, "public ECDSA key", "a", ask, 0666);
227         free(pubname);
228
229         if(!f)
230                 return false;
231
232         char *pubkey = ecdsa_get_base64_public_key(key);
233         fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
234         free(pubkey);
235
236         fclose(f);
237         ecdsa_free(key);
238
239         return true;
240 }
241
242 static bool try_bind(int port) {
243         struct addrinfo *ai = NULL;
244         struct addrinfo hint = {
245                 .ai_flags = AI_PASSIVE,
246                 .ai_family = AF_UNSPEC,
247                 .ai_socktype = SOCK_STREAM,
248                 .ai_protocol = IPPROTO_TCP,
249         };
250
251         char portstr[16];
252         snprintf(portstr, sizeof portstr, "%d", port);
253
254         if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
255                 return false;
256
257         while(ai) {
258                 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
259                 if(!fd)
260                         return false;
261                 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
262                 closesocket(fd);
263                 if(result)
264                         return false;
265                 ai = ai->ai_next;
266         }
267
268         return true;
269 }
270
271 int check_port(const char *name) {
272         if(try_bind(655))
273                 return 655;
274
275         fprintf(stderr, "Warning: could not bind to port 655. ");
276
277         for(int i = 0; i < 100; i++) {
278                 int port = 0x1000 + (rand() & 0x7fff);
279                 if(try_bind(port)) {
280                         char *filename;
281                         xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
282                         FILE *f = fopen(filename, "a");
283                         free(filename);
284                         if(!f) {
285                                 fprintf(stderr, "Please change tinc's Port manually.\n");
286                                 return 0;
287                         }
288
289                         fprintf(f, "Port = %d\n", port);
290                         fclose(f);
291                         fprintf(stderr, "Tinc will instead listen on port %d.\n", port);
292                         return port;
293                 }
294         }
295
296         fprintf(stderr, "Please change tinc's Port manually.\n");
297         return 0;
298 }
299 //tinc_setup() should basically do what cmd_init() from src/tincctl.c does, except it doesn't have to generate a tinc-up script.
300 bool tinc_setup(const char* confbaseapi, const char* name) {
301         confbase = xstrdup(confbaseapi);
302         xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
303         xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
304         if(!access(tinc_conf, F_OK)) {
305                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
306                 return false;
307         }
308
309         if(!check_id(name)) {
310                 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
311                 return false;
312         }
313
314         if(mkdir(confbase, 0777) && errno != EEXIST) {
315                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
316                 return false;
317         }
318
319         if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
320                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
321                 return false;
322         }
323
324         FILE *f = fopen(tinc_conf, "w");
325         if(!f) {
326                 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
327                 return 1;
328         }
329
330         fprintf(f, "Name = %s\n", name);
331         fclose(f);
332
333         if(!ecdsa_keygen(false))
334                 return false;
335
336         check_port(name);
337
338         return true;
339
340 }
341
342
343 bool tinc_start(const char* confbaseapi) {
344         pthread_t tincThread;
345         confbase = xstrdup(confbaseapi);
346         pthread_create(&tincThread,NULL,tinc_main_thread,confbase);
347         pthread_detach(tincThread);
348 return true;
349 }
350
351 __attribute__((constructor)) static void meshlink_init(void) {
352         /* Slllluuuuuuurrrrp! */
353
354         gettimeofday(&now, NULL);
355         srand(now.tv_sec + now.tv_usec);
356         crypto_init();
357 }
358
359 __attribute__((destructor)) static void meshlink_exit(void) {
360         crypto_exit();
361 }
362
363
364 void *tinc_main_thread(void * in) {
365         static bool status = false;
366
367         /* If nonzero, write log entries to a separate file. */
368         bool use_logfile = false;
369
370         confbase = (char*) in;
371
372         openlogger("tinc", LOGMODE_STDERR);
373
374         init_configuration(&config_tree);
375
376         if(!read_server_config())
377                 return false;
378
379         //char *priority = NULL; //shoud be not needed in libmeshlink
380
381         /* Setup sockets and open device. */
382
383         if(!setup_network())
384                 goto end;
385
386         /* Start main loop. It only exits when tinc is killed. */
387
388         logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
389
390         try_outgoing_connections();
391
392         status = main_loop();
393
394         /* Shutdown properly. */
395
396 end:
397         close_network_connections();
398
399         logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
400
401         //free(priority);
402
403         exit_configuration(&config_tree);
404
405         return (void *)status;
406 }
407
408 bool tinc_stop();
409
410 // can be called from any thread
411 bool tinc_send_packet(node_t *receiver, const char* buf, unsigned int len) {
412
413         vpn_packet_t packet;
414         tincpackethdr* hdr = malloc(sizeof(tincpackethdr));
415         if (sizeof(tincpackethdr) + len > MAXSIZE) {
416
417         //log something
418         return false;
419         }
420
421         memset(hdr->legacymtu,1,sizeof(hdr->legacymtu));
422         memcpy(hdr->destination,receiver->name,sizeof(hdr->destination));
423         memcpy(hdr->source,myself->name,sizeof(hdr->source));
424
425         packet.priority = 0;
426         packet.len = sizeof(tincpackethdr) + len;
427
428         memcpy(packet.data,hdr,sizeof(tincpackethdr));
429         memcpy(packet.data+sizeof(tincpackethdr),buf,len);
430
431         myself->in_packets++;
432         myself->in_bytes += packet.len;
433         route(myself, &packet);
434
435 return true;
436 }
437
438 // handler runs in tinc thread and should return immediately
439 bool tinc_set_packet_receive_handler(void (*handler)(const char* sender, const char* buf, unsigned int len));
440
441
442 //It might also be a good idea to add the option of looking up hosts by public
443 //key (fingerprints) instead of names.
444
445 node_t *tinc_get_host(const char *name) {
446
447
448
449 };
450
451 bool tinc_get_hosts(node_t** hosts);
452
453 bool tinc_sign(const char* payload, unsigned int len, const char** signature);
454
455 int tinc_verify(const char* sender, const char* payload, unsigned int plen, const char* signature, unsigned int slen);
456
457 /*
458 TODO: It would be good to add a void pointer here that will be passed on to the
459 handler function whenever it is called, or have a void pointer in node_t
460 that can be filled in by the application. That way, you can easily link an
461 application-specific data structure to a node_t.
462 */
463 void channel_set_packet_send_handler(int (*handler)(const char* receiver, const char* buf, unsigned int len));
464 void channel_packet_receive_handler(const char* sender, const char* buf, unsigned int len);
465
466 bool channel_open(const char* partner, void(*read)(int id, const char* buf, unsigned int len), void(*result)(int result, int id));
467 void channel_close(int id);
468 bool channel_write(int id, const char* buf, unsigned int len, void(*result)(int result, int id, unsigned int written));
469
470
471 //We do need some more functions. First of all, we need to be able to add nodes
472 //to a VPN. To do that, either an invitation protocol should be used:
473
474 bool tinc_join_network(const char *invitation);
475 const char *tinc_generate_invitation(const char *name);
476
477 /*
478 Or two nodes should exchange some information (their name, address, public
479 key). If the application provides a way to exchange some data with another
480 node, then:
481 */
482
483 bool tinc_export(char *buf, size_t *len);
484 node_t *tinc_import(const char *buf, size_t len);
485 /*
486 Last but not least, some way to get rid of unwanted nodes. Simplest is a
487 function that just blacklists a node.
488 Which should immediately cause the local tincd to ignore any data from that
489 host from that point on. Of course, a somewhat centrally managed,
490 automatically distributed blacklist or whitelist would be the next step.
491 */
492 bool tinc_blacklist(node_t *host);
493
494
495
496