1 From aa0c824bb2eeb8960ba02133faade72c837ea951 Mon Sep 17 00:00:00 2001
2 From: Stephen Smalley <sds@tycho.nsa.gov>
3 Date: Wed, 5 Oct 2016 10:45:35 -0400
4 Subject: [PATCH] libselinux: selinux_restorecon: fix realpath logic
6 The realpath logic in selinux_restorecon() was taken from the
7 Android libselinux fork. However, bionic dirname() and basename()
8 do not modify their argument and therefore are safe to call on a
9 const string. POSIX dirname() and basename() can modify their argument.
10 There is a GNU basename() that does not modify its argument, but not
12 For portability, create copies of the original pathname for each call
13 and keep them around until finished using the result.
15 Fixes "restorecon -r goes up the tree?" bug reported by Jason Zaman.
17 Reported-by: Jason Zaman <jason@perfinion.com>
18 Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
20 libselinux/src/selinux_restorecon.c | 26 +++++++++++++++++++++-----
21 1 file changed, 21 insertions(+), 5 deletions(-)
23 diff --git a/libselinux/src/selinux_restorecon.c b/libselinux/src/selinux_restorecon.c
24 index 0945138..e38d1d0 100644
25 --- libselinux/src/selinux_restorecon.c
26 +++ libselinux/src/selinux_restorecon.c
27 @@ -797,25 +797,41 @@ int selinux_restorecon(const char *pathname_orig,
28 * realpath of containing dir, then appending last component name.
30 if (flags.userealpath) {
31 - pathbname = basename((char *)pathname_orig);
32 + char *basename_cpy = strdup(pathname_orig);
35 + pathbname = basename(basename_cpy);
36 if (!strcmp(pathbname, "/") || !strcmp(pathbname, ".") ||
37 !strcmp(pathbname, "..")) {
38 pathname = realpath(pathname_orig, NULL);
45 - pathdname = dirname((char *)pathname_orig);
46 + char *dirname_cpy = strdup(pathname_orig);
51 + pathdname = dirname(dirname_cpy);
52 pathdnamer = realpath(pathdname, NULL);
59 if (!strcmp(pathdnamer, "/"))
60 error = asprintf(&pathname, "/%s", pathbname);
62 error = asprintf(&pathname, "%s/%s",
63 pathdnamer, pathbname);
72 pathname = strdup(pathname_orig);