1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "ppapi/proxy/nacl_message_scanner.h"
9 #include "ipc/ipc_message.h"
10 #include "ipc/ipc_message_macros.h"
11 #include "ppapi/proxy/ppapi_messages.h"
12 #include "ppapi/proxy/resource_message_params.h"
13 #include "ppapi/proxy/serialized_handle.h"
14 #include "ppapi/proxy/serialized_var.h"
22 using ppapi::proxy::ResourceMessageReplyParams
;
23 using ppapi::proxy::SerializedHandle
;
24 using ppapi::proxy::SerializedVar
;
28 typedef std::vector
<SerializedHandle
> Handles
;
30 struct ScanningResults
{
31 ScanningResults() : handle_index(0), pp_resource(0) {}
33 // Vector to hold handles found in the message.
35 // Current handle index in the rewritten message. During the scan, it will be
36 // be less than or equal to handles.size(). After the scan it should be equal.
38 // The rewritten message. This may be NULL, so all ScanParam overloads should
39 // check for NULL before writing to it. In some cases, a ScanParam overload
40 // may set this to NULL when it can determine that there are no parameters
41 // that need conversion. (See the ResourceMessageReplyParams overload.)
42 scoped_ptr
<IPC::Message
> new_msg
;
43 // Resource id for resource messages. Save this when scanning resource replies
44 // so when we audit the nested message, we know which resource it is for.
45 PP_Resource pp_resource
;
46 // Callback to receive the nested message in a resource message or reply.
47 base::Callback
<void(PP_Resource
, const IPC::Message
&, SerializedHandle
*)>
51 void WriteHandle(int handle_index
,
52 const SerializedHandle
& handle
,
54 SerializedHandle::WriteHeader(handle
.header(), msg
);
56 if (handle
.type() != SerializedHandle::INVALID
) {
57 // Now write the handle itself in POSIX style.
58 // See ParamTraits<FileDescriptor>::Read for where these values are read.
59 msg
->WriteBool(true); // valid == true
60 msg
->WriteInt(handle_index
);
64 // Define overloads for each kind of message parameter that requires special
65 // handling. See ScanTuple for how these get used.
67 // Overload to match SerializedHandle.
68 void ScanParam(const SerializedHandle
& handle
, ScanningResults
* results
) {
69 results
->handles
.push_back(handle
);
71 WriteHandle(results
->handle_index
++, handle
, results
->new_msg
.get());
74 void HandleWriter(int* handle_index
,
76 const SerializedHandle
& handle
) {
77 WriteHandle((*handle_index
)++, handle
, m
);
80 // Overload to match SerializedVar, which can contain handles.
81 void ScanParam(const SerializedVar
& var
, ScanningResults
* results
) {
82 std::vector
<SerializedHandle
*> var_handles
= var
.GetHandles();
83 // Copy any handles and then rewrite the message.
84 for (size_t i
= 0; i
< var_handles
.size(); ++i
)
85 results
->handles
.push_back(*var_handles
[i
]);
87 var
.WriteDataToMessage(results
->new_msg
.get(),
88 base::Bind(&HandleWriter
, &results
->handle_index
));
91 // For PpapiMsg_ResourceReply and the reply to PpapiHostMsg_ResourceSyncCall,
92 // the handles are carried inside the ResourceMessageReplyParams.
93 // NOTE: We only intercept handles from host->NaCl. The only kind of
94 // ResourceMessageParams that travels this direction is
95 // ResourceMessageReplyParams, so that's the only one we need to handle.
96 void ScanParam(const ResourceMessageReplyParams
& params
,
97 ScanningResults
* results
) {
98 results
->pp_resource
= params
.pp_resource();
99 // If the resource reply params don't contain handles, NULL the new message
100 // pointer to cancel further rewriting.
101 // NOTE: This works because only handles currently need rewriting, and we
102 // know at this point that this message has none.
103 if (params
.handles().empty()) {
104 results
->new_msg
.reset(NULL
);
108 // If we need to rewrite the message, write everything before the handles
109 // (there's nothing after the handles).
110 if (results
->new_msg
) {
111 params
.WriteReplyHeader(results
->new_msg
.get());
112 // IPC writes the vector length as an int before the contents of the
114 results
->new_msg
->WriteInt(static_cast<int>(params
.handles().size()));
116 for (Handles::const_iterator iter
= params
.handles().begin();
117 iter
!= params
.handles().end();
119 // ScanParam will write each handle to the new message, if necessary.
120 ScanParam(*iter
, results
);
122 // Tell ResourceMessageReplyParams that we have taken the handles, so it
123 // shouldn't close them. The NaCl runtime will take ownership of them.
124 params
.ConsumeHandles();
127 // Overload to match nested messages. If we need to rewrite the message, write
129 void ScanParam(const IPC::Message
& param
, ScanningResults
* results
) {
130 if (results
->pp_resource
&& !results
->nested_msg_callback
.is_null()) {
131 SerializedHandle
* handle
= NULL
;
132 if (results
->handles
.size() == 1)
133 handle
= &results
->handles
[0];
134 results
->nested_msg_callback
.Run(results
->pp_resource
, param
, handle
);
136 if (results
->new_msg
)
137 IPC::WriteParam(results
->new_msg
.get(), param
);
140 // Overload to match all other types. If we need to rewrite the message, write
143 void ScanParam(const T
& param
, ScanningResults
* results
) {
144 if (results
->new_msg
)
145 IPC::WriteParam(results
->new_msg
.get(), param
);
148 // These just break apart the given tuple and run ScanParam over each param.
149 // The idea is to scan elements in the tuple which require special handling,
150 // and write them into the |results| struct.
152 void ScanTuple(const base::Tuple
<A
>& t1
, ScanningResults
* results
) {
153 ScanParam(base::get
<0>(t1
), results
);
155 template <class A
, class B
>
156 void ScanTuple(const base::Tuple
<A
, B
>& t1
, ScanningResults
* results
) {
157 ScanParam(base::get
<0>(t1
), results
);
158 ScanParam(base::get
<1>(t1
), results
);
160 template <class A
, class B
, class C
>
161 void ScanTuple(const base::Tuple
<A
, B
, C
>& t1
, ScanningResults
* results
) {
162 ScanParam(base::get
<0>(t1
), results
);
163 ScanParam(base::get
<1>(t1
), results
);
164 ScanParam(base::get
<2>(t1
), results
);
166 template <class A
, class B
, class C
, class D
>
167 void ScanTuple(const base::Tuple
<A
, B
, C
, D
>& t1
, ScanningResults
* results
) {
168 ScanParam(base::get
<0>(t1
), results
);
169 ScanParam(base::get
<1>(t1
), results
);
170 ScanParam(base::get
<2>(t1
), results
);
171 ScanParam(base::get
<3>(t1
), results
);
174 template <class MessageType
>
175 class MessageScannerImpl
{
177 explicit MessageScannerImpl(const IPC::Message
* msg
)
178 : msg_(static_cast<const MessageType
*>(msg
)) {
180 bool ScanMessage(ScanningResults
* results
) {
181 typename
base::TupleTypes
<typename
MessageType::Schema::Param
>::ValueTuple
183 if (!MessageType::Read(msg_
, ¶ms
))
185 ScanTuple(params
, results
);
189 bool ScanReply(ScanningResults
* results
) {
190 typename
base::TupleTypes
<typename
MessageType::Schema::ReplyParam
>
192 if (!MessageType::ReadReplyParam(msg_
, ¶ms
))
194 // If we need to rewrite the message, write the message id first.
195 if (results
->new_msg
) {
196 results
->new_msg
->set_reply();
197 int id
= IPC::SyncMessage::GetMessageId(*msg_
);
198 results
->new_msg
->WriteInt(id
);
200 ScanTuple(params
, results
);
203 // TODO(dmichael): Add ScanSyncMessage for outgoing sync messages, if we ever
204 // need to scan those.
207 const MessageType
* msg_
;
212 #define CASE_FOR_MESSAGE(MESSAGE_TYPE) \
213 case MESSAGE_TYPE::ID: { \
214 MessageScannerImpl<MESSAGE_TYPE> scanner(&msg); \
216 results.new_msg.reset( \
217 new IPC::Message(msg.routing_id(), msg.type(), \
218 IPC::Message::PRIORITY_NORMAL)); \
219 if (!scanner.ScanMessage(&results)) \
223 #define CASE_FOR_REPLY(MESSAGE_TYPE) \
224 case MESSAGE_TYPE::ID: { \
225 MessageScannerImpl<MESSAGE_TYPE> scanner(&msg); \
227 results.new_msg.reset( \
228 new IPC::Message(msg.routing_id(), msg.type(), \
229 IPC::Message::PRIORITY_NORMAL)); \
230 if (!scanner.ScanReply(&results)) \
238 class SerializedHandle
;
240 NaClMessageScanner::FileSystem::FileSystem()
241 : reserved_quota_(0) {
244 NaClMessageScanner::FileSystem::~FileSystem() {
247 bool NaClMessageScanner::FileSystem::UpdateReservedQuota(int64_t delta
) {
248 base::AutoLock
lock(lock_
);
249 if (std::numeric_limits
<int64_t>::max() - reserved_quota_
< delta
)
250 return false; // reserved_quota_ + delta would overflow.
251 if (reserved_quota_
+ delta
< 0)
253 reserved_quota_
+= delta
;
257 NaClMessageScanner::FileIO::FileIO(FileSystem
* file_system
,
258 int64_t max_written_offset
)
259 : file_system_(file_system
),
260 max_written_offset_(max_written_offset
) {
263 NaClMessageScanner::FileIO::~FileIO() {
266 void NaClMessageScanner::FileIO::SetMaxWrittenOffset(
267 int64_t max_written_offset
) {
268 base::AutoLock
lock(lock_
);
269 max_written_offset_
= max_written_offset
;
272 bool NaClMessageScanner::FileIO::Grow(int64_t amount
) {
273 base::AutoLock
lock(lock_
);
275 if (!file_system_
->UpdateReservedQuota(-amount
))
277 max_written_offset_
+= amount
;
281 NaClMessageScanner::NaClMessageScanner() {
284 NaClMessageScanner::~NaClMessageScanner() {
285 for (FileSystemMap::iterator it
= file_systems_
.begin();
286 it
!= file_systems_
.end(); ++it
)
288 for (FileIOMap::iterator it
= files_
.begin(); it
!= files_
.end(); ++it
)
292 // Windows IPC differs from POSIX in that native handles are serialized in the
293 // message body, rather than passed in a separate FileDescriptorSet. Therefore,
294 // on Windows, any message containing handles must be rewritten in the POSIX
295 // format before we can send it to the NaCl plugin.
296 bool NaClMessageScanner::ScanMessage(
297 const IPC::Message
& msg
,
299 std::vector
<SerializedHandle
>* handles
,
300 scoped_ptr
<IPC::Message
>* new_msg_ptr
) {
302 DCHECK(handles
->empty());
304 DCHECK(!new_msg_ptr
->get());
313 // We can't always tell from the message ID if rewriting is needed. Therefore,
314 // scan any message types that might contain a handle. If we later determine
315 // that there are no handles, we can cancel the rewriting by clearing the
316 // results.new_msg pointer.
317 ScanningResults results
;
318 results
.nested_msg_callback
=
319 base::Bind(&NaClMessageScanner::AuditNestedMessage
,
320 base::Unretained(this));
322 CASE_FOR_MESSAGE(PpapiMsg_PPBAudio_NotifyAudioStreamCreated
)
323 CASE_FOR_MESSAGE(PpapiMsg_PPPMessaging_HandleMessage
)
324 CASE_FOR_MESSAGE(PpapiPluginMsg_ResourceReply
)
325 CASE_FOR_REPLY(PpapiHostMsg_OpenResource
)
326 CASE_FOR_REPLY(PpapiHostMsg_PPBGraphics3D_Create
)
327 CASE_FOR_REPLY(PpapiHostMsg_PPBGraphics3D_CreateTransferBuffer
)
328 CASE_FOR_REPLY(PpapiHostMsg_PPBImageData_CreateSimple
)
329 CASE_FOR_REPLY(PpapiHostMsg_ResourceSyncCall
)
330 CASE_FOR_REPLY(PpapiHostMsg_SharedMemory_CreateSharedMemory
)
332 // Do nothing for messages we don't know.
336 // Only messages containing handles need to be rewritten. If no handles are
337 // found, don't return the rewritten message either. This must be changed if
338 // we ever add new param types that also require rewriting.
339 if (!results
.handles
.empty()) {
340 handles
->swap(results
.handles
);
341 *new_msg_ptr
= results
.new_msg
.Pass();
346 void NaClMessageScanner::ScanUntrustedMessage(
347 const IPC::Message
& untrusted_msg
,
348 scoped_ptr
<IPC::Message
>* new_msg_ptr
) {
349 // Audit FileIO and FileSystem messages to ensure that the plugin doesn't
350 // exceed its file quota. If we find the message is malformed, just pass it
351 // through - we only care about well formed messages to the host.
352 if (untrusted_msg
.type() == PpapiHostMsg_ResourceCall::ID
) {
353 ResourceMessageCallParams params
;
354 IPC::Message nested_msg
;
355 if (!UnpackMessage
<PpapiHostMsg_ResourceCall
>(
356 untrusted_msg
, ¶ms
, &nested_msg
))
359 switch (nested_msg
.type()) {
360 case PpapiHostMsg_FileIO_Close::ID
: {
361 FileIOMap::iterator it
= files_
.find(params
.pp_resource());
362 if (it
== files_
.end())
364 // Audit FileIO Close messages to make sure the plugin reports an
365 // accurate file size.
366 FileGrowth file_growth
;
367 if (!UnpackMessage
<PpapiHostMsg_FileIO_Close
>(
368 nested_msg
, &file_growth
))
371 int64_t trusted_max_written_offset
= it
->second
->max_written_offset();
374 // If the plugin is under-reporting, rewrite the message with the
376 if (trusted_max_written_offset
> file_growth
.max_written_offset
) {
378 new PpapiHostMsg_ResourceCall(
380 PpapiHostMsg_FileIO_Close(
381 FileGrowth(trusted_max_written_offset
, 0))));
385 case PpapiHostMsg_FileIO_SetLength::ID
: {
386 FileIOMap::iterator it
= files_
.find(params
.pp_resource());
387 if (it
== files_
.end())
389 // Audit FileIO SetLength messages to make sure the plugin is within
390 // the current quota reservation. In addition, deduct the file size
391 // increase from the quota reservation.
393 if (!UnpackMessage
<PpapiHostMsg_FileIO_SetLength
>(
394 nested_msg
, &length
))
397 // Calculate file size increase, taking care to avoid overflows.
400 int64_t trusted_max_written_offset
= it
->second
->max_written_offset();
401 int64_t increase
= length
- trusted_max_written_offset
;
404 if (!it
->second
->Grow(increase
)) {
406 new PpapiHostMsg_ResourceCall(
408 PpapiHostMsg_FileIO_SetLength(-1)));
412 case PpapiHostMsg_FileSystem_ReserveQuota::ID
: {
413 // Audit FileSystem ReserveQuota messages to make sure the plugin
414 // reports accurate file sizes.
416 FileGrowthMap file_growths
;
417 if (!UnpackMessage
<PpapiHostMsg_FileSystem_ReserveQuota
>(
418 nested_msg
, &amount
, &file_growths
))
421 bool audit_failed
= false;
422 for (FileGrowthMap::iterator it
= file_growths
.begin();
423 it
!= file_growths
.end(); ++it
) {
424 FileIOMap::iterator file_it
= files_
.find(it
->first
);
425 if (file_it
== files_
.end())
427 int64_t trusted_max_written_offset
=
428 file_it
->second
->max_written_offset();
429 if (trusted_max_written_offset
> it
->second
.max_written_offset
) {
431 it
->second
.max_written_offset
= trusted_max_written_offset
;
433 if (it
->second
.append_mode_write_amount
< 0) {
435 it
->second
.append_mode_write_amount
= 0;
440 new PpapiHostMsg_ResourceCall(
442 PpapiHostMsg_FileSystem_ReserveQuota(
443 amount
, file_growths
)));
447 case PpapiHostMsg_ResourceDestroyed::ID
: {
448 // Audit resource destroyed messages to release FileSystems.
449 PP_Resource resource
;
450 if (!UnpackMessage
<PpapiHostMsg_ResourceDestroyed
>(
451 nested_msg
, &resource
))
453 FileSystemMap::iterator fs_it
= file_systems_
.find(resource
);
454 if (fs_it
!= file_systems_
.end()) {
455 delete fs_it
->second
;
456 file_systems_
.erase(fs_it
);
464 NaClMessageScanner::FileIO
* NaClMessageScanner::GetFile(
465 PP_Resource file_io
) {
466 FileIOMap::iterator it
= files_
.find(file_io
);
467 DCHECK(it
!= files_
.end());
471 void NaClMessageScanner::AuditNestedMessage(PP_Resource resource
,
472 const IPC::Message
& msg
,
473 SerializedHandle
* handle
) {
474 switch (msg
.type()) {
475 case PpapiPluginMsg_FileIO_OpenReply::ID
: {
476 // A file that requires quota checking was opened.
477 PP_Resource quota_file_system
;
478 int64_t max_written_offset
= 0;
479 if (ppapi::UnpackMessage
<PpapiPluginMsg_FileIO_OpenReply
>(
480 msg
, "a_file_system
, &max_written_offset
)) {
481 if (quota_file_system
) {
482 // Look up the FileSystem by inserting a new one. If it was already
483 // present, get the existing one, otherwise construct it.
484 FileSystem
* file_system
= NULL
;
485 std::pair
<FileSystemMap::iterator
, bool> insert_result
=
486 file_systems_
.insert(std::make_pair(quota_file_system
,
488 if (insert_result
.second
)
489 insert_result
.first
->second
= new FileSystem();
490 file_system
= insert_result
.first
->second
;
491 // Create the FileIO.
492 DCHECK(files_
.find(resource
) == files_
.end());
493 files_
.insert(std::make_pair(
495 new FileIO(file_system
, max_written_offset
)));
500 case PpapiPluginMsg_FileSystem_ReserveQuotaReply::ID
: {
501 // The amount of reserved quota for a FileSystem was refreshed.
503 FileSizeMap file_sizes
;
504 if (ppapi::UnpackMessage
<PpapiPluginMsg_FileSystem_ReserveQuotaReply
>(
505 msg
, &amount
, &file_sizes
)) {
506 FileSystemMap::iterator it
= file_systems_
.find(resource
);
507 DCHECK(it
!= file_systems_
.end());
508 it
->second
->UpdateReservedQuota(amount
);
510 FileSizeMap::const_iterator offset_it
= file_sizes
.begin();
511 for (; offset_it
!= file_sizes
.end(); ++offset_it
) {
512 FileIOMap::iterator fio_it
= files_
.find(offset_it
->first
);
513 DCHECK(fio_it
!= files_
.end());
514 if (fio_it
!= files_
.end())
515 fio_it
->second
->SetMaxWrittenOffset(offset_it
->second
);