Fatdog unshare xephyr capsh container

versatile 64-bit multi-user Linux distribution

Moderators: kirk, jamesbond, p310don, JakeSFR, step, Forum moderators

Post Reply
user1111

Fatdog unshare xephyr capsh container

Post by user1111 »

EDIT : A later version to that of the script/code posted here is available in this post -> viewtopic.php?p=16475#p16475

Updated version of May 2019 code. Crude and hard coded, but works and could be used as a template. Similar to a EasyOS container.

Basically when run (after making the appropriate edits to point to wherever), it starts a full screen Xephyr (another X server), using fd64.sfs as the base, and chroots into that with various capabilities dropped. When in that environment, open a terminal and run seamonkey (as root) ... but where that root is a duff-root (more restricted than even spot in a conventional Puppy).

My fd64.sfs is in /mnt/sda1/FATDOG811-FINAL, I use /mnt/sda4/changes as the working folder (needs to be a ext2/3/4 filesystem outside of 'Puppy space' i.e. on HDD) and /mnt/sda4/shared as a shared folder. Edit the pointers to those to wherever you might use instead.

I have pflask and empty installed, can't remember if that is by default or whether I installed them using gslapt/package manager.

To exit its alt-F4, or if you have other windows already running in the main session you can alt-tab to them. Some/many menu options might not work, primarily I use it to run seamonkey is a contained manner by opening a terminal and typing 'seamonkey' (the seamonkey in the Menu wont work)

If you'd rather run jwm instead of lxqt panel/openbox, then remove the
echo "lxqt-panel &" >>top/init
echo "openbox" >>top/init
lines and replace them with
echo "jwm" >>top/init

You might also want to change the dpi value from 144 (the more usual choice is 96).

Code: Select all

#!/bin/sh

# Rufwoof Jan 2021 (updated May 2019 version). Comments at end

xterm & # added so have at least one window I can alt-tab to out of the container
[ ! -d /mnt/sda4/shared ] && mkdir /mnt/sda4/shared # as a shared folder

CHANGES_LOC=/mnt/sda4/changes 		  # Non pre-existing ext fs work folder
MAIN_SFS=/mnt/sda1/FATDOG811-FINAL/fd64.sfs # Where the main sfs is located

# Xephyr parameters
XP="-fullscreen -title container -name Xephyr2 -dpi 144 -nolisten tcp"
   
# pflask parameters
PF="--mount=bind:/mnt/sda4/shared:/home/shared"
PF="${PF} --keepenv --no-ipcns --no-netns"
PF="${PF} --mount=bind:/mnt/sda4/shared:/home/shared"
PF="${PF} --mount=bind:/etc/resolv.conf:/etc/resolv.conf"  # dns (internet)
PF="${PF} --mount=bind:/dev/snd:/dev/snd"
PF="${PF} --mount=bind:/dev/mixer:/dev/mixer"
PF="${PF} --caps=all,-sys_admin,-sys_boot,-sys_chroot,-sys_ptrace,"
PF="${PF}-sys_time,-sys_tty_config,-chown,-kill,-dac_override,"
PF="${PF}-dac_read_search,-fowner,-setfcap,-setpcap,-net_admin,"
PF="${PF}-mknod,-sys_module,-sys_nice,-sys_resource"
PF="${PF} --chroot=${CHANGES_LOC}/top"   

# Avoid double click 2 instances
N=`date +%s` # Seconds since January 1970
if [ -f /tmp/container.run ];then
		L=`cat /tmp/container.run`
		D=`expr $N - $L`
		if [ $D -lt 2 ];then
			exit # quick 2 launches (doubled clicked ignore second click)
		fi
fi
echo $N >/tmp/container.run

# Create a separate X instance so isolated from the main real root X
T=`ps -ef | grep Xephyr2 | wc -l`
if [ $T -ne 2 ];then
		Xephyr :2 ${XP} & 
else
		exit # Xephyr2 already running
fi

# Create a changes folder, sfs mount point for main.sfs and top layer
# folders and aufs mount to combine changes and sfs folders -> top
cd ${CHANGES_LOC}
# Check for possible hangover - such as if restarted X and clean out if so
if [ -d top ] || [ -d sfs ] || [ -d changes ]; then	
		umount top sfs
		rm -rf changes
		rmdir top sfs
fi
mkdir top sfs changes
mount -r -t squashfs ${MAIN_SFS} sfs
mount -t aufs -o br=changes:sfs none top

# create a script to run inside the chroot (i.e. must be a script, not a bin)
echo "#!/bin/sh" >top/init
echo "lxqt-panel &" >>top/init
echo "openbox" >>top/init
chmod +x top/init

# The big Xephyr capabilities dropped chroot switch
DISPLAY=:2 empty -f unshare -m pflask ${PF} -- /init

wait # above backgrounds, so we wait until that ends

# Clean up
killall Xephyr
umount top sfs
rm -rf changes
rmdir top sfs
rm /tmp/container.run

############################################################################
# FOR FATDOG 811 ...
#
# Aufs mounts changes (initial empty rw folder), main sfs, that combined
# is visible/accessed via folder 'top', that we chroot into
#
# chroot with chroot capability dropped (to prevent chroot out of the chroot)
# using another X session (Xephyr) to isolate it from the main X session.
# We chroot using pflask as that makes things easier into the top folder 
# applying further restrictions. We use the main sfs as our base for the
# chroot, so very low overheads.
#
# alt-F4 	closes the Xephyr container (if not then ctrl-shift to unfocus 
# 			mouse/keyboard.
# alt Tab 	to step to another window in main system, but if use 
# 			xdotool keydown alt key Tab;xdotool keyup alt .... it doesn't
# 			work (as intended i.e. it's locked into the "container").
# seamonkey from menu doesn't work, run seamonkey from within urxvt
# We use DISPLAY :2 for the Xephyr server
#
# Requires empty, pflask and a ext filesystem to create/work within
#
# I use fatdog multi-session save type frugal boot, and periodically I've
# re-merged the save files into fd64.sfs so my fd64.sfs isn't the standard
# version (merging changes and not copying fd64.sfs to ram helps keep ram
# usage low). 
############################################################################

When in a terminal, check things out ... you can't for instance see the HDD's, nor chroot and if you run htop you'll see very few things. Can't pipe things into the main session window, nor keylog (or stuff key sequences). Whilst operational speed is as fast as the main session (when for instance viewing youtubes).

Instead of launching openbox/lxqt panel (or jwm), you could set it to just run seamonkey - as purely a form of contained browser.

Last edited by user1111 on Sun Jan 31, 2021 3:15 pm, edited 4 times in total.
user1111

Re: Fatdog unshare xephyr capsh container

Post by user1111 »

I've extended the code after the launching of the chroot, to include support for clipboard sharing, the relevant snippet now looking like ...

Code: Select all

.
.
DISPLAY=:2 empty -f unshare -m pflask ${PF} -- /init
PID=$!

# Clipboard sharing between main and container ... this requires xclip 
# to have been installed into fd64.sfs (or the main system) using gslapt
# package manager

watch_clip() {
	
		local curr="" prev="" from=$1 to=:0

		# On first run, we need to copy from :0 to :2 but not vice versa
		if [[ "$from" == ":0" ]]; then
			xclip -o -selection clipboard -d :0 2> /dev/null | xclip -
			selection clipboard -d :2
			to=:2
		fi
		while true; do
			# Get the current clipboard contents
			curr=`xclip -o -selection clipboard -d $from 2> /dev/null`
			# Compare to previous results and copy if it's changed
			if [[ "$curr" != "$prev" ]]; then
				echo "$curr" | xclip -selection clipboard -d $to
			fi
			prev="$curr"
			sleep 1
		done
}
watch_clip :0 &
P1=$!
watch_clip :2 &
P2=$!

wait $PID # earlier run container backgrounds, so we wait until that ends
.
.

So now when using a terminal in the main session to ssh into a server and where you might be running mutt/email, irc or whatever, you can select/copy text/links, switch over to the container that's running a browser and paste the link (or whatever text) there.

Requires xclip to have been installed from gslapt/package-manager.

user1111

Re: Fatdog unshare xephyr capsh container

Post by user1111 »

Swapping over to setting Xephyr to use -resizeable instead of -fullscreen and a issue is that as/when you resize the Xephyr window, windows within that such as a seamonkey browser window, both for jwm and openbox as the window manager, don't seem to accommodate that (the seamonkey window remains unchanged in size). Using cwm as the window manager within the Xephyr however and the ctrl-F key combination after resizing the Xephyr window does nicely realign the seamonkey window to the new Xephyr window size. cwm is also nice as it has no tray, window borders ...etc. so it blends in very well.

A bit of a inconvenience having to ctrl f each time after resizing the Xephyr window, but at the benefit of having the browser contained within a unshared, separate X session (Xephyr), chroot'd environment with capabilities dropped environment. And mostly browser windows tend to be left maximised anyway.

s243a
Posts: 501
Joined: Mon Dec 09, 2019 7:29 pm
Has thanked: 90 times
Been thanked: 37 times

Re: Fatdog unshare xephyr capsh container

Post by s243a »

rufwoof wrote: Sun Jan 17, 2021 12:16 am

Updated version of May 2019 code. Crude and hard coded, but works and could be used as a template. Similar to a EasyOS container.

Basically when run (after making the appropriate edits to point to wherever), it starts a full screen Xephyr (another X server), using fd64.sfs as the base, and chroots into that with various capabilities dropped. When in that environment, open a terminal and run seamonkey (as root) ... but where that root is a duff-root (more restricted than even spot in a conventional Puppy).

My fd64.sfs is in /mnt/sda1/FATDOG811-FINAL, I use /mnt/sda4/changes as the working folder (needs to be a ext2/3/4 filesystem outside of 'Puppy space' i.e. on HDD) and /mnt/sda4/shared as a shared folder. Edit the pointers to those to wherever you might use instead.

I have pflask and empty installed, can't remember if that is by default or whether I installed them using gslapt/package manager.

To exit its alt-F4, or if you have other windows already running in the main session you can alt-tab to them. Some/many menu options might not work, primarily I use it to run seamonkey is a contained manner by opening a terminal and typing 'seamonkey' (the seamonkey in the Menu wont work)

If you'd rather run jwm instead of lxqt panel/openbox, then remove the
echo "lxqt-panel &" >>top/init
echo "openbox" >>top/init
lines and replace them with
echo "jwm" >>top/init

You might also want to change the dpi value from 144 (the more usual choice is 96).

Code: Select all

#!/bin/sh

# Rufwoof Jan 2021 (updated May 2019 version). Comments at end

xterm & # added so have at least one window I can alt-tab to out of the container
[ ! -d /mnt/sda4/shared ] && mkdir /mnt/sda4/shared # as a shared folder

CHANGES_LOC=/mnt/sda4/changes 		  # Non pre-existing ext fs work folder
MAIN_SFS=/mnt/sda1/FATDOG811-FINAL/fd64.sfs # Where the main sfs is located

# Xephyr parameters
XP="-fullscreen -title container -name Xephyr2 -dpi 144 -nolisten tcp"
   
# pflask parameters
PF="--mount=bind:/mnt/sda4/shared:/home/shared"
PF="${PF} --keepenv --no-ipcns --no-netns"
PF="${PF} --mount=bind:/mnt/sda4/shared:/home/shared"
PF="${PF} --mount=bind:/etc/resolv.conf:/etc/resolv.conf"  # dns (internet)
PF="${PF} --mount=bind:/dev/snd:/dev/snd"
PF="${PF} --mount=bind:/dev/mixer:/dev/mixer"
PF="${PF} --caps=all,-sys_admin,-sys_boot,-sys_chroot,-sys_ptrace,"
PF="${PF}-sys_time,-sys_tty_config,-chown,-kill,-dac_override,"
PF="${PF}-dac_read_search,-fowner,-setfcap,-setpcap,-net_admin,"
PF="${PF}-mknod,-sys_module,-sys_nice,-sys_resource"
PF="${PF} --chroot=${CHANGES_LOC}/top"   

# Avoid double click 2 instances
N=`date +%s` # Seconds since January 1970
if [ -f /tmp/container.run ];then
		L=`cat /tmp/container.run`
		D=`expr $N - $L`
		if [ $D -lt 2 ];then
			exit # quick 2 launches (doubled clicked ignore second click)
		fi
fi
echo $N >/tmp/container.run

# Create a separate X instance so isolated from the main real root X
T=`ps -ef | grep Xephyr2 | wc -l`
if [ $T -ne 2 ];then
		Xephyr :2 ${XP} & 
else
		exit # Xephyr2 already running
fi

# Create a changes folder, sfs mount point for main.sfs and top layer
# folders and aufs mount to combine changes and sfs folders -> top
cd ${CHANGES_LOC}
# Check for possible hangover - such as if restarted X and clean out if so
if [ -d top ] || [ -d sfs ] || [ -d changes ]; then	
		umount top sfs
		rm -rf changes
		rmdir top sfs
fi
mkdir top sfs changes
mount -r -t squashfs ${MAIN_SFS} sfs
mount -t aufs -o br=changes:sfs none top

# create a script to run inside the chroot (i.e. must be a script, not a bin)
echo "#!/bin/sh" >top/init
echo "lxqt-panel &" >>top/init
echo "openbox" >>top/init
chmod +x top/init

# The big Xephyr capabilities dropped chroot switch
DISPLAY=:2 empty -f unshare -m pflask ${PF} -- /init

wait # above backgrounds, so we wait until that ends

# Clean up
killall Xephyr
umount top sfs
rm -rf changes
rmdir top sfs
rm /tmp/container.run

############################################################################
# FOR FATDOG 811 ...
#
# Aufs mounts changes (initial empty rw folder), main sfs, that combined
# is visible/accessed via folder 'top', that we chroot into
#
# chroot with chroot capability dropped (to prevent chroot out of the chroot)
# using another X session (Xephyr) to isolate it from the main X session.
# We chroot using pflask as that makes things easier into the top folder 
# applying further restrictions. We use the main sfs as our base for the
# chroot, so very low overheads.
#
# alt-F4 	closes the Xephyr container (if not then ctrl-shift to unfocus 
# 			mouse/keyboard.
# alt Tab 	to step to another window in main system, but if use 
# 			xdotool keydown alt key Tab;xdotool keyup alt .... it doesn't
# 			work (as intended i.e. it's locked into the "container").
# seamonkey from menu doesn't work, run seamonkey from within urxvt
# We use DISPLAY :2 for the Xephyr server
#
# Requires empty, pflask and a ext filesystem to create/work within
#
# I use fatdog multi-session save type frugal boot, and periodically I've
# re-merged the save files into fd64.sfs so my fd64.sfs isn't the standard
# version (merging changes and not copying fd64.sfs to ram helps keep ram
# usage low). 
############################################################################

When in a terminal, check things out ... you can't for instance see the HDD's, nor chroot and if you run htop you'll see very few things. Can't pipe things into the main session window, nor keylog (or stuff key sequences). Whilst operational speed is as fast as the main session (when for instance viewing youtubes).

Instead of launching openbox/lxqt panel (or jwm), you could set it to just run seamonkey - as purely a form of contained browser.

I don't see the capability dropping option (i.e. --caps) in the following pflask documentation:
https://ghedo.github.io/pflask/pflask.html

Are you using a modified version of pflask? Is this an undocumented feature? Or am I looking at old documentation?

user1111

Re: Fatdog unshare xephyr capsh container

Post by user1111 »

pflask from Fatdog's gslapt repo, indicates
# pflash -h

Code: Select all

pflask 0.2

Usage: pflask [OPTIONS]...

  -h, --help             Print help and exit
  -V, --version          Print version and exit
  -r, --chroot=STRING    Change the root directory inside the container
  -c, --chdir=STRING     Change the current directory inside the container
  -t, --hostname=STRING  Set the container hostname
  -m, --mount=STRING     Create a new mount point inside the container
  -n, --netif[=STRING]   Disconnect the container networking from the host
  -u, --user=STRING      Run the command under the specified user
                           (default=`root')
  -e, --user-map=STRING  Map container users to host users
  -w, --ephemeral        Discard changes to /  (default=off)
  -g, --cgroup=STRING    Create a new cgroup and move the container inside it
  -b, --caps=STRING      Change the effective capabilities inside the container
                           (default=`+all')
  -d, --detach           Detach from terminal  (default=off)
  -a, --attach=INT       Attach to the specified detached process
  -s, --setenv=STRING    Set additional environment variables
  -k, --keepenv          Do not clear environment  (default=off)
  -U, --no-userns        Disable user namespace support  (default=off)
  -M, --no-mountns       Disable mount namespace support  (default=off)
  -N, --no-netns         Disable net namespace support  (default=off)
  -I, --no-ipcns         Disable IPC namespace support  (default=off)
  -H, --no-utsns         Disable UTS namespace support  (default=off)
  -P, --no-pidns         Disable PID namespace support  (default=off)

which has a receipe http://distro.ibiblio.org/fatdog/source/800/recipes/ that uses the source from https://github.com/ghedo/pflask and within which the src/cmdline.c matches that as above ... so it doesn't look to me like any particular patching is being made by the Fatdog developers.

The bottom of the link you posted indicates a BSD licence, and capabilities are a Linux kernel thing, not applicable to BSD, so I guess that code is for the BSD's.

user1111

Re: Fatdog unshare xephyr capsh container

Post by user1111 »

For background info, OpenBSD uses kernel randomisation at each reboot i.e. re-links libs so they are moved around to different locations in memory rather than being at a constant fixed location. KASLR type kernel parameter type built.

Write xor Read (W^R) uses no execute mount settings for different slices (partitions/folders) and where the folder tree is structured for that, so hackers can't slip in and run some executable code in areas where non executables live.

Pledge and Unveil are similar to each other, but where pledge deals with processes, whilst unveil deals with files/folders. Each program in effect has a list of the libs/files/things it accesses/uses/runs, and anything outside of that set is blocked.

That's all far far simpler than Linus' choice and way less code to implement. OpenBSD consider more code to be a risk factor i.e. higher prospect of bugs - and security bugs are just normal bugs that permit potential security issues.

For X, OpenBSD uses Xenodm (its own version of startx type program), that basically is just invoked as root, but that then spawns the rest as different userid's such that nearly all of Linux X type risk factors are negated. By default OpenBSD uses just a single cpu, so pre-emptive factors/risks (Spectre/Meltdown) are eliminated. Most things are configured using rcctl (rcctl start sshd for example), that adjusts rc.conf. Setting it to use multiple cores doesn't seem to make things run any quicker that I've noticed. I think ??? that when multiple cores are available a lot of the pledge/unveil functions are thrown at that CPU so like having one core running usual things, another running security things, instead of the two both being used for both tasks.

Similarly the setup is dead easy, just a script where you download a <10MB bsd.rd file and boot that ... to mostly press Enter (10 minute job). Package manager is also cli based (pkg_add firefox-esr for instance). And where its a complete OS where the defaults are configured appropriately, and the man pages all correspond to what's installed and are extremely well written. Security auditing is a permanent ongoing thing.

In contrast Linux is a messy can of worms, that with the likes of systemD and pulseaudio ... is only getting worse, and where often finding the documentation that is respective to what you actually have installed is hit and miss.

OpenBSD is a bit like Puppy, minimalist/small, where the developers look at providing solutions that the easiest/smallest, and that shows in the total size of the source code. Hence of the order 3 million lines of code compared to Linux 15 million+ (and rising). The single central repo is another important factor IMO. Linux is increasing becoming more Windows like, where users install from here/there/anywhere. The licence is also much more accommodating, where you aren't forced to disclose all source code when redistributing systems (useful for those that want to charge for their products without having to fully disclosure intellectual property rights)

The downside is fewer developers (around 100 nowadays of a pretty close team) so fewer things supported, or rather more slowly being supported. However for much of later hardware OBSD does include support and apparently runs very quickly. My laptop wifi isn't supported for instance, so rather than tethering or using a external aerial that is supported I boot Fatdog - that wifi net connects etc. and then use kvm/qemu to boot OpenBSD - that picks up on the already established wifi net connection (Fatdog) as though it were a ethernet. I can then use that OpenBSD (with firefox esr installed) for browsing in a relatively 'contained' like manner, whilst Fatdog provides all of the Puppy like rest of functionality. A nice feature when doing it that way is that the OpenBSD disk can be booted as a 'snapshot' i.e. boot/use/shut-down without saving changes.

user1111

Re: Fatdog unshare xephyr capsh container

Post by user1111 »

Fatdog's multi-session save is great when used with 'containers'. Each save creates an additional save file (sfs) and when fatdog boots it loads the main sfs (fd64.sfs) which can be left on disk (direct) so little ram is used, and then all of the save sfs's are extracted on top of that. You can boot, delete all of the save sfs's and then run save to consolidate all of the save files into one (actually its two, base and save sfs's). Or you can unsquashfs the fd64.sfs, and then use -f -d switches to unsquashfs the save files on top of that, and then mksquashfs that combined set to create a new fd64.sfs with all of the changes incorporated into that (and delete all save files ... so again very little ram is used). When using direct (hdd based rather than fd64.sfs being copied into ram), lz4 -Xhc compression is a great choice as operationally that's very fast at reading/loading (mksquashfs squashfs-root fd64.sfs -comp lz4 -Xhc).

For a container that uses fd64.sfs as its base system, you can refine that appropriately relatively easily. For instance I don't want my ssh keys being stored within the fd64.sfs that is then visible to the container, so I ensure the ssh keys are just stored in save files (that isn't visible to the contained system). ssh from the main session, browse from within the contained session.

So even though multi-save was formerly for CD/DVD based boot, it works great when used in a HDD based frugal setup.

The 'container' script posted earlier has root inside that container as being like a very restricted userid, root for instance cannot even cd /home/spot as that folder is owned/grouped to 'spot' that 'root' cannot access. Being called root (even though a very restricted userid) means that the likes of sharing is simplified. If a shared folder is set up between the 'host' and 'guest' (container) then both sides read/write into that as userid 'root', so you don't have to mess around with changing permissions/ownership of files/folders as you would if using a restricted userid called by another name.

The contained session has its own separate X server (Xephyr) so its isolated and cannot access the main sessions X (no pirating windows/stuffing key combinations etc.), shares the network, but where firewall rules set in the main session cannot be changed in the contained session (block access to the router admin for instance). And where unsharing and capabilities dropping has that 'root' userid being comparable to a restricted userid - so there's no messing around with having to change userid (su/sudo) or file/folder permissions.

What I like about it over using something like kvm/qemu booted OpenBSD to browse with, is that its less contained than that, for instance I can view BBC videos whereas in the OpenBSD firefox-esr browser I can't (at least not without adding more things/configuring it to do so). It's also lighter/quicker to 'boot' (load) as its just using the same fd64.sfs that the main session was booted with.

Fatdog does have UML available, but I haven't managed to get that working, as such I'm unsure of the differences in security. I suspect UML would be slower operationally ???

s243a
Posts: 501
Joined: Mon Dec 09, 2019 7:29 pm
Has thanked: 90 times
Been thanked: 37 times

Re: Fatdog unshare xephyr capsh container

Post by s243a »

rufwoof wrote: Tue Jan 19, 2021 4:46 pm

Swapping over to setting Xephyr to use -resizeable instead of -fullscreen and a issue is that as/when you resize the Xephyr window, windows within that such as a seamonkey browser window, both for jwm and openbox as the window manager, don't seem to accommodate that (the seamonkey window remains unchanged in size). Using cwm as the window manager within the Xephyr however and the ctrl-F key combination after resizing the Xephyr window does nicely realign the seamonkey window to the new Xephyr window size. cwm is also nice as it has no tray, window borders ...etc. so it blends in very well.

A bit of a inconvenience having to ctrl f each time after resizing the Xephyr window, but at the benefit of having the browser contained within a unshared, separate X session (Xephyr), chroot'd environment with capabilities dropped environment. And mostly browser windows tend to be left maximised anyway.

Did you compile cwm? I don't see it via "which cwm" and I don't see it in gsplat.

user1111

Re: Fatdog unshare xephyr capsh container

Post by user1111 »

Yes I compiled cwm some time back. Can't recall where I sourced it from. Most like git, but not sure (I built is in a earlier Fatdog that is now archived and just copied across the cwm bin to my present 811).

[EDIT] was from ... https://github.com/leahneukirchen/cwm

I think running a full desktop is the nicer choice, so sticking with Openbox/lxqt panel. Under the Fatdog configuration for that alt-space presents the window menu, which in a full-screen Xephyr is the Xephyr's window menu from where you can close/iconify it. Unless you've locked the mouse/keyboard into the window, in which case alt-space shows the contained windows menu (and you can step between them using alt-tab). Pressing ctrl-shift ... toggles the mouse/keyboard focus.

Current issues are that rox desktop doesn't load/run (the way Fatdog has it configured), nor do some of the menu buttons/icons (you have to launch seamonkey from a root terminal window for instance, nor does file manager (again rox) run.

I presently have my main sessions /root/Startup having a item to launch the container ... so on bootup it drops straight into that desktop. Where other than the above issues it runs well (likely there are other issues that I haven't come across yet).

user1111

Re: Fatdog unshare xephyr capsh container

Post by user1111 »

... Actually ... on revisiting, using cwm can be very nice. I have tilda terminal installed and set to drop down - Quake style, when F1 is pressed (F1 is the show/hide toggle) and where its set to near full screen, just leaves the tray at the bottom of screen visible. That is ideal for toggling out of the 'container' also. So in the container, with cwm as the window manager, F1 will toggle the tilda terminal and also reveal the normal Fatdog tray at the bottom of the screen. ctrl-shift toggles locking the mouse/keyboard into the Xephyr window (or not), so when toggled to locked you can alt-tab between cwm windows, or if unlocked it will offer the usual available windows to switch to. I'm not one for many different key combinations being able to do many different things, instead I just know a small number of combinations that work for me. ctrl-shift to lock/unlock focus, alt-tab to flip between windows, F1 to toggle out of the container ... is near enough additional controls for me to add alongside the others such as for cwm ... ctrl-alt-enter to open a terminal. ctrl-alt-m to maximise a window, ctrl-alt-x to close a window, alt ? to launch the program launcher. Along with alt left-mouse drag to move a window, alt middle mouse to resize window. Quite a few, but not a over-whelming and relatively soon becomes second nature that you can come to love after a short while. Great for laptop usage.

So basically, tilda terminal, mc for file manager/text editor, cwm for the container window manager, openbox/lxqt/rox desktop for the main session.

I've rebuilt my fd64.sfs so that .ssh folder contents are sym-linked out to a HDD folder, which the container cannot access so they're locked away from that (ssh'ing from the main system is generally acceptable provided you don't download things or click url links that open the browser). Browser run in the container - that whilst running as root is very restricted. I also have the clipboard linked so I can copy URL's in ssh/irc/wherever within the main session into the browser running in the container. I also have /home/shared setup/linked so I can move files/folders between the two (main-systen/container) relatively easily. And no need to run the browser as spot.

I had to swap out urxvt as the 'xterm' for the real xterm as that works better within the container (with urxvt alt-tab'ing between windows didn't work correctly).

With lz4 -Xhc compression my fd64.sfs is around 850MB, that is directly accessed (not copied to ram), so initial boot sees around 250MB of ram being used. Non humongous style boot (initrd extracted out), so boots pretty quickly.

User avatar
wiak
Posts: 3623
Joined: Tue Dec 03, 2019 6:10 am
Location: Packing - big job
Has thanked: 56 times
Been thanked: 989 times
Contact:

Re: Fatdog unshare xephyr capsh container

Post by wiak »

rufwoof wrote: Wed Jan 20, 2021 12:44 pm

Fatdog does have UML available, but I haven't managed to get that working, as such I'm unsure of the differences in security. I suspect UML would be slower operationally ???

I used to love uml, and made small contributions, following emails with its author Jeff Dike, to the original project back in late 2001 (a C tweak and a system to auto-build a virtual network lab of interconnected computers for lab experiments re: routing and so on). I even published a few conference papers about the remote access network labs I was using with my students (via ssh plus browser-based java-script X server or vncclient connections remote access - though in practice (aside from demo that remote X or vnc was possible) simply via ssh since most everybody just had painfully slow 'dialup' internet at that time. I guess that's why I occasionally still dabble with the likes of vnc since times have changed and remote access solutions very relevant generally nowadays.

Even without the 'skas' patch variations that used to be around, it's not particularly slow and certainly much faster than qemu without kvm. Been so long since I used it though I'm not sure how it compares nowadays with the likes of qemu/kvm or virtualbox - probably slower but still pretty good depending on what it's used for.

I miss working with it actually, particularly since it was so easy to script complex network lab experiments with it (still remember the ethertap module TUN/TAP stuff and COW filesystem non-aufs layering uml very-efficiently involved), but since I don't teach Linux/datacomms anymore I have no personal needs for it nowadays per se (other than hobby interest, but sooooooo.... busy these days with even the small amount of Linux-related work I still do).

Which reminds me, it IS summer here, and I've been breaking my normal self-restricting-rules that I only do development work in the late autumn/winter season so planning to pull the plug for a few months (aside from reading/commenting) shortly. Time for a summer holiday whilst the sun still shines (and very fortunate for me, and others down here, there is no Covid in the community here at the moment - and no likely vaccines for a long time here either...).

wiak

https://www.tinylinux.info/
DOWNLOAD wd_multi for hundreds of 'distros' at your fingertips: viewtopic.php?p=99154#p99154
Αξίζει να μεταφραστεί;

s243a
Posts: 501
Joined: Mon Dec 09, 2019 7:29 pm
Has thanked: 90 times
Been thanked: 37 times

Re: Fatdog unshare xephyr capsh container

Post by s243a »

I was able to modify the script to get this working with the chrooted iron. Here are the most important parts of my init script:

Code: Select all

gdk-pixbuf-query-loaders --update-cache
DISPLAY=:2 jwm &
DISPLAY=:2 roxfiler &
DISPLAY=:2 xterm -e iron

Some differences are:
1. the script looks in the parent directory for the iron sfs file.
2. the script uses an existing mount point if the sfs file is already mounted.

Some issues:
1. fix menus doesn't seem to properly create the jwm menus
2. I can't seem to use the "&" operator for starting iron in the init script.
3. Exporting DISPLAY=:2 doesn't seem to always work as expected.
4. Binding the shared folder caused issues for me so I commented it out for now. For some reason it complained about relative paths.

Here is the complete code:

I called it ruf-iron-flask.sh as a way of recognizing rufwoofs contribution. I'm open to better name suggestions though.

s243a
Posts: 501
Joined: Mon Dec 09, 2019 7:29 pm
Has thanked: 90 times
Been thanked: 37 times

Re: Fatdog unshare xephyr capsh container

Post by s243a »

I see that we bind rather than copy resolv.conf. I haven't tested whether or not this allows the person in the container to modify this file in the host but if they could then I think there would be potential to redirect the user to some clone of a website made with something like ngrok. Of course this attack would only work if it was a non-encrypted site (i.e. http rather than https) since a user in the container shouldn't be able to modify the root certificates authorities of the host.

However, the attacker could could try to spoof an https site with an http site. Most users would like notice something is odd though. Or better yet, the name server could direct someone to the proper site but simply act as a way to track which sites a user is viewing.

user1111

Re: Fatdog unshare xephyr capsh container

Post by user1111 »

s243a wrote: Thu Jan 21, 2021 6:37 am

I see that we bind rather than copy resolv.conf.

Thanks s243a. I've changed that to do a copy over of /etc/resolv.conf after the aufs mount of 'top' (cp /etc/resolv.conf top/etc/resolv.conf) and removed the mount-bind of /etc/resolv.conf from the empty ... Xephyr line (i.e, removed it from the $PF string).

Perhaps interestingly within the contained session root cannot su or access spot owned files/folders, so conceptually you could set spot with a random and very long password - or rather some other userid created just for the purpose, and set any file/folder to that owner/group within the contained session, along with no permissions to 'others' ... and subject to the permissions granted the file/folders might be inaccessible (or read only perhaps - or whatever) to root within the contained session. That could however conflict with some programs that may require the permissions to be specifically owned by root (or whatever).

root within the contained session is just a very restricted userid, root in name only - but that in being so named helps with the interworkings and simplification of operation/running.

user1111

Re: Fatdog unshare xephyr capsh container

Post by user1111 »

I've added dissenter web browser to my fd64.sfs so that is now available within the container session. In turn that has both incognito and incognito with tor options available within its menu. Works really quickly for me, and even in normal mode it blocks the likes of youtube ads ...etc. It's based on Brave, and a older version of Chrome, so some vulnerabilities will be present however being run in a contained session that largely negates those weaknesses.

A bit of a personal choice however whether you opt for it over others as it has a political affiliation of sorts, Gab right wingers. However as it blocks ads then obviously it can't provide revenues that way, and relies upon bit coin or cheque/check donations, so if you don't donate then you're not contributing towards those political beliefs (even Firefox recently has become somewhat politicised). I guess that in being used for political discussion/privacy that the code/design is perhaps made the better for that i.e. many/more people actually using it and as such 'testing' its security.

user1111

Re: Fatdog unshare xephyr capsh container

Post by user1111 »

s243a wrote: Thu Jan 21, 2021 2:03 am

I was able to modify the script to get this working with the chrooted iron.
.
.
Some issues:
.
.

Given that there is no real root inside the contained session that will be problematic. Fundamentally securing 'spot' in a main session in a regular Puppy/system is at best difficult (unlikely), So rather than striving to fix all of the weaknesses in the main session the contained approach is the better path. Has its own/separate X, root is in name only (a highly restricted userid) ..etc.

I'm finding cwm as the window manager to be good for that purpose, as it doesn't have any decorations nor does it use a tray ...etc. But does require learning its control key sequences.

Presently the code starts clean each time, but there's no reason why the 'changes' folder content couldn't be left as-is so that you pick up on how the container was left last time it was used (with the option to delete that content prior to launch so you started with a 'clean' session again. Or equally that content could be saved, such as tar'd or mksquashfs of its content and 'restored' prior to launch. Which is basically what EasyOS is doing (snapshots/rollbacks)).

I wouldn't attribute the naming to me, rather I'm just standing on the shoulders of giants - in particular Barry, who sourced the fundamental concept/design/code. Basically not many picked up on learning/understanding/using his containers, I've just striven to help educate in that area where possible.

user1111

Re: Fatdog unshare xephyr capsh container

Post by user1111 »

I'm now running cwm (which you have to compile viewtopic.php?p=15583#p15583 as its not in the Fatdog repo) in the Xephyr, and have the clipboard set to be shared so I can select/copy/paste in both directions (main to Xephyr and Xephyr to main). I'm also using wmctrl (that I installed from gslapt) in order to monitor the current ctrl-shift (mouse/keyboard locked/unlocked to the Xephyr window) to change the cwm desktop background colour (blue = mouse/keyboard locked into the Xephyr window, so alt-tab for instance will step between windows within the Xephyr session; red = unlocked, so alt-tab will step between the Xephyr window, and any other main session windows).

Running Xephyr full screen means you don't see the usual Window title bar in which Xephyr indicates whether the mouse/keyboard are locked (host grabbed) or not. You also don't see the 'barrier' of trying to move the mouse outside of the window region being prevented. In the full screen mode absence of those visual indicators changing the desktop colour seemed like a reasonable alternative visual indicator of whether host-grab is active or not.

When no windows are running in the main session, even in the unlocked state you wont be able to 'step out' of the Xephyr window. I have tilda terminal installed with F1 set to show/hide that, so I'm using that as my 'step out of Xephyr' choice (i.e. when the Xephyr desktop colour has been toggle to being red, pressing F1 reveals tilda terminal along with the usual Fatdog tray appearing at the bottom of the screen).

The code also sets a iptables rule to block the router admin IP (which you have to specify/set using the ROUTER_IP variable in the code).

Code: Select all

#!/bin/bash

# Notes : 
# ssh sym linked to HDD in main fd64.sfs, so unavailable inside container
# tilda with F1 drop down ... useful as a means to 'switch' desktops
# removed -title container  from Xephyr ... so that we can use the standard
# title as a means to flag whether host-grab is on or off i.e. Xephyr
# changes the window title to show the host-grab status.

ROUTER_IP=192.168.100.1
SHARED=/mnt/sda4/shared 					
CHANGES_LOC=/mnt/sda4/changes 				
MAIN_SFS=/mnt/sda1/FATDOG811-FINAL/fd64.sfs 
XEPHYR="-fullscreen -name Xephyr2 -dpi 144 -nolisten tcp"
MOUNTS="--mount=bind:${SHARED}:/home/shared --mount=bind:/dev/snd:/dev/snd --mount=bind:/dev/mixer:/dev/mixer"
CAPS="--caps=all,-sys_admin,-sys_boot,-sys_chroot,-sys_ptrace,-sys_time,-sys_tty_config,-chown,-kill,-dac_override,-dac_read_search,-fowner,-setfcap,-setpcap,-net_admin,-mknod,-sys_module,-sys_nice,-sys_resource"
PFLASK="--keepenv --no-ipcns --no-netns ${MOUNTS} ${CAPS} --chroot=${CHANGES_LOC}/top"

# Function to share main system and container clipboards
share_clipboard() {
	
		local curr="" prev="" from=$1 to=:0

		if [[ "$from" == ":0" ]]; then
			xclip -o -selection clipboard -d :0 2> /dev/null | xclip -
			selection clipboard -d :2
			to=:2
		fi
		
		while true; do
			curr=`xclip -o -selection clipboard -d $from 2> /dev/null`
			if [[ "$curr" != "$prev" ]]; then
				echo "$curr" | xclip -selection clipboard -d $to
			fi
			prev="$curr"
			sleep 1
		done
}

# Function to monitor host-grab state of Xephyr window
# In Fatdog requires wmctrl to have been installed
hostgrabstate() {
	
		local cur=""
	
		while :; do
			C=`wmctrl -l | grep Xephyr | grep releases | wc -l` 
			if [ $C -ne 0 ]; then # locked=blue desktop else red desktop
				if [[ "$cur" != "locked" ]]; then # darkblue rgb #000066
					echo "xsetroot -solid '#000066'" >$SHARED/host-grab-state
					cur="locked"
				fi
			else
				if [[ "$cur" != "unlocked" ]]; then # red rgb #770000
					echo "xsetroot -solid '#770000'" >$SHARED/host-grab-state
					cur="unlocked"
				fi
			fi
			sleep 1
		done
		# Note that another script to update the desktop is also set
		# running in the Xephyr session/container (/tmp/hoststate that
		# just runs the above file (that sets the root window background))
}

# Block access to our main router admin
iptables -A INPUT -s ${ROUTER_IP} -j DROP

# Check not already running
if [ `ps -ef | grep Xephyr2 | wc -l` -ne 2 ];then 
		Xephyr :2 ${XEPHYR} &
else 
		exit
fi

# Check/prepare folders/environment and setup aufs mount
[ ! -d $SHARED ] && mkdir $SHARED
cd ${CHANGES_LOC}
if [ -d top ] || [ -d sfs ] || [ -d changes ]; then 
		umount -f top sfs;rm -rf changes;rmdir top sfs
fi
mkdir top sfs changes
mount -r -t squashfs ${MAIN_SFS} sfs
mount -t aufs -o br=changes:sfs none top
cp /var/lib/dbus/machine-id top/var/lib/dbus/machine-id
cp /etc/resolv.conf top/etc/resolv.conf
ln -s top/var/lib/dbus/machine-id top/etc/machine-id  

# Prepare /tmp/hostgrab (root window colour) script inside Xephyr 
printf "#!/bin/sh\n\nwhile :; do\n\tif [ -f /home/shared/host-grab-state ];then\n\t    sh /home/shared/host-grab-state\n\t    rm /home/shared/host-grab-state\n\tfi\n\tsleep 1\ndone\n" >top/tmp/hostgrab; chmod +x top/tmp/hostgrab
chmod +x top/tmp/hostgrab

# Prepare Xephyr's .cwmrc (which also launches /tmp/hostgrab)  
printf "#!/bin/sh\n/tmp/hostgrab &\ncwm -c /root/.cwmrc\n" >top/init; chmod +x top/init

# Start the Xephyr 'container'
DISPLAY=:2 empty -f unshare -m pflask ${PFLASK} -- /init
PID=$!

# Start host-grab monitor (in main session, that monitors the Xephyr window title)
hostgrabstate &
HOSTGRAB=$!

# Start sharing main and Xephyr clipboards
share_clipboard :0 &
CLIP0=$!
share_clipboard :2 &
CLIP2=$!

# Wait until container ends and tidy up
wait $PID;killall Xephyr;umount top sfs;rm -rf changes;rmdir top sfs
kill $CLIP0 $CLIP2;killall xclip
kill $HOSTGRAB; rm $SHARED/host-grab-state

For the host-grab code, it monitors the Xephyr Widows title (as returned by wmctrl) in the main session (while ... sleep loop) and creates a file in the shared folder when that changes. Within the Xephyr there's another while ... sleep loop script that runs looking for that file and when present it runs and then deletes it, and where the content of the file uses xsetroot to set the Xephyr's desktop background colour.

I've been using dissenter browser for a day now viewtopic.php?p=15626#p15626 running it as root within the Xephyr, and I like it. It starts similar to chrome, near full-screen but leaving a small border around the edges, which is nice for being able to see the current desktop colour (blue (host-grabbed or red (not host-grabbed)). That desktop border is also nice for cwm a you can left, middle or right mouse press to reveal the different cwm menus. In order to run dissenter as root you have to add the --no-sandbox --test-type parameters. Running as the browser as root within the Xephyr/unshared/capabilities-dropped/chroot is as good as running it as a highly restricted/contained userid that is isolated from the main session - where your data/ssh-keys ...etc. are stored.

user1111

Re: Fatdog unshare xephyr capsh container

Post by user1111 »

In my cwmrc I've added a gap 6 6 6 6 ... to leave a screen edge gap of 6 pixels all around the screen edge. Nice for being able to see the desktop colour (whether ctrl-shift host-grab is toggled on or off), and also for launching cwm menus (left, middle or right mouse press on the 'desktop')

cwmrc.png
cwmrc.png (274.21 KiB) Viewed 1317 times

When ctrl-shift toggled to blue, the likes of alt-tab steps between windows within the Xephyr. When toggled red, alt-tab will step between the Xephyr (full screened window) and other main system windows. Where that gap and desktop colour flipping provides a nice visual indicator of which mode its set to at any one time.

user1111

Re: Fatdog unshare xephyr capsh container

Post by user1111 »

MochiMoppel provided a better solution (xprop -spy) to the host-grab key monitoring viewtopic.php?p=15868#p15868 So now that monitoring runs much more lightly/colder than the sleep loops I was using before (within the Xephyr I'm now also using inotifywait instead of a second sleep loop).

So now the code that uses cwm as the Xephyr's (container) window manager ...

Code: Select all

#!/bin/bash

ROUTER_IP=192.168.100.1
SHARED=/mnt/sda4/shared
CHANGES_LOC=/mnt/sda4/changes # Must be HDD ext fs (not 'inside Puppyspace')
MAIN_SFS=/mnt/sda1/FATDOG811-FINAL/fd64.sfs
XEPHYR="-fullscreen -name Xephyr2 -dpi 144 -nolisten tcp"
MOUNTS="--mount=bind:${SHARED}:/home/shared --mount=bind:/dev/snd:/dev/snd \
        --mount=bind:/dev/mixer:/dev/mixer"
CAPS="--caps=all,-sys_admin,-sys_boot,-sys_chroot,-sys_ptrace,-sys_time,\
-sys_tty_config,-chown,-kill,-dac_override,-dac_read_search,\
-fowner,-setfcap,-setpcap,-net_admin,-mknod,-sys_module,\
-sys_nice,-sys_resource"
PFLASK="--keepenv --no-ipcns --no-netns ${MOUNTS} ${CAPS} \
        --chroot=${CHANGES_LOC}/top"

if [ `ps -ef | grep Xephyr2 | wc -l` -ne 2 ];then # Start Xephyr X server
	Xephyr :2 ${XEPHYR} &
else
	exit
fi

iptables -A INPUT -s ${ROUTER_IP} -j DROP 	# Drop access to router admin

# Prepare and launch 'container' and shared folder
[ ! -d $SHARED ] && mkdir $SHARED
[ ! -d ${SHARED}/flags ] && mkdir ${SHARED}/flags
cd ${CHANGES_LOC}
if [ -d top ] || [ -d sfs ] || [ -d changes ]; then
	umount -f top sfs;rm -rf changes;rmdir top sfs
fi
mkdir top sfs changes
mount -r -t squashfs ${MAIN_SFS} sfs
mount -t aufs -o br=changes:sfs none top
cp /var/lib/dbus/machine-id top/var/lib/dbus/machine-id
cp /etc/resolv.conf top/etc/resolv.conf
ln -s top/var/lib/dbus/machine-id top/etc/machine-id
echo >$SHARED/flags/host-grab
cat <<EOF >top/tmp/hostgrab
#!/bin/bash
xsetroot -bg \#ff0000 -mod 5 5
while inotifywait -e modify /home/shared/flags; do
	C=\$(tail -1 /home/shared/flags/host-grab | grep release)
	if [ ! -z "\${C}" ]; then
		xsetroot -bg \#0000ff -mod 5 5
	else
		xsetroot -bg \#ff0000 -mod 5 5
	fi
done
EOF
chmod +x top/tmp/hostgrab
cat <<EOF >top/init
#!/bin/sh
/tmp/hostgrab &
/usr/bin/help &
cwm -c /root/.cwmrc
EOF
chmod +x top/init
cat <<EOF >top/usr/bin/help
#!/bin/sh
message() {
	Xdialog --title Information --msgbox "\$1" 0 0
}
M="This is a Xephyr X session window where cwm is the window manager.\n"
M="\${M}cwm is great for laptops (nearly all OpenBSD developer use cwm) and is relatively easy to learn.\n"
M="\${M}Whilst you run as 'root' within Xephyr, root is actually a highly restricted userid that is running\n"
M="\${M}in a contained environment, as such some programs may not run as expected.\n"
M="\${M}\nLeft mouse press on desktop shows windows menu, right mouse press for applications menu\n"
M="\${M}(a gap is left around the screen edges so the desktop is still accessible even if a window is maximised)\n\n"
M="\${M}Ctrl Alt Enter : terminal. Alt m : toggles maximise. Ctrl Alt x : close window. Alt ? : Open exec launcher\n"
M="\${M}\nCtrl Shift : toggles mouse/keyboard focus (desktop changes between red and blue)\n"
M="\${M}Alt Tab : if desktop is red - steps between main session windows\n"
M="\${M}OR if desktop is blue - steps between windows within the Xephyr container\n"
M="\${M}\nWHEN THE DESKTOP IS BLUE (mouse/keyboard locked into Xephyr) ...\n"
M="\${M}Alt middle mouse drag: resizes window. Alt left mouse drag : moves window\n"
M="\${M}\nWHEN THE DESKTOP IS RED (mouse/keyboard unlocked from Xephyr) ...\n"
M="\${M}you can use usual main system controls such as Alt-F1 for menu, Alt-F4 to close the Xephyr ...etc.\n"
M="\${M}\nRevisit this list again at any time by running 'help', or search online for the cwm manual"
message "\${M}"
EOF
chmod +x top/usr/bin/help
DISPLAY=:2 empty -f unshare -m pflask ${PFLASK} -- /init
PID=$!

_hostgrabstate() {

	local WID=""

	while [ -z "${WID}" ]; do
		WID=$(wmctrl -lp | grep Xephyr | cut -d ' ' -f 1)
		sleep 1
	done
	sleep 2
	xprop -id ${WID} -spy WM_NAME >>$SHARED/flags/host-grab	
}
_hostgrabstate &
HOSTGRAB=$!

# Housekeeping
wait $PID;killall Xephyr;umount top sfs;rm -rf changes;rmdir top sfs;kill $HOSTGRAB

The ~/.cwmrc (cwm configuration) file content I'm using ...

Code: Select all

gap 8 8 8 8
borderwidth 2
color inactiveborder "#726B57"
color activeborder "#ffc100" 
color groupborder "#01a252"
color urgencyborder "#3d9751"
color selfont "#0034A9"
color font "#FFFFFF"
color menufg "#49F6F6"
color menubg "#333333"
fontname  "News10:size=12:antialias=true"
command "Dissenter" "dissenter-browser-stable --no-sandbox --test-type"

Works well for me. ctrl-shift to toggle the desktop to blue (which as cwm is set to leave a 8 pixel gap all around the screen edge is also visible if windows are full-screened) and alt-tab steps between windows within the Xephyr. If toggled to red then alt-tab steps between the main session winows. Whilst the monitoring for that ctrl-shift toggling is now running much more lightly :)

s1.png
s1.png (372.25 KiB) Viewed 1286 times
s.png
s.png (283.39 KiB) Viewed 1286 times

BTW the xclip clipboard sharing has been removed as that messed up when using LibreOffice calc (spreadsheet cells copying/pasting). For the time being I'm using the shared folder to have both the main and Xephyr sessions having geany opened the same file as a means to copy/paste between the sessions.

s243a
Posts: 501
Joined: Mon Dec 09, 2019 7:29 pm
Has thanked: 90 times
Been thanked: 37 times

Re: Fatdog unshare xephyr capsh container

Post by s243a »

After good luck building a container for iron in slack 571/5.7.2 (see post). I thought it might be fun to combine Puli with the Ungoogled Chromium.

I was not able to succeed with or without ungoogled chromium. For starters puli doesn't have a new enough version of glibc (need glibc 2.27 or 2.28 have glibc 2.23) for ungoogled chromium. The puli version I tried is based on Xenial64 Pup.

If the init fails then everything started within the init seems to crash. Removing ungoogled chromium wasn't sufficient. I tried chrooting into the layered file system (i.e. top) with the following chroot script:

Code: Select all

#!/bin/bash
mount --bind /dev container/top/dev
mount --bind /proc container/top/proc
mount --bind /sys container/top/sys
mount -t devpts devpts container/top/dev/pts
DISPLAY=:2 chroot container/top /bin/bash
umount -l container/top/dev
umount -l container/top/proc
umount -l container/top/sys

and when I do this I can run my init script without errors.

Code: Select all

#!/bin/sh
export DISPLAY=:2
. /etc/DISTRO_SPECS
if [ "$DISTRO_ARCHDIR" ] ; then
	ARCHDIR="/$DISTRO_ARCHDIR"
fi
ldconfig
iconvconfig
#update-pango-querymodules
#Failed to create file /usr/lib/i86/-linux-gnu/pango/1.8.0/modules.cache.8P0KX0 No such file or directory
gdk-pixbuf-query-loaders --update-cache
update-mime-database -V /usr/share/mime/
status_func $?
UPDATE_MIME_DATABASE_DONE=1

source /etc/profile
fixmenus #probably not necessary
keymap-set --update
userresources=$HOME/.Xresources
usermodmap=$HOME/.Xmodmap
sysresources=/usr/lib/X11/xinit/Xresources
sysmodmap=/usr/lib/X11/xinit/.Xmodmap

# merge in defaults and keymaps

if [ -f $sysresources ]; then
    xrdb -merge -nocpp $sysresources
fi

if [ -f $sysmodmap ]; then
    xmodmap $sysmodmap
fi

if [ -f $userresources ]; then
    xrdb -merge -nocpp $userresources
fi

if [ -f $usermodmap ]; then
    xmodmap $usermodmap
fi
setxkbmap -option keypad:pointerkeys
DISPLAY=:2 jwm &
DISPLAY=:2 roxfiler &

I need to test if this will succeed without the autostart items disabled. I disabled them due to an error related to iptables (see post) but this error might be related to not first binding /sys and /dev prior to doing the chroot. I notice that the container doesn't create these binds in the top folder and said binds only exist within the container. Anyway, here was my attempted script.

I don't think this cript is significantly different than the one I mentioned above (which works) so I'm not sure why it isn't working:

P.S. This is how I disabled the autostart items:

Code: Select all

for a_autostart in dunst.desktop firewallstatus.desktop flsynclient.desktop freememapplet.desktop netmon_wce.desktop powerapplet.desktop retrovol.desktop; do
  mv top/root/.config/autostart/"$a_autostart" top/root/.config/autostart/"$a_autostart"-disable
done

As another side note, I notice that there are very few items we are binding in dev. For instance the container doesn't bind /dev/pts and this seemed to work when I tried it for iron. However, if one loses a terminal (e.g. init crashes), then there is no way to get a new terminal. I noticed this when I tried to chroot into "top". I can't start urxvt without a pseudo-termianl. In the container this seems to be provided by this init script rather then via /dev/pts.

Edit: Perhaps I need to add the kernal Modlues as one of the layers for this container to work.

P.S. I may try upgrading glibc for puli / Xenial.

Edit #2. I tried appending the zdrv as a layer but it didn't solve my problems.

user1111

Re: Fatdog unshare xephyr capsh container

Post by user1111 »

I notice that there are very few items we are binding in dev
.
.
but this error might be related to not first binding /sys and /dev prior to doing the chroot. I notice that the container doesn't create these binds in the top folder and said binds only exist within the container.
.
.
the container doesn't bind /dev/pts

I have experienced some oddities when using Libre Office calc with using cwm within the Xephyr/container session, such as when locking focus onto a chart with the intent to move that chart (drag/drop) losing focus. When using jwm that issues isn't evident, so swapping over to jwm I reworked the code to be specific to that. Note that I've tried different choices for a visual indicator or whether the mouse/keyboard were locked into the Xephyr (full screened) window or released (whole normal system). Background wallpaper colour changing, tray colour changing ... etc. None of those were nice however, and the best so far I've come up with is to have a sys-tray icon (different coloured ball)

Code: Select all

#!/bin/bash

# Rufwoof January 2021                               (re-worked May 2019 version)
#
# For Fatdog 811.                     jwm based 'container' (Xephyr with unshare,
#                                   capabilities dropped, chroot), such that root
#                                       within that jwm session is like a heavily
#                                       restricted userid within its own separate
#                                   (isolated from main session) X server session

                                               # CHANGE THESE FOUR AS APPROPRIATE
ROUTER_IP=192.168.100.1                        #               IP of router admin
SHARED=/mnt/sda4/shared                        #               Folder for sharing
CHANGES_LOC=/mnt/sda4/changes                  #                 EMPTY ext folder
MAIN_SFS=/mnt/sda1/FATDOG811-FINAL/fd64.sfs    #                fd64.sfs location

XEPHYR="-fullscreen -name Xephyr2 -dpi 144 -nolisten tcp"
MOUNTS="--mount=bind:${SHARED}:/home/shared \
        --mount=bind:/dev/snd:/dev/snd \
        --mount=bind:/dev/mixer:/dev/mixer"
CAPS="--caps=all,-sys_admin,-sys_boot,-sys_chroot,-sys_ptrace,-sys_time,\
-sys_tty_config,-chown,-kill,-dac_override,-dac_read_search,-fowner,-setfcap,\
-setpcap,-net_admin,-mknod,-sys_module,-sys_nice,-sys_resource"
PFLASK="--keepenv --no-ipcns --no-netns ${MOUNTS} ${CAPS} \
        --chroot=${CHANGES_LOC}/top"

SVG_PREFIX="<svg height=\"100\" width=\"100\"><circle cx=\"50\" cy=\"50\" \
r=\"40\" stroke=\"black\" stroke-width=\"3\""
SVG_SUFFIX="/></svg>"
BLUE_SVG="${SVG_PREFIX} fill=\"#54F3FF\" ${SVG_SUFFIX}"
GREEN_SVG="${SVG_PREFIX} fill=\"#4FF40A\" ${SVG_SUFFIX}"
HOST_GRAB_TIP="Xephyr Ctrl Shift mouse/keyboard \
focus toggle. Green=unlocked, Blue=locked"
HOST_GRAB_IMG="/tmp/.container-img.svg"
HG="top/tmp/.hostgrab"

_create_hostgrab() {  # container script - waits for /home/shared/flags/host-grab
                      # file changes (as driven by _hostgrabstate function below)
                      #   and changes tray icon colour to reflect locked/unlocked
                      #       mouse focus for the Xephyr (full screened) 'window'

        printf "#!/bin/bash\n\nHGF=/home/shared/.hostgrab-flag\n"           > $HG
        printf "BSVG='$BLUE_SVG'\nGSVG='$GREEN_SVG'\n"                     >> $HG
        printf "HGT='$HOST_GRAB_TIP'\nHGI=$HOST_GRAB_IMG\n\n"              >> $HG
        printf "while inotifywait -e modify \$HGF; do\n"                   >> $HG
        printf "\tC=\$(tail -1 \${HGF}/host-grab | grep release)\n"        >> $HG
        printf "\tif [ ! -z \"\${C}\" ]; then\n"                           >> $HG
        printf "\t\techo \${BSVG}>\${HGI}\n"                               >> $HG
        printf "\telse\n\t\techo \${GSVG}>\${HGI}\n\tfi\n\tkill \$PID\n"   >> $HG
        printf "\tsit \${HGI} \"\${HGT}\" &\n\tPID=\$!\ndone\n"            >> $HG
        chmod +x $HG
}

_hostgrabstate() { # Main systems Xephyr window title monitor. Xephyr changes the
                   #    window title when ctrl-shift toggle of the mouse/keyboard
                   # focus occurs and we capture those changes and flag them into
                   #      the container. We delay the start so _create_hostgrab()
                   #   listening within the container should have already started

        while [ -z "${WID}" ]; do
            sleep 3
            WID=$(wmctrl -lp | grep Xephyr | cut -d ' ' -f 1)
        done
        xprop -id ${WID} -spy WM_NAME >$SHARED/.hostgrab-flag/host-grab
}

_prepfolders() {                             # Prepare main systems files/folders

        [ ! -d ${SHARED} ] && mkdir ${SHARED}
        [ ! -d ${SHARED}/flags ] && mkdir ${SHARED}/.hostgrab-flag
        cd ${CHANGES_LOC}
        if [ -d top ] || [ -d sfs ] || [ -d changes ]; then
            umount -f top sfs;rm -rf changes;rmdir top sfs
        fi
        mkdir top sfs changes
}

_fix_environment() {   # Need to tweak things inside the container to work better

        echo "exec /usr/local/apps/ROX-Filer-jun7/AppRun" >top/usr/bin/rox
        rm top/usr/local/bin/defaultbrowser
        echo "seamonkey \"$\@\"" > top/usr/local/bin/defaultbrowser
        chmod +x top/usr/local/bin/defaultbrowser
}

_prepcontainer() {                             # Prepare containers files/folders

        cp /var/lib/dbus/machine-id top/var/lib/dbus/machine-id
        cp /etc/resolv.conf top/etc/resolv.conf
        ln -s top/var/lib/dbus/machine-id top/etc/machine-id
        echo >$SHARED/.hostgrab-flag/host-grab # inotifywait requires pre-created
        _create_hostgrab
        printf "#!/bin/sh\n\npmcputemp &\nvattery &\n"                  >top/init
        printf "lockstate &\n/tmp/.hostgrab &\n"                       >>top/init
        printf "export PATH=$PATH:/usr/local/bin\njwm\n"               >>top/init
        chmod +x top/init
        _fix_environment
}

### MAIN ###

if [ ! -f ${MAIN_SFS} ];then                       # Ensure main sfs is available
        Xdialog --title "Error" \
                --infobox "Main sfs\n${MAIN_SFS}\nnot found" 0 0 4000
        exit 1
fi

if [ $(ps -ef | grep Xephyr2 | wc -l) -ne 2 ];then  # Start Xephyr X server on :2
        Xephyr :2 ${XEPHYR} &
        XEPHYR_PID=$!
else
        exit 2
fi

iptables -A INPUT -s ${ROUTER_IP} -j DROP           # Drop access to router admin

_prepfolders
mount -r -t squashfs ${MAIN_SFS} sfs                                  # Mount sfs
mount -t aufs -o br=changes:sfs none top                      # aufs layers mount
_prepcontainer
DISPLAY=:2 empty -f unshare -m pflask ${PFLASK} -- /init       # Launch container
CONTAINER_PID=$!

_hostgrabstate &                               #    Start main systems monitor of
HOSTGRAB=$!                                    # Xephyr sessions host-grab status

wait $CONTAINER_PID                                   # Wait until container done

                                                                   # Housekeeping
kill $XEPHYR_PID;umount top sfs;rm -rf changes;rmdir top sfs;kill $HOSTGRAB

That aside, the code is specific to Fatdog 811. Fundamentally "empty" is being used as the pseudo terminal, and where mount points are unshared to isolate disks. For 'containment' (security) we don't really want pseudo terminals being shared across the main and contained systems such that they might be a attack vector. Similarly we want to 'distance' as much of proc, sys and other dev as possible, but where sharing the likes of sound devices is considered acceptable for the functionality that provides whilst being relatively low risk. Using pflask helps with simplification of setting up much of the chroot containment - such as dropping namespaces. Using Xephyr is a means to 'use a different X server' - as otherwise access to the same X server even as different userid's is a (very) weak point. Capabilities are also selectively dropped to provide further containment.

The difficulty is figuring out what can be dropped/restricted whilst still having a usable system/function within that contained environment. As defined in the above code containment is pretty good, whilst operation as a 'desktop' is still reasonable. At least for Fatdog 811. When ported however, and more so if you start re-introducing the likes of sharing devices (/dev) ... etc. then the peaking of striving towards the maximum functionality within the maximised security/containment - tails off.

I'm running with the above code as my everyday desktop, and functionality wise its good-enough. Just some quirks in a otherwise usable desktop for general purposes (browsing, office, vlc/media ...etc.).

s.png
s.png (294.32 KiB) Viewed 1448 times

The ideal would be fixed hardware and fixed software. OpenBSD for instance approach it from a different angle and for each program that is sought to be contained they define all of the devs, memory, libs, progams, files, folders ...etc. that are permissible to be accessed/used and by default block everything else. But they have the benefit of a fixed OS setup for that as OpenBSD is a complete OS, not for example separate providers of kernel and things such as busybox for commands. Apple have it even easier, fixed hardware and OS. At the other extreme, looking to provide a portable type version its more awkward. Qubes uses the approach of a separate container (VM) for separation. That's pretty heavyweight however (install size), and for most desktop users perhaps just a single VM might suffice that keeps data and sensitive files content (keys, passwords ...etc.) isolated from the (virtual) machine that is used to browse with. Again the above code is more along those lines but whilst doing so in a very 'light' manner.

Last edited by user1111 on Thu Jan 28, 2021 1:27 pm, edited 2 times in total.
s243a
Posts: 501
Joined: Mon Dec 09, 2019 7:29 pm
Has thanked: 90 times
Been thanked: 37 times

Re: Fatdog unshare xephyr capsh container

Post by s243a »

rufwoof wrote: Tue Jan 26, 2021 1:24 pm

I notice that there are very few items we are binding in dev
.
.
but this error might be related to not first binding /sys and /dev prior to doing the chroot. I notice that the container doesn't create these binds in the top folder and said binds only exist within the container.
.
.
the container doesn't bind /dev/pts

I have experienced some oddities when using Libre Office calc with using cwm within the Xephyr/container session, such as when locking focus onto a chart with the intent to move that chart (drag/drop) losing focus.
...
That aside, the code is specific to Fatdog 811. Fundamentally "empty" is being used as the pseudo terminal, and where mount points are unshared to isolate disks.

I'm thinking that's how it works and you have a much better idea of that than me. I wonder if there is a way to use empty in the container to emulate a pseudo-terminal. I see some stuff in the man pages about named pipes for I/O. My question likey shows my lack of understanding about pseudo-terminals. I actually need to google what they are. I Will do that later.

For 'containment' (security) we don't really want pseudo terminals being shared across the main and contained systems such that they might be a attack vector.

I agree. Best to avoid that if we can and if all we are trying to do is run a browser in a basic windows manager we can.

Similarly we want to 'distance' as much of proc, sys and other dev as possible,

I'm actually surprised that these aren't needed. That said, I wonder if we can recreate some of them inside the container. I tried to do stuff like the following:
mknod -m 622 top/dev/console c 5 1
based on:
http://www.linuxfromscratch.org/lfs/vie ... vices.html

but this crashed my host system and I really don't understand all these mknod commands.

but where sharing the likes of sound devices is considered acceptable for the functionality that provides whilst being relatively low risk.

I'll buy that but what if you are are worried about someone eavesdropping on your online chat. In such cases might one not also want to avoid sharing these between the guest and host. I wonder if one can use say a different sound card for the container. I'll also note that even speaker sounds can be used for tracking purposes provide there are mikes looking for unique sound signatures. This shouldn't be an issue in peoples home though. Perhaps rather than sharing snd and mixer one could network sound over the loop device or local network.

Using pflask helps with simplification of setting up much of the chroot containment - such as dropping namespaces.

Makes me wonder what I can do without using pflask. For instance just using unshare instead.

Using Xephyr is a means to 'use a different X server' - as otherwise access to the same X server even as different userid's is a (very) weak point.

I agree. A shared Xserver seems to be a major weak-point. I wonder though if ssh untrusted forwarding might help address some of these concerns. Of course I doubt that such an approach would be as robust as using a second Xserver like Xephyr.

Capabilities are also selectively dropped to provide further containment.

Thankyou for these. I wouldn't have know to do this otherwise.

The difficulty is figuring out what can be dropped/restricted whilst still having a usable system/function within that contained environment. As defined in the above code containment is pretty good, whilst operation as a 'desktop' is still reasonable. At least for Fatdog 811.

I confess that while I'm testing these with puppy as the guest, I haven't tried puppy as the host yet.

When ported however, and more so if you start re-introducing the likes of sharing devices (/dev) ... etc. then the peaking of striving towards the maximum functionality within the maximised security/containment - tails off.

Not having access a pseudotermianl seems to present roadblocks in some cases. I was able to remedy these by stripping things out of .jwmrc and .jwmrc-tray. The biggist culprit I think was the xload function, which was used in the system tray. Here is my sed code to strip these startup/config files:

Code: Select all

cat << "EOF" >top/strip_jwm.sh
#!bin/sh
sed -inr '$! {H};$ {H;x;s#(<StartupCommand>)(.*)(</StartupCommand>)##g;p}' /root/.jwmrc
sed -inr '/.*xload*./! {p}' /root/.jwmrc-tray
EOF

I'm running with the above code as my everyday desktop, and functionality wise its good-enough. Just some quirks in a otherwise usable desktop for general purposes (browsing, office, vlc/media ...etc.).

I haven't got to this point yet but I may use them much more often once I create menu items for them.

user1111

Re: Fatdog unshare xephyr capsh container

Post by user1111 »

In ramdisk console mode, I've used

Code: Select all

setsid cttyhack /bin/sh

to establish a tty, that may work for you. You may have to exec it to avoid creating a child shell
exec setsid cttyhack /bin/sh
I know that will give you a shell with job control where job control is otherwise unavailable (such as in a console) i.e. you're able to run
ctrl-z to background it (it stops at that point)
bg ... to set that bg job running in the background
fg to bring it back to the foreground
disown to release its dependency upon its parent (shell process you used to run it) ...etc.

Failing that, try creating a pseudo terminal first ...

mount -t devpts non /dev/pts -o ptmxmode=0666,newinstance

(and maybe run the setsid cttyhack /bin/sh again).

user1111

Re: Fatdog unshare xephyr capsh container

Post by user1111 »

pflask does take care of creating the proc and sys within the container.

user1111

Re: Fatdog unshare xephyr capsh container

Post by user1111 »

Good points about sound/mic. Relatively easy to disable sharing of the main systems speaker. Subject to what's being run the sound as you say could be forwarded via tcp. For the time being however I'm leaving mine as-is as I do visit news type sites where I'd rather have sound directly available.

user1111

WIN+d container minimise to tray

Post by user1111 »

Default Fatdog has Openbox (window manager) having 'WIN d' key combination as the 'show desktop' toggle (as defined in /etc/xdg/openbox/rc.xml).

When in the container - a full screen window, with the tray icon for Ctrl-Shift (mouse/keyboard focus locked/unlocked toggle) toggled to blue (locked), the desktop is pretty much a conventional jwm desktop, alt tab steps between windows within that etc. When toggled to green (unlocked) alt-tab steps between the main session windows, of which the Xephyr (container) is just one. However if the Xephyr window is the only window open, alt-tab when in the green (unlocked) mode doesn't get you out of the container and back into the normal Fatdog Openbox desktop. That's where Win+d comes in handy as you can 'show desktop' to in effect iconise (minimise to tray) the Xephyr container window and get back to the normal Fatdog Openbox desktop.

Either way, the container can't drive those actions, its controlled at the main session (parent) level (Fatdog/Openbox). So even if the container is hacked, the key sequences to escape that containment isn't available to the hacker. The can't key-stuff or otherwise view/control Openbox windows.

user1111

Re: Fatdog unshare xephyr capsh container

Post by user1111 »

EDIT: Feb 5th 2021 Updated the container.sh script to include a minimise the full screened Xephyr container window button within the containers tray

container.sh.gz
(22 KiB) Downloaded 61 times

Ensure that wmctrl and xdotool are installed (from gslapt). Download and decompress the above script, edit the section near the top (to identify where fd64.sfs is ...etc.) ... and then run the script to drop into a 'contained' desktop. Rox is set to use the file /home/shared/wallpaper.jpg within the container (that I have /home/shared within the container configured to be /mnt/sda4/shared outside of the container).

Further refinements. Now doesn't need a ext folder for mounts and storing changes, runs in ram (I'm using encrypted swap along with ram space being resized so it supports more ram 'space' being available). Moving changes over from being a ext folder to using ram provides better security, i.e. forensics might use ext3/4 journalling to otherwise recover even 'shredded' files contents. The encrypted swap method I use uses a different random key (sourced from /dev/urandom) after each reboot, so not even I know the key.

Much of the larger file size is due to .jwmrc, rox Options and .Xdefaults also being included i.e. are appended at the end of the script and that are extracted/used as part of running the script. For me, it sets up a good enough jwm style desktop to be usable enough as my default desktop i.e. I boot straight in and use it as my regular default boot. I've gone with a 'container' type looking wallpaper in reflection of the containment

s.jpg
s.jpg (125.92 KiB) Viewed 1394 times

I have Fatdog setup to use multi-session save styles. I don't copy the fd64.sfs to ram and instead just have it lz4 compressed (and where fd64.sfs is separated out from initrd). Boots quickly that way and lz4 compressed fd64.sfs is quick to read/use. Initially uses around 250MB of ram after being booted, that rises to around 320MB when the 'container' is run. Container is very quick to start and use, comparable to as though the main session was being used. Primarily after I've set things up the way I like I just boot, use, shutdown without saving changes and using this script that leaves no fingerprints. When in use 'root' is comparable to a highly restricted user but where you can still surf/browse, do office tasks etc. as normal. With dissenter as the browser - that strives for privacy and duckduckgo as the default search engine is fine. Dissenter also includes a menu option to run it using tor - to add to online privacy.

wallpaper.jpg
wallpaper.jpg (102.5 KiB) Viewed 1387 times
s243a
Posts: 501
Joined: Mon Dec 09, 2019 7:29 pm
Has thanked: 90 times
Been thanked: 37 times

Re: Fatdog unshare xephyr capsh container

Post by s243a »

rufwoof wrote: Wed Jan 20, 2021 11:11 am

pflask from Fatdog's gslapt repo, indicates
# pflash -h

Code: Select all

pflask 0.2

Usage: pflask [OPTIONS]...

  -h, --help             Print help and exit
  -V, --version          Print version and exit
  -r, --chroot=STRING    Change the root directory inside the container
  -c, --chdir=STRING     Change the current directory inside the container
  -t, --hostname=STRING  Set the container hostname
  -m, --mount=STRING     Create a new mount point inside the container
  -n, --netif[=STRING]   Disconnect the container networking from the host
  -u, --user=STRING      Run the command under the specified user
                           (default=`root')
  -e, --user-map=STRING  Map container users to host users
  -w, --ephemeral        Discard changes to /  (default=off)
  -g, --cgroup=STRING    Create a new cgroup and move the container inside it
  -b, --caps=STRING      Change the effective capabilities inside the container
                           (default=`+all')
  -d, --detach           Detach from terminal  (default=off)
  -a, --attach=INT       Attach to the specified detached process
  -s, --setenv=STRING    Set additional environment variables
  -k, --keepenv          Do not clear environment  (default=off)
  -U, --no-userns        Disable user namespace support  (default=off)
  -M, --no-mountns       Disable mount namespace support  (default=off)
  -N, --no-netns         Disable net namespace support  (default=off)
  -I, --no-ipcns         Disable IPC namespace support  (default=off)
  -H, --no-utsns         Disable UTS namespace support  (default=off)
  -P, --no-pidns         Disable PID namespace support  (default=off)

which has a receipe http://distro.ibiblio.org/fatdog/source/800/recipes/ that uses the source from https://github.com/ghedo/pflask and within which the src/cmdline.c matches that as above ... so it doesn't look to me like any particular patching is being made by the Fatdog developers.

The bottom of the link you posted indicates a BSD licence, and capabilities are a Linux kernel thing, not applicable to BSD, so I guess that code is for the BSD's.

v0.2 is from 2014. I wonder if there is a newer version somewhere:
https://github.com/ghedo/pflask/releases

Feek
Posts: 394
Joined: Sun Oct 18, 2020 8:48 am
Location: cze
Has thanked: 44 times
Been thanked: 86 times

Re: Fatdog unshare xephyr capsh container

Post by Feek »

Hello @rufwoof ,

thanks for sharing this container script.
It works very well in version 812.

I would be satisfied with seamonkey but I found later out that the default version in main .sfs is 2.49.5, which was released more than 2 years ago (e.g. the videos on youtube do not play).

Just out of curiosity I tried another ways of how to add a browser into the container environment (instead of the recommended way of adding it into the main .sfs).

Here are my attempts:

I tried to install Firefox from inside of the container but the installing of gtk3 failed (I assumed it).

I also tried to add an appimage of Firefox through the shared folder but I wasn't able to launch it (I assumed it).

And my last but successful attempt was to install Palemoon with gslapt :thumbup: .
This works well, maybe because Palemoon doesn't require to install gtk3 stuff.

Post Reply

Return to “FatDog64”