2 * cgi-io - LuCI non-RPC helper
4 * Copyright (C) 2013 Jo-Philipp Wich <jo@mein.io>
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 #define _GNU_SOURCE /* splice(), SPLICE_F_MORE */
31 #include <sys/sendfile.h>
32 #include <sys/ioctl.h>
36 #include <libubox/blobmsg.h>
38 #include "multipart_parser.h"
41 #define O_TMPFILE (020000000 | O_DIRECTORY)
44 #define READ_BLOCK 4096
45 #define POST_LIMIT 131072
55 const char *parts
[] = {
65 bool is_content_disposition
;
80 static const struct blobmsg_policy ses_policy
[__SES_MAX
] = {
81 [SES_ACCESS
] = { .name
= "access", .type
= BLOBMSG_TYPE_BOOL
},
85 static struct state st
;
88 session_access_cb(struct ubus_request
*req
, int type
, struct blob_attr
*msg
)
90 struct blob_attr
*tb
[__SES_MAX
];
91 bool *allow
= (bool *)req
->priv
;
96 blobmsg_parse(ses_policy
, __SES_MAX
, tb
, blob_data(msg
), blob_len(msg
));
99 *allow
= blobmsg_get_bool(tb
[SES_ACCESS
]);
103 session_access(const char *sid
, const char *scope
, const char *obj
, const char *func
)
107 struct ubus_context
*ctx
;
108 static struct blob_buf req
;
110 ctx
= ubus_connect(NULL
);
112 if (!ctx
|| !obj
|| ubus_lookup_id(ctx
, "session", &id
))
115 blob_buf_init(&req
, 0);
116 blobmsg_add_string(&req
, "ubus_rpc_session", sid
);
117 blobmsg_add_string(&req
, "scope", scope
);
118 blobmsg_add_string(&req
, "object", obj
);
119 blobmsg_add_string(&req
, "function", func
);
121 ubus_invoke(ctx
, id
, "access", req
.head
, session_access_cb
, &allow
, 500);
131 checksum(const char *applet
, size_t sumlen
, const char *file
)
136 static char chksum
[65];
141 switch ((pid
= fork()))
156 if (execl("/bin/busybox", "/bin/busybox", applet
, file
, NULL
))
162 memset(chksum
, 0, sizeof(chksum
));
163 r
= read(fds
[0], chksum
, sumlen
);
165 waitpid(pid
, NULL
, 0);
177 datadup(const void *in
, size_t len
)
179 char *out
= malloc(len
+ 1);
184 memcpy(out
, in
, len
);
200 (((x) <= '9') ? ((x) - '0') : \
201 (((x) <= 'F') ? ((x) - 'A' + 10) : \
204 for (c
= p
= buf
; *p
; c
++)
208 if (!isxdigit(*(p
+ 1)) || !isxdigit(*(p
+ 2)))
211 *c
= (char)(16 * hex(*(p
+ 1)) + hex(*(p
+ 2)));
232 postdecode(char **fields
, int n_fields
)
236 int i
, field
, found
= 0;
237 ssize_t len
= 0, rlen
= 0, content_length
= 0;
239 var
= getenv("CONTENT_TYPE");
241 if (!var
|| strncmp(var
, "application/x-www-form-urlencoded", 33))
244 var
= getenv("CONTENT_LENGTH");
249 content_length
= strtol(var
, &p
, 10);
251 if (p
== var
|| content_length
<= 0 || content_length
>= POST_LIMIT
)
254 postbuf
= calloc(1, content_length
+ 1);
259 for (len
= 0; len
< content_length
; )
261 rlen
= read(0, postbuf
+ len
, content_length
- len
);
269 if (len
< content_length
)
275 for (p
= postbuf
, i
= 0; i
<= len
; i
++)
277 if (postbuf
[i
] == '=')
281 for (field
= 0; field
< (n_fields
* 2); field
+= 2)
283 if (!strcmp(p
, fields
[field
]))
285 fields
[field
+ 1] = postbuf
+ i
+ 1;
290 else if (postbuf
[i
] == '&' || postbuf
[i
] == '\0')
294 if (found
>= n_fields
)
301 for (field
= 0; field
< (n_fields
* 2); field
+= 2)
303 if (!urldecode(fields
[field
+ 1]))
314 canonicalize_path(const char *path
, size_t len
)
316 char *canonpath
, *cp
;
319 if (path
== NULL
|| *path
== '\0')
322 canonpath
= datadup(path
, len
);
324 if (canonpath
== NULL
)
328 for (cp
= canonpath
, p
= path
, e
= path
+ len
; p
< e
; ) {
332 /* skip repeating / */
333 if ((p
+ 1 < e
) && (p
[1] == '/')) {
339 if ((p
+ 1 < e
) && (p
[1] == '.')) {
341 if ((p
+ 2 >= e
) || (p
[2] == '/')) {
346 /* collapse /x/../ */
347 if ((p
+ 2 < e
) && (p
[2] == '.') && ((p
+ 3 >= e
) || (p
[3] == '/'))) {
348 while ((cp
> canonpath
) && (*--cp
!= '/'))
360 /* remove trailing slash if not root / */
361 if ((cp
> canonpath
+ 1) && (cp
[-1] == '/'))
363 else if (cp
== canonpath
)
372 response(bool success
, const char *message
)
377 printf("Status: 200 OK\r\n");
378 printf("Content-Type: text/plain\r\n\r\n{\n");
382 if (!stat(st
.filename
, &s
))
383 printf("\t\"size\": %u,\n", (unsigned int)s
.st_size
);
385 printf("\t\"size\": null,\n");
387 chksum
= checksum("md5sum", 32, st
.filename
);
388 printf("\t\"checksum\": %s%s%s,\n",
390 chksum
? chksum
: "null",
393 chksum
= checksum("sha256sum", 64, st
.filename
);
394 printf("\t\"sha256sum\": %s%s%s\n",
396 chksum
? chksum
: "null",
402 printf("\t\"message\": \"%s\",\n", message
);
404 printf("\t\"failure\": [ %u, \"%s\" ]\n", errno
, strerror(errno
));
406 if (st
.filefd
> -1 && st
.filename
)
416 failure(int code
, int e
, const char *message
)
418 printf("Status: %d %s\r\n", code
, message
);
419 printf("Content-Type: text/plain\r\n\r\n");
420 printf("%s", message
);
423 printf(": %s", strerror(e
));
434 char buf
[READ_BLOCK
];
440 return response(false, "No file data received");
443 snprintf(buf
, sizeof(buf
), "/proc/self/fd/%d", st
.tempfd
);
445 if (unlink(st
.filename
) < 0 && errno
!= ENOENT
)
448 return response(false, "Failed to unlink existing file");
451 if (linkat(AT_FDCWD
, buf
, AT_FDCWD
, st
.filename
, AT_SYMLINK_FOLLOW
) < 0)
453 if (lseek(st
.tempfd
, 0, SEEK_SET
) < 0)
456 return response(false, "Failed to rewind temp file");
459 st
.filefd
= open(st
.filename
, O_CREAT
| O_TRUNC
| O_WRONLY
, 0600);
464 return response(false, "Failed to open target file");
467 while ((len
= read(st
.tempfd
, buf
, sizeof(buf
))) > 0)
469 if (write(st
.filefd
, buf
, len
) != len
)
473 return response(false, "I/O failure while writing target file");
482 if (chmod(st
.filename
, st
.filemode
))
483 return response(false, "Failed to chmod target file");
489 header_field(multipart_parser
*p
, const char *data
, size_t len
)
491 st
.is_content_disposition
= !strncasecmp(data
, "Content-Disposition", len
);
496 header_value(multipart_parser
*p
, const char *data
, size_t len
)
500 if (!st
.is_content_disposition
)
503 if (len
< 10 || strncasecmp(data
, "form-data", 9))
506 for (data
+= 9, len
-= 9; *data
== ' ' || *data
== ';'; data
++, len
--);
508 if (len
< 8 || strncasecmp(data
, "name=\"", 6))
511 for (data
+= 6, len
-= 6, i
= 0; i
<= len
; i
++)
513 if (*(data
+ i
) != '"')
516 for (j
= 1; j
< sizeof(parts
) / sizeof(parts
[0]); j
++)
517 if (!strncmp(data
, parts
[j
], i
))
527 data_begin_cb(multipart_parser
*p
)
529 if (st
.parttype
== PART_FILEDATA
)
532 return response(false, "File data without session");
535 return response(false, "File data without name");
537 if (!session_access(st
.sessionid
, "file", st
.filename
, "write"))
538 return response(false, "Access to path denied by ACL");
540 st
.tempfd
= open("/tmp", O_TMPFILE
| O_RDWR
, S_IRUSR
| S_IWUSR
);
543 return response(false, "Failed to create temporary file");
550 data_cb(multipart_parser
*p
, const char *data
, size_t len
)
557 st
.sessionid
= datadup(data
, len
);
561 st
.filename
= canonicalize_path(data
, len
);
565 st
.filemode
= strtoul(data
, NULL
, 8);
569 if (write(st
.tempfd
, data
, len
) != wlen
)
572 return response(false, "I/O failure while writing temporary file");
576 st
.filedata
= !!wlen
;
588 data_end_cb(multipart_parser
*p
)
590 if (st
.parttype
== PART_SESSIONID
)
592 if (!session_access(st
.sessionid
, "cgi-io", "upload", "write"))
595 return response(false, "Upload permission denied");
598 else if (st
.parttype
== PART_FILEDATA
)
601 return response(false, "Internal program failure");
604 /* prepare directory */
605 for (ptr
= st
.filename
; *ptr
; ptr
++)
611 if (mkdir(st
.filename
, 0755))
614 return response(false, "Failed to create destination directory");
625 return response(true, NULL
);
628 st
.parttype
= PART_UNKNOWN
;
632 static multipart_parser
*
639 static multipart_parser_settings s
= {
640 .on_part_data
= data_cb
,
641 .on_headers_complete
= data_begin_cb
,
642 .on_part_data_end
= data_end_cb
,
643 .on_header_field
= header_field
,
644 .on_header_value
= header_value
647 var
= getenv("CONTENT_TYPE");
649 if (!var
|| strncmp(var
, "multipart/form-data;", 20))
652 for (var
+= 20; *var
&& *var
!= '='; var
++);
657 boundary
= malloc(strlen(var
) + 3);
662 strcpy(boundary
, "--");
663 strcpy(boundary
+ 2, var
);
669 p
= multipart_parser_init(boundary
, &s
);
677 main_upload(int argc
, char *argv
[])
681 char buf
[READ_BLOCK
];
689 return response(false, "Invalid request");
692 while ((len
= read(0, buf
, sizeof(buf
))) > 0)
695 rem
= multipart_parser_execute(p
, buf
, len
);
700 multipart_parser_free(p
);
706 free_charp(char **ptr
)
711 #define autochar __attribute__((__cleanup__(free_charp))) char
714 main_download(int argc
, char **argv
)
716 char *fields
[] = { "sessionid", NULL
, "path", NULL
, "filename", NULL
, "mimetype", NULL
};
717 unsigned long long size
= 0;
718 char *p
, buf
[READ_BLOCK
];
723 autochar
*post
= postdecode(fields
, 4);
725 if (!fields
[1] || !session_access(fields
[1], "cgi-io", "download", "read"))
726 return failure(403, 0, "Download permission denied");
728 if (!fields
[3] || !session_access(fields
[1], "file", fields
[3], "read"))
729 return failure(403, 0, "Access to path denied by ACL");
731 if (stat(fields
[3], &s
))
732 return failure(404, errno
, "Failed to stat requested path");
734 if (!S_ISREG(s
.st_mode
) && !S_ISBLK(s
.st_mode
))
735 return failure(403, 0, "Requested path is not a regular file or block device");
737 for (p
= fields
[5]; p
&& *p
; p
++)
738 if (!isalnum(*p
) && !strchr(" ()<>@,;:[]?.=%-", *p
))
739 return failure(400, 0, "Invalid characters in filename");
741 for (p
= fields
[7]; p
&& *p
; p
++)
742 if (!isalnum(*p
) && !strchr(" .;=/-", *p
))
743 return failure(400, 0, "Invalid characters in mimetype");
745 rfd
= open(fields
[3], O_RDONLY
);
748 return failure(500, errno
, "Failed to open requested path");
750 if (S_ISBLK(s
.st_mode
))
751 ioctl(rfd
, BLKGETSIZE64
, &size
);
753 size
= (unsigned long long)s
.st_size
;
755 printf("Status: 200 OK\r\n");
756 printf("Content-Type: %s\r\n", fields
[7] ? fields
[7] : "application/octet-stream");
759 printf("Content-Disposition: attachment; filename=\"%s\"\r\n", fields
[5]);
762 printf("Content-Length: %llu\r\n\r\n", size
);
766 len
= sendfile(1, rfd
, NULL
, size
);
769 if (errno
== ENOSYS
|| errno
== EINVAL
) {
770 while ((len
= read(rfd
, buf
, sizeof(buf
))) > 0)
771 fwrite(buf
, len
, 1, stdout
);
777 if (errno
== EINTR
|| errno
== EAGAIN
)
790 while ((len
= read(rfd
, buf
, sizeof(buf
))) > 0)
791 fwrite(buf
, len
, 1, stdout
);
802 main_backup(int argc
, char **argv
)
810 char datestr
[16] = { 0 };
811 char hostname
[64] = { 0 };
812 char *fields
[] = { "sessionid", NULL
};
814 autochar
*post
= postdecode(fields
, 1);
816 if (!fields
[1] || !session_access(fields
[1], "cgi-io", "backup", "read"))
817 return failure(403, 0, "Backup permission denied");
820 return failure(500, errno
, "Failed to spawn pipe");
822 switch ((pid
= fork()))
825 return failure(500, errno
, "Failed to fork process");
837 return failure(500, errno
, "Failed chdir('/')");
839 execl("/sbin/sysupgrade", "/sbin/sysupgrade",
840 "--create-backup", "-", NULL
);
848 strftime(datestr
, sizeof(datestr
) - 1, "%Y-%m-%d", localtime(&now
));
850 if (gethostname(hostname
, sizeof(hostname
) - 1))
851 sprintf(hostname
, "OpenWrt");
853 printf("Status: 200 OK\r\n");
854 printf("Content-Type: application/x-targz\r\n");
855 printf("Content-Disposition: attachment; "
856 "filename=\"backup-%s-%s.tar.gz\"\r\n\r\n", hostname
, datestr
);
861 len
= splice(fds
[0], NULL
, 1, NULL
, READ_BLOCK
, SPLICE_F_MORE
);
864 waitpid(pid
, &status
, 0);
874 lookup_executable(const char *cmd
)
876 size_t plen
= 0, clen
;
877 static char path
[PATH_MAX
];
884 clen
= strlen(cmd
) + 1;
886 if (!stat(cmd
, &s
) && S_ISREG(s
.st_mode
))
889 search
= getenv("PATH");
892 search
= "/bin:/usr/bin:/sbin:/usr/sbin";
897 if (*p
!= ':' && *p
!= '\0')
902 if ((plen
+ clen
) >= sizeof(path
))
905 strncpy(path
, search
, plen
);
906 sprintf(path
+ plen
, "/%s", cmd
);
908 if (!stat(path
, &s
) && S_ISREG(s
.st_mode
))
918 parse_command(const char *cmdline
)
920 const char *p
= cmdline
, *s
;
921 char **argv
= NULL
, *out
;
926 while (isspace(*cmdline
))
929 for (p
= cmdline
, s
= p
, esc
= false; p
; p
++) {
933 else if (*p
== '\\' && p
[1] != 0) {
936 else if (isspace(*p
) || *p
== 0) {
939 arglen
+= sizeof(char *) + (p
- s
) + 1;
952 argv
= calloc(1, arglen
+ sizeof(char *));
957 out
= (char *)argv
+ sizeof(char *) * (argnum
+ 1);
960 for (p
= cmdline
, s
= p
, esc
= false, argnum
= 0; p
; p
++) {
965 else if (*p
== '\\' && p
[1] != 0) {
968 else if (isspace(*p
) || *p
== 0) {
971 argv
[++argnum
] = out
;
991 main_exec(int argc
, char **argv
)
993 char *fields
[] = { "sessionid", NULL
, "command", NULL
, "filename", NULL
, "mimetype", NULL
};
994 int i
, devnull
, status
, fds
[2];
995 bool allowed
= false;
1001 autochar
*post
= postdecode(fields
, 4);
1003 if (!fields
[1] || !session_access(fields
[1], "cgi-io", "exec", "read"))
1004 return failure(403, 0, "Exec permission denied");
1006 for (p
= fields
[5]; p
&& *p
; p
++)
1007 if (!isalnum(*p
) && !strchr(" ()<>@,;:[]?.=%-", *p
))
1008 return failure(400, 0, "Invalid characters in filename");
1010 for (p
= fields
[7]; p
&& *p
; p
++)
1011 if (!isalnum(*p
) && !strchr(" .;=/-", *p
))
1012 return failure(400, 0, "Invalid characters in mimetype");
1014 args
= fields
[3] ? parse_command(fields
[3]) : NULL
;
1017 return failure(400, 0, "Invalid command parameter");
1019 /* First check if we find an ACL match for the whole cmdline ... */
1020 allowed
= session_access(fields
[1], "file", args
[0], "exec");
1022 /* Now split the command vector... */
1023 for (i
= 1; args
[i
]; i
++)
1026 /* Find executable... */
1027 exe
= lookup_executable(args
[0]);
1031 return failure(404, 0, "Executable not found");
1034 /* If there was no ACL match, check for a match on the executable */
1035 if (!allowed
&& !session_access(fields
[1], "file", exe
, "exec")) {
1037 return failure(403, 0, "Access to command denied by ACL");
1042 return failure(500, errno
, "Failed to spawn pipe");
1045 switch ((pid
= fork()))
1051 return failure(500, errno
, "Failed to fork process");
1054 devnull
= open("/dev/null", O_RDWR
);
1070 if (chdir("/") < 0) {
1072 return failure(500, errno
, "Failed chdir('/')");
1075 if (execv(exe
, args
) < 0) {
1077 return failure(500, errno
, "Failed execv(...)");
1085 printf("Status: 200 OK\r\n");
1086 printf("Content-Type: %s\r\n",
1087 fields
[7] ? fields
[7] : "application/octet-stream");
1090 printf("Content-Disposition: attachment; filename=\"%s\"\r\n",
1097 len
= splice(fds
[0], NULL
, 1, NULL
, READ_BLOCK
, SPLICE_F_MORE
);
1100 waitpid(pid
, &status
, 0);
1109 int main(int argc
, char **argv
)
1111 if (strstr(argv
[0], "cgi-upload"))
1112 return main_upload(argc
, argv
);
1113 else if (strstr(argv
[0], "cgi-download"))
1114 return main_download(argc
, argv
);
1115 else if (strstr(argv
[0], "cgi-backup"))
1116 return main_backup(argc
, argv
);
1117 else if (strstr(argv
[0], "cgi-exec"))
1118 return main_exec(argc
, argv
);