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