sys: packagelist: allow listing all packages
[project/rpcd.git] / session.c
1 /*
2  * rpcd - UBUS RPC server
3  *
4  *   Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
5  *   Copyright (C) 2013-2014 Jo-Philipp Wich <jow@openwrt.org>
6  *
7  * Permission to use, copy, modify, and/or distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19
20 #define _GNU_SOURCE     /* crypt() */
21
22 #include <libubox/avl-cmp.h>
23 #include <libubox/blobmsg.h>
24 #include <libubox/utils.h>
25 #include <libubus.h>
26 #include <fnmatch.h>
27 #include <glob.h>
28 #include <uci.h>
29 #include <limits.h>
30
31 #ifdef HAVE_SHADOW
32 #include <shadow.h>
33 #endif
34
35 #include <rpcd/session.h>
36
37 static struct avl_tree sessions;
38 static struct blob_buf buf;
39
40 static LIST_HEAD(create_callbacks);
41 static LIST_HEAD(destroy_callbacks);
42
43 enum {
44         RPC_SN_TIMEOUT,
45         __RPC_SN_MAX,
46 };
47 static const struct blobmsg_policy new_policy[__RPC_SN_MAX] = {
48         [RPC_SN_TIMEOUT] = { .name = "timeout", .type = BLOBMSG_TYPE_INT32 },
49 };
50
51 enum {
52         RPC_SI_SID,
53         __RPC_SI_MAX,
54 };
55 static const struct blobmsg_policy sid_policy[__RPC_SI_MAX] = {
56         [RPC_SI_SID] = { .name = "ubus_rpc_session", .type = BLOBMSG_TYPE_STRING },
57 };
58
59 enum {
60         RPC_SS_SID,
61         RPC_SS_VALUES,
62         __RPC_SS_MAX,
63 };
64 static const struct blobmsg_policy set_policy[__RPC_SS_MAX] = {
65         [RPC_SS_SID] = { .name = "ubus_rpc_session", .type = BLOBMSG_TYPE_STRING },
66         [RPC_SS_VALUES] = { .name = "values", .type = BLOBMSG_TYPE_TABLE },
67 };
68
69 enum {
70         RPC_SG_SID,
71         RPC_SG_KEYS,
72         __RPC_SG_MAX,
73 };
74 static const struct blobmsg_policy get_policy[__RPC_SG_MAX] = {
75         [RPC_SG_SID] = { .name = "ubus_rpc_session", .type = BLOBMSG_TYPE_STRING },
76         [RPC_SG_KEYS] = { .name = "keys", .type = BLOBMSG_TYPE_ARRAY },
77 };
78
79 enum {
80         RPC_SA_SID,
81         RPC_SA_SCOPE,
82         RPC_SA_OBJECTS,
83         __RPC_SA_MAX,
84 };
85 static const struct blobmsg_policy acl_policy[__RPC_SA_MAX] = {
86         [RPC_SA_SID] = { .name = "ubus_rpc_session", .type = BLOBMSG_TYPE_STRING },
87         [RPC_SA_SCOPE] = { .name = "scope", .type = BLOBMSG_TYPE_STRING },
88         [RPC_SA_OBJECTS] = { .name = "objects", .type = BLOBMSG_TYPE_ARRAY },
89 };
90
91 enum {
92         RPC_SP_SID,
93         RPC_SP_SCOPE,
94         RPC_SP_OBJECT,
95         RPC_SP_FUNCTION,
96         __RPC_SP_MAX,
97 };
98 static const struct blobmsg_policy perm_policy[__RPC_SP_MAX] = {
99         [RPC_SP_SID] = { .name = "ubus_rpc_session", .type = BLOBMSG_TYPE_STRING },
100         [RPC_SP_SCOPE] = { .name = "scope", .type = BLOBMSG_TYPE_STRING },
101         [RPC_SP_OBJECT] = { .name = "object", .type = BLOBMSG_TYPE_STRING },
102         [RPC_SP_FUNCTION] = { .name = "function", .type = BLOBMSG_TYPE_STRING },
103 };
104
105 enum {
106         RPC_DUMP_SID,
107         RPC_DUMP_TIMEOUT,
108         RPC_DUMP_EXPIRES,
109         RPC_DUMP_DATA,
110         __RPC_DUMP_MAX,
111 };
112 static const struct blobmsg_policy dump_policy[__RPC_DUMP_MAX] = {
113         [RPC_DUMP_SID] = { .name = "ubus_rpc_session", .type = BLOBMSG_TYPE_STRING },
114         [RPC_DUMP_TIMEOUT] = { .name = "timeout", .type = BLOBMSG_TYPE_INT32 },
115         [RPC_DUMP_EXPIRES] = { .name = "expires", .type = BLOBMSG_TYPE_INT32 },
116         [RPC_DUMP_DATA] = { .name = "data", .type = BLOBMSG_TYPE_TABLE },
117 };
118
119 enum {
120         RPC_L_USERNAME,
121         RPC_L_PASSWORD,
122         RPC_L_TIMEOUT,
123         __RPC_L_MAX,
124 };
125 static const struct blobmsg_policy login_policy[__RPC_L_MAX] = {
126         [RPC_L_USERNAME] = { .name = "username", .type = BLOBMSG_TYPE_STRING },
127         [RPC_L_PASSWORD] = { .name = "password", .type = BLOBMSG_TYPE_STRING },
128         [RPC_L_TIMEOUT]  = { .name = "timeout", .type = BLOBMSG_TYPE_INT32 },
129 };
130
131 /*
132  * Keys in the AVL tree contain all pattern characters up to the first wildcard.
133  * To look up entries, start with the last entry that has a key less than or
134  * equal to the method name, then work backwards as long as the AVL key still
135  * matches its counterpart in the object name
136  */
137 #define uh_foreach_matching_acl_prefix(_acl, _avl, _obj, _func)         \
138         for (_acl = avl_find_le_element(_avl, _obj, _acl, avl);                 \
139              _acl;                                                                                                              \
140              _acl = avl_is_first(_avl, &(_acl)->avl) ? NULL :                   \
141                     avl_prev_element((_acl), avl))
142
143 #define uh_foreach_matching_acl(_acl, _avl, _obj, _func)                        \
144         uh_foreach_matching_acl_prefix(_acl, _avl, _obj, _func)                 \
145                 if (!strncmp((_acl)->object, _obj, (_acl)->sort_len) &&         \
146                     !fnmatch((_acl)->object, (_obj), FNM_NOESCAPE) &&           \
147                     !fnmatch((_acl)->function, (_func), FNM_NOESCAPE))
148
149 static int
150 rpc_random(char *dest)
151 {
152         unsigned char buf[16] = { 0 };
153         FILE *f;
154         int i;
155         int ret;
156
157         f = fopen("/dev/urandom", "r");
158         if (!f)
159                 return -1;
160
161         ret = fread(buf, 1, sizeof(buf), f);
162         fclose(f);
163
164         if (ret < 0)
165                 return ret;
166
167         for (i = 0; i < sizeof(buf); i++)
168                 sprintf(dest + (i<<1), "%02x", buf[i]);
169
170         return 0;
171 }
172
173 static void
174 rpc_session_dump_data(struct rpc_session *ses, struct blob_buf *b)
175 {
176         struct rpc_session_data *d;
177
178         avl_for_each_element(&ses->data, d, avl) {
179                 blobmsg_add_field(b, blobmsg_type(d->attr), blobmsg_name(d->attr),
180                                   blobmsg_data(d->attr), blobmsg_data_len(d->attr));
181         }
182 }
183
184 static void
185 rpc_session_dump_acls(struct rpc_session *ses, struct blob_buf *b)
186 {
187         struct rpc_session_acl *acl;
188         struct rpc_session_acl_scope *acl_scope;
189         const char *lastobj = NULL;
190         const char *lastscope = NULL;
191         void *c = NULL, *d = NULL;
192
193         avl_for_each_element(&ses->acls, acl_scope, avl) {
194                 if (!lastscope || strcmp(acl_scope->avl.key, lastscope))
195                 {
196                         if (c) blobmsg_close_table(b, c);
197                         c = blobmsg_open_table(b, acl_scope->avl.key);
198                         lastobj = NULL;
199                 }
200
201                 d = NULL;
202
203                 avl_for_each_element(&acl_scope->acls, acl, avl) {
204                         if (!lastobj || strcmp(acl->object, lastobj))
205                         {
206                                 if (d) blobmsg_close_array(b, d);
207                                 d = blobmsg_open_array(b, acl->object);
208                         }
209
210                         blobmsg_add_string(b, NULL, acl->function);
211                         lastobj = acl->object;
212                 }
213
214                 if (d) blobmsg_close_array(b, d);
215         }
216
217         if (c) blobmsg_close_table(b, c);
218 }
219
220 static void
221 rpc_session_to_blob(struct rpc_session *ses, bool acls)
222 {
223         void *c;
224
225         blob_buf_init(&buf, 0);
226
227         blobmsg_add_string(&buf, "ubus_rpc_session", ses->id);
228         blobmsg_add_u32(&buf, "timeout", ses->timeout);
229         blobmsg_add_u32(&buf, "expires", uloop_timeout_remaining(&ses->t) / 1000);
230
231         if (acls) {
232                 c = blobmsg_open_table(&buf, "acls");
233                 rpc_session_dump_acls(ses, &buf);
234                 blobmsg_close_table(&buf, c);
235         }
236
237         c = blobmsg_open_table(&buf, "data");
238         rpc_session_dump_data(ses, &buf);
239         blobmsg_close_table(&buf, c);
240 }
241
242 static void
243 rpc_session_dump(struct rpc_session *ses, struct ubus_context *ctx,
244                  struct ubus_request_data *req)
245 {
246         rpc_session_to_blob(ses, true);
247
248         ubus_send_reply(ctx, req, buf.head);
249 }
250
251 static void
252 rpc_touch_session(struct rpc_session *ses)
253 {
254         if (ses->timeout > 0)
255                 uloop_timeout_set(&ses->t, ses->timeout * 1000);
256 }
257
258 static void
259 rpc_session_destroy(struct rpc_session *ses)
260 {
261         struct rpc_session_acl *acl, *nacl;
262         struct rpc_session_acl_scope *acl_scope, *nacl_scope;
263         struct rpc_session_data *data, *ndata;
264         struct rpc_session_cb *cb;
265
266         list_for_each_entry(cb, &destroy_callbacks, list)
267                 cb->cb(ses, cb->priv);
268
269         uloop_timeout_cancel(&ses->t);
270
271         avl_for_each_element_safe(&ses->acls, acl_scope, avl, nacl_scope) {
272                 avl_remove_all_elements(&acl_scope->acls, acl, avl, nacl)
273                         free(acl);
274
275                 avl_delete(&ses->acls, &acl_scope->avl);
276                 free(acl_scope);
277         }
278
279         avl_remove_all_elements(&ses->data, data, avl, ndata)
280                 free(data);
281
282         avl_delete(&sessions, &ses->avl);
283         free(ses);
284 }
285
286 static void rpc_session_timeout(struct uloop_timeout *t)
287 {
288         struct rpc_session *ses;
289
290         ses = container_of(t, struct rpc_session, t);
291         rpc_session_destroy(ses);
292 }
293
294 static struct rpc_session *
295 rpc_session_new(void)
296 {
297         struct rpc_session *ses;
298
299         ses = calloc(1, sizeof(*ses));
300
301         if (!ses)
302                 return NULL;
303
304         ses->avl.key = ses->id;
305
306         avl_init(&ses->acls, avl_strcmp, true, NULL);
307         avl_init(&ses->data, avl_strcmp, false, NULL);
308
309         ses->t.cb = rpc_session_timeout;
310
311         return ses;
312 }
313
314 static struct rpc_session *
315 rpc_session_create(int timeout)
316 {
317         struct rpc_session *ses;
318         struct rpc_session_cb *cb;
319
320         ses = rpc_session_new();
321
322         if (!ses)
323                 return NULL;
324
325         if (rpc_random(ses->id))
326                 return NULL;
327
328         ses->timeout = timeout;
329
330         avl_insert(&sessions, &ses->avl);
331
332         rpc_touch_session(ses);
333
334         list_for_each_entry(cb, &create_callbacks, list)
335                 cb->cb(ses, cb->priv);
336
337         return ses;
338 }
339
340 static struct rpc_session *
341 rpc_session_get(const char *id)
342 {
343         struct rpc_session *ses;
344
345         ses = avl_find_element(&sessions, id, ses, avl);
346         if (!ses)
347                 return NULL;
348
349         rpc_touch_session(ses);
350         return ses;
351 }
352
353 static int
354 rpc_handle_create(struct ubus_context *ctx, struct ubus_object *obj,
355                   struct ubus_request_data *req, const char *method,
356                   struct blob_attr *msg)
357 {
358         struct rpc_session *ses;
359         struct blob_attr *tb;
360         int timeout = RPC_DEFAULT_SESSION_TIMEOUT;
361
362         blobmsg_parse(new_policy, __RPC_SN_MAX, &tb, blob_data(msg), blob_len(msg));
363         if (tb)
364                 timeout = blobmsg_get_u32(tb);
365
366         ses = rpc_session_create(timeout);
367         if (ses)
368                 rpc_session_dump(ses, ctx, req);
369
370         return 0;
371 }
372
373 static int
374 rpc_handle_list(struct ubus_context *ctx, struct ubus_object *obj,
375                 struct ubus_request_data *req, const char *method,
376                 struct blob_attr *msg)
377 {
378         struct rpc_session *ses;
379         struct blob_attr *tb;
380
381         blobmsg_parse(sid_policy, __RPC_SI_MAX, &tb, blob_data(msg), blob_len(msg));
382
383         if (!tb) {
384                 avl_for_each_element(&sessions, ses, avl)
385                         rpc_session_dump(ses, ctx, req);
386                 return 0;
387         }
388
389         ses = rpc_session_get(blobmsg_data(tb));
390         if (!ses)
391                 return UBUS_STATUS_NOT_FOUND;
392
393         rpc_session_dump(ses, ctx, req);
394
395         return 0;
396 }
397
398 static int
399 uh_id_len(const char *str)
400 {
401         return strcspn(str, "*?[");
402 }
403
404 static int
405 rpc_session_grant(struct rpc_session *ses,
406                   const char *scope, const char *object, const char *function)
407 {
408         struct rpc_session_acl *acl;
409         struct rpc_session_acl_scope *acl_scope;
410         char *new_scope, *new_obj, *new_func, *new_id;
411         int id_len;
412
413         if (!object || !function)
414                 return UBUS_STATUS_INVALID_ARGUMENT;
415
416         acl_scope = avl_find_element(&ses->acls, scope, acl_scope, avl);
417
418         if (acl_scope) {
419                 uh_foreach_matching_acl_prefix(acl, &acl_scope->acls, object, function) {
420                         if (!strcmp(acl->object, object) &&
421                                 !strcmp(acl->function, function))
422                                 return 0;
423                 }
424         }
425
426         if (!acl_scope) {
427                 acl_scope = calloc_a(sizeof(*acl_scope),
428                                      &new_scope, strlen(scope) + 1);
429
430                 if (!acl_scope)
431                         return UBUS_STATUS_UNKNOWN_ERROR;
432
433                 acl_scope->avl.key = strcpy(new_scope, scope);
434                 avl_init(&acl_scope->acls, avl_strcmp, true, NULL);
435                 avl_insert(&ses->acls, &acl_scope->avl);
436         }
437
438         id_len = uh_id_len(object);
439         acl = calloc_a(sizeof(*acl),
440                 &new_obj, strlen(object) + 1,
441                 &new_func, strlen(function) + 1,
442                 &new_id, id_len + 1);
443
444         if (!acl)
445                 return UBUS_STATUS_UNKNOWN_ERROR;
446
447         acl->object = strcpy(new_obj, object);
448         acl->function = strcpy(new_func, function);
449         acl->avl.key = strncpy(new_id, object, id_len);
450         avl_insert(&acl_scope->acls, &acl->avl);
451
452         return 0;
453 }
454
455 static int
456 rpc_session_revoke(struct rpc_session *ses,
457                    const char *scope, const char *object, const char *function)
458 {
459         struct rpc_session_acl *acl, *next;
460         struct rpc_session_acl_scope *acl_scope;
461         int id_len;
462         char *id;
463
464         acl_scope = avl_find_element(&ses->acls, scope, acl_scope, avl);
465
466         if (!acl_scope)
467                 return 0;
468
469         if (!object && !function) {
470                 avl_remove_all_elements(&acl_scope->acls, acl, avl, next)
471                         free(acl);
472                 avl_delete(&ses->acls, &acl_scope->avl);
473                 free(acl_scope);
474                 return 0;
475         }
476
477         id_len = uh_id_len(object);
478         id = alloca(id_len + 1);
479         strncpy(id, object, id_len);
480         id[id_len] = 0;
481
482         acl = avl_find_element(&acl_scope->acls, id, acl, avl);
483         while (acl) {
484                 if (!avl_is_last(&acl_scope->acls, &acl->avl))
485                         next = avl_next_element(acl, avl);
486                 else
487                         next = NULL;
488
489                 if (strcmp(id, acl->avl.key) != 0)
490                         break;
491
492                 if (!strcmp(acl->object, object) &&
493                     !strcmp(acl->function, function)) {
494                         avl_delete(&acl_scope->acls, &acl->avl);
495                         free(acl);
496                 }
497                 acl = next;
498         }
499
500         if (avl_is_empty(&acl_scope->acls)) {
501                 avl_delete(&ses->acls, &acl_scope->avl);
502                 free(acl_scope);
503         }
504
505         return 0;
506 }
507
508
509 static int
510 rpc_handle_acl(struct ubus_context *ctx, struct ubus_object *obj,
511                struct ubus_request_data *req, const char *method,
512                struct blob_attr *msg)
513 {
514         struct rpc_session *ses;
515         struct blob_attr *tb[__RPC_SA_MAX];
516         struct blob_attr *attr, *sattr;
517         const char *object, *function;
518         const char *scope = "ubus";
519         int rem1, rem2;
520
521         int (*cb)(struct rpc_session *ses,
522                   const char *scope, const char *object, const char *function);
523
524         blobmsg_parse(acl_policy, __RPC_SA_MAX, tb, blob_data(msg), blob_len(msg));
525
526         if (!tb[RPC_SA_SID])
527                 return UBUS_STATUS_INVALID_ARGUMENT;
528
529         ses = rpc_session_get(blobmsg_data(tb[RPC_SA_SID]));
530         if (!ses)
531                 return UBUS_STATUS_NOT_FOUND;
532
533         if (tb[RPC_SA_SCOPE])
534                 scope = blobmsg_data(tb[RPC_SA_SCOPE]);
535
536         if (!strcmp(method, "grant"))
537                 cb = rpc_session_grant;
538         else
539                 cb = rpc_session_revoke;
540
541         if (!tb[RPC_SA_OBJECTS])
542                 return cb(ses, scope, NULL, NULL);
543
544         blobmsg_for_each_attr(attr, tb[RPC_SA_OBJECTS], rem1) {
545                 if (blobmsg_type(attr) != BLOBMSG_TYPE_ARRAY)
546                         continue;
547
548                 object = NULL;
549                 function = NULL;
550
551                 blobmsg_for_each_attr(sattr, attr, rem2) {
552                         if (blobmsg_type(sattr) != BLOBMSG_TYPE_STRING)
553                                 continue;
554
555                         if (!object)
556                                 object = blobmsg_data(sattr);
557                         else if (!function)
558                                 function = blobmsg_data(sattr);
559                         else
560                                 break;
561                 }
562
563                 if (object && function)
564                         cb(ses, scope, object, function);
565         }
566
567         return 0;
568 }
569
570 static bool
571 rpc_session_acl_allowed(struct rpc_session *ses, const char *scope,
572                         const char *obj, const char *fun)
573 {
574         struct rpc_session_acl *acl;
575         struct rpc_session_acl_scope *acl_scope;
576
577         acl_scope = avl_find_element(&ses->acls, scope, acl_scope, avl);
578
579         if (acl_scope) {
580                 uh_foreach_matching_acl(acl, &acl_scope->acls, obj, fun)
581                         return true;
582         }
583
584         return false;
585 }
586
587 static int
588 rpc_handle_access(struct ubus_context *ctx, struct ubus_object *obj,
589                   struct ubus_request_data *req, const char *method,
590                   struct blob_attr *msg)
591 {
592         struct rpc_session *ses;
593         struct blob_attr *tb[__RPC_SP_MAX];
594         const char *scope = "ubus";
595         bool allow;
596
597         blobmsg_parse(perm_policy, __RPC_SP_MAX, tb, blob_data(msg), blob_len(msg));
598
599         if (!tb[RPC_SP_SID])
600                 return UBUS_STATUS_INVALID_ARGUMENT;
601
602         ses = rpc_session_get(blobmsg_data(tb[RPC_SP_SID]));
603         if (!ses)
604                 return UBUS_STATUS_NOT_FOUND;
605
606         blob_buf_init(&buf, 0);
607
608         if (tb[RPC_SP_OBJECT] && tb[RPC_SP_FUNCTION])
609         {
610                 if (tb[RPC_SP_SCOPE])
611                         scope = blobmsg_data(tb[RPC_SP_SCOPE]);
612
613                 allow = rpc_session_acl_allowed(ses, scope,
614                                                 blobmsg_data(tb[RPC_SP_OBJECT]),
615                                                 blobmsg_data(tb[RPC_SP_FUNCTION]));
616
617                 blobmsg_add_u8(&buf, "access", allow);
618         }
619         else
620         {
621                 rpc_session_dump_acls(ses, &buf);
622         }
623
624         ubus_send_reply(ctx, req, buf.head);
625
626         return 0;
627 }
628
629 static void
630 rpc_session_set(struct rpc_session *ses, const char *key, struct blob_attr *val)
631 {
632         struct rpc_session_data *data;
633
634         data = avl_find_element(&ses->data, key, data, avl);
635         if (data) {
636                 avl_delete(&ses->data, &data->avl);
637                 free(data);
638         }
639
640         data = calloc(1, sizeof(*data) + blob_pad_len(val));
641         if (!data)
642                 return;
643
644         memcpy(data->attr, val, blob_pad_len(val));
645         data->avl.key = blobmsg_name(data->attr);
646         avl_insert(&ses->data, &data->avl);
647 }
648
649 static int
650 rpc_handle_set(struct ubus_context *ctx, struct ubus_object *obj,
651                struct ubus_request_data *req, const char *method,
652                struct blob_attr *msg)
653 {
654         struct rpc_session *ses;
655         struct blob_attr *tb[__RPC_SS_MAX];
656         struct blob_attr *attr;
657         int rem;
658
659         blobmsg_parse(set_policy, __RPC_SS_MAX, tb, blob_data(msg), blob_len(msg));
660
661         if (!tb[RPC_SS_SID] || !tb[RPC_SS_VALUES])
662                 return UBUS_STATUS_INVALID_ARGUMENT;
663
664         ses = rpc_session_get(blobmsg_data(tb[RPC_SS_SID]));
665         if (!ses)
666                 return UBUS_STATUS_NOT_FOUND;
667
668         blobmsg_for_each_attr(attr, tb[RPC_SS_VALUES], rem) {
669                 if (!blobmsg_name(attr)[0])
670                         continue;
671
672                 rpc_session_set(ses, blobmsg_name(attr), attr);
673         }
674
675         return 0;
676 }
677
678 static int
679 rpc_handle_get(struct ubus_context *ctx, struct ubus_object *obj,
680                struct ubus_request_data *req, const char *method,
681                struct blob_attr *msg)
682 {
683         struct rpc_session *ses;
684         struct rpc_session_data *data;
685         struct blob_attr *tb[__RPC_SG_MAX];
686         struct blob_attr *attr;
687         void *c;
688         int rem;
689
690         blobmsg_parse(get_policy, __RPC_SG_MAX, tb, blob_data(msg), blob_len(msg));
691
692         if (!tb[RPC_SG_SID])
693                 return UBUS_STATUS_INVALID_ARGUMENT;
694
695         ses = rpc_session_get(blobmsg_data(tb[RPC_SG_SID]));
696         if (!ses)
697                 return UBUS_STATUS_NOT_FOUND;
698
699         blob_buf_init(&buf, 0);
700         c = blobmsg_open_table(&buf, "values");
701
702         if (tb[RPC_SG_KEYS])
703                 blobmsg_for_each_attr(attr, tb[RPC_SG_KEYS], rem) {
704                         if (blobmsg_type(attr) != BLOBMSG_TYPE_STRING)
705                                 continue;
706
707                         data = avl_find_element(&ses->data, blobmsg_data(attr), data, avl);
708                         if (!data)
709                                 continue;
710
711                         blobmsg_add_field(&buf, blobmsg_type(data->attr),
712                                           blobmsg_name(data->attr),
713                                           blobmsg_data(data->attr),
714                                           blobmsg_data_len(data->attr));
715                 }
716         else
717                 rpc_session_dump_data(ses, &buf);
718
719         blobmsg_close_table(&buf, c);
720         ubus_send_reply(ctx, req, buf.head);
721
722         return 0;
723 }
724
725 static int
726 rpc_handle_unset(struct ubus_context *ctx, struct ubus_object *obj,
727                  struct ubus_request_data *req, const char *method,
728                  struct blob_attr *msg)
729 {
730         struct rpc_session *ses;
731         struct rpc_session_data *data, *ndata;
732         struct blob_attr *tb[__RPC_SA_MAX];
733         struct blob_attr *attr;
734         int rem;
735
736         blobmsg_parse(get_policy, __RPC_SG_MAX, tb, blob_data(msg), blob_len(msg));
737
738         if (!tb[RPC_SG_SID])
739                 return UBUS_STATUS_INVALID_ARGUMENT;
740
741         ses = rpc_session_get(blobmsg_data(tb[RPC_SG_SID]));
742         if (!ses)
743                 return UBUS_STATUS_NOT_FOUND;
744
745         if (!tb[RPC_SG_KEYS]) {
746                 avl_remove_all_elements(&ses->data, data, avl, ndata)
747                         free(data);
748                 return 0;
749         }
750
751         blobmsg_for_each_attr(attr, tb[RPC_SG_KEYS], rem) {
752                 if (blobmsg_type(attr) != BLOBMSG_TYPE_STRING)
753                         continue;
754
755                 data = avl_find_element(&ses->data, blobmsg_data(attr), data, avl);
756                 if (!data)
757                         continue;
758
759                 avl_delete(&ses->data, &data->avl);
760                 free(data);
761         }
762
763         return 0;
764 }
765
766 static int
767 rpc_handle_destroy(struct ubus_context *ctx, struct ubus_object *obj,
768                    struct ubus_request_data *req, const char *method,
769                    struct blob_attr *msg)
770 {
771         struct rpc_session *ses;
772         struct blob_attr *tb;
773
774         blobmsg_parse(sid_policy, __RPC_SI_MAX, &tb, blob_data(msg), blob_len(msg));
775
776         if (!tb)
777                 return UBUS_STATUS_INVALID_ARGUMENT;
778
779         if (!strcmp(blobmsg_get_string(tb), RPC_DEFAULT_SESSION_ID))
780                 return UBUS_STATUS_PERMISSION_DENIED;
781
782         ses = rpc_session_get(blobmsg_data(tb));
783         if (!ses)
784                 return UBUS_STATUS_NOT_FOUND;
785
786         rpc_session_destroy(ses);
787
788         return 0;
789 }
790
791
792 static bool
793 rpc_login_test_password(const char *hash, const char *password)
794 {
795         char *crypt_hash;
796
797         /* password is not set */
798         if (!hash || !*hash || !strcmp(hash, "!") || !strcmp(hash, "x"))
799         {
800                 return true;
801         }
802
803         /* password hash refers to shadow/passwd */
804         else if (!strncmp(hash, "$p$", 3))
805         {
806 #ifdef HAVE_SHADOW
807                 struct spwd *sp = getspnam(hash + 3);
808
809                 if (!sp)
810                         return false;
811
812                 return rpc_login_test_password(sp->sp_pwdp, password);
813 #else
814                 struct passwd *pw = getpwnam(hash + 3);
815
816                 if (!pw)
817                         return false;
818
819                 return rpc_login_test_password(pw->pw_passwd, password);
820 #endif
821         }
822
823         crypt_hash = crypt(password, hash);
824
825         return !strcmp(crypt_hash, hash);
826 }
827
828 static struct uci_section *
829 rpc_login_test_login(struct uci_context *uci,
830                      const char *username, const char *password)
831 {
832         struct uci_package *p = NULL;
833         struct uci_section *s;
834         struct uci_element *e;
835         struct uci_ptr ptr = { .package = "rpcd" };
836
837         uci_load(uci, ptr.package, &p);
838
839         if (!p)
840                 return false;
841
842         uci_foreach_element(&p->sections, e)
843         {
844                 s = uci_to_section(e);
845
846                 if (strcmp(s->type, "login"))
847                         continue;
848
849                 ptr.section = s->e.name;
850                 ptr.s = NULL;
851
852                 /* test for matching username */
853                 ptr.option = "username";
854                 ptr.o = NULL;
855
856                 if (uci_lookup_ptr(uci, &ptr, NULL, true))
857                         continue;
858
859                 if (ptr.o->type != UCI_TYPE_STRING)
860                         continue;
861
862                 if (strcmp(ptr.o->v.string, username))
863                         continue;
864
865                 /* If password is NULL, we're restoring ACLs for an existing session,
866                  * in this case do not check the password again. */
867                 if (!password)
868                         return ptr.s;
869
870                 /* test for matching password */
871                 ptr.option = "password";
872                 ptr.o = NULL;
873
874                 if (uci_lookup_ptr(uci, &ptr, NULL, true))
875                         continue;
876
877                 if (ptr.o->type != UCI_TYPE_STRING)
878                         continue;
879
880                 if (rpc_login_test_password(ptr.o->v.string, password))
881                         return ptr.s;
882         }
883
884         return NULL;
885 }
886
887 static bool
888 rpc_login_test_permission(struct uci_section *s,
889                           const char *perm, const char *group)
890 {
891         const char *p;
892         struct uci_option *o;
893         struct uci_element *e, *l;
894
895         /* If the login section is not provided, we're setting up acls for the
896          * default session, in this case uncondionally allow access to the
897          * "unauthenticated" access group */
898         if (!s) {
899                 return !strcmp(group, "unauthenticated");
900         }
901
902         uci_foreach_element(&s->options, e)
903         {
904                 o = uci_to_option(e);
905
906                 if (o->type != UCI_TYPE_LIST)
907                         continue;
908
909                 if (strcmp(o->e.name, perm))
910                         continue;
911
912                 /* Match negative expressions first. If a negative expression matches
913                  * the current group name then deny access. */
914                 uci_foreach_element(&o->v.list, l) {
915                         p = l->name;
916
917                         if (!p || *p != '!')
918                                 continue;
919
920                         while (isspace(*++p));
921
922                         if (!*p)
923                                 continue;
924
925                         if (!fnmatch(p, group, 0))
926                                 return false;
927                 }
928
929                 uci_foreach_element(&o->v.list, l) {
930                         if (!l->name || !*l->name || *l->name == '!')
931                                 continue;
932
933                         if (!fnmatch(l->name, group, 0))
934                                 return true;
935                 }
936         }
937
938         /* make sure that write permission implies read permission */
939         if (!strcmp(perm, "read"))
940                 return rpc_login_test_permission(s, "write", group);
941
942         return false;
943 }
944
945 static void
946 rpc_login_setup_acl_scope(struct rpc_session *ses,
947                           struct blob_attr *acl_perm,
948                           struct blob_attr *acl_scope)
949 {
950         struct blob_attr *acl_obj, *acl_func;
951         int rem, rem2;
952
953         /*
954          * Parse ACL scopes in table notation.
955          *
956          *      "<scope>": {
957          *              "<object>": [
958          *                      "<function>",
959          *                      "<function>",
960          *                      ...
961          *              ]
962          *      }
963          */
964         if (blobmsg_type(acl_scope) == BLOBMSG_TYPE_TABLE) {
965                 blobmsg_for_each_attr(acl_obj, acl_scope, rem) {
966                         if (blobmsg_type(acl_obj) != BLOBMSG_TYPE_ARRAY)
967                                 continue;
968
969                         blobmsg_for_each_attr(acl_func, acl_obj, rem2) {
970                                 if (blobmsg_type(acl_func) != BLOBMSG_TYPE_STRING)
971                                         continue;
972
973                                 rpc_session_grant(ses, blobmsg_name(acl_scope),
974                                                        blobmsg_name(acl_obj),
975                                                        blobmsg_data(acl_func));
976                         }
977                 }
978         }
979
980         /*
981          * Parse ACL scopes in array notation. The permission ("read" or "write")
982          * will be used as function name for each object.
983          *
984          *      "<scope>": [
985          *              "<object>",
986          *              "<object>",
987          *              ...
988          *      ]
989          */
990         else if (blobmsg_type(acl_scope) == BLOBMSG_TYPE_ARRAY) {
991                 blobmsg_for_each_attr(acl_obj, acl_scope, rem) {
992                         if (blobmsg_type(acl_obj) != BLOBMSG_TYPE_STRING)
993                                 continue;
994
995                         rpc_session_grant(ses, blobmsg_name(acl_scope),
996                                                blobmsg_data(acl_obj),
997                                                blobmsg_name(acl_perm));
998                 }
999         }
1000 }
1001
1002 static void
1003 rpc_login_setup_acl_file(struct rpc_session *ses, struct uci_section *login,
1004                          const char *path)
1005 {
1006         struct blob_buf acl = { 0 };
1007         struct blob_attr *acl_group, *acl_perm, *acl_scope;
1008         int rem, rem2, rem3;
1009
1010         blob_buf_init(&acl, 0);
1011
1012         if (!blobmsg_add_json_from_file(&acl, path)) {
1013                 fprintf(stderr, "Failed to parse %s\n", path);
1014                 goto out;
1015         }
1016
1017         /* Iterate access groups in toplevel object */
1018         blob_for_each_attr(acl_group, acl.head, rem) {
1019                 /* Iterate permission objects in each access group object */
1020                 blobmsg_for_each_attr(acl_perm, acl_group, rem2) {
1021                         if (blobmsg_type(acl_perm) != BLOBMSG_TYPE_TABLE)
1022                                 continue;
1023
1024                         /* Only "read" and "write" permissions are defined */
1025                         if (strcmp(blobmsg_name(acl_perm), "read") &&
1026                                 strcmp(blobmsg_name(acl_perm), "write"))
1027                                 continue;
1028
1029                         /*
1030                          * Check if the current user context specifies the current
1031                          * "read" or "write" permission in the given access group.
1032                          */
1033                         if (!rpc_login_test_permission(login, blobmsg_name(acl_perm),
1034                                                               blobmsg_name(acl_group)))
1035                                 continue;
1036
1037                         /* Iterate scope objects within the permission object */
1038                         blobmsg_for_each_attr(acl_scope, acl_perm, rem3) {
1039                                 /* Setup the scopes of the access group */
1040                                 rpc_login_setup_acl_scope(ses, acl_perm, acl_scope);
1041
1042                                 /*
1043                                  * Add the access group itself as object to the "access-group"
1044                                  * meta scope and the the permission level ("read" or "write")
1045                                  * as function, so
1046                                  *      "<group>": {
1047                                  *              "<permission>": {
1048                                  *                      "<scope>": ...
1049                                  *              }
1050                                  *      }
1051                                  * becomes
1052                                  *      "access-group": {
1053                                  *              "<group>": [
1054                                  *                      "<permission>"
1055                                  *              ]
1056                                  *      }
1057                                  *
1058                                  * This allows session clients to easily query the allowed
1059                                  * access groups without having to test access of each single
1060                                  * <scope>/<object>/<function> tuple defined in a group.
1061                                  */
1062                                 rpc_session_grant(ses, "access-group",
1063                                                        blobmsg_name(acl_group),
1064                                                        blobmsg_name(acl_perm));
1065                         }
1066                 }
1067         }
1068
1069 out:
1070         blob_buf_free(&acl);
1071 }
1072
1073 static void
1074 rpc_login_setup_acls(struct rpc_session *ses, struct uci_section *login)
1075 {
1076         int i;
1077         glob_t gl;
1078
1079         if (glob(RPC_SESSION_ACL_DIR "/*.json", 0, NULL, &gl))
1080                 return;
1081
1082         for (i = 0; i < gl.gl_pathc; i++)
1083                 rpc_login_setup_acl_file(ses, login, gl.gl_pathv[i]);
1084
1085         globfree(&gl);
1086 }
1087
1088 static int
1089 rpc_handle_login(struct ubus_context *ctx, struct ubus_object *obj,
1090                  struct ubus_request_data *req, const char *method,
1091                  struct blob_attr *msg)
1092 {
1093         struct uci_context *uci = NULL;
1094         struct uci_section *login;
1095         struct rpc_session *ses;
1096         struct blob_attr *tb[__RPC_L_MAX];
1097         int timeout = RPC_DEFAULT_SESSION_TIMEOUT;
1098         int rv = 0;
1099
1100         blobmsg_parse(login_policy, __RPC_L_MAX, tb, blob_data(msg), blob_len(msg));
1101
1102         if (!tb[RPC_L_USERNAME] || !tb[RPC_L_PASSWORD]) {
1103                 rv = UBUS_STATUS_INVALID_ARGUMENT;
1104                 goto out;
1105         }
1106
1107         uci = uci_alloc_context();
1108
1109         if (!uci) {
1110                 rv = UBUS_STATUS_UNKNOWN_ERROR;
1111                 goto out;
1112         }
1113
1114         login = rpc_login_test_login(uci, blobmsg_get_string(tb[RPC_L_USERNAME]),
1115                                           blobmsg_get_string(tb[RPC_L_PASSWORD]));
1116
1117         if (!login) {
1118                 rv = UBUS_STATUS_PERMISSION_DENIED;
1119                 goto out;
1120         }
1121
1122         if (tb[RPC_L_TIMEOUT])
1123                 timeout = blobmsg_get_u32(tb[RPC_L_TIMEOUT]);
1124
1125         ses = rpc_session_create(timeout);
1126
1127         if (!ses) {
1128                 rv = UBUS_STATUS_UNKNOWN_ERROR;
1129                 goto out;
1130         }
1131
1132         rpc_login_setup_acls(ses, login);
1133
1134         rpc_session_set(ses, "user", tb[RPC_L_USERNAME]);
1135         rpc_session_dump(ses, ctx, req);
1136
1137 out:
1138         if (uci)
1139                 uci_free_context(uci);
1140
1141         return rv;
1142 }
1143
1144
1145 static bool
1146 rpc_validate_sid(const char *id)
1147 {
1148         if (!id)
1149                 return false;
1150
1151         if (strlen(id) != RPC_SID_LEN)
1152                 return false;
1153
1154         while (*id)
1155                 if (!isxdigit(*id++))
1156                         return false;
1157
1158         return true;
1159 }
1160
1161 static int
1162 rpc_blob_to_file(const char *path, struct blob_attr *attr)
1163 {
1164         int fd, len;
1165
1166         fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0600);
1167
1168         if (fd < 0)
1169                 return fd;
1170
1171         len = write(fd, attr, blob_pad_len(attr));
1172
1173         close(fd);
1174
1175         if (len != blob_pad_len(attr))
1176         {
1177                 unlink(path);
1178                 return -1;
1179         }
1180
1181         return len;
1182 }
1183
1184 static struct blob_attr *
1185 rpc_blob_from_file(const char *path)
1186 {
1187         int fd = -1, len;
1188         struct stat s;
1189         struct blob_attr head, *attr = NULL;
1190
1191         if (stat(path, &s) || !S_ISREG(s.st_mode))
1192                 return NULL;
1193
1194         fd = open(path, O_RDONLY);
1195
1196         if (fd < 0)
1197                 goto fail;
1198
1199         len = read(fd, &head, sizeof(head));
1200
1201         if (len != sizeof(head) || blob_pad_len(&head) != s.st_size)
1202                 goto fail;
1203
1204         attr = calloc(1, s.st_size);
1205
1206         if (!attr)
1207                 goto fail;
1208
1209         memcpy(attr, &head, sizeof(head));
1210
1211         len += read(fd, (char *)attr + sizeof(head), s.st_size - sizeof(head));
1212
1213         if (len != blob_pad_len(&head))
1214                 goto fail;
1215
1216         close(fd);
1217
1218         return attr;
1219
1220 fail:
1221         if (fd >= 0)
1222                 close(fd);
1223
1224         if (attr)
1225                 free(attr);
1226
1227         return NULL;
1228 }
1229
1230 static bool
1231 rpc_session_from_blob(struct uci_context *uci, struct blob_attr *attr)
1232 {
1233         int i, rem;
1234         const char *user = NULL;
1235         struct rpc_session *ses;
1236         struct uci_section *login;
1237         struct blob_attr *tb[__RPC_DUMP_MAX], *data;
1238
1239         blobmsg_parse(dump_policy, __RPC_DUMP_MAX, tb,
1240                       blob_data(attr), blob_len(attr));
1241
1242         for (i = 0; i < __RPC_DUMP_MAX; i++)
1243                 if (!tb[i])
1244                         return false;
1245
1246         ses = rpc_session_new();
1247
1248         if (!ses)
1249                 return false;
1250
1251         memcpy(ses->id, blobmsg_data(tb[RPC_DUMP_SID]), RPC_SID_LEN);
1252
1253         ses->timeout = blobmsg_get_u32(tb[RPC_DUMP_TIMEOUT]);
1254
1255         blobmsg_for_each_attr(data, tb[RPC_DUMP_DATA], rem) {
1256                 rpc_session_set(ses, blobmsg_name(data), data);
1257
1258                 if (!strcmp(blobmsg_name(data), "username"))
1259                         user = blobmsg_get_string(data);
1260         }
1261
1262         if (uci && user) {
1263                 login = rpc_login_test_login(uci, user, NULL);
1264                 if (login)
1265                         rpc_login_setup_acls(ses, login);
1266         }
1267
1268         avl_insert(&sessions, &ses->avl);
1269
1270         uloop_timeout_set(&ses->t, blobmsg_get_u32(tb[RPC_DUMP_EXPIRES]) * 1000);
1271
1272         return true;
1273 }
1274
1275 int rpc_session_api_init(struct ubus_context *ctx)
1276 {
1277         struct rpc_session *ses;
1278
1279         static const struct ubus_method session_methods[] = {
1280                 UBUS_METHOD("create",  rpc_handle_create,  new_policy),
1281                 UBUS_METHOD("list",    rpc_handle_list,    sid_policy),
1282                 UBUS_METHOD("grant",   rpc_handle_acl,     acl_policy),
1283                 UBUS_METHOD("revoke",  rpc_handle_acl,     acl_policy),
1284                 UBUS_METHOD("access",  rpc_handle_access,  perm_policy),
1285                 UBUS_METHOD("set",     rpc_handle_set,     set_policy),
1286                 UBUS_METHOD("get",     rpc_handle_get,     get_policy),
1287                 UBUS_METHOD("unset",   rpc_handle_unset,   get_policy),
1288                 UBUS_METHOD("destroy", rpc_handle_destroy, sid_policy),
1289                 UBUS_METHOD("login",   rpc_handle_login,   login_policy),
1290         };
1291
1292         static struct ubus_object_type session_type =
1293                 UBUS_OBJECT_TYPE("luci-rpc-session", session_methods);
1294
1295         static struct ubus_object obj = {
1296                 .name = "session",
1297                 .type = &session_type,
1298                 .methods = session_methods,
1299                 .n_methods = ARRAY_SIZE(session_methods),
1300         };
1301
1302         avl_init(&sessions, avl_strcmp, false, NULL);
1303
1304         /* setup the default session */
1305         ses = rpc_session_new();
1306
1307         if (ses) {
1308                 strcpy(ses->id, RPC_DEFAULT_SESSION_ID);
1309                 rpc_login_setup_acls(ses, NULL);
1310                 avl_insert(&sessions, &ses->avl);
1311         }
1312
1313         return ubus_add_object(ctx, &obj);
1314 }
1315
1316 bool rpc_session_access(const char *sid, const char *scope,
1317                         const char *object, const char *function)
1318 {
1319         struct rpc_session *ses = rpc_session_get(sid);
1320
1321         if (!ses)
1322                 return false;
1323
1324         return rpc_session_acl_allowed(ses, scope, object, function);
1325 }
1326
1327 void rpc_session_create_cb(struct rpc_session_cb *cb)
1328 {
1329         if (cb && cb->cb)
1330                 list_add(&cb->list, &create_callbacks);
1331 }
1332
1333 void rpc_session_destroy_cb(struct rpc_session_cb *cb)
1334 {
1335         if (cb && cb->cb)
1336                 list_add(&cb->list, &destroy_callbacks);
1337 }
1338
1339 void rpc_session_freeze(void)
1340 {
1341         struct stat s;
1342         struct rpc_session *ses;
1343         char path[PATH_MAX];
1344
1345         if (stat(RPC_SESSION_DIRECTORY, &s))
1346                 mkdir(RPC_SESSION_DIRECTORY, 0700);
1347
1348         avl_for_each_element(&sessions, ses, avl) {
1349                 /* skip default session */
1350                 if (!strcmp(ses->id, RPC_DEFAULT_SESSION_ID))
1351                         continue;
1352
1353                 snprintf(path, sizeof(path) - 1, RPC_SESSION_DIRECTORY "/%s", ses->id);
1354                 rpc_session_to_blob(ses, false);
1355                 rpc_blob_to_file(path, buf.head);
1356         }
1357 }
1358
1359 void rpc_session_thaw(void)
1360 {
1361         DIR *d;
1362         char path[PATH_MAX];
1363         struct dirent *e;
1364         struct blob_attr *attr;
1365         struct uci_context *uci;
1366
1367         d = opendir(RPC_SESSION_DIRECTORY);
1368
1369         if (!d)
1370                 return;
1371
1372         uci = uci_alloc_context();
1373
1374         if (!uci)
1375                 return;
1376
1377         while ((e = readdir(d)) != NULL) {
1378                 if (!rpc_validate_sid(e->d_name))
1379                         continue;
1380
1381                 snprintf(path, sizeof(path) - 1,
1382                          RPC_SESSION_DIRECTORY "/%s", e->d_name);
1383
1384                 attr = rpc_blob_from_file(path);
1385
1386                 if (attr) {
1387                         rpc_session_from_blob(uci, attr);
1388                         free(attr);
1389                 }
1390
1391                 unlink(path);
1392         }
1393
1394         closedir(d);
1395
1396         uci_free_context(uci);
1397 }