nacl_message_scanner.cc revision 03b57e008b61dfcb1fbad3aea950ae0e001748b0
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. 4 5#include "ppapi/proxy/nacl_message_scanner.h" 6 7#include <vector> 8#include "base/bind.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" 15 16class NaClDescImcShm; 17 18namespace IPC { 19class Message; 20} 21 22using ppapi::proxy::ResourceMessageReplyParams; 23using ppapi::proxy::SerializedHandle; 24using ppapi::proxy::SerializedVar; 25 26namespace { 27 28typedef std::vector<SerializedHandle> Handles; 29 30struct ScanningResults { 31 ScanningResults() : handle_index(0), pp_resource(0) {} 32 33 // Vector to hold handles found in the message. 34 Handles handles; 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. 37 int handle_index; 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*)> 48 nested_msg_callback; 49}; 50 51void WriteHandle(int handle_index, 52 const SerializedHandle& handle, 53 IPC::Message* msg) { 54 SerializedHandle::WriteHeader(handle.header(), msg); 55 56 // Now write the handle itself in POSIX style. 57 msg->WriteBool(true); // valid == true 58 msg->WriteInt(handle_index); 59} 60 61// Define overloads for each kind of message parameter that requires special 62// handling. See ScanTuple for how these get used. 63 64// Overload to match SerializedHandle. 65void ScanParam(const SerializedHandle& handle, ScanningResults* results) { 66 results->handles.push_back(handle); 67 if (results->new_msg) 68 WriteHandle(results->handle_index++, handle, results->new_msg.get()); 69} 70 71void HandleWriter(int* handle_index, 72 IPC::Message* m, 73 const SerializedHandle& handle) { 74 WriteHandle((*handle_index)++, handle, m); 75} 76 77// Overload to match SerializedVar, which can contain handles. 78void ScanParam(const SerializedVar& var, ScanningResults* results) { 79 std::vector<SerializedHandle*> var_handles = var.GetHandles(); 80 // Copy any handles and then rewrite the message. 81 for (size_t i = 0; i < var_handles.size(); ++i) 82 results->handles.push_back(*var_handles[i]); 83 if (results->new_msg) 84 var.WriteDataToMessage(results->new_msg.get(), 85 base::Bind(&HandleWriter, &results->handle_index)); 86} 87 88// For PpapiMsg_ResourceReply and the reply to PpapiHostMsg_ResourceSyncCall, 89// the handles are carried inside the ResourceMessageReplyParams. 90// NOTE: We only intercept handles from host->NaCl. The only kind of 91// ResourceMessageParams that travels this direction is 92// ResourceMessageReplyParams, so that's the only one we need to handle. 93void ScanParam(const ResourceMessageReplyParams& params, 94 ScanningResults* results) { 95 results->pp_resource = params.pp_resource(); 96 // If the resource reply params don't contain handles, NULL the new message 97 // pointer to cancel further rewriting. 98 // NOTE: This works because only handles currently need rewriting, and we 99 // know at this point that this message has none. 100 if (params.handles().empty()) { 101 results->new_msg.reset(NULL); 102 return; 103 } 104 105 // If we need to rewrite the message, write everything before the handles 106 // (there's nothing after the handles). 107 if (results->new_msg) { 108 params.WriteReplyHeader(results->new_msg.get()); 109 // IPC writes the vector length as an int before the contents of the 110 // vector. 111 results->new_msg->WriteInt(static_cast<int>(params.handles().size())); 112 } 113 for (Handles::const_iterator iter = params.handles().begin(); 114 iter != params.handles().end(); 115 ++iter) { 116 // ScanParam will write each handle to the new message, if necessary. 117 ScanParam(*iter, results); 118 } 119 // Tell ResourceMessageReplyParams that we have taken the handles, so it 120 // shouldn't close them. The NaCl runtime will take ownership of them. 121 params.ConsumeHandles(); 122} 123 124// Overload to match nested messages. If we need to rewrite the message, write 125// the parameter. 126void ScanParam(const IPC::Message& param, ScanningResults* results) { 127 if (results->pp_resource && !results->nested_msg_callback.is_null()) { 128 SerializedHandle* handle = NULL; 129 if (results->handles.size() == 1) 130 handle = &results->handles[0]; 131 results->nested_msg_callback.Run(results->pp_resource, param, handle); 132 } 133 if (results->new_msg) 134 IPC::WriteParam(results->new_msg.get(), param); 135} 136 137// Overload to match all other types. If we need to rewrite the message, write 138// the parameter. 139template <class T> 140void ScanParam(const T& param, ScanningResults* results) { 141 if (results->new_msg) 142 IPC::WriteParam(results->new_msg.get(), param); 143} 144 145// These just break apart the given tuple and run ScanParam over each param. 146// The idea is to scan elements in the tuple which require special handling, 147// and write them into the |results| struct. 148template <class A> 149void ScanTuple(const Tuple1<A>& t1, ScanningResults* results) { 150 ScanParam(t1.a, results); 151} 152template <class A, class B> 153void ScanTuple(const Tuple2<A, B>& t1, ScanningResults* results) { 154 ScanParam(t1.a, results); 155 ScanParam(t1.b, results); 156} 157template <class A, class B, class C> 158void ScanTuple(const Tuple3<A, B, C>& t1, ScanningResults* results) { 159 ScanParam(t1.a, results); 160 ScanParam(t1.b, results); 161 ScanParam(t1.c, results); 162} 163template <class A, class B, class C, class D> 164void ScanTuple(const Tuple4<A, B, C, D>& t1, ScanningResults* results) { 165 ScanParam(t1.a, results); 166 ScanParam(t1.b, results); 167 ScanParam(t1.c, results); 168 ScanParam(t1.d, results); 169} 170 171template <class MessageType> 172class MessageScannerImpl { 173 public: 174 explicit MessageScannerImpl(const IPC::Message* msg) 175 : msg_(static_cast<const MessageType*>(msg)) { 176 } 177 bool ScanMessage(ScanningResults* results) { 178 typename TupleTypes<typename MessageType::Schema::Param>::ValueTuple params; 179 if (!MessageType::Read(msg_, ¶ms)) 180 return false; 181 ScanTuple(params, results); 182 return true; 183 } 184 185 bool ScanReply(ScanningResults* results) { 186 typename TupleTypes<typename MessageType::Schema::ReplyParam>::ValueTuple 187 params; 188 if (!MessageType::ReadReplyParam(msg_, ¶ms)) 189 return false; 190 // If we need to rewrite the message, write the message id first. 191 if (results->new_msg) { 192 results->new_msg->set_reply(); 193 int id = IPC::SyncMessage::GetMessageId(*msg_); 194 results->new_msg->WriteInt(id); 195 } 196 ScanTuple(params, results); 197 return true; 198 } 199 // TODO(dmichael): Add ScanSyncMessage for outgoing sync messages, if we ever 200 // need to scan those. 201 202 private: 203 const MessageType* msg_; 204}; 205 206} // namespace 207 208#define CASE_FOR_MESSAGE(MESSAGE_TYPE) \ 209 case MESSAGE_TYPE::ID: { \ 210 MessageScannerImpl<MESSAGE_TYPE> scanner(&msg); \ 211 if (rewrite_msg) \ 212 results.new_msg.reset( \ 213 new IPC::Message(msg.routing_id(), msg.type(), \ 214 IPC::Message::PRIORITY_NORMAL)); \ 215 if (!scanner.ScanMessage(&results)) \ 216 return false; \ 217 break; \ 218 } 219#define CASE_FOR_REPLY(MESSAGE_TYPE) \ 220 case MESSAGE_TYPE::ID: { \ 221 MessageScannerImpl<MESSAGE_TYPE> scanner(&msg); \ 222 if (rewrite_msg) \ 223 results.new_msg.reset( \ 224 new IPC::Message(msg.routing_id(), msg.type(), \ 225 IPC::Message::PRIORITY_NORMAL)); \ 226 if (!scanner.ScanReply(&results)) \ 227 return false; \ 228 break; \ 229 } 230 231namespace ppapi { 232namespace proxy { 233 234class SerializedHandle; 235 236NaClMessageScanner::FileSystem::FileSystem() 237 : reserved_quota_(0) { 238} 239 240NaClMessageScanner::FileSystem::~FileSystem() { 241} 242 243bool NaClMessageScanner::FileSystem::UpdateReservedQuota(int64_t delta) { 244 base::AutoLock lock(lock_); 245 if (std::numeric_limits<int64_t>::max() - reserved_quota_ < delta) 246 return false; // reserved_quota_ + delta would overflow. 247 if (reserved_quota_ + delta < 0) 248 return false; 249 reserved_quota_ += delta; 250 return true; 251} 252 253NaClMessageScanner::FileIO::FileIO(FileSystem* file_system, 254 int64_t max_written_offset) 255 : file_system_(file_system), 256 max_written_offset_(max_written_offset) { 257} 258 259NaClMessageScanner::FileIO::~FileIO() { 260} 261 262void NaClMessageScanner::FileIO::SetMaxWrittenOffset( 263 int64_t max_written_offset) { 264 base::AutoLock lock(lock_); 265 max_written_offset_ = max_written_offset; 266} 267 268bool NaClMessageScanner::FileIO::Grow(int64_t amount) { 269 base::AutoLock lock(lock_); 270 DCHECK(amount > 0); 271 if (!file_system_->UpdateReservedQuota(-amount)) 272 return false; 273 max_written_offset_ += amount; 274 return true; 275} 276 277NaClMessageScanner::NaClMessageScanner() { 278} 279 280NaClMessageScanner::~NaClMessageScanner() { 281 for (FileSystemMap::iterator it = file_systems_.begin(); 282 it != file_systems_.end(); ++it) 283 delete it->second; 284 for (FileIOMap::iterator it = files_.begin(); it != files_.end(); ++it) 285 delete it->second; 286} 287 288// Windows IPC differs from POSIX in that native handles are serialized in the 289// message body, rather than passed in a separate FileDescriptorSet. Therefore, 290// on Windows, any message containing handles must be rewritten in the POSIX 291// format before we can send it to the NaCl plugin. 292bool NaClMessageScanner::ScanMessage( 293 const IPC::Message& msg, 294 uint32_t type, 295 std::vector<SerializedHandle>* handles, 296 scoped_ptr<IPC::Message>* new_msg_ptr) { 297 DCHECK(handles); 298 DCHECK(handles->empty()); 299 DCHECK(new_msg_ptr); 300 DCHECK(!new_msg_ptr->get()); 301 302 bool rewrite_msg = 303#if defined(OS_WIN) 304 true; 305#else 306 false; 307#endif 308 309 // We can't always tell from the message ID if rewriting is needed. Therefore, 310 // scan any message types that might contain a handle. If we later determine 311 // that there are no handles, we can cancel the rewriting by clearing the 312 // results.new_msg pointer. 313 ScanningResults results; 314 results.nested_msg_callback = 315 base::Bind(&NaClMessageScanner::AuditNestedMessage, 316 base::Unretained(this)); 317 switch (type) { 318 CASE_FOR_MESSAGE(PpapiMsg_PPBAudio_NotifyAudioStreamCreated) 319 CASE_FOR_MESSAGE(PpapiMsg_PPPMessaging_HandleMessage) 320 CASE_FOR_MESSAGE(PpapiPluginMsg_ResourceReply) 321 CASE_FOR_REPLY(PpapiHostMsg_PPBGraphics3D_CreateTransferBuffer) 322 CASE_FOR_REPLY(PpapiHostMsg_PPBImageData_CreateSimple) 323 CASE_FOR_REPLY(PpapiHostMsg_ResourceSyncCall) 324 CASE_FOR_REPLY(PpapiHostMsg_SharedMemory_CreateSharedMemory) 325 default: 326 // Do nothing for messages we don't know. 327 break; 328 } 329 330 // Only messages containing handles need to be rewritten. If no handles are 331 // found, don't return the rewritten message either. This must be changed if 332 // we ever add new param types that also require rewriting. 333 if (!results.handles.empty()) { 334 handles->swap(results.handles); 335 *new_msg_ptr = results.new_msg.Pass(); 336 } 337 return true; 338} 339 340void NaClMessageScanner::ScanUntrustedMessage( 341 const IPC::Message& untrusted_msg, 342 scoped_ptr<IPC::Message>* new_msg_ptr) { 343 // Audit FileIO and FileSystem messages to ensure that the plugin doesn't 344 // exceed its file quota. If we find the message is malformed, just pass it 345 // through - we only care about well formed messages to the host. 346 if (untrusted_msg.type() == PpapiHostMsg_ResourceCall::ID) { 347 ResourceMessageCallParams params; 348 IPC::Message nested_msg; 349 if (!UnpackMessage<PpapiHostMsg_ResourceCall>( 350 untrusted_msg, ¶ms, &nested_msg)) 351 return; 352 353 switch (nested_msg.type()) { 354 case PpapiHostMsg_FileIO_Close::ID: { 355 FileIOMap::iterator it = files_.find(params.pp_resource()); 356 if (it == files_.end()) 357 return; 358 // Audit FileIO Close messages to make sure the plugin reports an 359 // accurate file size. 360 FileGrowth file_growth; 361 if (!UnpackMessage<PpapiHostMsg_FileIO_Close>( 362 nested_msg, &file_growth)) 363 return; 364 365 int64_t trusted_max_written_offset = it->second->max_written_offset(); 366 delete it->second; 367 files_.erase(it); 368 // If the plugin is under-reporting, rewrite the message with the 369 // trusted value. 370 if (trusted_max_written_offset > file_growth.max_written_offset) { 371 new_msg_ptr->reset( 372 new PpapiHostMsg_ResourceCall( 373 params, 374 PpapiHostMsg_FileIO_Close( 375 FileGrowth(trusted_max_written_offset, 0)))); 376 } 377 break; 378 } 379 case PpapiHostMsg_FileIO_SetLength::ID: { 380 FileIOMap::iterator it = files_.find(params.pp_resource()); 381 if (it == files_.end()) 382 return; 383 // Audit FileIO SetLength messages to make sure the plugin is within 384 // the current quota reservation. In addition, deduct the file size 385 // increase from the quota reservation. 386 int64_t length = 0; 387 if (!UnpackMessage<PpapiHostMsg_FileIO_SetLength>( 388 nested_msg, &length)) 389 return; 390 391 // Calculate file size increase, taking care to avoid overflows. 392 if (length < 0) 393 return; 394 int64_t trusted_max_written_offset = it->second->max_written_offset(); 395 int64_t increase = length - trusted_max_written_offset; 396 if (increase <= 0) 397 return; 398 if (!it->second->Grow(increase)) { 399 new_msg_ptr->reset( 400 new PpapiHostMsg_ResourceCall( 401 params, 402 PpapiHostMsg_FileIO_SetLength(-1))); 403 } 404 break; 405 } 406 case PpapiHostMsg_FileSystem_ReserveQuota::ID: { 407 // Audit FileSystem ReserveQuota messages to make sure the plugin 408 // reports accurate file sizes. 409 int64_t amount = 0; 410 FileGrowthMap file_growths; 411 if (!UnpackMessage<PpapiHostMsg_FileSystem_ReserveQuota>( 412 nested_msg, &amount, &file_growths)) 413 return; 414 415 bool audit_failed = false; 416 for (FileGrowthMap::iterator it = file_growths.begin(); 417 it != file_growths.end(); ++it) { 418 FileIOMap::iterator file_it = files_.find(it->first); 419 if (file_it == files_.end()) 420 continue; 421 int64_t trusted_max_written_offset = 422 file_it->second->max_written_offset(); 423 if (trusted_max_written_offset > it->second.max_written_offset) { 424 audit_failed = true; 425 it->second.max_written_offset = trusted_max_written_offset; 426 } 427 if (it->second.append_mode_write_amount < 0) { 428 audit_failed = true; 429 it->second.append_mode_write_amount = 0; 430 } 431 } 432 if (audit_failed) { 433 new_msg_ptr->reset( 434 new PpapiHostMsg_ResourceCall( 435 params, 436 PpapiHostMsg_FileSystem_ReserveQuota( 437 amount, file_growths))); 438 } 439 break; 440 } 441 case PpapiHostMsg_ResourceDestroyed::ID: { 442 // Audit resource destroyed messages to release FileSystems. 443 PP_Resource resource; 444 if (!UnpackMessage<PpapiHostMsg_ResourceDestroyed>( 445 nested_msg, &resource)) 446 return; 447 FileSystemMap::iterator fs_it = file_systems_.find(resource); 448 if (fs_it != file_systems_.end()) { 449 delete fs_it->second; 450 file_systems_.erase(fs_it); 451 } 452 break; 453 } 454 } 455 } 456} 457 458NaClMessageScanner::FileIO* NaClMessageScanner::GetFile( 459 PP_Resource file_io) { 460 FileIOMap::iterator it = files_.find(file_io); 461 DCHECK(it != files_.end()); 462 return it->second; 463} 464 465void NaClMessageScanner::AuditNestedMessage(PP_Resource resource, 466 const IPC::Message& msg, 467 SerializedHandle* handle) { 468 switch (msg.type()) { 469 case PpapiPluginMsg_FileIO_OpenReply::ID: { 470 // A file that requires quota checking was opened. 471 PP_Resource quota_file_system; 472 int64_t max_written_offset = 0; 473 if (ppapi::UnpackMessage<PpapiPluginMsg_FileIO_OpenReply>( 474 msg, "a_file_system, &max_written_offset)) { 475 if (quota_file_system) { 476 // Look up the FileSystem by inserting a new one. If it was already 477 // present, get the existing one, otherwise construct it. 478 FileSystem* file_system = NULL; 479 std::pair<FileSystemMap::iterator, bool> insert_result = 480 file_systems_.insert(std::make_pair(quota_file_system, 481 file_system)); 482 if (insert_result.second) 483 insert_result.first->second = new FileSystem(); 484 file_system = insert_result.first->second; 485 // Create the FileIO. 486 DCHECK(files_.find(resource) == files_.end()); 487 files_.insert(std::make_pair( 488 resource, 489 new FileIO(file_system, max_written_offset))); 490 } 491 } 492 break; 493 } 494 case PpapiPluginMsg_FileSystem_ReserveQuotaReply::ID: { 495 // The amount of reserved quota for a FileSystem was refreshed. 496 int64_t amount = 0; 497 FileSizeMap file_sizes; 498 if (ppapi::UnpackMessage<PpapiPluginMsg_FileSystem_ReserveQuotaReply>( 499 msg, &amount, &file_sizes)) { 500 FileSystemMap::iterator it = file_systems_.find(resource); 501 DCHECK(it != file_systems_.end()); 502 it->second->UpdateReservedQuota(amount); 503 504 FileSizeMap::const_iterator offset_it = file_sizes.begin(); 505 for (; offset_it != file_sizes.end(); ++offset_it) { 506 FileIOMap::iterator fio_it = files_.find(offset_it->first); 507 DCHECK(fio_it != files_.end()); 508 if (fio_it != files_.end()) 509 fio_it->second->SetMaxWrittenOffset(offset_it->second); 510 } 511 } 512 break; 513 } 514 } 515} 516 517} // namespace proxy 518} // namespace ppapi 519