client: fix invalid data access through invalid content-length values
[project/uhttpd.git] / ubus.c
1 /*
2 * uhttpd - Tiny single-threaded httpd
3 *
4 * Copyright (C) 2010-2013 Jo-Philipp Wich <xm@subsignal.org>
5 * Copyright (C) 2013 Felix Fietkau <nbd@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 #include <libubox/blobmsg.h>
21 #include <libubox/blobmsg_json.h>
22 #include <libubox/avl.h>
23 #include <libubox/avl-cmp.h>
24 #include <stdio.h>
25 #include <poll.h>
26
27 #include "uhttpd.h"
28 #include "plugin.h"
29
30 static const struct uhttpd_ops *ops;
31 static struct config *_conf;
32 #define conf (*_conf)
33
34 static struct ubus_context *ctx;
35 static struct blob_buf buf;
36
37 #define UH_UBUS_MAX_POST_SIZE 65536
38 #define UH_UBUS_DEFAULT_SID "00000000000000000000000000000000"
39
40 enum {
41 RPC_JSONRPC,
42 RPC_METHOD,
43 RPC_PARAMS,
44 RPC_ID,
45 __RPC_MAX,
46 };
47
48 static const struct blobmsg_policy rpc_policy[__RPC_MAX] = {
49 [RPC_JSONRPC] = { .name = "jsonrpc", .type = BLOBMSG_TYPE_STRING },
50 [RPC_METHOD] = { .name = "method", .type = BLOBMSG_TYPE_STRING },
51 [RPC_PARAMS] = { .name = "params", .type = BLOBMSG_TYPE_ARRAY },
52 [RPC_ID] = { .name = "id", .type = BLOBMSG_TYPE_UNSPEC },
53 };
54
55 enum {
56 SES_ACCESS,
57 __SES_MAX,
58 };
59
60 static const struct blobmsg_policy ses_policy[__SES_MAX] = {
61 [SES_ACCESS] = { .name = "access", .type = BLOBMSG_TYPE_BOOL },
62 };
63
64 struct rpc_data {
65 struct blob_attr *id;
66 const char *sid;
67 const char *method;
68 const char *object;
69 const char *function;
70 struct blob_attr *data;
71 struct blob_attr *params;
72 };
73
74 struct list_data {
75 bool verbose;
76 struct blob_buf *buf;
77 };
78
79 enum rpc_error {
80 ERROR_PARSE,
81 ERROR_REQUEST,
82 ERROR_METHOD,
83 ERROR_PARAMS,
84 ERROR_INTERNAL,
85 ERROR_OBJECT,
86 ERROR_SESSION,
87 ERROR_ACCESS,
88 ERROR_TIMEOUT,
89 __ERROR_MAX
90 };
91
92 static const struct {
93 int code;
94 const char *msg;
95 } json_errors[__ERROR_MAX] = {
96 [ERROR_PARSE] = { -32700, "Parse error" },
97 [ERROR_REQUEST] = { -32600, "Invalid request" },
98 [ERROR_METHOD] = { -32601, "Method not found" },
99 [ERROR_PARAMS] = { -32602, "Invalid parameters" },
100 [ERROR_INTERNAL] = { -32603, "Internal error" },
101 [ERROR_OBJECT] = { -32000, "Object not found" },
102 [ERROR_SESSION] = { -32001, "Session not found" },
103 [ERROR_ACCESS] = { -32002, "Access denied" },
104 [ERROR_TIMEOUT] = { -32003, "ubus request timed out" },
105 };
106
107 enum cors_hdr {
108 HDR_ORIGIN,
109 HDR_ACCESS_CONTROL_REQUEST_METHOD,
110 HDR_ACCESS_CONTROL_REQUEST_HEADERS,
111 __HDR_MAX
112 };
113
114 static void __uh_ubus_next_batched_request(struct uloop_timeout *timeout);
115
116 static void uh_ubus_next_batched_request(struct client *cl)
117 {
118 struct dispatch_ubus *du = &cl->dispatch.ubus;
119
120 du->timeout.cb = __uh_ubus_next_batched_request;
121 uloop_timeout_set(&du->timeout, 1);
122 }
123
124 static void uh_ubus_add_cors_headers(struct client *cl)
125 {
126 struct blob_attr *tb[__HDR_MAX];
127 static const struct blobmsg_policy hdr_policy[__HDR_MAX] = {
128 [HDR_ORIGIN] = { "origin", BLOBMSG_TYPE_STRING },
129 [HDR_ACCESS_CONTROL_REQUEST_METHOD] = { "access-control-request-method", BLOBMSG_TYPE_STRING },
130 [HDR_ACCESS_CONTROL_REQUEST_HEADERS] = { "access-control-request-headers", BLOBMSG_TYPE_STRING },
131 };
132
133 blobmsg_parse(hdr_policy, __HDR_MAX, tb, blob_data(cl->hdr.head), blob_len(cl->hdr.head));
134
135 if (!tb[HDR_ORIGIN])
136 return;
137
138 if (tb[HDR_ACCESS_CONTROL_REQUEST_METHOD])
139 {
140 char *hdr = (char *) blobmsg_data(tb[HDR_ACCESS_CONTROL_REQUEST_METHOD]);
141
142 if (strcmp(hdr, "POST") && strcmp(hdr, "OPTIONS"))
143 return;
144 }
145
146 ustream_printf(cl->us, "Access-Control-Allow-Origin: %s\r\n",
147 blobmsg_get_string(tb[HDR_ORIGIN]));
148
149 if (tb[HDR_ACCESS_CONTROL_REQUEST_HEADERS])
150 ustream_printf(cl->us, "Access-Control-Allow-Headers: %s\r\n",
151 blobmsg_get_string(tb[HDR_ACCESS_CONTROL_REQUEST_HEADERS]));
152
153 ustream_printf(cl->us, "Access-Control-Allow-Methods: POST, OPTIONS\r\n");
154 ustream_printf(cl->us, "Access-Control-Allow-Credentials: true\r\n");
155 }
156
157 static void uh_ubus_send_header(struct client *cl)
158 {
159 ops->http_header(cl, 200, "OK");
160
161 if (conf.ubus_cors)
162 uh_ubus_add_cors_headers(cl);
163
164 ustream_printf(cl->us, "Content-Type: application/json\r\n");
165
166 if (cl->request.method == UH_HTTP_MSG_OPTIONS)
167 ustream_printf(cl->us, "Content-Length: 0\r\n");
168
169 ustream_printf(cl->us, "\r\n");
170 }
171
172 static void uh_ubus_send_response(struct client *cl)
173 {
174 struct dispatch_ubus *du = &cl->dispatch.ubus;
175 const char *sep = "";
176 char *str;
177
178 if (du->array && du->array_idx > 1)
179 sep = ",";
180
181 str = blobmsg_format_json(buf.head, true);
182 ops->chunk_printf(cl, "%s%s", sep, str);
183 free(str);
184
185 du->jsobj_cur = NULL;
186 if (du->array)
187 uh_ubus_next_batched_request(cl);
188 else
189 return ops->request_done(cl);
190 }
191
192 static void uh_ubus_init_response(struct client *cl)
193 {
194 struct dispatch_ubus *du = &cl->dispatch.ubus;
195 struct json_object *obj = du->jsobj_cur, *obj2 = NULL;
196
197 blob_buf_init(&buf, 0);
198 blobmsg_add_string(&buf, "jsonrpc", "2.0");
199
200 if (obj)
201 json_object_object_get_ex(obj, "id", &obj2);
202
203 if (obj2)
204 blobmsg_add_json_element(&buf, "id", obj2);
205 else
206 blobmsg_add_field(&buf, BLOBMSG_TYPE_UNSPEC, "id", NULL, 0);
207 }
208
209 static void uh_ubus_json_error(struct client *cl, enum rpc_error type)
210 {
211 void *c;
212
213 uh_ubus_init_response(cl);
214 c = blobmsg_open_table(&buf, "error");
215 blobmsg_add_u32(&buf, "code", json_errors[type].code);
216 blobmsg_add_string(&buf, "message", json_errors[type].msg);
217 blobmsg_close_table(&buf, c);
218 uh_ubus_send_response(cl);
219 }
220
221 static void
222 uh_ubus_request_data_cb(struct ubus_request *req, int type, struct blob_attr *msg)
223 {
224 struct dispatch_ubus *du = container_of(req, struct dispatch_ubus, req);
225
226 blobmsg_add_field(&du->buf, BLOBMSG_TYPE_TABLE, "", blob_data(msg), blob_len(msg));
227 }
228
229 static void
230 uh_ubus_request_cb(struct ubus_request *req, int ret)
231 {
232 struct dispatch_ubus *du = container_of(req, struct dispatch_ubus, req);
233 struct client *cl = container_of(du, struct client, dispatch.ubus);
234 struct blob_attr *cur;
235 void *r;
236 int rem;
237
238 uloop_timeout_cancel(&du->timeout);
239 uh_ubus_init_response(cl);
240 r = blobmsg_open_array(&buf, "result");
241 blobmsg_add_u32(&buf, "", ret);
242 blob_for_each_attr(cur, du->buf.head, rem)
243 blobmsg_add_blob(&buf, cur);
244 blobmsg_close_array(&buf, r);
245 uh_ubus_send_response(cl);
246 }
247
248 static void
249 uh_ubus_timeout_cb(struct uloop_timeout *timeout)
250 {
251 struct dispatch_ubus *du = container_of(timeout, struct dispatch_ubus, timeout);
252 struct client *cl = container_of(du, struct client, dispatch.ubus);
253
254 ubus_abort_request(ctx, &du->req);
255 uh_ubus_json_error(cl, ERROR_TIMEOUT);
256 }
257
258 static void uh_ubus_close_fds(struct client *cl)
259 {
260 if (ctx->sock.fd < 0)
261 return;
262
263 close(ctx->sock.fd);
264 ctx->sock.fd = -1;
265 }
266
267 static void uh_ubus_request_free(struct client *cl)
268 {
269 struct dispatch_ubus *du = &cl->dispatch.ubus;
270
271 blob_buf_free(&du->buf);
272 uloop_timeout_cancel(&du->timeout);
273
274 if (du->jsobj)
275 json_object_put(du->jsobj);
276
277 if (du->jstok)
278 json_tokener_free(du->jstok);
279
280 if (du->req_pending)
281 ubus_abort_request(ctx, &du->req);
282 }
283
284 static void uh_ubus_single_error(struct client *cl, enum rpc_error type)
285 {
286 uh_ubus_send_header(cl);
287 uh_ubus_json_error(cl, type);
288 ops->request_done(cl);
289 }
290
291 static void uh_ubus_send_request(struct client *cl, json_object *obj, const char *sid, struct blob_attr *args)
292 {
293 struct dispatch *d = &cl->dispatch;
294 struct dispatch_ubus *du = &d->ubus;
295 struct blob_attr *cur;
296 static struct blob_buf req;
297 int ret, rem;
298
299 blob_buf_init(&req, 0);
300 blobmsg_for_each_attr(cur, args, rem) {
301 if (!strcmp(blobmsg_name(cur), "ubus_rpc_session"))
302 return uh_ubus_json_error(cl, ERROR_PARAMS);
303 blobmsg_add_blob(&req, cur);
304 }
305
306 blobmsg_add_string(&req, "ubus_rpc_session", sid);
307
308 blob_buf_init(&du->buf, 0);
309 memset(&du->req, 0, sizeof(du->req));
310 ret = ubus_invoke_async(ctx, du->obj, du->func, req.head, &du->req);
311 if (ret)
312 return uh_ubus_json_error(cl, ERROR_INTERNAL);
313
314 du->req.data_cb = uh_ubus_request_data_cb;
315 du->req.complete_cb = uh_ubus_request_cb;
316 ubus_complete_request_async(ctx, &du->req);
317
318 du->timeout.cb = uh_ubus_timeout_cb;
319 uloop_timeout_set(&du->timeout, conf.script_timeout * 1000);
320
321 du->req_pending = true;
322 }
323
324 static void uh_ubus_list_cb(struct ubus_context *ctx, struct ubus_object_data *obj, void *priv)
325 {
326 struct blob_attr *sig, *attr;
327 struct list_data *data = priv;
328 int rem, rem2;
329 void *t, *o;
330
331 if (!data->verbose) {
332 blobmsg_add_string(data->buf, NULL, obj->path);
333 return;
334 }
335
336 if (!obj->signature)
337 return;
338
339 o = blobmsg_open_table(data->buf, obj->path);
340 blob_for_each_attr(sig, obj->signature, rem) {
341 t = blobmsg_open_table(data->buf, blobmsg_name(sig));
342 rem2 = blobmsg_data_len(sig);
343 __blob_for_each_attr(attr, blobmsg_data(sig), rem2) {
344 if (blob_id(attr) != BLOBMSG_TYPE_INT32)
345 continue;
346
347 switch (blobmsg_get_u32(attr)) {
348 case BLOBMSG_TYPE_INT8:
349 blobmsg_add_string(data->buf, blobmsg_name(attr), "boolean");
350 break;
351 case BLOBMSG_TYPE_INT32:
352 blobmsg_add_string(data->buf, blobmsg_name(attr), "number");
353 break;
354 case BLOBMSG_TYPE_STRING:
355 blobmsg_add_string(data->buf, blobmsg_name(attr), "string");
356 break;
357 case BLOBMSG_TYPE_ARRAY:
358 blobmsg_add_string(data->buf, blobmsg_name(attr), "array");
359 break;
360 case BLOBMSG_TYPE_TABLE:
361 blobmsg_add_string(data->buf, blobmsg_name(attr), "object");
362 break;
363 default:
364 blobmsg_add_string(data->buf, blobmsg_name(attr), "unknown");
365 break;
366 }
367 }
368 blobmsg_close_table(data->buf, t);
369 }
370 blobmsg_close_table(data->buf, o);
371 }
372
373 static void uh_ubus_send_list(struct client *cl, json_object *obj, struct blob_attr *params)
374 {
375 struct blob_attr *cur, *dup;
376 struct list_data data = { .buf = &cl->dispatch.ubus.buf, .verbose = false };
377 void *r;
378 int rem;
379
380 blob_buf_init(data.buf, 0);
381
382 uh_client_ref(cl);
383
384 if (!params || blob_id(params) != BLOBMSG_TYPE_ARRAY) {
385 r = blobmsg_open_array(data.buf, "result");
386 ubus_lookup(ctx, NULL, uh_ubus_list_cb, &data);
387 blobmsg_close_array(data.buf, r);
388 }
389 else {
390 r = blobmsg_open_table(data.buf, "result");
391 dup = blob_memdup(params);
392 if (dup)
393 {
394 rem = blobmsg_data_len(dup);
395 data.verbose = true;
396 __blob_for_each_attr(cur, blobmsg_data(dup), rem)
397 ubus_lookup(ctx, blobmsg_data(cur), uh_ubus_list_cb, &data);
398 free(dup);
399 }
400 blobmsg_close_table(data.buf, r);
401 }
402
403 uh_client_unref(cl);
404
405 uh_ubus_init_response(cl);
406 blobmsg_add_blob(&buf, blob_data(data.buf->head));
407 uh_ubus_send_response(cl);
408 }
409
410 static bool parse_json_rpc(struct rpc_data *d, struct blob_attr *data)
411 {
412 const struct blobmsg_policy data_policy[] = {
413 { .type = BLOBMSG_TYPE_STRING },
414 { .type = BLOBMSG_TYPE_STRING },
415 { .type = BLOBMSG_TYPE_STRING },
416 { .type = BLOBMSG_TYPE_TABLE },
417 };
418 struct blob_attr *tb[__RPC_MAX];
419 struct blob_attr *tb2[4];
420 struct blob_attr *cur;
421
422 blobmsg_parse(rpc_policy, __RPC_MAX, tb, blob_data(data), blob_len(data));
423
424 cur = tb[RPC_JSONRPC];
425 if (!cur || strcmp(blobmsg_data(cur), "2.0") != 0)
426 return false;
427
428 cur = tb[RPC_METHOD];
429 if (!cur)
430 return false;
431
432 d->id = tb[RPC_ID];
433 d->method = blobmsg_data(cur);
434
435 cur = tb[RPC_PARAMS];
436 if (!cur)
437 return true;
438
439 d->params = blob_memdup(cur);
440 if (!d->params)
441 return false;
442
443 blobmsg_parse_array(data_policy, ARRAY_SIZE(data_policy), tb2,
444 blobmsg_data(d->params), blobmsg_data_len(d->params));
445
446 if (tb2[0])
447 d->sid = blobmsg_data(tb2[0]);
448
449 if (conf.ubus_noauth && (!d->sid || !*d->sid))
450 d->sid = UH_UBUS_DEFAULT_SID;
451
452 if (tb2[1])
453 d->object = blobmsg_data(tb2[1]);
454
455 if (tb2[2])
456 d->function = blobmsg_data(tb2[2]);
457
458 d->data = tb2[3];
459
460 return true;
461 }
462
463 static void uh_ubus_init_batch(struct client *cl)
464 {
465 struct dispatch_ubus *du = &cl->dispatch.ubus;
466
467 du->array = true;
468 uh_ubus_send_header(cl);
469 ops->chunk_printf(cl, "[");
470 }
471
472 static void uh_ubus_complete_batch(struct client *cl)
473 {
474 ops->chunk_printf(cl, "]");
475 ops->request_done(cl);
476 }
477
478 static void uh_ubus_allowed_cb(struct ubus_request *req, int type, struct blob_attr *msg)
479 {
480 struct blob_attr *tb[__SES_MAX];
481 bool *allow = (bool *)req->priv;
482
483 if (!msg)
484 return;
485
486 blobmsg_parse(ses_policy, __SES_MAX, tb, blob_data(msg), blob_len(msg));
487
488 if (tb[SES_ACCESS])
489 *allow = blobmsg_get_bool(tb[SES_ACCESS]);
490 }
491
492 static bool uh_ubus_allowed(const char *sid, const char *obj, const char *fun)
493 {
494 uint32_t id;
495 bool allow = false;
496 static struct blob_buf req;
497
498 if (ubus_lookup_id(ctx, "session", &id))
499 return false;
500
501 blob_buf_init(&req, 0);
502 blobmsg_add_string(&req, "ubus_rpc_session", sid);
503 blobmsg_add_string(&req, "object", obj);
504 blobmsg_add_string(&req, "function", fun);
505
506 ubus_invoke(ctx, id, "access", req.head, uh_ubus_allowed_cb, &allow, conf.script_timeout * 500);
507
508 return allow;
509 }
510
511 static void uh_ubus_handle_request_object(struct client *cl, struct json_object *obj)
512 {
513 struct dispatch_ubus *du = &cl->dispatch.ubus;
514 struct rpc_data data = {};
515 enum rpc_error err = ERROR_PARSE;
516
517 uh_client_ref(cl);
518
519 if (json_object_get_type(obj) != json_type_object)
520 goto error;
521
522 du->jsobj_cur = obj;
523 blob_buf_init(&buf, 0);
524 if (!blobmsg_add_object(&buf, obj))
525 goto error;
526
527 if (!parse_json_rpc(&data, buf.head))
528 goto error;
529
530 if (!strcmp(data.method, "call")) {
531 if (!data.sid || !data.object || !data.function || !data.data)
532 goto error;
533
534 du->func = data.function;
535 if (ubus_lookup_id(ctx, data.object, &du->obj)) {
536 err = ERROR_OBJECT;
537 goto error;
538 }
539
540 if (!conf.ubus_noauth && !uh_ubus_allowed(data.sid, data.object, data.function)) {
541 err = ERROR_ACCESS;
542 goto error;
543 }
544
545 uh_ubus_send_request(cl, obj, data.sid, data.data);
546 goto out;
547 }
548 else if (!strcmp(data.method, "list")) {
549 uh_ubus_send_list(cl, obj, data.params);
550 goto out;
551 }
552 else {
553 err = ERROR_METHOD;
554 goto error;
555 }
556
557 error:
558 uh_ubus_json_error(cl, err);
559 out:
560 if (data.params)
561 free(data.params);
562
563 uh_client_unref(cl);
564 }
565
566 static void __uh_ubus_next_batched_request(struct uloop_timeout *timeout)
567 {
568 struct dispatch_ubus *du = container_of(timeout, struct dispatch_ubus, timeout);
569 struct client *cl = container_of(du, struct client, dispatch.ubus);
570 struct json_object *obj = du->jsobj;
571 int len;
572
573 len = json_object_array_length(obj);
574 if (du->array_idx >= len)
575 return uh_ubus_complete_batch(cl);
576
577 obj = json_object_array_get_idx(obj, du->array_idx++);
578 uh_ubus_handle_request_object(cl, obj);
579 }
580
581 static void uh_ubus_data_done(struct client *cl)
582 {
583 struct dispatch_ubus *du = &cl->dispatch.ubus;
584 struct json_object *obj = du->jsobj;
585
586 switch (obj ? json_object_get_type(obj) : json_type_null) {
587 case json_type_object:
588 uh_ubus_send_header(cl);
589 return uh_ubus_handle_request_object(cl, obj);
590 case json_type_array:
591 uh_ubus_init_batch(cl);
592 return uh_ubus_next_batched_request(cl);
593 default:
594 return uh_ubus_single_error(cl, ERROR_PARSE);
595 }
596 }
597
598 static int uh_ubus_data_send(struct client *cl, const char *data, int len)
599 {
600 struct dispatch_ubus *du = &cl->dispatch.ubus;
601
602 if (du->jsobj || !du->jstok)
603 goto error;
604
605 du->post_len += len;
606 if (du->post_len > UH_UBUS_MAX_POST_SIZE)
607 goto error;
608
609 du->jsobj = json_tokener_parse_ex(du->jstok, data, len);
610 return len;
611
612 error:
613 uh_ubus_single_error(cl, ERROR_PARSE);
614 return 0;
615 }
616
617 static void uh_ubus_handle_request(struct client *cl, char *url, struct path_info *pi)
618 {
619 struct dispatch *d = &cl->dispatch;
620
621 blob_buf_init(&buf, 0);
622
623 switch (cl->request.method)
624 {
625 case UH_HTTP_MSG_POST:
626 d->data_send = uh_ubus_data_send;
627 d->data_done = uh_ubus_data_done;
628 d->close_fds = uh_ubus_close_fds;
629 d->free = uh_ubus_request_free;
630 d->ubus.jstok = json_tokener_new();
631 break;
632
633 case UH_HTTP_MSG_OPTIONS:
634 uh_ubus_send_header(cl);
635 ops->request_done(cl);
636 break;
637
638 default:
639 ops->client_error(cl, 400, "Bad Request", "Invalid Request");
640 }
641 }
642
643 static bool
644 uh_ubus_check_url(const char *url)
645 {
646 return ops->path_match(conf.ubus_prefix, url);
647 }
648
649 static int
650 uh_ubus_init(void)
651 {
652 static struct dispatch_handler ubus_dispatch = {
653 .check_url = uh_ubus_check_url,
654 .handle_request = uh_ubus_handle_request,
655 };
656
657 ctx = ubus_connect(conf.ubus_socket);
658 if (!ctx) {
659 fprintf(stderr, "Unable to connect to ubus socket\n");
660 exit(1);
661 }
662
663 ops->dispatch_add(&ubus_dispatch);
664
665 uloop_done();
666 return 0;
667 }
668
669
670 static int uh_ubus_plugin_init(const struct uhttpd_ops *o, struct config *c)
671 {
672 ops = o;
673 _conf = c;
674 return uh_ubus_init();
675 }
676
677 static void uh_ubus_post_init(void)
678 {
679 ubus_add_uloop(ctx);
680 }
681
682 struct uhttpd_plugin uhttpd_plugin = {
683 .init = uh_ubus_plugin_init,
684 .post_init = uh_ubus_post_init,
685 };