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