File: broker_host.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,122,156 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (545 lines) | stat: -rw-r--r-- 17,596 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/351564777): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include "sandbox/linux/syscall_broker/broker_host.h"

#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stddef.h>
#include <sys/inotify.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>

#include <array>
#include <string>
#include <tuple>
#include <utility>

#include "base/files/scoped_file.h"
#include "base/logging.h"
#include "base/posix/eintr_wrapper.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "sandbox/linux/services/syscall_wrappers.h"
#include "sandbox/linux/syscall_broker/broker_command.h"
#include "sandbox/linux/syscall_broker/broker_permission_list.h"
#include "sandbox/linux/syscall_broker/broker_simple_message.h"
#include "sandbox/linux/system_headers/linux_stat.h"
#include "sandbox/linux/system_headers/linux_syscalls.h"

namespace sandbox {
namespace syscall_broker {

namespace {

const char kProcSelf[] = "/proc/self/";
const size_t kProcSelfNumChars = sizeof(kProcSelf) - 1;

// A little open(2) wrapper to handle some oddities for us. In the general case
// make a direct system call since we want to keep in control of the broker
// process' system calls profile to be able to loosely sandbox it.
int sys_open(const char* pathname, int flags) {
  // Hardcode mode to rw------- when creating files.
  int mode = (flags & O_CREAT) ? 0600 : 0;
  return syscall(__NR_openat, AT_FDCWD, pathname, flags, mode);
}

}  // namespace

// Applies a rewrite from /proc/self/ to /proc/[pid of sandboxed process]/.
// Returns either a rewritten or the original pathname.
std::optional<std::string> BrokerHost::RewritePathname(const char* pathname) {
  if (base::StartsWith(pathname, kProcSelf)) {
    return base::StringPrintf("/proc/%d/%s", sandboxed_process_pid_,
                              pathname + kProcSelfNumChars);
  }

  return std::nullopt;
}

std::optional<std::pair<const char*, int>> BrokerHost::GetPathAndFlags(
    BrokerSimpleMessage* message) {
  const char* pathname;
  int flags;
  if (!message->ReadString(&pathname) || !message->ReadInt(&flags)) {
    return std::nullopt;
  }
  return {{pathname, flags}};
}

// Perform access(2) on |requested_filename| with mode |mode| if allowed by our
// permission_list. Write the syscall return value (-errno) to |reply|.
void BrokerHost::AccessFileForIPC(const char* requested_filename,
                                  int mode,
                                  BrokerSimpleMessage* reply) {
  const char* file_to_access =
      CommandAccessIsSafe(policy_->allowed_command_set,
                          *policy_->file_permissions, requested_filename, mode);
  if (!file_to_access) {
    RAW_CHECK(
        reply->AddIntToMessage(-policy_->file_permissions->denied_errno()));
    return;
  }

  std::optional<std::string> rewritten_filename =
      RewritePathname(file_to_access);
  if (rewritten_filename.has_value()) {
    file_to_access = rewritten_filename.value().c_str();
  }

  if (access(file_to_access, mode) < 0) {
    RAW_CHECK(reply->AddIntToMessage(-errno));
    return;
  }

  RAW_CHECK(reply->AddIntToMessage(0));
}

// Performs mkdir(2) on |requested_filename| with mode |mode| if allowed by our
// permission_list. Write the syscall return value (-errno) to |reply|.
void BrokerHost::MkdirFileForIPC(const char* requested_filename,
                                 int mode,
                                 BrokerSimpleMessage* reply) {
  const char* file_to_access =
      CommandMkdirIsSafe(policy_->allowed_command_set,
                         *policy_->file_permissions, requested_filename);
  if (!file_to_access) {
    RAW_CHECK(
        reply->AddIntToMessage(-policy_->file_permissions->denied_errno()));
    return;
  }

  std::optional<std::string> rewritten_filename =
      RewritePathname(file_to_access);
  if (rewritten_filename.has_value()) {
    file_to_access = rewritten_filename.value().c_str();
  }

  if (mkdir(file_to_access, mode) < 0) {
    RAW_CHECK(reply->AddIntToMessage(-errno));
    return;
  }
  RAW_CHECK(reply->AddIntToMessage(0));
}

// Open |requested_filename| with |flags| if allowed by our permission list.
// Write the syscall return value (-errno) to |reply| and return the
// file descriptor in the |opened_file| if relevant.
void BrokerHost::OpenFileForIPC(const char* requested_filename,
                                int flags,
                                BrokerSimpleMessage* reply,
                                base::ScopedFD* opened_file) {
  const char* file_to_open = nullptr;
  bool unlink_after_open = false;
  std::tie(file_to_open, unlink_after_open) =
      CommandOpenIsSafe(policy_->allowed_command_set,
                        *policy_->file_permissions, requested_filename, flags);
  if (!file_to_open) {
    RAW_CHECK(
        reply->AddIntToMessage(-policy_->file_permissions->denied_errno()));
    return;
  }

  std::optional<std::string> rewritten_filename = RewritePathname(file_to_open);
  if (rewritten_filename.has_value()) {
    file_to_open = rewritten_filename.value().c_str();
  }

  opened_file->reset(sys_open(file_to_open, flags));
  if (!opened_file->is_valid()) {
    RAW_CHECK(reply->AddIntToMessage(-errno));
    return;
  }

  if (unlink_after_open)
    unlink(file_to_open);

  RAW_CHECK(reply->AddIntToMessage(0));
}

// Perform rename(2) on |old_filename| to |new_filename| and write the
// result to |return_val|.
void BrokerHost::RenameFileForIPC(const char* old_filename,
                                  const char* new_filename,
                                  BrokerSimpleMessage* reply) {
  const char* old_file_to_access = nullptr;
  const char* new_file_to_access = nullptr;
  std::tie(old_file_to_access, new_file_to_access) = CommandRenameIsSafe(
      policy_->allowed_command_set, *policy_->file_permissions, old_filename,
      new_filename);
  if (!old_file_to_access || !new_file_to_access) {
    RAW_CHECK(
        reply->AddIntToMessage(-policy_->file_permissions->denied_errno()));
    return;
  }

  std::optional<std::string> old_rewritten_filename =
      RewritePathname(old_file_to_access);
  if (old_rewritten_filename) {
    old_file_to_access = old_rewritten_filename.value().c_str();
  }

  std::optional<std::string> new_rewritten_filename =
      RewritePathname(new_file_to_access);
  if (new_rewritten_filename) {
    new_file_to_access = new_rewritten_filename.value().c_str();
  }

  if (rename(old_file_to_access, new_file_to_access) < 0) {
    RAW_CHECK(reply->AddIntToMessage(-errno));
    return;
  }
  RAW_CHECK(reply->AddIntToMessage(0));
}

// Perform readlink(2) on |filename| using a buffer of MAX_PATH bytes.
void BrokerHost::ReadlinkFileForIPC(const char* requested_filename,
                                    BrokerSimpleMessage* reply) {
  const char* file_to_access =
      CommandReadlinkIsSafe(policy_->allowed_command_set,
                            *policy_->file_permissions, requested_filename);
  if (!file_to_access) {
    RAW_CHECK(
        reply->AddIntToMessage(-policy_->file_permissions->denied_errno()));
    return;
  }

  std::optional<std::string> rewritten_filename =
      RewritePathname(file_to_access);
  if (rewritten_filename.has_value()) {
    file_to_access = rewritten_filename.value().c_str();
  }

  char buf[PATH_MAX];
  ssize_t result = readlink(file_to_access, buf, sizeof(buf));
  if (result < 0) {
    RAW_CHECK(reply->AddIntToMessage(-errno));
    return;
  }
  RAW_CHECK(reply->AddIntToMessage(result));
  RAW_CHECK(reply->AddDataToMessage(buf, result));
}

void BrokerHost::RmdirFileForIPC(const char* requested_filename,
                                 BrokerSimpleMessage* reply) {
  const char* file_to_access =
      CommandRmdirIsSafe(policy_->allowed_command_set,
                         *policy_->file_permissions, requested_filename);
  if (!file_to_access) {
    RAW_CHECK(
        reply->AddIntToMessage(-policy_->file_permissions->denied_errno()));
    return;
  }

  std::optional<std::string> rewritten_filename =
      RewritePathname(file_to_access);
  if (rewritten_filename.has_value()) {
    file_to_access = rewritten_filename.value().c_str();
  }

  if (rmdir(file_to_access) < 0) {
    RAW_CHECK(reply->AddIntToMessage(-errno));
    return;
  }
  RAW_CHECK(reply->AddIntToMessage(0));
}

// Perform stat(2) on |requested_filename| and write the result to
// |return_val|.
void BrokerHost::StatFileForIPC(BrokerCommand command_type,

                                const char* requested_filename,
                                bool follow_links,
                                BrokerSimpleMessage* reply) {
  const char* file_to_access =
      CommandStatIsSafe(policy_->allowed_command_set,
                        *policy_->file_permissions, requested_filename);
  if (!file_to_access) {
    RAW_CHECK(
        reply->AddIntToMessage(-policy_->file_permissions->denied_errno()));
    return;
  }

  std::optional<std::string> rewritten_filename =
      RewritePathname(file_to_access);
  if (rewritten_filename.has_value()) {
    file_to_access = rewritten_filename.value().c_str();
  }

  if (command_type == COMMAND_STAT) {
    struct kernel_stat sb;

    int sts = follow_links ? sandbox::sys_stat(file_to_access, &sb)
                           : sandbox::sys_lstat(file_to_access, &sb);
    if (sts < 0) {
      RAW_CHECK(reply->AddIntToMessage(-errno));
      return;
    }
    RAW_CHECK(reply->AddIntToMessage(0));
    RAW_CHECK(
        reply->AddDataToMessage(reinterpret_cast<char*>(&sb), sizeof(sb)));
  } else {
#if defined(__NR_fstatat64)
    DCHECK(command_type == COMMAND_STAT64);
    struct kernel_stat64 sb;

    int sts = sandbox::sys_fstatat64(AT_FDCWD, file_to_access, &sb,
                                     follow_links ? 0 : AT_SYMLINK_NOFOLLOW);
    if (sts < 0) {
      RAW_CHECK(reply->AddIntToMessage(-errno));
      return;
    }
    RAW_CHECK(reply->AddIntToMessage(0));
    RAW_CHECK(
        reply->AddDataToMessage(reinterpret_cast<char*>(&sb), sizeof(sb)));
#else  // defined(__NR_fstatat64)
    // We should not reach here on 64-bit systems, as the *stat*64() are only
    // necessary on 32-bit.
    RAW_CHECK(false);
#endif
  }
}

void BrokerHost::UnlinkFileForIPC(const char* requested_filename,
                                  BrokerSimpleMessage* reply) {
  const char* file_to_access =
      CommandUnlinkIsSafe(policy_->allowed_command_set,
                          *policy_->file_permissions, requested_filename);
  if (!file_to_access) {
    RAW_CHECK(
        reply->AddIntToMessage(-policy_->file_permissions->denied_errno()));
    return;
  }

  std::optional<std::string> rewritten_filename =
      RewritePathname(file_to_access);
  if (rewritten_filename.has_value()) {
    file_to_access = rewritten_filename.value().c_str();
  }

  if (unlink(file_to_access) < 0) {
    RAW_CHECK(reply->AddIntToMessage(-errno));
    return;
  }
  RAW_CHECK(reply->AddIntToMessage(0));
}

void BrokerHost::InotifyAddWatchForIPC(base::ScopedFD inotify_fd,
                                       const char* requested_filename,
                                       uint32_t mask,
                                       BrokerSimpleMessage* message) {
  const char* file_to_access = CommandInotifyAddWatchIsSafe(
      policy_->allowed_command_set, *policy_->file_permissions,
      requested_filename, mask);
  if (!file_to_access) {
    RAW_CHECK(
        message->AddIntToMessage(-policy_->file_permissions->denied_errno()));
    return;
  }

  std::optional<std::string> rewritten_filename =
      RewritePathname(file_to_access);
  if (rewritten_filename.has_value()) {
    file_to_access = rewritten_filename.value().c_str();
  }

  int wd = inotify_add_watch(inotify_fd.get(), file_to_access, mask);
  if (wd < 0) {
    RAW_CHECK(message->AddIntToMessage(-errno));
    return;
  }
  RAW_CHECK(message->AddIntToMessage(wd));
}

// Handle a |command_type| request contained in |iter| and write the reply
// to |reply|.
bool BrokerHost::HandleRemoteCommand(BrokerSimpleMessage* message,
                                     base::span<base::ScopedFD> recv_fds,
                                     BrokerSimpleMessage* reply,
                                     base::ScopedFD* opened_file) {
  // Message structure:
  //   int:    command type
  //   char[]: pathname
  //   int:    flags
  int command_type;
  if (!message->ReadInt(&command_type))
    return false;

  switch (command_type) {
    case COMMAND_ACCESS: {
      const char* requested_filename;
      int flags = 0;
      auto result = GetPathAndFlags(message);
      if (!result) {
        return false;
      }
      std::tie(requested_filename, flags) = *result;
      AccessFileForIPC(requested_filename, flags, reply);
      break;
    }
    case COMMAND_MKDIR: {
      const char* requested_filename;
      int mode = 0;
      auto result = GetPathAndFlags(message);
      if (!result) {
        return false;
      }
      std::tie(requested_filename, mode) = *result;
      MkdirFileForIPC(requested_filename, mode, reply);
      break;
    }
    case COMMAND_OPEN: {
      const char* requested_filename;
      int flags = 0;
      auto result = GetPathAndFlags(message);
      if (!result) {
        return false;
      }
      std::tie(requested_filename, flags) = *result;
      OpenFileForIPC(requested_filename, flags, reply, opened_file);
      break;
    }
    case COMMAND_READLINK: {
      const char* filename;
      if (!message->ReadString(&filename)) {
        return false;
      }

      ReadlinkFileForIPC(filename, reply);
      break;
    }
    case COMMAND_RENAME: {
      const char* old_filename;
      if (!message->ReadString(&old_filename)) {
        return false;
      }

      const char* new_filename;
      if (!message->ReadString(&new_filename)) {
        return false;
      }

      RenameFileForIPC(old_filename, new_filename, reply);
      break;
    }
    case COMMAND_RMDIR: {
      const char* requested_filename;
      if (!message->ReadString(&requested_filename)) {
        return false;
      }
      RmdirFileForIPC(requested_filename, reply);
      break;
    }
    case COMMAND_STAT:
    case COMMAND_STAT64: {
      const char* requested_filename;
      if (!message->ReadString(&requested_filename)) {
        return false;
      }
      int follow_links;
      if (!message->ReadInt(&follow_links)) {
        return false;
      }
      StatFileForIPC(static_cast<BrokerCommand>(command_type),
                     requested_filename, !!follow_links, reply);
      break;
    }
    case COMMAND_UNLINK: {
      const char* requested_filename;
      if (!message->ReadString(&requested_filename)) {
        return false;
      }
      UnlinkFileForIPC(requested_filename, reply);
      break;
    }
    case COMMAND_INOTIFY_ADD_WATCH: {
      const char* requested_filename;
      if (!message->ReadString(&requested_filename)) {
        return false;
      }
      int mask;
      if (!message->ReadInt(&mask)) {
        return false;
      }
      if (!recv_fds[0].is_valid()) {
        return false;
      }
      InotifyAddWatchForIPC(std::move(recv_fds[0]), requested_filename, mask,
                            reply);
      break;
    }
    default:
      LOG(ERROR) << "Invalid IPC command";
      return false;
  }
  return true;
}

BrokerHost::BrokerHost(const BrokerSandboxConfig& policy,
                       BrokerChannel::EndPoint ipc_channel,
                       pid_t sandboxed_process_pid)
    : policy_(policy),
      ipc_channel_(std::move(ipc_channel)),
      sandboxed_process_pid_(sandboxed_process_pid) {}

BrokerHost::~BrokerHost() = default;

// Handle a request on the IPC channel ipc_channel_.
// A request should have a file descriptor attached on which we will reply and
// that we will then close.
// A request should start with an int that will be used as the command type.
void BrokerHost::LoopAndHandleRequests() {
  for (;;) {
    BrokerSimpleMessage message;
    errno = 0;
    base::ScopedFD temporary_ipc;
    std::array<base::ScopedFD, 2> recv_fds_arr;
    base::span<base::ScopedFD> recv_fds(recv_fds_arr);
    const ssize_t msg_len =
        message.RecvMsgWithFlagsMultipleFds(ipc_channel_.get(), 0, recv_fds);

    if (msg_len == 0 || (msg_len == -1 && errno == ECONNRESET)) {
      // EOF from the client, or the client died, we should finish looping.
      return;
    }

    // This indicates an error occurred in IPC. For example, too many fds were
    // sent along with the message.
    if (msg_len < 0 || !recv_fds[0].is_valid()) {
      if (!recv_fds[0].is_valid()) {
        errno = EBADF;
      }
      PLOG(ERROR) << "Error reading message from the client";
      continue;
    }

    temporary_ipc = std::move(recv_fds[0]);

    BrokerSimpleMessage reply;
    base::ScopedFD opened_file;
    if (!HandleRemoteCommand(&message, recv_fds.subspan<1>(), &reply,
                             &opened_file)) {
      // Does not exit if we received a malformed message.
      LOG(ERROR) << "Received malformed message from the client";
      continue;
    }

    ssize_t sent = reply.SendMsg(temporary_ipc.get(), opened_file.get());
    if (sent < 0)
      LOG(ERROR) << "sent failed";
  }
}

}  // namespace syscall_broker

}  // namespace sandbox