Bug 1308400 - Symlink handling for read brokering. r=jld
authorGian-Carlo Pascutto <gcp@mozilla.com>
Thu, 06 Jul 2017 15:31:13 +0200
changeset 419462 84b1aafdc1c21d18e060a7059f0af373b683ed9e
parent 419461 167f91f87172c3fd4ca7ac8f8e1f6bd6a2bf2dc1
child 419463 f180a4ed7aabe89f5c038f59a4f7a69d0200a6db
push id7566
push usermtabara@mozilla.com
push dateWed, 02 Aug 2017 08:25:16 +0000
treeherdermozilla-beta@86913f512c3c [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersjld
bugs1308400
milestone56.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1308400 - Symlink handling for read brokering. r=jld MozReview-Commit-ID: BP1gFdDbqXD
security/sandbox/linux/SandboxBrokerClient.cpp
security/sandbox/linux/broker/SandboxBroker.cpp
security/sandbox/linux/broker/SandboxBroker.h
security/sandbox/linux/broker/SandboxBrokerCommon.cpp
security/sandbox/linux/broker/SandboxBrokerCommon.h
security/sandbox/linux/broker/SandboxBrokerRealpath.cpp
security/sandbox/linux/broker/moz.build
--- a/security/sandbox/linux/SandboxBrokerClient.cpp
+++ b/security/sandbox/linux/SandboxBrokerClient.cpp
@@ -138,17 +138,17 @@ SandboxBrokerClient::DoCall(const Reques
     }
     return resp.mError;
   }
   if (SandboxInfo::Get().Test(SandboxInfo::kVerbose)) {
     // Keep in mind that "rejected" files can include ones that don't
     // actually exist, if it's something that's optional or part of a
     // search path (e.g., shared libraries).  In those cases, this
     // error message is expected.
-    SANDBOX_LOG_ERROR("Rejected errno %d op %d flags 0%o path %s",
+    SANDBOX_LOG_ERROR("Failed errno %d op %d flags 0%o path %s",
                       resp.mError, aReq->mOp, aReq->mFlags, path);
   }
   if (openedFd >= 0) {
     close(openedFd);
   }
   return resp.mError;
 }
 
--- a/security/sandbox/linux/broker/SandboxBroker.cpp
+++ b/security/sandbox/linux/broker/SandboxBroker.cpp
@@ -16,16 +16,17 @@
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
 
 #ifdef XP_LINUX
 #include <sys/prctl.h>
 #endif
 
+#include "base/string_util.h"
 #include "mozilla/Assertions.h"
 #include "mozilla/DebugOnly.h"
 #include "mozilla/Move.h"
 #include "mozilla/NullPtr.h"
 #include "mozilla/Sprintf.h"
 #include "mozilla/ipc/FileDescriptor.h"
 #include "sandbox/linux/system_headers/linux_syscalls.h"
 
@@ -195,24 +196,30 @@ SandboxBroker::Policy::AddDir(int aPerms
   if (stat(aPath, &statBuf) != 0) {
     return;
   }
 
   if (!S_ISDIR(statBuf.st_mode)) {
     return;
   }
 
+  // Add a Prefix permission on things inside the dir.
   nsDependentCString path(aPath);
   MOZ_ASSERT(path.Length() <= kMaxPathLen - 1);
   // Enforce trailing / on aPath
-  if (path[path.Length() - 1] != '/') {
+  if (path.Last() != '/') {
     path.Append('/');
   }
+  Policy::AddPrefixInternal(aPerms, path);
 
-  Policy::AddPrefixInternal(aPerms, path);
+  // Add a path permission on the dir itself so it can
+  // be opened. We're guaranteed to have a trailing / now,
+  // so just cut that.
+  path.Truncate(path.Length() - 1);
+  Policy::AddPath(aPerms, path.get(), AddAlways);
 }
 
 void
 SandboxBroker::Policy::AddPrefix(int aPerms, const char* aPath)
 {
   Policy::AddPrefixInternal(aPerms, nsDependentCString(aPath));
 }
 
@@ -418,27 +425,84 @@ DoLink(const char* aPath, const char* aP
 }
 
 size_t
 SandboxBroker::ConvertToRealPath(char* aPath, size_t aBufSize, size_t aPathLen)
 {
   if (strstr(aPath, "..") != nullptr) {
     char* result = realpath(aPath, nullptr);
     if (result != nullptr) {
-      strncpy(aPath, result, aBufSize);
-      aPath[aBufSize - 1] = '\0';
+      base::strlcpy(aPath, result, aBufSize);
       free(result);
       // Size changed, but guaranteed to be 0 terminated
       aPathLen = strlen(aPath);
     }
     // ValidatePath will handle failure to translate
   }
   return aPathLen;
 }
 
+nsCString
+SandboxBroker::ReverseSymlinks(const nsACString& aPath)
+{
+  // Revert any symlinks we previously resolved.
+  int32_t cutLength = aPath.Length();
+  nsCString cutPath(Substring(aPath, 0, cutLength));
+
+  for (;;) {
+    nsCString orig;
+    bool found = mSymlinkMap.Get(cutPath, &orig);
+    if (found) {
+      orig.Append(Substring(aPath, cutLength, aPath.Length() - cutLength));
+      return orig;
+    }
+    // Not found? Remove a path component and try again.
+    int32_t pos = cutPath.RFindChar('/');
+    if (pos == kNotFound || pos <= 0) {
+      // will be empty
+      return orig;
+    } else {
+      // Cut until just before the /
+      cutLength = pos;
+      cutPath.Assign(Substring(cutPath, 0, cutLength));
+    }
+  }
+}
+
+int
+SandboxBroker::SymlinkPermissions(const char* aPath, const size_t aPathLen)
+{
+  // Work on a temporary copy, so we can reverse it.
+  // Because we bail on a writable dir, SymlinkPath
+  // might not restore the callers' path exactly.
+  char pathBufSymlink[kMaxPathLen + 1];
+  strcpy(pathBufSymlink, aPath);
+
+  nsCString orig = ReverseSymlinks(nsDependentCString(pathBufSymlink, aPathLen));
+  if (!orig.IsEmpty()) {
+    if (SandboxInfo::Get().Test(SandboxInfo::kVerbose)) {
+      SANDBOX_LOG_ERROR("Reversing %s -> %s", aPath, orig.get());
+    }
+    base::strlcpy(pathBufSymlink, orig.get(), sizeof(pathBufSymlink));
+  }
+
+  int perms = 0;
+  // Resolve relative paths, propagate permissions and
+  // fail if a symlink is in a writable path. The output is in perms.
+  char* result = SandboxBroker::SymlinkPath(mPolicy.get(), pathBufSymlink, NULL, &perms);
+  if (result != NULL) {
+    free(result);
+    // We finished the translation, so we have a usable return in "perms".
+    return perms;
+  } else {
+    // Empty path means we got a writable dir in the chain.
+    return 0;
+  }
+}
+
 void
 SandboxBroker::ThreadMain(void)
 {
   char threadName[16];
   SprintfLiteral(threadName, "FS Broker %d", mChildPid);
   PlatformThread::SetName(threadName);
 
   // Permissive mode can only be enabled through an environment variable,
@@ -447,18 +511,18 @@ SandboxBroker::ThreadMain(void)
   bool permissive = SandboxInfo::Get().Test(SandboxInfo::kPermissive);
 
   while (true) {
     struct iovec ios[2];
     // We will receive the path strings in 1 buffer and split them back up.
     char recvBuf[2 * (kMaxPathLen + 1)];
     char pathBuf[kMaxPathLen + 1];
     char pathBuf2[kMaxPathLen + 1];
-    size_t pathLen;
-    size_t pathLen2;
+    size_t pathLen = 0;
+    size_t pathLen2 = 0;
     char respBuf[kMaxPathLen + 1]; // Also serves as struct stat
     Request req;
     Response resp;
     int respfd;
 
     // Make sure stat responses fit in the response buffer
     MOZ_ASSERT((kMaxPathLen + 1) > sizeof(struct stat));
 
@@ -533,16 +597,28 @@ SandboxBroker::ThreadMain(void)
 
       // First string is guaranteed to be 0-terminated.
       pathLen = first_len;
 
       // Look up the first pathname but first translate relative paths.
       pathLen = ConvertToRealPath(pathBuf, sizeof(pathBuf), pathLen);
       perms = mPolicy->Lookup(nsDependentCString(pathBuf, pathLen));
 
+      // We don't have read permissions on the requested dir.
+      // Did we arrive from a symlink in a path that is not writable?
+      // Then try to figure out the original path and see if that is readable.
+      if (!(perms & MAY_READ)) {
+          // Work on the original path,
+          // this reverses ConvertToRealPath above.
+          int symlinkPerms = SymlinkPermissions(recvBuf, first_len);
+          if (symlinkPerms > 0) {
+            perms = symlinkPerms;
+          }
+      }
+
       // Same for the second path.
       pathLen2 = strnlen(pathBuf2, kMaxPathLen);
       if (pathLen2 > 0) {
         // Force 0 termination.
         pathBuf2[pathLen2] = '\0';
         pathLen2 = ConvertToRealPath(pathBuf2, sizeof(pathBuf2), pathLen2);
         int perms2 = mPolicy->Lookup(nsDependentCString(pathBuf2, pathLen2));
 
@@ -693,16 +769,44 @@ SandboxBroker::ThreadMain(void)
           AuditDenial(req.mOp, req.mFlags, perms, pathBuf);
         }
         break;
 
       case SANDBOX_FILE_READLINK:
         if (permissive || AllowOperation(R_OK, perms)) {
           ssize_t respSize = readlink(pathBuf, (char*)&respBuf, sizeof(respBuf));
           if (respSize >= 0) {
+              if (respSize > 0) {
+              // Record the mapping so we can invert the file to the original
+              // symlink.
+              nsDependentCString orig(pathBuf, pathLen);
+              nsDependentCString xlat(respBuf, respSize);
+              if (!orig.Equals(xlat) && xlat[0] == '/') {
+                if (SandboxInfo::Get().Test(SandboxInfo::kVerbose)) {
+                  SANDBOX_LOG_ERROR("Recording mapping %s -> %s",
+                                    xlat.get(), orig.get());
+                }
+                mSymlinkMap.Put(xlat, orig);
+              }
+              // Make sure we can invert a fully resolved mapping too. If our
+              // caller is realpath, and there's a relative path involved, the
+              // client side will try to open this one.
+              char *resolvedBuf = realpath(pathBuf, nullptr);
+              if (resolvedBuf) {
+                nsDependentCString resolvedXlat(resolvedBuf);
+                if (!orig.Equals(resolvedXlat) && !xlat.Equals(resolvedXlat)) {
+                  if (SandboxInfo::Get().Test(SandboxInfo::kVerbose)) {
+                    SANDBOX_LOG_ERROR("Recording mapping %s -> %s",
+                                      resolvedXlat.get(), orig.get());
+                  }
+                  mSymlinkMap.Put(resolvedXlat, orig);
+                }
+                free(resolvedBuf);
+              }
+            }
             resp.mError = respSize;
             ios[1].iov_base = &respBuf;
             ios[1].iov_len = respSize;
           } else {
             resp.mError = -errno;
           }
         } else {
           AuditDenial(req.mOp, req.mFlags, perms, pathBuf);
@@ -742,16 +846,16 @@ SandboxBroker::AuditPermissive(int aOp, 
                     " permissive=1 error=\"%s\"", aOp, aFlags, aPerms,
                     aPath, mChildPid, strerror(errno));
 }
 
 void
 SandboxBroker::AuditDenial(int aOp, int aFlags, int aPerms, const char* aPath)
 {
   if (SandboxInfo::Get().Test(SandboxInfo::kVerbose)) {
-    SANDBOX_LOG_ERROR("SandboxBroker: denied op=%d rflags=%o perms=%d path=%s for pid=%d" \
-                      " error=\"%s\"", aOp, aFlags, aPerms, aPath, mChildPid,
-                      strerror(errno));
+    SANDBOX_LOG_ERROR("SandboxBroker: denied op=%s rflags=%o perms=%d path=%s for pid=%d",
+                      OperationDescription[aOp], aFlags,
+                      aPerms, aPath, mChildPid);
   }
 }
 
 
 } // namespace mozilla
--- a/security/sandbox/linux/broker/SandboxBroker.h
+++ b/security/sandbox/linux/broker/SandboxBroker.h
@@ -51,20 +51,20 @@ class SandboxBroker final
     // (This overrides all other flags.)
     CRASH_INSTEAD = 1 << 4,
     // Applies to everything below this path, including subdirs created
     // at runtime
     RECURSIVE     = 1 << 5,
   };
   // Bitwise operations on enum values return ints, so just use int in
   // the hash table type (and below) to avoid cluttering code with casts.
-  typedef nsDataHashtable<nsCStringHashKey, int> PathMap;
+  typedef nsDataHashtable<nsCStringHashKey, int> PathPermissionMap;
 
   class Policy {
-    PathMap mMap;
+    PathPermissionMap mMap;
   public:
     Policy();
     Policy(const Policy& aOther);
     ~Policy();
 
     enum AddCondition {
       AddIfExistsNow,
       AddAlways,
@@ -115,23 +115,32 @@ class SandboxBroker final
   virtual ~SandboxBroker();
 
  private:
   PlatformThreadHandle mThread;
   int mFileDesc;
   const int mChildPid;
   const UniquePtr<const Policy> mPolicy;
 
+  typedef nsDataHashtable<nsCStringHashKey, nsCString> PathMap;
+  PathMap mSymlinkMap;
+
   SandboxBroker(UniquePtr<const Policy> aPolicy, int aChildPid,
                 int& aClientFd);
   void ThreadMain(void) override;
   void AuditPermissive(int aOp, int aFlags, int aPerms, const char* aPath);
   void AuditDenial(int aOp, int aFlags, int aPerms, const char* aPath);
   // Remap relative paths to absolute paths.
   size_t ConvertToRealPath(char* aPath, size_t aBufSize, size_t aPathLen);
+  nsCString ReverseSymlinks(const nsACString& aPath);
+  // Retrieves permissions for the path the original symlink sits in.
+  int SymlinkPermissions(const char* aPath, const size_t aPathLen);
+  // In SandboxBrokerRealPath.cpp
+  char* SymlinkPath(const Policy* aPolicy, const char* __restrict aPath,
+                    char* __restrict aResolved, int* aPermission);
 
   // Holding a UniquePtr should disallow copying, but to make that explicit:
   SandboxBroker(const SandboxBroker&) = delete;
   void operator=(const SandboxBroker&) = delete;
 };
 
 } // namespace mozilla
 
--- a/security/sandbox/linux/broker/SandboxBrokerCommon.cpp
+++ b/security/sandbox/linux/broker/SandboxBrokerCommon.cpp
@@ -25,16 +25,30 @@
 // In the future, if the broker becomes a dedicated executable, this
 // can change.
 #error "No MSG_CMSG_CLOEXEC?"
 #endif // XP_LINUX
 #endif // MSG_CMSG_CLOEXEC
 
 namespace mozilla {
 
+const char* SandboxBrokerCommon::OperationDescription[] = {
+  "open",
+  "access",
+  "stat",
+  "chmod",
+  "link",
+  "symlink",
+  "mkdir",
+  "rename",
+  "rmdir",
+  "unlink",
+  "readlink"
+};
+
 /* static */ ssize_t
 SandboxBrokerCommon::RecvWithFd(int aFd, const iovec* aIO, size_t aNumIO,
                                     int* aPassedFdPtr)
 {
   struct msghdr msg = {};
   msg.msg_iov = const_cast<iovec*>(aIO);
   msg.msg_iovlen = aNumIO;
 
--- a/security/sandbox/linux/broker/SandboxBrokerCommon.h
+++ b/security/sandbox/linux/broker/SandboxBrokerCommon.h
@@ -33,16 +33,18 @@ public:
     SANDBOX_FILE_LINK,
     SANDBOX_FILE_SYMLINK,
     SANDBOX_FILE_MKDIR,
     SANDBOX_FILE_RENAME,
     SANDBOX_FILE_RMDIR,
     SANDBOX_FILE_UNLINK,
     SANDBOX_FILE_READLINK,
   };
+  // String versions of the above
+  static const char* OperationDescription[];
 
   struct Request {
     Operation mOp;
     // For open, flags; for access, "mode"; for stat, O_NOFOLLOW for lstat.
     int mFlags;
     // Size of return value buffer, if any
     size_t mBufSize;
     // The rest of the packet is the pathname.
new file mode 100644
--- /dev/null
+++ b/security/sandbox/linux/broker/SandboxBrokerRealpath.cpp
@@ -0,0 +1,302 @@
+/*
+ * Copyright (c) 2003 Constantin S. Svintsoff <kostik@iclub.nsu.ru>
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The names of the authors may not be used to endorse or promote
+ *    products derived from this software without specific prior written
+ *    permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * This is originally from:
+ * android-n-mr2-preview-1-303-gccec0f4c1
+ * libc/upstream-freebsd/lib/libc/stdlib/realpath.c
+ */
+
+#if defined(LIBC_SCCS) && !defined(lint)
+static char sccsid[] = "@(#)realpath.c	8.1 (Berkeley) 2/16/94";
+#endif /* LIBC_SCCS and not lint */
+#include <sys/cdefs.h>
+
+#include <sys/param.h>
+#include <sys/stat.h>
+
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "base/string_util.h"
+#include "SandboxBroker.h"
+
+// base::strlcpy
+using namespace base;
+
+// Original copy in, but not usable from here:
+// toolkit/crashreporter/google-breakpad/src/common/linux/linux_libc_support.cc
+static size_t my_strlcat(char* s1, const char* s2, size_t len) {
+  size_t pos1 = 0;
+
+  while (pos1 < len && s1[pos1] != '\0')
+    pos1++;
+
+  if (pos1 == len)
+    return pos1;
+
+  return pos1 + strlcpy(s1 + pos1, s2, len - pos1);
+}
+
+namespace mozilla {
+
+/*
+ * Original: realpath
+ * Find the real name of path, by removing all ".", ".." and symlink
+ * components.  Returns (resolved) on success, or (NULL) on failure,
+ * in which case the path which caused trouble is left in (resolved).
+ * Changes:
+ * Resolve relative paths, but don't allow backing out of a symlink
+ * target. Fail with permission error if any dir is writable.
+ */
+char* SandboxBroker::SymlinkPath(const Policy* policy,
+                                 const char* __restrict path,
+                                 char* __restrict resolved,
+                                 int* perms)
+{
+    struct stat sb;
+    char *p, *q, *s;
+    size_t left_len, resolved_len, backup_allowed;
+    unsigned symlinks;
+    int m, slen;
+    char left[PATH_MAX], next_token[PATH_MAX], symlink[PATH_MAX];
+
+    if (*perms) {
+        *perms = 0;
+    }
+    if (path == NULL) {
+        errno = EINVAL;
+        return (NULL);
+    }
+    if (path[0] == '\0') {
+        errno = ENOENT;
+        return (NULL);
+    }
+    if (resolved == NULL) {
+        resolved = (char*)malloc(PATH_MAX);
+        if (resolved == NULL)
+            return (NULL);
+        m = 1;
+    } else
+        m = 0;
+    symlinks = 0;
+    backup_allowed = PATH_MAX;
+    if (path[0] == '/') {
+        resolved[0] = '/';
+        resolved[1] = '\0';
+        if (path[1] == '\0')
+            return (resolved);
+        resolved_len = 1;
+        left_len = strlcpy(left, path + 1, sizeof(left));
+    } else {
+        if (getcwd(resolved, PATH_MAX) == NULL) {
+            if (m)
+                free(resolved);
+            else {
+                resolved[0] = '.';
+                resolved[1] = '\0';
+            }
+            return (NULL);
+        }
+        resolved_len = strlen(resolved);
+        left_len = strlcpy(left, path, sizeof(left));
+    }
+    if (left_len >= sizeof(left) || resolved_len >= PATH_MAX) {
+        if (m)
+            free(resolved);
+        errno = ENAMETOOLONG;
+        return (NULL);
+    }
+
+    /*
+     * Iterate over path components in `left'.
+     */
+    while (left_len != 0) {
+        /*
+         * Extract the next path component and adjust `left'
+         * and its length.
+         */
+        p = strchr(left, '/');
+        s = p ? p : left + left_len;
+        if (s - left >= (ssize_t)sizeof(next_token)) {
+            if (m)
+                free(resolved);
+            errno = ENAMETOOLONG;
+            return (NULL);
+        }
+        memcpy(next_token, left, s - left);
+        next_token[s - left] = '\0';
+        left_len -= s - left;
+        if (p != NULL)
+            memmove(left, s + 1, left_len + 1);
+        if (resolved[resolved_len - 1] != '/') {
+            if (resolved_len + 1 >= PATH_MAX) {
+                if (m)
+                    free(resolved);
+                errno = ENAMETOOLONG;
+                return (NULL);
+            }
+            resolved[resolved_len++] = '/';
+            resolved[resolved_len] = '\0';
+        }
+        if (next_token[0] == '\0') {
+            /* Handle consequential slashes. */
+            continue;
+        }
+        else if (strcmp(next_token, ".") == 0)
+            continue;
+        else if (strcmp(next_token, "..") == 0) {
+            /*
+             * Strip the last path component except when we have
+             * single "/"
+             */
+            if (resolved_len > 1) {
+                if (backup_allowed > 0) {
+                    resolved[resolved_len - 1] = '\0';
+                    q = strrchr(resolved, '/') + 1;
+                    *q = '\0';
+                    resolved_len = q - resolved;
+                    backup_allowed--;
+                } else {
+                    // Backing out past a symlink target.
+                    // We don't allow this, because it can eliminate
+                    // permissions we accumulated while descending.
+                    if (m)
+                        free(resolved);
+                    errno = EPERM;
+                    return (NULL);
+                }
+            }
+            continue;
+        }
+
+        /*
+         * Append the next path component and lstat() it.
+         */
+        resolved_len = my_strlcat(resolved, next_token, PATH_MAX);
+        backup_allowed++;
+        if (resolved_len >= PATH_MAX) {
+            if (m)
+                free(resolved);
+            errno = ENAMETOOLONG;
+            return (NULL);
+        }
+        if (lstat(resolved, &sb) != 0) {
+            if (m)
+                free(resolved);
+            return (NULL);
+        }
+        if (S_ISLNK(sb.st_mode)) {
+            if (symlinks++ > MAXSYMLINKS) {
+                if (m)
+                    free(resolved);
+                errno = ELOOP;
+                return (NULL);
+            }
+            /* Our changes start here:
+             * It's a symlink, check for write permissions on the path where
+             * it sits in, in which case we won't resolve and just error out. */
+            int link_path_perms = policy->Lookup(resolved);
+            if (link_path_perms & MAY_WRITE) {
+                if (m)
+                    free(resolved);
+                errno = EPERM;
+                return (NULL);
+            } else {
+                /* Accumulate permissions so far */
+                *perms |= link_path_perms;
+            }
+            /* Original symlink lookup code */
+            slen = readlink(resolved, symlink, sizeof(symlink) - 1);
+            if (slen < 0) {
+                if (m)
+                    free(resolved);
+                return (NULL);
+            }
+            symlink[slen] = '\0';
+            if (symlink[0] == '/') {
+                resolved[1] = 0;
+                resolved_len = 1;
+            } else if (resolved_len > 1) {
+                /* Strip the last path component. */
+                resolved[resolved_len - 1] = '\0';
+                q = strrchr(resolved, '/') + 1;
+                *q = '\0';
+                resolved_len = q - resolved;
+            }
+
+            /*
+             * If there are any path components left, then
+             * append them to symlink. The result is placed
+             * in `left'.
+             */
+            if (p != NULL) {
+                if (symlink[slen - 1] != '/') {
+                    if (slen + 1 >= (ssize_t)sizeof(symlink)) {
+                        if (m)
+                            free(resolved);
+                        errno = ENAMETOOLONG;
+                        return (NULL);
+                    }
+                    symlink[slen] = '/';
+                    symlink[slen + 1] = 0;
+                }
+                left_len = my_strlcat(symlink, left, sizeof(symlink));
+                if (left_len >= sizeof(left)) {
+                    if (m)
+                        free(resolved);
+                    errno = ENAMETOOLONG;
+                    return (NULL);
+                }
+            }
+            left_len = strlcpy(left, symlink, sizeof(left));
+            backup_allowed = 0;
+        } else if (!S_ISDIR(sb.st_mode) && p != NULL) {
+            if (m)
+                free(resolved);
+            errno = ENOTDIR;
+            return (NULL);
+        }
+    }
+
+    /*
+     * Remove trailing slash except when the resolved pathname
+     * is a single "/".
+     */
+    if (resolved_len > 1 && resolved[resolved_len - 1] == '/')
+        resolved[resolved_len - 1] = '\0';
+
+    /* Accumulate permissions. */
+    *perms |= policy->Lookup(resolved);
+
+    return (resolved);
+}
+
+}
--- a/security/sandbox/linux/broker/moz.build
+++ b/security/sandbox/linux/broker/moz.build
@@ -9,16 +9,17 @@ EXPORTS.mozilla += [
     'SandboxBrokerCommon.h',
     'SandboxBrokerPolicyFactory.h',
 ]
 
 SOURCES += [
     'SandboxBroker.cpp',
     'SandboxBrokerCommon.cpp',
     'SandboxBrokerPolicyFactory.cpp',
+    'SandboxBrokerRealpath.cpp',
 ]
 
 if CONFIG['MOZ_ALSA']:
     DEFINES['MOZ_ALSA'] = True
 
 LOCAL_INCLUDES += [
     '/security/sandbox/linux', # SandboxLogging.h, SandboxInfo.h
 ]