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