Shell – Is it possible to drop all write privileges in a shell for the current user

posixselinuxshell

This is NOT for security purposes.

Suppose I wanted to execute a shell script and, on a best effort basis, assume it left no side effects aside from things like auditd logging, avc reports, syslog, etc. Effectively, I want to drop all write privileges for the current user for the entire shell session. I'm not interested in setting up groups and lower privileged users with carefully managed file permissions. What options exist?

Ideally I'd like to target any posix shell, but I started with bash because it's what I'm most familiar with.

Reading through man bash, restricted shells looked promising but they're too restrictive in the wrong places. e.g. I still want to be able use cd and it doesn't prevent something like echo foo | tee /file. Likewise, bash set options aren't restrictive enough since they don't restrict subprocesses from writing as well, e.g. (set -C; echo foo | tee /file) doesn't accomplish what I'm looking for.

I'd also like to avoid overlayfs, as I'd like to be able to enter/exit this "read-only" mode in a single SSH session.

The closest I've gotten is dropping the max filesize ulimit to 0:

(ulimit -f 0; echo "blows up w/ signal SIGXFSZ" > file; ); echo $?

This seems pretty close to what I'm looking for and works in shells like dash, but it still suffers from leaving empty files around. So in the example above "file" would have been created, but would be empty.

I feel like there is a way to confine my user session with SELinux to something more restrictive, but could use a pointer to help.

Any other options?

Another option I'm interested in is simply monitoring any IO write during a process. Perhaps cgroups could be used for this, but I'm unfamiliar with them. Or perhaps systemd-run could be useful too.

Best Answer

Not a complete answer, but maybe a pointer towards one...

Perhaps something like the Linux Diskquota system would work, the Debian quota package description:

  Description-en: disk quota management tools
   This package provides the standard set of utilities for manipulating
   file system usage caps via the Linux Diskquota system. It can set hard
   or soft limits with adjustable grace periods on block or inode usage for
   users and groups. It allows users to check their quota status,
   integrates with LDAP, and supports quotas on remote machines via NFS.

A rough outline would be:

  1. set up a guest system or home directory with most everything write protected, then

  2. turn on the quota system for user foobar, set to 0.