session: disallow destroying the null session
[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 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 = "sid", .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 = "sid", .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 = "sid", .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 = "sid", .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 = "sid", .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_ACLS,
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 = "sid", .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_ACLS] = { .name = "acls", .type = BLOBMSG_TYPE_TABLE },
109         [RPC_DUMP_DATA] = { .name = "data", .type = BLOBMSG_TYPE_TABLE },
110 };
111
112 enum {
113         RPC_L_USERNAME,
114         RPC_L_PASSWORD,
115         RPC_L_TIMEOUT,
116         __RPC_L_MAX,
117 };
118 static const struct blobmsg_policy login_policy[__RPC_L_MAX] = {
119         [RPC_L_USERNAME] = { .name = "username", .type = BLOBMSG_TYPE_STRING },
120         [RPC_L_PASSWORD] = { .name = "password", .type = BLOBMSG_TYPE_STRING },
121         [RPC_L_TIMEOUT]  = { .name = "timeout", .type = BLOBMSG_TYPE_INT32 },
122 };
123
124 /*
125  * Keys in the AVL tree contain all pattern characters up to the first wildcard.
126  * To look up entries, start with the last entry that has a key less than or
127  * equal to the method name, then work backwards as long as the AVL key still
128  * matches its counterpart in the object name
129  */
130 #define uh_foreach_matching_acl_prefix(_acl, _avl, _obj, _func)         \
131         for (_acl = avl_find_le_element(_avl, _obj, _acl, avl);                 \
132              _acl;                                                                                                              \
133              _acl = avl_is_first(_avl, &(_acl)->avl) ? NULL :                   \
134                     avl_prev_element((_acl), avl))
135
136 #define uh_foreach_matching_acl(_acl, _avl, _obj, _func)                        \
137         uh_foreach_matching_acl_prefix(_acl, _avl, _obj, _func)                 \
138                 if (!strncmp((_acl)->object, _obj, (_acl)->sort_len) &&         \
139                     !fnmatch((_acl)->object, (_obj), FNM_NOESCAPE) &&           \
140                     !fnmatch((_acl)->function, (_func), FNM_NOESCAPE))
141
142 static void
143 rpc_random(char *dest)
144 {
145         unsigned char buf[16] = { 0 };
146         FILE *f;
147         int i;
148
149         f = fopen("/dev/urandom", "r");
150         if (!f)
151                 return;
152
153         fread(buf, 1, sizeof(buf), f);
154         fclose(f);
155
156         for (i = 0; i < sizeof(buf); i++)
157                 sprintf(dest + (i<<1), "%02x", buf[i]);
158 }
159
160 static void
161 rpc_session_dump_data(struct rpc_session *ses, struct blob_buf *b)
162 {
163         struct rpc_session_data *d;
164
165         avl_for_each_element(&ses->data, d, avl) {
166                 blobmsg_add_field(b, blobmsg_type(d->attr), blobmsg_name(d->attr),
167                                   blobmsg_data(d->attr), blobmsg_data_len(d->attr));
168         }
169 }
170
171 static void
172 rpc_session_dump_acls(struct rpc_session *ses, struct blob_buf *b)
173 {
174         struct rpc_session_acl *acl;
175         struct rpc_session_acl_scope *acl_scope;
176         const char *lastobj = NULL;
177         const char *lastscope = NULL;
178         void *c = NULL, *d = NULL;
179
180         avl_for_each_element(&ses->acls, acl_scope, avl) {
181                 if (!lastscope || strcmp(acl_scope->avl.key, lastscope))
182                 {
183                         if (c) blobmsg_close_table(b, c);
184                         c = blobmsg_open_table(b, acl_scope->avl.key);
185                         lastobj = NULL;
186                 }
187
188                 d = NULL;
189
190                 avl_for_each_element(&acl_scope->acls, acl, avl) {
191                         if (!lastobj || strcmp(acl->object, lastobj))
192                         {
193                                 if (d) blobmsg_close_array(b, d);
194                                 d = blobmsg_open_array(b, acl->object);
195                         }
196
197                         blobmsg_add_string(b, NULL, acl->function);
198                         lastobj = acl->object;
199                 }
200
201                 if (d) blobmsg_close_array(b, d);
202         }
203
204         if (c) blobmsg_close_table(b, c);
205 }
206
207 static void
208 rpc_session_to_blob(struct rpc_session *ses)
209 {
210         void *c;
211
212         blob_buf_init(&buf, 0);
213
214         blobmsg_add_string(&buf, "sid", ses->id);
215         blobmsg_add_u32(&buf, "timeout", ses->timeout);
216         blobmsg_add_u32(&buf, "expires", uloop_timeout_remaining(&ses->t) / 1000);
217
218         c = blobmsg_open_table(&buf, "acls");
219         rpc_session_dump_acls(ses, &buf);
220         blobmsg_close_table(&buf, c);
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);
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, struct ubus_context *ctx,
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, struct ubus_context *ctx,
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, struct ubus_context *ctx,
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, ctx, scope, NULL, NULL);
527
528         blobmsg_for_each_attr(attr, tb[RPC_SA_OBJECTS], rem1) {
529                 if (blob_id(attr) != BLOBMSG_TYPE_ARRAY)
530                         continue;
531
532                 object = NULL;
533                 function = NULL;
534
535                 blobmsg_for_each_attr(sattr, attr, rem2) {
536                         if (blob_id(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, ctx, 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] || !tb[RPC_SP_OBJECT] || !tb[RPC_SP_FUNCTION])
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         if (tb[RPC_SP_SCOPE])
591                 scope = blobmsg_data(tb[RPC_SP_SCOPE]);
592
593         allow = rpc_session_acl_allowed(ses, scope,
594                                                                         blobmsg_data(tb[RPC_SP_OBJECT]),
595                                                                         blobmsg_data(tb[RPC_SP_FUNCTION]));
596
597         blob_buf_init(&buf, 0);
598         blobmsg_add_u8(&buf, "access", allow);
599         ubus_send_reply(ctx, req, buf.head);
600
601         return 0;
602 }
603
604 static void
605 rpc_session_set(struct rpc_session *ses, const char *key, struct blob_attr *val)
606 {
607         struct rpc_session_data *data;
608
609         data = avl_find_element(&ses->data, key, data, avl);
610         if (data) {
611                 avl_delete(&ses->data, &data->avl);
612                 free(data);
613         }
614
615         data = calloc(1, sizeof(*data) + blob_pad_len(val));
616         if (!data)
617                 return;
618
619         memcpy(data->attr, val, blob_pad_len(val));
620         data->avl.key = blobmsg_name(data->attr);
621         avl_insert(&ses->data, &data->avl);
622 }
623
624 static int
625 rpc_handle_set(struct ubus_context *ctx, struct ubus_object *obj,
626                struct ubus_request_data *req, const char *method,
627                struct blob_attr *msg)
628 {
629         struct rpc_session *ses;
630         struct blob_attr *tb[__RPC_SA_MAX];
631         struct blob_attr *attr;
632         int rem;
633
634         blobmsg_parse(set_policy, __RPC_SS_MAX, tb, blob_data(msg), blob_len(msg));
635
636         if (!tb[RPC_SS_SID] || !tb[RPC_SS_VALUES])
637                 return UBUS_STATUS_INVALID_ARGUMENT;
638
639         ses = rpc_session_get(blobmsg_data(tb[RPC_SS_SID]));
640         if (!ses)
641                 return UBUS_STATUS_NOT_FOUND;
642
643         blobmsg_for_each_attr(attr, tb[RPC_SS_VALUES], rem) {
644                 if (!blobmsg_name(attr)[0])
645                         continue;
646
647                 rpc_session_set(ses, blobmsg_name(attr), attr);
648         }
649
650         return 0;
651 }
652
653 static int
654 rpc_handle_get(struct ubus_context *ctx, struct ubus_object *obj,
655                struct ubus_request_data *req, const char *method,
656                struct blob_attr *msg)
657 {
658         struct rpc_session *ses;
659         struct rpc_session_data *data;
660         struct blob_attr *tb[__RPC_SA_MAX];
661         struct blob_attr *attr;
662         void *c;
663         int rem;
664
665         blobmsg_parse(get_policy, __RPC_SG_MAX, tb, blob_data(msg), blob_len(msg));
666
667         if (!tb[RPC_SG_SID])
668                 return UBUS_STATUS_INVALID_ARGUMENT;
669
670         ses = rpc_session_get(blobmsg_data(tb[RPC_SG_SID]));
671         if (!ses)
672                 return UBUS_STATUS_NOT_FOUND;
673
674         blob_buf_init(&buf, 0);
675         c = blobmsg_open_table(&buf, "values");
676
677         if (tb[RPC_SG_KEYS])
678                 blobmsg_for_each_attr(attr, tb[RPC_SG_KEYS], rem) {
679                         if (blob_id(attr) != BLOBMSG_TYPE_STRING)
680                                 continue;
681
682                         data = avl_find_element(&ses->data, blobmsg_data(attr), data, avl);
683                         if (!data)
684                                 continue;
685
686                         blobmsg_add_field(&buf, blobmsg_type(data->attr),
687                                           blobmsg_name(data->attr),
688                                           blobmsg_data(data->attr),
689                                           blobmsg_data_len(data->attr));
690                 }
691         else
692                 rpc_session_dump_data(ses, &buf);
693
694         blobmsg_close_table(&buf, c);
695         ubus_send_reply(ctx, req, buf.head);
696
697         return 0;
698 }
699
700 static int
701 rpc_handle_unset(struct ubus_context *ctx, struct ubus_object *obj,
702                  struct ubus_request_data *req, const char *method,
703                  struct blob_attr *msg)
704 {
705         struct rpc_session *ses;
706         struct rpc_session_data *data, *ndata;
707         struct blob_attr *tb[__RPC_SA_MAX];
708         struct blob_attr *attr;
709         int rem;
710
711         blobmsg_parse(get_policy, __RPC_SG_MAX, tb, blob_data(msg), blob_len(msg));
712
713         if (!tb[RPC_SG_SID])
714                 return UBUS_STATUS_INVALID_ARGUMENT;
715
716         ses = rpc_session_get(blobmsg_data(tb[RPC_SG_SID]));
717         if (!ses)
718                 return UBUS_STATUS_NOT_FOUND;
719
720         if (!tb[RPC_SG_KEYS]) {
721                 avl_remove_all_elements(&ses->data, data, avl, ndata)
722                         free(data);
723                 return 0;
724         }
725
726         blobmsg_for_each_attr(attr, tb[RPC_SG_KEYS], rem) {
727                 if (blob_id(attr) != BLOBMSG_TYPE_STRING)
728                         continue;
729
730                 data = avl_find_element(&ses->data, blobmsg_data(attr), data, avl);
731                 if (!data)
732                         continue;
733
734                 avl_delete(&ses->data, &data->avl);
735                 free(data);
736         }
737
738         return 0;
739 }
740
741 static int
742 rpc_handle_destroy(struct ubus_context *ctx, struct ubus_object *obj,
743                    struct ubus_request_data *req, const char *method,
744                    struct blob_attr *msg)
745 {
746         struct rpc_session *ses;
747         struct blob_attr *tb;
748
749         blobmsg_parse(&sid_policy, 1, &tb, blob_data(msg), blob_len(msg));
750
751         if (!tb)
752                 return UBUS_STATUS_INVALID_ARGUMENT;
753
754         if (!strcmp(blobmsg_get_string(tb), RPC_DEFAULT_SESSION_ID))
755                 return UBUS_STATUS_PERMISSION_DENIED;
756
757         ses = rpc_session_get(blobmsg_data(tb));
758         if (!ses)
759                 return UBUS_STATUS_NOT_FOUND;
760
761         rpc_session_destroy(ses);
762
763         return 0;
764 }
765
766
767 static bool
768 rpc_login_test_password(const char *hash, const char *password)
769 {
770         char *crypt_hash;
771
772         /* password is not set */
773         if (!hash || !*hash || !strcmp(hash, "!") || !strcmp(hash, "x"))
774         {
775                 return true;
776         }
777
778         /* password hash refers to shadow/passwd */
779         else if (!strncmp(hash, "$p$", 3))
780         {
781 #ifdef HAVE_SHADOW
782                 struct spwd *sp = getspnam(hash + 3);
783
784                 if (!sp)
785                         return false;
786
787                 return rpc_login_test_password(sp->sp_pwdp, password);
788 #else
789                 struct passwd *pw = getpwnam(hash + 3);
790
791                 if (!pw)
792                         return false;
793
794                 return rpc_login_test_password(pw->pw_passwd, password);
795 #endif
796         }
797
798         crypt_hash = crypt(password, hash);
799
800         return !strcmp(crypt_hash, hash);
801 }
802
803 static struct uci_section *
804 rpc_login_test_login(struct uci_context *uci,
805                      const char *username, const char *password)
806 {
807         struct uci_package *p = NULL;
808         struct uci_section *s;
809         struct uci_element *e;
810         struct uci_ptr ptr = { .package = "rpcd" };
811
812         uci_load(uci, ptr.package, &p);
813
814         if (!p)
815                 return false;
816
817         uci_foreach_element(&p->sections, e)
818         {
819                 s = uci_to_section(e);
820
821                 if (strcmp(s->type, "login"))
822                         continue;
823
824                 ptr.section = s->e.name;
825                 ptr.s = NULL;
826
827                 /* test for matching username */
828                 ptr.option = "username";
829                 ptr.o = NULL;
830
831                 if (uci_lookup_ptr(uci, &ptr, NULL, true))
832                         continue;
833
834                 if (ptr.o->type != UCI_TYPE_STRING)
835                         continue;
836
837                 if (strcmp(ptr.o->v.string, username))
838                         continue;
839
840                 /* test for matching password */
841                 ptr.option = "password";
842                 ptr.o = NULL;
843
844                 if (uci_lookup_ptr(uci, &ptr, NULL, true))
845                         continue;
846
847                 if (ptr.o->type != UCI_TYPE_STRING)
848                         continue;
849
850                 if (rpc_login_test_password(ptr.o->v.string, password))
851                         return ptr.s;
852         }
853
854         return NULL;
855 }
856
857 static bool
858 rpc_login_test_permission(struct uci_section *s,
859                           const char *perm, const char *group)
860 {
861         struct uci_option *o;
862         struct uci_element *e, *l;
863
864         /* If the login section is not provided, we're setting up acls for the
865          * default session, in this case uncondionally allow access to the
866          * "unauthenticated" access group */
867         if (!s) {
868                 return !strcmp(group, "unauthenticated");
869         }
870
871         uci_foreach_element(&s->options, e)
872         {
873                 o = uci_to_option(e);
874
875                 if (o->type != UCI_TYPE_LIST)
876                         continue;
877
878                 if (strcmp(o->e.name, perm))
879                         continue;
880
881                 uci_foreach_element(&o->v.list, l)
882                         if (l->name && !fnmatch(l->name, group, 0))
883                                 return true;
884         }
885
886         /* make sure that write permission implies read permission */
887         if (!strcmp(perm, "read"))
888                 return rpc_login_test_permission(s, "write", group);
889
890         return false;
891 }
892
893 static void
894 rpc_login_setup_acl_scope(struct rpc_session *ses,
895                           struct blob_attr *acl_perm,
896                           struct blob_attr *acl_scope)
897 {
898         struct blob_attr *acl_obj, *acl_func;
899         int rem, rem2;
900
901         /*
902          * Parse ACL scopes in table notation.
903          *
904          *      "<scope>": {
905          *              "<object>": [
906          *                      "<function>",
907          *                      "<function>",
908          *                      ...
909          *              ]
910          *      }
911          */
912         if (blob_id(acl_scope) == BLOBMSG_TYPE_TABLE) {
913                 blobmsg_for_each_attr(acl_obj, acl_scope, rem) {
914                         if (blob_id(acl_obj) != BLOBMSG_TYPE_ARRAY)
915                                 continue;
916
917                         blobmsg_for_each_attr(acl_func, acl_obj, rem2) {
918                                 if (blob_id(acl_func) != BLOBMSG_TYPE_STRING)
919                                         continue;
920
921                                 rpc_session_grant(ses, NULL, blobmsg_name(acl_scope),
922                                                              blobmsg_name(acl_obj),
923                                                              blobmsg_data(acl_func));
924                         }
925                 }
926         }
927
928         /*
929          * Parse ACL scopes in array notation. The permission ("read" or "write")
930          * will be used as function name for each object.
931          *
932          *      "<scope>": [
933          *              "<object>",
934          *              "<object>",
935          *              ...
936          *      ]
937          */
938         else if (blob_id(acl_scope) == BLOBMSG_TYPE_ARRAY) {
939                 blobmsg_for_each_attr(acl_obj, acl_scope, rem) {
940                         if (blob_id(acl_obj) != BLOBMSG_TYPE_STRING)
941                                 continue;
942
943                         rpc_session_grant(ses, NULL, blobmsg_name(acl_scope),
944                                                          blobmsg_data(acl_obj),
945                                                          blobmsg_name(acl_perm));
946                 }
947         }
948 }
949
950 static void
951 rpc_login_setup_acl_file(struct rpc_session *ses, struct uci_section *login,
952                          const char *path)
953 {
954         struct blob_buf acl = { 0 };
955         struct blob_attr *acl_group, *acl_perm, *acl_scope;
956         int rem, rem2, rem3;
957
958         blob_buf_init(&acl, 0);
959
960         if (!blobmsg_add_json_from_file(&acl, path)) {
961                 fprintf(stderr, "Failed to parse %s\n", path);
962                 goto out;
963         }
964
965         /* Iterate access groups in toplevel object */
966         blob_for_each_attr(acl_group, acl.head, rem) {
967                 /* Iterate permission objects in each access group object */
968                 blobmsg_for_each_attr(acl_perm, acl_group, rem2) {
969                         if (blob_id(acl_perm) != BLOBMSG_TYPE_TABLE)
970                                 continue;
971
972                         /* Only "read" and "write" permissions are defined */
973                         if (strcmp(blobmsg_name(acl_perm), "read") &&
974                                 strcmp(blobmsg_name(acl_perm), "write"))
975                                 continue;
976
977                         /*
978                          * Check if the current user context specifies the current
979                          * "read" or "write" permission in the given access group.
980                          */
981                         if (!rpc_login_test_permission(login, blobmsg_name(acl_perm),
982                                                               blobmsg_name(acl_group)))
983                                 continue;
984
985                         /* Iterate scope objects within the permission object */
986                         blobmsg_for_each_attr(acl_scope, acl_perm, rem3) {
987                                 /* Setup the scopes of the access group */
988                                 rpc_login_setup_acl_scope(ses, acl_perm, acl_scope);
989
990                                 /*
991                                  * Add the access group itself as object to the "access-group"
992                                  * meta scope and the the permission level ("read" or "write")
993                                  * as function, so
994                                  *      "<group>": {
995                                  *              "<permission>": {
996                                  *                      "<scope>": ...
997                                  *              }
998                                  *      }
999                                  * becomes
1000                                  *      "access-group": {
1001                                  *              "<group>": [
1002                                  *                      "<permission>"
1003                                  *              ]
1004                                  *      }
1005                                  *
1006                                  * This allows session clients to easily query the allowed
1007                                  * access groups without having to test access of each single
1008                                  * <scope>/<object>/<function> tuple defined in a group.
1009                                  */
1010                                 rpc_session_grant(ses, NULL, "access-group",
1011                                                              blobmsg_name(acl_group),
1012                                                              blobmsg_name(acl_perm));
1013                         }
1014                 }
1015         }
1016
1017 out:
1018         blob_buf_free(&acl);
1019 }
1020
1021 static void
1022 rpc_login_setup_acls(struct rpc_session *ses, struct uci_section *login)
1023 {
1024         int i;
1025         glob_t gl;
1026
1027         if (glob(RPC_SESSION_ACL_DIR "/*.json", 0, NULL, &gl))
1028                 return;
1029
1030         for (i = 0; i < gl.gl_pathc; i++)
1031                 rpc_login_setup_acl_file(ses, login, gl.gl_pathv[i]);
1032
1033         globfree(&gl);
1034 }
1035
1036 static int
1037 rpc_handle_login(struct ubus_context *ctx, struct ubus_object *obj,
1038                  struct ubus_request_data *req, const char *method,
1039                  struct blob_attr *msg)
1040 {
1041         struct uci_context *uci = NULL;
1042         struct uci_section *login;
1043         struct rpc_session *ses;
1044         struct blob_attr *tb[__RPC_L_MAX];
1045         int timeout = RPC_DEFAULT_SESSION_TIMEOUT;
1046         int rv = 0;
1047
1048         blobmsg_parse(login_policy, __RPC_L_MAX, tb, blob_data(msg), blob_len(msg));
1049
1050         if (!tb[RPC_L_USERNAME] || !tb[RPC_L_PASSWORD]) {
1051                 rv = UBUS_STATUS_INVALID_ARGUMENT;
1052                 goto out;
1053         }
1054
1055         uci = uci_alloc_context();
1056
1057         if (!uci) {
1058                 rv = UBUS_STATUS_UNKNOWN_ERROR;
1059                 goto out;
1060         }
1061
1062         login = rpc_login_test_login(uci, blobmsg_get_string(tb[RPC_L_USERNAME]),
1063                                           blobmsg_get_string(tb[RPC_L_PASSWORD]));
1064
1065         if (!login) {
1066                 rv = UBUS_STATUS_PERMISSION_DENIED;
1067                 goto out;
1068         }
1069
1070         if (tb[RPC_L_TIMEOUT])
1071                 timeout = blobmsg_get_u32(tb[RPC_L_TIMEOUT]);
1072
1073         ses = rpc_session_create(timeout);
1074
1075         if (!ses) {
1076                 rv = UBUS_STATUS_UNKNOWN_ERROR;
1077                 goto out;
1078         }
1079
1080         rpc_login_setup_acls(ses, login);
1081
1082         rpc_session_set(ses, "user", tb[RPC_L_USERNAME]);
1083         rpc_session_dump(ses, ctx, req);
1084
1085 out:
1086         if (uci)
1087                 uci_free_context(uci);
1088
1089         return rv;
1090 }
1091
1092
1093 static bool
1094 rpc_validate_sid(const char *id)
1095 {
1096         if (!id)
1097                 return false;
1098
1099         if (strlen(id) != RPC_SID_LEN)
1100                 return false;
1101
1102         while (*id)
1103                 if (!isxdigit(*id++))
1104                         return false;
1105
1106         return true;
1107 }
1108
1109 static int
1110 rpc_blob_to_file(const char *path, struct blob_attr *attr)
1111 {
1112         int fd, len;
1113
1114         fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0600);
1115
1116         if (fd < 0)
1117                 return fd;
1118
1119         len = write(fd, attr, blob_pad_len(attr));
1120
1121         close(fd);
1122
1123         if (len != blob_pad_len(attr))
1124         {
1125                 unlink(path);
1126                 return -1;
1127         }
1128
1129         return len;
1130 }
1131
1132 static struct blob_attr *
1133 rpc_blob_from_file(const char *path)
1134 {
1135         int fd = -1, len;
1136         struct stat s;
1137         struct blob_attr head, *attr = NULL;
1138
1139         if (stat(path, &s) || !S_ISREG(s.st_mode))
1140                 return NULL;
1141
1142         fd = open(path, O_RDONLY);
1143
1144         if (fd < 0)
1145                 goto fail;
1146
1147         len = read(fd, &head, sizeof(head));
1148
1149         if (len != sizeof(head) || blob_pad_len(&head) != s.st_size)
1150                 goto fail;
1151
1152         attr = calloc(1, s.st_size);
1153
1154         if (!attr)
1155                 goto fail;
1156
1157         memcpy(attr, &head, sizeof(head));
1158
1159         len += read(fd, (char *)attr + sizeof(head), s.st_size - sizeof(head));
1160
1161         if (len != blob_pad_len(&head))
1162                 goto fail;
1163
1164         return attr;
1165
1166 fail:
1167         if (fd >= 0)
1168                 close(fd);
1169
1170         if (attr)
1171                 free(attr);
1172
1173         return NULL;
1174 }
1175
1176 static bool
1177 rpc_session_from_blob(struct blob_attr *attr)
1178 {
1179         int i, rem, rem2, rem3;
1180         struct rpc_session *ses;
1181         struct blob_attr *tb[__RPC_DUMP_MAX], *scope, *object, *function;
1182
1183         blobmsg_parse(dump_policy, __RPC_DUMP_MAX, tb,
1184                       blob_data(attr), blob_len(attr));
1185
1186         for (i = 0; i < __RPC_DUMP_MAX; i++)
1187                 if (!tb[i])
1188                         return false;
1189
1190         ses = rpc_session_new();
1191
1192         if (!ses)
1193                 return false;
1194
1195         memcpy(ses->id, blobmsg_data(tb[RPC_DUMP_SID]), RPC_SID_LEN);
1196
1197         ses->timeout = blobmsg_get_u32(tb[RPC_DUMP_TIMEOUT]);
1198
1199         blobmsg_for_each_attr(scope, tb[RPC_DUMP_ACLS], rem) {
1200                 blobmsg_for_each_attr(object, scope, rem2) {
1201                         blobmsg_for_each_attr(function, object, rem3) {
1202                                 rpc_session_grant(ses, NULL, blobmsg_name(scope),
1203                                                              blobmsg_name(object),
1204                                                              blobmsg_data(function));
1205                         }
1206                 }
1207         }
1208
1209         blobmsg_for_each_attr(object, tb[RPC_DUMP_DATA], rem) {
1210                 rpc_session_set(ses, blobmsg_name(object), object);
1211         }
1212
1213         avl_insert(&sessions, &ses->avl);
1214
1215         uloop_timeout_set(&ses->t, blobmsg_get_u32(tb[RPC_DUMP_EXPIRES]) * 1000);
1216
1217         return true;
1218 }
1219
1220 int rpc_session_api_init(struct ubus_context *ctx)
1221 {
1222         struct rpc_session *ses;
1223
1224         static const struct ubus_method session_methods[] = {
1225                 UBUS_METHOD("create",  rpc_handle_create,  &new_policy),
1226                 UBUS_METHOD("list",    rpc_handle_list,    &sid_policy),
1227                 UBUS_METHOD("grant",   rpc_handle_acl,     acl_policy),
1228                 UBUS_METHOD("revoke",  rpc_handle_acl,     acl_policy),
1229                 UBUS_METHOD("access",  rpc_handle_access,  perm_policy),
1230                 UBUS_METHOD("set",     rpc_handle_set,     set_policy),
1231                 UBUS_METHOD("get",     rpc_handle_get,     get_policy),
1232                 UBUS_METHOD("unset",   rpc_handle_unset,   get_policy),
1233                 UBUS_METHOD("destroy", rpc_handle_destroy, &sid_policy),
1234                 UBUS_METHOD("login",   rpc_handle_login,   login_policy),
1235         };
1236
1237         static struct ubus_object_type session_type =
1238                 UBUS_OBJECT_TYPE("luci-rpc-session", session_methods);
1239
1240         static struct ubus_object obj = {
1241                 .name = "session",
1242                 .type = &session_type,
1243                 .methods = session_methods,
1244                 .n_methods = ARRAY_SIZE(session_methods),
1245         };
1246
1247         avl_init(&sessions, avl_strcmp, false, NULL);
1248
1249         /* setup the default session */
1250         ses = rpc_session_new();
1251
1252         if (ses) {
1253                 strcpy(ses->id, RPC_DEFAULT_SESSION_ID);
1254                 rpc_login_setup_acls(ses, NULL);
1255                 avl_insert(&sessions, &ses->avl);
1256         }
1257
1258         return ubus_add_object(ctx, &obj);
1259 }
1260
1261 bool rpc_session_access(const char *sid, const char *scope,
1262                         const char *object, const char *function)
1263 {
1264         struct rpc_session *ses = rpc_session_get(sid);
1265
1266         if (!ses)
1267                 return false;
1268
1269         return rpc_session_acl_allowed(ses, scope, object, function);
1270 }
1271
1272 void rpc_session_create_cb(struct rpc_session_cb *cb)
1273 {
1274         if (cb && cb->cb)
1275                 list_add(&cb->list, &create_callbacks);
1276 }
1277
1278 void rpc_session_destroy_cb(struct rpc_session_cb *cb)
1279 {
1280         if (cb && cb->cb)
1281                 list_add(&cb->list, &destroy_callbacks);
1282 }
1283
1284 void rpc_session_freeze(void)
1285 {
1286         struct stat s;
1287         struct rpc_session *ses;
1288         char path[PATH_MAX];
1289
1290         if (stat(RPC_SESSION_DIRECTORY, &s))
1291                 mkdir(RPC_SESSION_DIRECTORY, 0700);
1292
1293         avl_for_each_element(&sessions, ses, avl) {
1294                 /* skip default session */
1295                 if (!strcmp(ses->id, RPC_DEFAULT_SESSION_ID))
1296                         continue;
1297
1298                 snprintf(path, sizeof(path) - 1, RPC_SESSION_DIRECTORY "/%s", ses->id);
1299                 rpc_session_to_blob(ses);
1300                 rpc_blob_to_file(path, buf.head);
1301         }
1302 }
1303
1304 void rpc_session_thaw(void)
1305 {
1306         DIR *d;
1307         char path[PATH_MAX];
1308         struct dirent *e;
1309         struct blob_attr *attr;
1310
1311         d = opendir(RPC_SESSION_DIRECTORY);
1312
1313         if (!d)
1314                 return;
1315
1316         while ((e = readdir(d)) != NULL) {
1317                 if (!rpc_validate_sid(e->d_name))
1318                         continue;
1319
1320                 snprintf(path, sizeof(path) - 1,
1321                          RPC_SESSION_DIRECTORY "/%s", e->d_name);
1322
1323                 attr = rpc_blob_from_file(path);
1324
1325                 if (attr) {
1326                         rpc_session_from_blob(attr);
1327                         free(attr);
1328                 }
1329
1330                 unlink(path);
1331         }
1332
1333         closedir(d);
1334 }