228 Commits
Author SHA1 Message Date
gVisor bot 808fe43d6a Merge pull request #14354 from tamird:checklocks-network-annotations
PiperOrigin-RevId: 973552848
2026-08-30 15:19:19 -07:00
Etienne Perot 054f876575 Fix //test/syscalls:tcp_socket_test_native failing on newer kernels.
As of Linux commit 5d39580f68e6, SO_ATTACH_FILTER requires
CAP_NET_ADMIN for TCP sockets.

Skip in tests if we don't have it, and update Netstack to require it
too.
2026-08-28 13:16:50 -07:00
Tamir DubersteinandHanzo Dev 5d4b282975 checklocks: annotate network lock ownership
Make existing mutex and atomic ownership explicit for networking state.
Annotate self-locking helpers and synchronous forwarding paths, keeping
queue references and callback lifetime requirements in their comments.

Document collection, callback and helper identity limits where the
checker cannot enforce the existing ownership contract.

Co-authored-by: Hanzo Dev <[email protected]>
2026-08-26 12:56:52 -04:00
Shayon Mukherjee 5b002692af vfs: skip write tracking for special files on open
Linux skips the mount-level write check when opening a character device, block device, FIFO, or socket, so write-opening /dev/null on a read-only bind mount succeeds.

Mark the remaining FileDescriptions backed by special-file inodes. Also skip overlay copy-up for writable opens of special files; Linux overlayfs applies the same special_file() exception before deciding whether copy-up is required.

Add regression coverage for character devices and FIFOs through read-only bind mounts.
2026-07-28 06:47:46 -04:00
Nayana BidariandgVisor bot 51723ede44 Support the SO_MARK socket option and Netfilter mark matching.
- This change enables sockets to set and get the `SO_MARK` option, which marks
outgoing packets.
- It also implements Netfilter (iptables) support for matching
packet marks using the `mark` match extension.
- Added unit and E2E tests to verify mark match and capabilities.

PiperOrigin-RevId: 938123591
2026-06-25 12:16:10 -07:00
Tan Yifeng 45596a2399 net: Support getsockopt with small buffer for int TCP options
Linux's do_tcp_getsockopt() clamps the user-supplied buflen via
len = min_t(unsigned int, len, sizeof(int)) and copies that many
bytes of the integer value, so a sub-int (or zero-length) buffer
returns a truncated result rather than EINVAL. gVisor instead
rejects any outLen < 4 with EINVAL, which breaks real callers:
python-trio probes TCP_NODELAY with buflen=1 to detect its
availability and fails with OSError(EINVAL).

Route all 12 integer TCP options (TCP_NODELAY, TCP_CORK,
TCP_QUICKACK, TCP_MAXSEG, TCP_KEEPIDLE, TCP_KEEPINTVL,
TCP_KEEPCNT, TCP_USER_TIMEOUT, TCP_LINGER2, TCP_DEFER_ACCEPT,
TCP_SYNCNT, TCP_WINDOW_CLAMP) through a shared helper that
truncates the value to outLen bytes, matching Linux. outLen == 0
is a valid (zero-byte) read and must not be rejected.

Reference: net/ipv4/tcp.c:do_tcp_getsockopt()
Signed-off-by: Tan Yifeng <[email protected]>
2026-04-27 16:40:25 +08:00
gVisor bot fda893428f Merge pull request #12949 from tanyifeng:net-interface-order
PiperOrigin-RevId: 904671911
2026-04-23 15:44:00 -07:00
Tan Yifeng e2bd312913 net: Ensure deterministic interface enumeration order
Go map iteration randomness causes network interface enumeration
(getifaddrs, RTM_GETADDR, RTM_GETLINK, /proc/net/*, SIOCGIFCONF)
to return nondeterministic order, breaking applications like
asciidoctor that expect stable ordering across repeated calls.

Since gVisor allocates NIC IDs monotonically (like Linux ifindex),
sorting by NICID is equivalent to registration order. Add
InterfaceIDs() to inet.Stack so all consumer paths iterate in
deterministic ascending-ID order without ad-hoc sorting at each
call site.

Signed-off-by: Tan Yifeng <[email protected]>
2026-04-23 10:16:47 +08:00
8b8ee76e29 Add missing Linux capability checks for SO_BINDTODEVICE, mknod, sched_setaffinity, and setpriority
## Summary

This patch adds capability and permission checks that the Linux kernel enforces but gVisor currently omits. Each fix was verified against native Linux behavior using `bazel test` on both native and `runsc_ptrace` platforms.

## Changes

### 1. `SO_BINDTODEVICE`: Add `CAP_NET_RAW` check
**File:** `pkg/sentry/socket/netstack/netstack.go`
**Linux reference:** `net/core/sock.c:sock_setsockopt()` checks `ns_capable(sock_net(sk)->user_ns, CAP_NET_RAW)`
**Evidence this is unintended:** gVisor's own test suite asserts `"CAP_NET_RAW is required to use SO_BINDTODEVICE"` (`test/syscalls/linux/socket_bind_to_device.cc:52`), and `SO_RCVBUFFORCE` in the same file already correctly checks `CAP_NET_ADMIN`.

### 2. `mknod(S_IFBLK/S_IFCHR)`: Add `CAP_MKNOD` check
**File:** `pkg/sentry/syscalls/linux/sys_file.go`
**Linux reference:** `fs/namei.c:vfs_mknod()` checks `capable(CAP_MKNOD)` for block/char device creation
**Evidence this is unintended:** `CAP_MKNOD` is defined (`pkg/abi/linux/capability.go:56`), parsed from OCI specs (`runsc/specutils/specutils.go:491`), and has strace formatting — but is never checked anywhere. Zero `HasCapability` calls for it exist in the codebase.

### 3. `sched_setaffinity`: Add UID match / `CAP_SYS_NICE` check
**File:** `pkg/sentry/syscalls/linux/sys_thread.go`
**Linux reference:** `kernel/sched/core.c:check_same_owner()` requires EUID match or `CAP_SYS_NICE`
**Impact:** Without this check, any unprivileged process could modify another process's CPU affinity mask.

### 4. `setpriority`: Add UID match / `CAP_SYS_NICE` check
**File:** `pkg/sentry/syscalls/linux/sys_thread.go`
**Linux reference:** `kernel/sys.c:set_one_prio()` requires UID match or `CAP_SYS_NICE`
**Impact:** Without this check, any unprivileged process could change another process's scheduling priority.

## Testing

Tests added in `test/syscalls/linux/capability_checks.cc`, verified on both native Linux and gVisor:

```
bazel test //test/syscalls:capability_checks_test_native        → 6/6 passed
bazel test //test/syscalls:capability_checks_test_runsc_ptrace  → 4 passed, 2 skipped
```

The 2 skipped tests are the mknod positive cases (creating device nodes with `CAP_MKNOD`), which are skipped on gVisor because the sandbox does not permit device node creation regardless of capabilities.

| Test | What it verifies |
|------|-----------------|
| `SoBindToDeviceCapTest.RequiresCapNetRaw` | `EPERM` without `CAP_NET_RAW` |
| `MknodCapTest.CharDevRequiresCapMknod` | `EPERM` for `S_IFCHR` without `CAP_MKNOD` (native only) |
| `MknodCapTest.BlockDevRequiresCapMknod` | `EPERM` for `S_IFBLK` without `CAP_MKNOD` (native only) |
| `MknodCapTest.FifoDoesNotRequireCapMknod` | `S_IFIFO` succeeds without `CAP_MKNOD` |
| `SchedSetaffinityCapTest.OtherUidRequiresCapSysNice` | `EPERM` without UID match or `CAP_SYS_NICE` |
| `SetpriorityCapTest.OtherUidRequiresCapSysNice` | `EPERM` without UID match or `CAP_SYS_NICE` |

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/gvisor/pull/12872 from petrmarinec:fix/missing-capability-checks 70b4e0fa308ba182e7916112e90aed40cdea75f3
PiperOrigin-RevId: 903343461

Co-authored-by: Hanzo Dev <[email protected]>
2026-04-21 11:43:53 -07:00
Parth SarthiandgVisor bot 3605395498 netstack: Added check for CAP_NET_ADMIN for get/setsockopt.
Based on `net/ipv[4|6]/netfilter/ip6?_tables.c`

Added syscall tests for the same.

PiperOrigin-RevId: 869826812
2026-02-13 11:53:47 -08:00
Parth SarthiandgVisor bot f55c24980a sockets: Bind get/set sockopts to socket types.
- Pruned invalid get/setsockopts from unix-sockets
  (unix socket only supports SOL_SOCKET level).
- Binded the get/setsockopts to netstack sockets.

PiperOrigin-RevId: 866055123
2026-02-05 12:11:52 -08:00
Ayush RanjanandgVisor bot 154327a661 netstack: Use ctx.BlockWithTimeout() directly while releasing socket.
When ctx is of type `kernel.taskAsyncContext`, calling
`kernel.TaskFromContext(ctx)` on it returns the original task (even though this
is an async goroutine). And then calling methods like Block() on it would panic
because it expects to be running on the task goroutine. Furthermore, the Task
could have exited so working on a dead task could cause other issues too.

Instead, use `kernel.taskAsyncContext` methods via the context.Context
interface. This change adds BlockWithTimeout() to the context interface and
implements it for context.NoTask. kernel.Task already implements this.

The current implementation of context.NoTask.BlockWithTimeoutOn was buggy:
- It returned true when the desired event occurred OR when the timeout expired.
  However, context.Blocker interface docstring suggest that true should only
  be returned when the desired event occurs, which kernel.Task implements
  correctly.
- Instead of returning the remaining timeout, it returned the duration passed
  since the timer started.

Fixed these two bugs and made the implementations of kernel.Task and
context.NoTask consistent with one another.

Also clarified docstrings for some Task.Block*() methods about the precondition
of "The caller must be running on the task goroutine.".

Reported-by: [email protected]
Reported-by: [email protected]
PiperOrigin-RevId: 853557307
2026-01-07 22:17:38 -08:00
Shailend ChandandgVisor bot 4c77fa8b9a Fix creds checks for SO_RCVBUFFORCE and UCOUNT_RLIMIT_NPROC
PiperOrigin-RevId: 853451466
2026-01-07 16:16:29 -08:00
Shailend ChandandgVisor bot e428bbea51 Fix creds check in linkat(AT_EMPTY_PATH)
linkat(AT_EMPTY_PATH) needs to check for CAP_DAC_READ_SEARCH in the userns in
which the fd was opened, not the userns of the task running linkat().

To get at that userns, vfs.FileDescription now saves a pointer to the creds
at the time of its creation: plumbing these creds in accounts for much of the
diff. This is similar to how `struct file` stores creds in `f_cred` in Linux.

Moreover, since the Linux patch "vfs: relax linkat() AT_EMPTY_PATH..." [1], the
need for this cap is excused if the creds of the calling task are literally
the same as the one stored in the fd.

[1] https://github.com/torvalds/linux/commit/42bd2af5950456d

PiperOrigin-RevId: 853374474
2026-01-07 12:48:17 -08:00
AnilAltinayandgVisor bot be847fb825 Implement SO_PEERCRED socket option for UNIX sockets and its tests.
PiperOrigin-RevId: 828197810
2025-11-04 17:24:56 -08:00
Shailend ChandandgVisor bot 888c8f0a3a Deny SOL_IP socket options for raw AF_INET6 sockets
PiperOrigin-RevId: 813907049
2025-10-01 14:13:01 -07:00
Shailend ChandandgVisor bot eb11519f52 Support IPv6_MULTICAST_IF
Of the 11 java runtime tests that were anticipating this socket option, 8 now
pass. Of the 3 that still fail, 1 now needs IPV6_MULTICAST_HOPS. The other 2
fail due to an unknown reason: they fail with runc too.

PiperOrigin-RevId: 813839126
2025-10-01 11:37:14 -07:00
AnilAltinayandgVisor bot 601fd6e05a Automated rollback of changelist 798788535
PiperOrigin-RevId: 803481970
2025-09-05 09:03:06 -07:00
AnilAltinayandgVisor bot eb1c87dc72 Implement SO_PEERCRED socket option for UNIX sockets and its tests.
PiperOrigin-RevId: 798788535
2025-08-24 05:08:00 -07:00
Ayush RanjanandgVisor bot 58f4d1739e hostinet: Add SO_ORIGINAL_DST and IP6T_ORIGINAL_DST.
Acknowledgements: handpickencounter <[email protected]>.

Fixes #8564

PiperOrigin-RevId: 751587679
2025-04-25 15:56:07 -07:00
Etienne PerotandgVisor bot 757a66c88d Consolidate helper functions around unimplemented socket option metrics
This fixes the underflow case in case the passed-in socket option is
negative.

Reported-by: [email protected]
PiperOrigin-RevId: 750307682
2025-04-22 13:32:19 -07:00
Etienne PerotandgVisor bot cbd7ca6d82 Fix range check on socket option counter metric.
Also avoid successive re-allocations when initializing the slice of field
names.

Reported-by: [email protected]
PiperOrigin-RevId: 748844855
2025-04-17 16:15:20 -07:00
Lucas ManningandgVisor bot c1e5b6eb8b Return ENOPROTOOPT from setsockopt syscalls as default.
gVisor has historically silently failed for unknown protocol options. In
the interest of not breaking existing users, we want to keep that behavior
while adding metrics to track how much this behavior is used in practice.
Eventually we'd like gVisor's behavior to be in line with Linux's.

PiperOrigin-RevId: 748459211
2025-04-16 16:22:52 -07:00
Lucas ManningandgVisor bot 303d04e744 Add a metric to track unimplemented setsockopt options.
PiperOrigin-RevId: 748432265
2025-04-16 14:53:19 -07:00
Lucas ManningandgVisor bot 7d31cdfcc2 Add support for PACKET_STATISTICS.
PiperOrigin-RevId: 725271073
2025-02-10 10:46:54 -08:00
Lucas ManningandgVisor bot 85faf17998 Implement GetSockOpt PACKET_HDRLEN and add a test for tcpdump.
PiperOrigin-RevId: 724445536
2025-02-07 13:06:14 -08:00
Lucas ManningandgVisor bot ed33702a8b Don't switch to using the packet mmap endpoint for zero length requests.
This matches linux's behavior.

Reported-by: [email protected]
Reported-by: [email protected]
PiperOrigin-RevId: 724032784
2025-02-06 12:34:46 -08:00
Ayush RanjanandgVisor bot 17b4a2259d Validate PACKET_RX_RING and PACKET_VERSION socket option value size.
Reported-by: [email protected]
Reported-by: [email protected]
PiperOrigin-RevId: 723999333
2025-02-06 11:04:23 -08:00
Lucas ManningandgVisor bot d31f849160 Add support for setting PACKET_VERSION for PACKET_MMAP.
tcpdump requires TPACKET_V2 to work properly.

PiperOrigin-RevId: 723670574
2025-02-05 15:19:34 -08:00
Lucas ManningandgVisor bot b8826118f4 Implement MappablePacketEndpoint for PACKET_MMAP and add tests.
PiperOrigin-RevId: 723590936
2025-02-05 11:39:27 -08:00
clickyotomy 75ac9bcc48 netfilter: Support multiport matching (-m multiport)
This set of changes adds:

  - support for `xt_multiport_{,v1}` matchers for matching for
    a range of ports and their inverse, i.e.,:

      ```
      -m multiport [!] --[s|d]ports (PORT,...|PORT:PORT,...)
      ```

  - support for `IP{,6}T_SO_GET_REVISION_MATCH` socket options,
    which allows `iptables` to query for the highest supported
    revision for a given matcher
2025-01-18 09:46:30 -05:00
Lucas ManningandgVisor bot 18e7409c73 Add support for custom socket options and setting the experiment IP option.
PiperOrigin-RevId: 700011458
2024-11-25 09:43:21 -08:00
Jamie LiuandgVisor bot 19f12e64c8 Move //pkg/sentry/kernel/time to //pkg/sentry/ktime.
This avoids needing to rename it everywhere it's imported.

PiperOrigin-RevId: 693930089
2024-11-06 18:13:51 -08:00
Koichi Shiraishi 5677ce4285 all: remove use io/ioutil deprecated package & fix some deprecated thing
Signed-off-by: Koichi Shiraishi <[email protected]>
2024-10-10 20:36:24 +09:00
Kevin KrakauerandgVisor bot e85e82f436 noop upon IP_PMTUDISC_INTERFACE and IP_PMTUDISC_OMIT
This is what we did previously, and doing so avoids breaking some users.

Fixes #10760.

PiperOrigin-RevId: 663358270
2024-08-15 10:35:00 -07:00
Ayush RanjanandgVisor bot 3968e3bb4f Log endpoint type when SOL_IP options are not supported.
PiperOrigin-RevId: 647392128
2024-06-27 11:43:48 -07:00
Etienne PerotandgVisor bot a8eecc9746 Metrics: Refactor uint64 metric constructor, allow non-cumulative gauges.
This turns the uint64 metric constructor arguments into a struct, making it
more explicit as to what each part means. It also allows the creation of
non-cumulative uint64 (gauge) metrics, and adds methods to decrement or set
them.

PiperOrigin-RevId: 647134245
2024-06-26 17:41:24 -07:00
Kevin KrakauerandgVisor bot 5a7de6a798 make PMTUD on by default and settable via sockopt
We've supported PMTUD for a long time and just never turned it on.

Addresses #10344.

PiperOrigin-RevId: 634003508
2024-05-15 10:44:02 -07:00
Kevin KrakauerandgVisor bot 585da0c2b4 netstack: remove stale TODOs
PiperOrigin-RevId: 633751715
2024-05-14 17:11:30 -07:00
Nayana BidariandgVisor bot 8350f308b0 Remove TODOs for supporting TCP_INFO option.
TCP_INFO option is supported in gVisor, but does not return all the fields
in struct TCP_INFO. The fields which were required for debugging are added.
The support for other fields in the struct can be added when required.

PiperOrigin-RevId: 632621246
2024-05-10 15:40:45 -07:00
Kevin KrakauerandgVisor bot 75cb6c0c5d netstack: don't allocate interfaces when copying data in and out
In a redis-benchmark PING_INLINE test, this reduces allocations by 32%.

PiperOrigin-RevId: 618248114
2024-03-22 12:01:02 -07:00
Kevin KrakauerandgVisor bot ceacdacbca iptables: check revision numbers and support owner matcher v1
This change also replaces use of kernel.Task with a narrower type (IDMapper) in
preparation for a follow-up CL.

PiperOrigin-RevId: 578387814
2023-10-31 21:17:26 -07:00
Nayana BidariandgVisor bot a8a77eba88 Fix SO_ACCEPTCONN option for unix sockets.
SO_ACCEPTCONN returns true for TCP sockets which are in a listening state.
Added this socket option support for unix sockets.

PiperOrigin-RevId: 577008617
2023-10-26 15:48:38 -07:00
Nicolas LacasseandgVisor bot fd8f39c53b Emit SentryTcpListenEvent when the application listens on a tcp port.
PiperOrigin-RevId: 562957239
2023-09-05 19:15:45 -07:00
Andrei VaginandgVisor bot c5493106c6 Implement the setns syscall
This change introduces the nsfs file system. Each new namespace allocates
a new nsfs inode.

Here are reasons why we need these inodes:
* each namespace has to have an unique id.
* proc/pid/ns/ contains one entry for each namespace. Bind mounting one of
  the files in this directory to somewhere else in the filesystem keeps the
  corresponding namespace alive even if all processes currently in
  the namespace terminate.
* setns() allows the calling process to join an existing namespace specified
  by a file descriptor.

PiperOrigin-RevId: 550694515
2023-07-24 15:45:08 -07:00
Andrew Dunham 5496367f50 pkg/tcpip/transport/tcp: add statistics for dropped connections
When the TCP forwarder ignores a connection due to having too many
in-flight connections, it's not easy to log a message or update a metric
for later debugging. Add a metric that will be incremented in this case
so that the user of the Forwarder can observe this.

Signed-off-by: Andrew Dunham <[email protected]>
2023-07-17 15:07:55 -04:00
Kevin KrakauerandgVisor bot ef88b30bff netstack: make tcpip.Address an opaque type
The important change here is in tcpip/tcpip.go, where tcpip.Address is defined.
The rest is updating uses of tcpip.Address.

This is preparation for netip.Addr or []byte based addresses, which should save
us a bunch of allocations. Currently, we allocate every time we want to, say,
get a tcpip.Address from a header. This is because the header is a byte slice,
but Address is a string. Strings are immutable, so Go allocates and copies.

PiperOrigin-RevId: 532284732
2023-05-15 18:07:03 -07:00
Etienne PerotandgVisor bot ba61bf6e93 gVisor metric library: Change interface for passing in field values.
This introduces a `metric.FieldValue` struct type that wraps a string.
All metric interfaces that deal with field values have been updated to use
pointers to this type instead of strings.

The intent of this change is to make it more obvious that field values must
be passed using references. Prior to this change, this was done using string
pointer comparisons. Now this must be done by using a pointer to the same
`metric.FieldValue` struct.

The struct type still externally exposes its string so that it can be referred
to in value function callbacks by "custom" metrics. (Though there are no
current uses of callback metrics with fields.)

PiperOrigin-RevId: 527030738
2023-04-25 11:49:02 -07:00
Kevin KrakauerandgVisor bot 60a2432dff stop using tcpip.FullAddress with unix sockets
It's unnecessarily overloading the type, which makes it hard to change the type
in netstack.

PiperOrigin-RevId: 526168235
2023-04-21 16:48:37 -07:00
Etienne PerotandgVisor bot c6d19db4e4 Update unimpl.EmitUnimplementedEvent interface to add the syscall number.
This catches up the interface to the `EmitUnimplementedEvent` method signature
on `kernel.Kernel`.

Also add build-time test to verify that `kernel.Kernel` implements this
interface, in order to catch such breakages at build time in the future.

PiperOrigin-RevId: 519000411
2023-03-23 17:01:37 -07:00