xref: /aosp_15_r20/external/cronet/base/memory/platform_shared_memory_region_win.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2018 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/memory/platform_shared_memory_region.h"
6 
7 #include <aclapi.h>
8 #include <stddef.h>
9 #include <stdint.h>
10 
11 #include "base/bits.h"
12 #include "base/logging.h"
13 #include "base/metrics/histogram_functions.h"
14 #include "base/metrics/histogram_macros.h"
15 #include "base/process/process_handle.h"
16 #include "base/strings/string_util.h"
17 #include "partition_alloc/page_allocator.h"
18 
19 namespace base::subtle {
20 
21 namespace {
22 
23 typedef enum _SECTION_INFORMATION_CLASS {
24   SectionBasicInformation,
25 } SECTION_INFORMATION_CLASS;
26 
27 typedef struct _SECTION_BASIC_INFORMATION {
28   PVOID BaseAddress;
29   ULONG Attributes;
30   LARGE_INTEGER Size;
31 } SECTION_BASIC_INFORMATION, *PSECTION_BASIC_INFORMATION;
32 
33 typedef ULONG(__stdcall* NtQuerySectionType)(
34     HANDLE SectionHandle,
35     SECTION_INFORMATION_CLASS SectionInformationClass,
36     PVOID SectionInformation,
37     ULONG SectionInformationLength,
38     PULONG ResultLength);
39 
40 // Checks if the section object is safe to map. At the moment this just means
41 // it's not an image section.
IsSectionSafeToMap(HANDLE handle)42 bool IsSectionSafeToMap(HANDLE handle) {
43   static NtQuerySectionType nt_query_section_func =
44       reinterpret_cast<NtQuerySectionType>(
45           ::GetProcAddress(::GetModuleHandle(L"ntdll.dll"), "NtQuerySection"));
46   DCHECK(nt_query_section_func);
47 
48   // The handle must have SECTION_QUERY access for this to succeed.
49   SECTION_BASIC_INFORMATION basic_information = {};
50   ULONG status =
51       nt_query_section_func(handle, SectionBasicInformation, &basic_information,
52                             sizeof(basic_information), nullptr);
53   if (status)
54     return false;
55   return (basic_information.Attributes & SEC_IMAGE) != SEC_IMAGE;
56 }
57 
58 // Returns a HANDLE on success and |nullptr| on failure.
59 // This function is similar to CreateFileMapping, but removes the permissions
60 // WRITE_DAC, WRITE_OWNER, READ_CONTROL, and DELETE.
61 //
62 // A newly created file mapping has two sets of permissions. It has access
63 // control permissions (WRITE_DAC, WRITE_OWNER, READ_CONTROL, and DELETE) and
64 // file permissions (FILE_MAP_READ, FILE_MAP_WRITE, etc.). The Chrome sandbox
65 // prevents HANDLEs with the WRITE_DAC permission from being duplicated into
66 // unprivileged processes.
67 //
68 // In order to remove the access control permissions, after being created the
69 // handle is duplicated with only the file access permissions.
CreateFileMappingWithReducedPermissions(SECURITY_ATTRIBUTES * sa,size_t rounded_size,LPCWSTR name)70 HANDLE CreateFileMappingWithReducedPermissions(SECURITY_ATTRIBUTES* sa,
71                                                size_t rounded_size,
72                                                LPCWSTR name) {
73   HANDLE h = CreateFileMapping(INVALID_HANDLE_VALUE, sa, PAGE_READWRITE, 0,
74                                static_cast<DWORD>(rounded_size), name);
75   if (!h) {
76     return nullptr;
77   }
78 
79   HANDLE h2;
80   ProcessHandle process = GetCurrentProcess();
81   BOOL success = ::DuplicateHandle(
82       process, h, process, &h2, FILE_MAP_READ | FILE_MAP_WRITE | SECTION_QUERY,
83       FALSE, 0);
84   BOOL rv = ::CloseHandle(h);
85   DCHECK(rv);
86 
87   if (!success) {
88     return nullptr;
89   }
90 
91   return h2;
92 }
93 
94 }  // namespace
95 
96 // static
Take(win::ScopedHandle handle,Mode mode,size_t size,const UnguessableToken & guid)97 PlatformSharedMemoryRegion PlatformSharedMemoryRegion::Take(
98     win::ScopedHandle handle,
99     Mode mode,
100     size_t size,
101     const UnguessableToken& guid) {
102   if (!handle.is_valid())
103     return {};
104 
105   if (size == 0)
106     return {};
107 
108   if (size > static_cast<size_t>(std::numeric_limits<int>::max()))
109     return {};
110 
111   if (!IsSectionSafeToMap(handle.get()))
112     return {};
113 
114   CHECK(
115       CheckPlatformHandlePermissionsCorrespondToMode(handle.get(), mode, size));
116 
117   return PlatformSharedMemoryRegion(std::move(handle), mode, size, guid);
118 }
119 
GetPlatformHandle() const120 HANDLE PlatformSharedMemoryRegion::GetPlatformHandle() const {
121   return handle_.get();
122 }
123 
IsValid() const124 bool PlatformSharedMemoryRegion::IsValid() const {
125   return handle_.is_valid();
126 }
127 
Duplicate() const128 PlatformSharedMemoryRegion PlatformSharedMemoryRegion::Duplicate() const {
129   if (!IsValid())
130     return {};
131 
132   CHECK_NE(mode_, Mode::kWritable)
133       << "Duplicating a writable shared memory region is prohibited";
134 
135   HANDLE duped_handle;
136   ProcessHandle process = GetCurrentProcess();
137   BOOL success =
138       ::DuplicateHandle(process, handle_.get(), process, &duped_handle, 0,
139                         FALSE, DUPLICATE_SAME_ACCESS);
140   if (!success)
141     return {};
142 
143   return PlatformSharedMemoryRegion(win::ScopedHandle(duped_handle), mode_,
144                                     size_, guid_);
145 }
146 
ConvertToReadOnly()147 bool PlatformSharedMemoryRegion::ConvertToReadOnly() {
148   if (!IsValid())
149     return false;
150 
151   CHECK_EQ(mode_, Mode::kWritable)
152       << "Only writable shared memory region can be converted to read-only";
153 
154   win::ScopedHandle handle_copy(handle_.release());
155 
156   HANDLE duped_handle;
157   ProcessHandle process = GetCurrentProcess();
158   BOOL success =
159       ::DuplicateHandle(process, handle_copy.get(), process, &duped_handle,
160                         FILE_MAP_READ | SECTION_QUERY, FALSE, 0);
161   if (!success)
162     return false;
163 
164   handle_.Set(duped_handle);
165   mode_ = Mode::kReadOnly;
166   return true;
167 }
168 
ConvertToUnsafe()169 bool PlatformSharedMemoryRegion::ConvertToUnsafe() {
170   if (!IsValid())
171     return false;
172 
173   CHECK_EQ(mode_, Mode::kWritable)
174       << "Only writable shared memory region can be converted to unsafe";
175 
176   mode_ = Mode::kUnsafe;
177   return true;
178 }
179 
180 // static
Create(Mode mode,size_t size)181 PlatformSharedMemoryRegion PlatformSharedMemoryRegion::Create(Mode mode,
182                                                               size_t size) {
183   // TODO(crbug.com/210609): NaCl forces us to round up 64k here, wasting 32k
184   // per mapping on average.
185   static const size_t kSectionSize = 65536;
186   if (size == 0) {
187     return {};
188   }
189 
190   // Aligning may overflow so check that the result doesn't decrease.
191   size_t rounded_size = bits::AlignUp(size, kSectionSize);
192   if (rounded_size < size ||
193       rounded_size > static_cast<size_t>(std::numeric_limits<int>::max())) {
194     return {};
195   }
196 
197   CHECK_NE(mode, Mode::kReadOnly) << "Creating a region in read-only mode will "
198                                      "lead to this region being non-modifiable";
199 
200   // Add an empty DACL to enforce anonymous read-only sections.
201   ACL dacl;
202   SECURITY_DESCRIPTOR sd;
203   if (!InitializeAcl(&dacl, sizeof(dacl), ACL_REVISION)) {
204     return {};
205   }
206   if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) {
207     return {};
208   }
209   if (!SetSecurityDescriptorDacl(&sd, TRUE, &dacl, FALSE)) {
210     return {};
211   }
212 
213   std::u16string name;
214   SECURITY_ATTRIBUTES sa = {sizeof(sa), &sd, FALSE};
215   // Ask for the file mapping with reduced permisions to avoid passing the
216   // access control permissions granted by default into unpriviledged process.
217   HANDLE h = CreateFileMappingWithReducedPermissions(
218       &sa, rounded_size, name.empty() ? nullptr : as_wcstr(name));
219   if (h == nullptr) {
220     // The error is logged within CreateFileMappingWithReducedPermissions().
221     return {};
222   }
223 
224   win::ScopedHandle scoped_h(h);
225   // Check if the shared memory pre-exists.
226   if (GetLastError() == ERROR_ALREADY_EXISTS) {
227     return {};
228   }
229 
230   return PlatformSharedMemoryRegion(std::move(scoped_h), mode, size,
231                                     UnguessableToken::Create());
232 }
233 
234 // static
CheckPlatformHandlePermissionsCorrespondToMode(PlatformSharedMemoryHandle handle,Mode mode,size_t size)235 bool PlatformSharedMemoryRegion::CheckPlatformHandlePermissionsCorrespondToMode(
236     PlatformSharedMemoryHandle handle,
237     Mode mode,
238     size_t size) {
239   // Call ::DuplicateHandle() with FILE_MAP_WRITE as a desired access to check
240   // if the |handle| has a write access.
241   ProcessHandle process = GetCurrentProcess();
242   HANDLE duped_handle;
243   BOOL success = ::DuplicateHandle(process, handle, process, &duped_handle,
244                                    FILE_MAP_WRITE, FALSE, 0);
245   if (success) {
246     BOOL rv = ::CloseHandle(duped_handle);
247     DCHECK(rv);
248   }
249 
250   bool is_read_only = !success;
251   bool expected_read_only = mode == Mode::kReadOnly;
252 
253   if (is_read_only != expected_read_only) {
254     DLOG(ERROR) << "File mapping handle has wrong access rights: it is"
255                 << (is_read_only ? " " : " not ") << "read-only but it should"
256                 << (expected_read_only ? " " : " not ") << "be";
257     return false;
258   }
259 
260   return true;
261 }
262 
PlatformSharedMemoryRegion(win::ScopedHandle handle,Mode mode,size_t size,const UnguessableToken & guid)263 PlatformSharedMemoryRegion::PlatformSharedMemoryRegion(
264     win::ScopedHandle handle,
265     Mode mode,
266     size_t size,
267     const UnguessableToken& guid)
268     : handle_(std::move(handle)), mode_(mode), size_(size), guid_(guid) {}
269 
270 }  // namespace base::subtle
271