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