335 Commits
Author SHA1 Message Date
Danny Hershko Shemesh c619177102 Refuse a veth peer attribute shorter than its ifinfomsg
The peer payload is sliced at the size of a struct ifinfomsg before anything measures it, so 4 bytes panic the Sentry and take the sandbox with it. Any user reaches it after unshare -Ur -n.

Check the length instead of re-testing a lookup that already succeeded. A short payload now answers EINVAL.

Fixes #14516
2026-08-31 16:08:32 +03:00
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
gVisor bot f5233ba717 Merge pull request #13149 from shayonj:fix-special-file-rofs
PiperOrigin-RevId: 959878764
2026-08-05 14:45:23 -07:00
Parth SarthiandgVisor bot c2e9a88ab3 NIC: Added support to return kind with info.
PiperOrigin-RevId: 959288350
2026-08-04 16:25:37 -07: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 3846731234 Refactor network configuration during restore and defer link creation in runsc
This change refactors the network configuration flow during sandbox restore
and defers the creation of network links and routes in runsc to run after
seccomp filters are installed.

- Replaced ReplaceConfig with ResetConfig in inet.Stack. Introduced
inet.NetworkArgs to configure the stack during restore, updating k.LoadFrom
to use it.
- Renamed CreateLinksAndRoutes URPC to SetNetworkArgs, which now configures
host sockets before seccomp is installed, deferring link/route creation to run
after seccomp.
- Fixed S/R support by saving and restoring limit/burst state.
- Minor seccomp filter adjustments and test updates.

PiperOrigin-RevId: 945995430
2026-07-10 18:52:31 -07:00
Nayana BidariandgVisor bot 7e09cf7be6 Automated rollback of changelist 941330876
PiperOrigin-RevId: 944161934
2026-07-07 16:47:40 -07:00
Nayana BidariandgVisor bot 997db57cd5 Refactor setting up network during restore.
Previously, during sandbox restore the network configuration was restored by
creating a new network stack (which has all the config scraped from the host)
and the replacing this new config such as NICs, routes and IP addresses from
the new stack to the loaded/restored stack.

This change refactors the process by introducing a new `inet.NetworkArgs`
interface that abstracts how the network stack is configured. The `Loader` now
implements this interface and configures the loaded stack directly using the
configuration scraped from the host during restore. `Kernel.LoadFrom` accepts
this interface (instead of stack), allowing it to configure the restored stack
using either the Loader's configuration.

PiperOrigin-RevId: 941330876
2026-07-01 15:37:56 -07: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
lyphyserandHanzo Dev c161e690a0 netstack: log the correct field in the unsupported ifi_flags warning
The warning for unsupported ifi_flags printed ifinfomsg.Change instead of
ifinfomsg.Flags. Print the field actually being validated.

Co-authored-by: Hanzo Dev <[email protected]>
2026-06-19 08:29:46 +00: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
Nayana BidariandgVisor bot 1e6759d3d9 Remove usages of save-restore-netstack flag.
This flag has been true by default for a while, remove its usages and
deprecate the flag.

PiperOrigin-RevId: 903909652
2026-04-22 10:15:08 -07: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
Shailend ChandandgVisor bot e37f1fe8d0 netstack: Fix cap check around IFLA_NET_NS_FD
When bridging, or when moving a veth, we must check if we have CAP_NET_ADMIN
in the target netns.

PiperOrigin-RevId: 889518624
2026-03-25 17:36:05 -07:00
Jing ChenandgVisor bot 0b3a2d95e3 Fix nil pointer dereference in netstack.Stack.
The netstack.Stack.Destroy method call s.Stack.Close() without checking
if s.Stack is nil. In some edge cases (e.g., during failed restore),
s.Stack can be nil, leading to a panic.

PiperOrigin-RevId: 882212491
2026-03-11 14:59:32 -07:00
Jamie LiuandgVisor bot bed85b28f5 Internal change.
PiperOrigin-RevId: 878145516
2026-03-03 15:12:27 -08: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
Nayana BidariandgVisor bot a41a6099f9 Terminate connections only for restore (not for resume).
Previously, external connections were terminated during both restore and
resume operations, causing a reconnection after every resume. By limiting
termination to the restore only, connections now remain active during resumes
as intended.

Added tests to verify that resume does not terminate the connection.

PiperOrigin-RevId: 868830577
2026-02-12 14:35:26 -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
Shailend ChandandgVisor bot 1b8a025e4a Cleanup creds-related funcs and change CapError behavior
- Introduce Credentials.HasRootCapability().
 - Rename Credentials.HasCapability() to Credentials.HasSelfCapability().
 - Rename Task.HasCapability() to Task.HasSelfCapability().
 - Introduce inet.Namespace.HasCapability(ctx).
 - CapError(), invoked by unimplemented syscalls' stubs, now checks
   against the root userns.

All towards making it less easy to evaluate creds relative to self userns
instead of root userns in the future.

PiperOrigin-RevId: 853942212
2026-01-08 17:23:58 -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
Shailend ChandandgVisor bot 7920d34651 netlink: Supply IFLA_MASTER in RTM_NEWLINK messages
This allows `ip link show master` to work.

PiperOrigin-RevId: 845470317
2025-12-16 16:07:24 -08:00
Shailend ChandandgVisor bot 3860ef4de3 socket(): Check for CAP_NET_RAW in the netns-owning userns
And not the userns of the calling Task. Analogous to Linux's
`ns_capable(net->user_ns, CAP_NET_RAW)`.

PiperOrigin-RevId: 843929192
2025-12-12 20:09:51 -08:00
Shailend ChandandgVisor bot aa19062305 Fix a bug around IFLA_NET_NS_FD
IFLA_NET_NS_FD is supplied in an RTM_SETLINK message from userland to move a
link to a new netns. The same message might mutate other attributes of the
link. Thus far we were applying those changes to a different link in the source
netns.

PiperOrigin-RevId: 842358153
2025-12-09 12:54:40 -08:00
Shailend ChandandgVisor bot b30c659b42 Add RTNLGRP_LINK netlink multicast support for recv
Only netstack supports sending link events, requests to join multicast
groups for netlink sockets continue to be denied when hostinet is in use.

connect() and sendmsg() to RTMGRP_LINK still fails.

PiperOrigin-RevId: 831688843
2025-11-12 22:04:10 -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
Nayana BidariandgVisor bot c52821b3e0 Remove old NICs and routes during save/restore.
During restore there will be new NICs and routes created based on the network
config. Close these old NICs and routes in beforeSave() only for save/restore.
For save/resume, do not close them.

As new link endpoints are created during restore, there is no need to start
the associated old processor goroutines in afterLoad. Start them only for
save/resume.

PiperOrigin-RevId: 804994281
2025-09-09 11:33:49 -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
Lucas ManningandgVisor bot 0a66fa458c Add locking around ringbuffer fields and reserve in packetmmap endpoint.
Reported-by: [email protected]
Reported-by: [email protected]
PiperOrigin-RevId: 759230496
2025-05-15 11:35:27 -07:00
Andrei VaginandgVisor bot 09e82a6dc8 netstack/tuntap: implement the IFF_TUN_EXCL flag
Update #11665

PiperOrigin-RevId: 755947224
2025-05-07 11:59:29 -07:00
Lucas ManningandgVisor bot ff0611ab38 Lock around grabbing the version and hdrLen in packetmmap.
Reported-by: [email protected]
Reported-by: [email protected]
PiperOrigin-RevId: 755581142
2025-05-06 17:05:22 -07:00
Lucas ManningandgVisor bot 22305de482 lock around getting the current time from the stack.
Reported-by: [email protected]
PiperOrigin-RevId: 753748087
2025-05-01 15:22:38 -07:00
Lucas ManningandgVisor bot 57827bf0c4 Don't use cached values for net proto and nic ID in packet mmap.
PiperOrigin-RevId: 753306169
2025-04-30 14:10:46 -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 de1f94f689 Don't allow reinit of already mapped packet mmap endpoints.
Reported-by: [email protected]
Reported-by: [email protected]
PiperOrigin-RevId: 746169213
2025-04-10 14:16:28 -07:00
Lucas ManningandgVisor bot ddb7bd2c14 Don't return empty translation in ring buffer during bus error.
Reported-by: [email protected]
PiperOrigin-RevId: 726111936
2025-02-12 10:43:52 -08:00
Lucas ManningandgVisor bot ede0ace60e Lock around packetmmap cooked field and check for PACKET_RESERVE opt size.
Reported-by: [email protected]
Reported-by: [email protected]
PiperOrigin-RevId: 725302503
2025-02-10 12:18:14 -08:00