]> git.tuebingen.mpg.de Git - paraslash.git/blob - client_common.c
Implement aes_ctr128 and prefer it over RC4.
[paraslash.git] / client_common.c
1 /*
2  * Copyright (C) 1997-2013 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file client_common.c Common functions of para_client and para_audiod. */
8
9 #include <regex.h>
10 #include <sys/types.h>
11
12 #include "para.h"
13 #include "error.h"
14 #include "list.h"
15 #include "sched.h"
16 #include "crypt.h"
17 #include "net.h"
18 #include "fd.h"
19 #include "sideband.h"
20 #include "string.h"
21 #include "client.cmdline.h"
22 #include "client.h"
23 #include "buffer_tree.h"
24 #include "version.h"
25 #include "ggo.h"
26
27 /** The size of the receiving buffer. */
28 #define CLIENT_BUFSIZE 4000
29
30 /**
31  * Close the connection to para_server and deallocate per-command resources.
32  *
33  * \param ct The client task.
34  *
35  * This frees all resources of the current command but keeps the configuration
36  * in \p ct->conf.
37  *
38  * \sa \ref client_close().
39  */
40 void client_disconnect(struct client_task *ct)
41 {
42         if (!ct)
43                 return;
44         if (ct->scc.fd >= 0)
45                 close(ct->scc.fd);
46         free_argv(ct->features);
47         ct->features = NULL;
48         sc_free(ct->scc.recv);
49         ct->scc.recv = NULL;
50         sc_free(ct->scc.send);
51         ct->scc.send = NULL;
52         btr_remove_node(&ct->btrn[0]);
53         btr_remove_node(&ct->btrn[1]);
54 }
55
56 /**
57  * Close the connection to para_server and free all resources.
58  *
59  * \param ct Pointer to the client data.
60  *
61  * \sa \ref client_open(), \ref client_disconnect().
62  */
63 void client_close(struct client_task *ct)
64 {
65         if (!ct)
66                 return;
67         client_disconnect(ct);
68         free(ct->user);
69         free(ct->config_file);
70         free(ct->key_file);
71         client_cmdline_parser_free(&ct->conf);
72         free(ct->challenge_hash);
73         sb_free(ct->sbc[0]);
74         sb_free(ct->sbc[1]);
75         free(ct);
76 }
77
78 /**
79  * The preselect hook for server commands.
80  *
81  * \param s Pointer to the scheduler.
82  * \param t Pointer to the task struct for this command.
83  *
84  * The task pointer must contain a pointer to the initialized client data
85  * structure as it is returned by client_open().
86  *
87  * This function checks the state of the connection and adds the file descriptor
88  * of the connection to the read or write fd set of \a s accordingly.
89  *
90  * \sa register_task() client_open(), struct sched, struct task.
91  */
92 static void client_pre_select(struct sched *s, struct task *t)
93 {
94         int ret;
95         struct client_task *ct = container_of(t, struct client_task, task);
96
97         if (ct->scc.fd < 0)
98                 return;
99         switch (ct->status) {
100         case CL_CONNECTED:
101         case CL_SENT_AUTH:
102         case CL_SENT_CH_RESPONSE:
103                 para_fd_set(ct->scc.fd, &s->rfds, &s->max_fileno);
104                 return;
105
106         case CL_RECEIVED_WELCOME:
107         case CL_RECEIVED_PROCEED:
108         case CL_RECEIVED_CHALLENGE:
109                 para_fd_set(ct->scc.fd, &s->wfds, &s->max_fileno);
110                 return;
111
112         case CL_SENDING:
113                 if (ct->btrn[1]) {
114                         ret = btr_node_status(ct->btrn[1], 0, BTR_NT_LEAF);
115                         if (ret < 0)
116                                 sched_min_delay(s);
117                         else if (ret > 0)
118                                 para_fd_set(ct->scc.fd, &s->wfds, &s->max_fileno);
119                 }
120                 /* fall though */
121         case CL_EXECUTING:
122                 if (ct->btrn[0]) {
123                         ret = btr_node_status(ct->btrn[0], 0, BTR_NT_ROOT);
124                         if (ret < 0)
125                                 sched_min_delay(s);
126                         else if (ret > 0)
127                                 para_fd_set(ct->scc.fd, &s->rfds, &s->max_fileno);
128                 }
129                 return;
130         }
131 }
132
133 static int send_sb(struct client_task *ct, int channel, void *buf, size_t numbytes,
134                 enum sb_designator band, bool dont_free)
135 {
136         int ret, fd = ct->scc.fd;
137         struct iovec iov[2];
138
139         if (!ct->sbc[channel]) {
140                 struct sb_buffer sbb;
141                 sb_transformation trafo = ct->status < CL_RECEIVED_PROCEED?
142                         NULL : sc_trafo;
143                 sbb = (typeof(sbb))SBB_INIT(band, buf, numbytes);
144                 ct->sbc[channel] = sb_new_send(&sbb, dont_free, trafo, ct->scc.send);
145         }
146         ret = sb_get_send_buffers(ct->sbc[channel], iov);
147         ret = xwritev(fd, iov, ret);
148         if (ret < 0) {
149                 sb_free(ct->sbc[channel]);
150                 ct->sbc[channel] = NULL;
151                 return ret;
152         }
153         if (sb_sent(ct->sbc[channel], ret)) {
154                 ct->sbc[channel] = NULL;
155                 return 1;
156         }
157         return 0;
158 }
159
160 static int recv_sb(struct client_task *ct, fd_set *rfds,
161                 struct sb_buffer *result)
162 {
163         int ret;
164         size_t n;
165         sb_transformation trafo;
166         void *trafo_context;
167         struct iovec iov;
168
169         if (!FD_ISSET(ct->scc.fd, rfds))
170                 return 0;
171         if (ct->status < CL_SENT_CH_RESPONSE)
172                 trafo = trafo_context = NULL;
173         else {
174                 trafo = sc_trafo;
175                 trafo_context = ct->scc.recv;
176         }
177         if (!ct->sbc[0])
178                 ct->sbc[0] = sb_new_recv(0, trafo, trafo_context);
179 again:
180         sb_get_recv_buffer(ct->sbc[0], &iov);
181         ret = read_nonblock(ct->scc.fd, iov.iov_base, iov.iov_len, rfds, &n);
182         if (ret < 0) {
183                 sb_free(ct->sbc[0]);
184                 ct->sbc[0] = NULL;
185                 return ret;
186         }
187         if (n == 0)
188                 return 0;
189         if (!sb_received(ct->sbc[0], n, result))
190                 goto again;
191         ct->sbc[0] = NULL;
192         return 1;
193 }
194
195
196 static char **parse_features(char *buf)
197 {
198         int i;
199         const char id[] = "\nFeatures: ";
200         char *p, *q, **features;
201
202         p = strstr(buf, id);
203         if (!p)
204                 return NULL;
205         p += strlen(id);
206         q = strchr(p, '\n');
207         if (!q)
208                 return NULL;
209         *q = '\0';
210         create_argv(p, ",", &features);
211         for (i = 0; features[i]; i++)
212                 PARA_INFO_LOG("server feature: %s\n", features[i]);
213         return features;
214 }
215
216 static int dispatch_sbb(struct client_task *ct, struct sb_buffer *sbb)
217 {
218         int ret;
219         const char *designator[] = {SB_DESIGNATORS_ARRAY};
220
221         if (!sbb)
222                 return 0;
223         if (sbb->band < NUM_SB_DESIGNATORS)
224                 PARA_DEBUG_LOG("band: %s\n", designator[sbb->band]);
225
226         switch (sbb->band) {
227         case SBD_AWAITING_DATA:
228                 ct->status = CL_SENDING;
229                 ret = 1;
230                 goto out;
231         case SBD_OUTPUT:
232                 if (iov_valid(&sbb->iov))
233                         btr_add_output(sbb->iov.iov_base, sbb->iov.iov_len,
234                                 ct->btrn[0]);
235                 ret = 1;
236                 goto out;
237         case SBD_DEBUG_LOG:
238         case SBD_INFO_LOG:
239         case SBD_NOTICE_LOG:
240         case SBD_WARNING_LOG:
241         case SBD_ERROR_LOG:
242         case SBD_CRIT_LOG:
243         case SBD_EMERG_LOG:
244                 if (iov_valid(&sbb->iov)) {
245                         int ll = sbb->band - SBD_DEBUG_LOG;
246                         para_log(ll, "remote: %s", (char *)sbb->iov.iov_base);
247                 }
248                 ret = 1;
249                 goto deallocate;
250         case SBD_EXIT__SUCCESS:
251                 ret = -E_SERVER_CMD_SUCCESS;
252                 goto deallocate;
253         case SBD_EXIT__FAILURE:
254                 ret = -E_SERVER_CMD_FAILURE;
255                 goto deallocate;
256         default:
257                 PARA_ERROR_LOG("invalid band %d\n", sbb->band);
258                 ret = -E_BAD_BAND;
259                 goto deallocate;
260         }
261 deallocate:
262         free(sbb->iov.iov_base);
263 out:
264         sbb->iov.iov_base = NULL;
265         return ret;
266 }
267
268 static bool has_feature(const char *feature, struct client_task *ct)
269 {
270         return find_arg(feature, ct->features) >= 0? true : false;
271 }
272
273 static int send_sb_command(struct client_task *ct)
274 {
275         int i;
276         char *command, *p;
277         size_t len = 0;
278
279         if (ct->sbc[1])
280                 return send_sb(ct, 0, NULL, 0, 0, false);
281
282         for (i = 0; i < ct->conf.inputs_num; i++)
283                 len += strlen(ct->conf.inputs[i]) + 1;
284         p = command = para_malloc(len);
285         for (i = 0; i < ct->conf.inputs_num; i++) {
286                 strcpy(p, ct->conf.inputs[i]);
287                 p += strlen(ct->conf.inputs[i]) + 1;
288         }
289         PARA_DEBUG_LOG("--> %s\n", command);
290         return send_sb(ct, 0, command, len, SBD_COMMAND, false);
291 }
292
293 /**
294  * The post select hook for client commands.
295  *
296  * \param s Pointer to the scheduler.
297  * \param t Pointer to the task struct for this command.
298  *
299  * Depending on the current state of the connection and the status of the read
300  * and write fd sets of \a s, this function performs the necessary steps to
301  * authenticate the connection, to send the command given by \a t->private_data
302  * and to receive para_server's output, if any.
303  *
304  * \sa struct sched, struct task.
305  */
306 static int client_post_select(struct sched *s, struct task *t)
307 {
308         struct client_task *ct = container_of(t, struct client_task, task);
309         int ret = 0;
310         size_t n;
311         char buf[CLIENT_BUFSIZE];
312
313         ret = task_get_notification(t);
314         if (ret < 0)
315                 goto out;
316         if (ct->scc.fd < 0)
317                 return 0;
318         switch (ct->status) {
319         case CL_CONNECTED: /* receive welcome message */
320                 ret = read_nonblock(ct->scc.fd, buf, sizeof(buf), &s->rfds, &n);
321                 if (ret < 0 || n == 0)
322                         goto out;
323                 ct->features = parse_features(buf);
324                 if (!has_feature("sideband", ct)) {
325                         PARA_ERROR_LOG("server has no sideband support\n");
326                         ret = -E_INCOMPAT_FEAT;
327                         goto out;
328                 }
329                 ct->status = CL_RECEIVED_WELCOME;
330                 return 0;
331         case CL_RECEIVED_WELCOME: /* send auth command */
332                 if (!FD_ISSET(ct->scc.fd, &s->wfds))
333                         return 0;
334                 sprintf(buf, AUTH_REQUEST_MSG "%s sideband%s", ct->user,
335                         has_feature("aes_ctr128", ct)? ",aes_ctr128" : "");
336                 PARA_INFO_LOG("--> %s\n", buf);
337                 ret = write_buffer(ct->scc.fd, buf);
338                 if (ret < 0)
339                         goto out;
340                 ct->status = CL_SENT_AUTH;
341                 return 0;
342         case CL_SENT_AUTH:
343                 /*
344                  * Receive challenge and session keys, decrypt the challenge and
345                  * send back the hash of the decrypted challenge.
346                  */
347                 {
348                 /* decrypted challenge/session key buffer */
349                 unsigned char crypt_buf[1024];
350                 struct sb_buffer sbb;
351                 bool use_aes;
352
353                 ret = recv_sb(ct, &s->rfds, &sbb);
354                 if (ret <= 0)
355                         goto out;
356                 if (sbb.band != SBD_CHALLENGE) {
357                         ret = -E_BAD_BAND;
358                         free(sbb.iov.iov_base);
359                                 goto out;
360                 }
361                 n = sbb.iov.iov_len;
362                 PARA_INFO_LOG("<-- [challenge] (%zu bytes)\n", n);
363                 ret = priv_decrypt(ct->key_file, crypt_buf,
364                         sbb.iov.iov_base, n);
365                 free(sbb.iov.iov_base);
366                 if (ret < 0)
367                         goto out;
368                 ct->challenge_hash = para_malloc(HASH_SIZE);
369                 hash_function((char *)crypt_buf, CHALLENGE_SIZE, ct->challenge_hash);
370                 use_aes = has_feature("aes_ctr128", ct);
371                 ct->scc.send = sc_new(crypt_buf + CHALLENGE_SIZE, SESSION_KEY_LEN, use_aes);
372                 ct->scc.recv = sc_new(crypt_buf + CHALLENGE_SIZE + SESSION_KEY_LEN,
373                         SESSION_KEY_LEN, use_aes);
374                 hash_to_asc(ct->challenge_hash, buf);
375                 PARA_INFO_LOG("--> %s\n", buf);
376                 ct->status = CL_RECEIVED_CHALLENGE;
377                 return 0;
378                 }
379         case CL_RECEIVED_CHALLENGE:
380                 ret = send_sb(ct, 0, ct->challenge_hash, HASH_SIZE,
381                         SBD_CHALLENGE_RESPONSE, false);
382                 if (ret != 0)
383                         ct->challenge_hash = NULL;
384                 if (ret <= 0)
385                         goto out;
386                 ct->status = CL_SENT_CH_RESPONSE;
387                 goto out;
388         case CL_SENT_CH_RESPONSE: /* read server response */
389                 {
390                 struct sb_buffer sbb;
391                 ret = recv_sb(ct, &s->rfds, &sbb);
392                 if (ret <= 0)
393                         goto out;
394                 free(sbb.iov.iov_base);
395                 if (sbb.band != SBD_PROCEED)
396                         ret = -E_BAD_BAND;
397                 else
398                         ct->status = CL_RECEIVED_PROCEED;
399                 goto out;
400                 }
401         case CL_RECEIVED_PROCEED: /* concat args and send command */
402                 {
403                 if (!FD_ISSET(ct->scc.fd, &s->wfds))
404                         return 0;
405                 ret = send_sb_command(ct);
406                 if (ret <= 0)
407                         goto out;
408                 ct->status = CL_EXECUTING;
409                 return 0;
410                 }
411         case CL_SENDING:
412                 if (ct->btrn[1]) {
413                         char *buf2;
414                         size_t sz;
415                         ret = btr_node_status(ct->btrn[1], 0, BTR_NT_LEAF);
416                         if (ret == -E_BTR_EOF) {
417                                 /* empty blob data packet indicates EOF */
418                                 PARA_INFO_LOG("blob sent\n");
419                                 ret = send_sb(ct, 1, NULL, 0, SBD_BLOB_DATA, true);
420                                 if (ret >= 0)
421                                         ret = -E_BTR_EOF;
422                         }
423                         if (ret < 0)
424                                 goto close1;
425                         if (ret > 0 && FD_ISSET(ct->scc.fd, &s->wfds)) {
426                                 sz = btr_next_buffer(ct->btrn[1], &buf2);
427                                 assert(sz);
428                                 ret = send_sb(ct, 1, buf2, sz, SBD_BLOB_DATA, true);
429                                 if (ret < 0)
430                                         goto close1;
431                                 if (ret > 0)
432                                         btr_consume(ct->btrn[1], sz);
433                         }
434                 }
435                 /* fall though */
436         case CL_EXECUTING:
437                 if (ct->btrn[0]) {
438                         ret = btr_node_status(ct->btrn[0], 0, BTR_NT_ROOT);
439                         if (ret < 0)
440                                 goto close0;
441                         if (ret > 0 && FD_ISSET(ct->scc.fd, &s->rfds)) {
442                                 struct sb_buffer sbb;
443                                 ret = recv_sb(ct, &s->rfds, &sbb);
444                                 if (ret < 0)
445                                         goto close0;
446                                 if (ret > 0) {
447                                         ret = dispatch_sbb(ct, &sbb);
448                                         if (ret < 0)
449                                                 goto close0;
450                                 }
451                         }
452                 }
453                 ret = 0;
454                 goto out;
455         }
456 close1:
457         PARA_INFO_LOG("channel 1: %s\n", para_strerror(-ret));
458         btr_remove_node(&ct->btrn[1]);
459         if (ct->btrn[0])
460                 return 0;
461         goto out;
462 close0:
463         PARA_INFO_LOG("channel 0: %s\n", para_strerror(-ret));
464         btr_remove_node(&ct->btrn[0]);
465         if (ct->btrn[1] && ct->status == CL_SENDING)
466                 return 0;
467 out:
468         if (ret >= 0)
469                 return 0;
470         btr_remove_node(&ct->btrn[0]);
471         btr_remove_node(&ct->btrn[1]);
472         if (ret != -E_SERVER_CMD_SUCCESS && ret != -E_SERVER_CMD_FAILURE)
473                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
474         return ret;
475 }
476
477 /**
478  * Connect to para_server and register the client task.
479  *
480  * \param ct The initialized client task structure.
481  * \param s The scheduler instance to register the client task to.
482  * \param parent The parent node of the client btr node.
483  * \param child The child node of the client node.
484  *
485  * The client task structure given by \a ct  must be allocated and initialized
486  * by \ref client_parse_config() before this function is called.
487  *
488  * \return Standard.
489  */
490 int client_connect(struct client_task *ct, struct sched *s,
491                 struct btr_node *parent, struct btr_node *child)
492 {
493         int ret;
494
495         PARA_NOTICE_LOG("connecting %s:%d\n", ct->conf.hostname_arg,
496                 ct->conf.server_port_arg);
497         ct->scc.fd = -1;
498         ret = para_connect_simple(IPPROTO_TCP, ct->conf.hostname_arg,
499                                                ct->conf.server_port_arg);
500         if (ret < 0)
501                 return ret;
502         ct->scc.fd = ret;
503         ret = mark_fd_nonblocking(ct->scc.fd);
504         if (ret < 0)
505                 goto err_out;
506         ct->status = CL_CONNECTED;
507         ct->btrn[0] = btr_new_node(&(struct btr_node_description)
508                 EMBRACE(.name = "client recv", .parent = NULL, .child = child));
509         ct->btrn[1] = btr_new_node(&(struct btr_node_description)
510                 EMBRACE(.name = "client send", .parent = parent, .child = NULL));
511         ct->task.pre_select = client_pre_select;
512         ct->task.post_select = client_post_select;
513         ct->task.error = 0;
514         sprintf(ct->task.status, "client");
515         register_task(s, &ct->task);
516         return 1;
517 err_out:
518         close(ct->scc.fd);
519         ct->scc.fd = -1;
520         return ret;
521 }
522
523 __noreturn static void print_help_and_die(struct client_task *ct)
524 {
525         struct ggo_help h = DEFINE_GGO_HELP(client);
526         bool d = ct->conf.detailed_help_given;
527
528         ggo_print_help(&h, d? GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS);
529         exit(0);
530 }
531
532 /**
533  * Parse a client configuration.
534  *
535  * \param argc Usual argument count.
536  * \param argv Usual argument vector.
537  * \param ct_ptr Filled in by this function.
538  * \param loglevel If not \p NULL, the number of the loglevel is stored here.
539  *
540  * This checks the command line options given by \a argc and \a argv, sets
541  * default values for the user name and the name of the rsa key file and reads
542  * further options from the config file.
543  *
544  * Upon successful return, \a ct_ptr points to a dynamically allocated and
545  * initialized client task struct.
546  *
547  * \return The number of non-option arguments in \a argc/argv on success,
548  * negative on errors.
549  */
550 int client_parse_config(int argc, char *argv[], struct client_task **ct_ptr,
551                 int *loglevel)
552 {
553         char *home = para_homedir();
554         int ret;
555         struct client_task *ct = para_calloc(sizeof(struct client_task));
556
557         *ct_ptr = ct;
558         ct->scc.fd = -1;
559         ret = -E_CLIENT_SYNTAX;
560         if (client_cmdline_parser(argc, argv, &ct->conf))
561                 goto out;
562         version_handle_flag("client", ct->conf.version_given);
563         if (ct->conf.help_given || ct->conf.detailed_help_given)
564                 print_help_and_die(ct);
565
566         ct->config_file = ct->conf.config_file_given?
567                 para_strdup(ct->conf.config_file_arg) :
568                 make_message("%s/.paraslash/client.conf", home);
569         ret = file_exists(ct->config_file);
570         if (!ret && ct->conf.config_file_given) {
571                 ret = -E_NO_CONFIG;
572                 goto out;
573         }
574         if (ret) {
575                 struct client_cmdline_parser_params params = {
576                         .override = 0,
577                         .initialize = 0,
578                         .check_required = 0,
579                         .check_ambiguity = 0,
580                         .print_errors = 0
581                 };
582                 ret = -E_BAD_CONFIG;
583                 if (client_cmdline_parser_config_file(ct->config_file,
584                         &ct->conf, &params))
585                         goto out;
586         }
587         ct->user = ct->conf.user_given?
588                 para_strdup(ct->conf.user_arg) : para_logname();
589
590         if (ct->conf.key_file_given)
591                 ct->key_file = para_strdup(ct->conf.key_file_arg);
592         else {
593                 ct->key_file = make_message("%s/.paraslash/key.%s",
594                         home, ct->user);
595                 if (!file_exists(ct->key_file)) {
596                         free(ct->key_file);
597                         ct->key_file = make_message("%s/.ssh/id_rsa", home);
598                 }
599         }
600
601         if (loglevel)
602                 *loglevel = get_loglevel_by_name(ct->conf.loglevel_arg);
603         PARA_INFO_LOG("loglevel: %s\n", ct->conf.loglevel_arg);
604         PARA_INFO_LOG("config_file: %s\n", ct->config_file);
605         PARA_INFO_LOG("key_file: %s\n", ct->key_file);
606         ret = ct->conf.inputs_num;
607 out:
608         free(home);
609         if (ret < 0) {
610                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
611                 client_close(ct);
612                 *ct_ptr = NULL;
613         }
614         return ret;
615 }
616
617 /**
618  * Parse the client configuration and open a connection to para_server.
619  *
620  * \param argc See \ref client_parse_config.
621  * \param argv See \ref client_parse_config.
622  * \param ct_ptr See \ref client_parse_config.
623  * \param loglevel See \ref client_parse_config.
624  * \param parent See \ref client_connect().
625  * \param child See \ref client_connect().
626  * \param sched See \ref client_connect().
627  *
628  * This function combines client_parse_config() and client_connect(). It is
629  * considered a syntax error if no command was given, i.e. if the number
630  * of non-option arguments is zero.
631  *
632  * \return Standard.
633  */
634 int client_open(int argc, char *argv[], struct client_task **ct_ptr,
635                 int *loglevel, struct btr_node *parent, struct btr_node *child,
636                 struct sched *sched)
637 {
638         int ret = client_parse_config(argc, argv, ct_ptr, loglevel);
639
640         if (ret < 0)
641                 return ret;
642         if (ret == 0) {
643                 ret = -E_CLIENT_SYNTAX;
644                 goto fail;
645         }
646         ret = client_connect(*ct_ptr, sched, parent, child);
647         if (ret < 0)
648                 goto fail;
649         return 1;
650 fail:
651         client_close(*ct_ptr);
652         *ct_ptr = NULL;
653         return ret;
654 }