# Issue when starting graphical session with selinux

## Fulgurance

Hello, I'm from a while a Gentoo Linux user with an selinux installation. And from the moment I changed to a new laptop and I setup again for my new installation selinux, it's the first time I'm totally unable to start a graphical session. Is it possible it's because now gentoo use display-manager-init instead of xdm I have this issue ? Maybe actually there isn't any selinux policies for this ?

When I boot, I don't have any warning or error when openrc start, just when the display-manager try to start sddm, Gentoo go back to the TTY.

I use MCS.

Emerge --info:

```
Portage 3.0.30 (python 3.9.9-final-0, default/linux/amd64/17.1/hardened/selinux, gcc-11.2.1, glibc-2.34-r4, 5.15.10-gentoo x86_64)

=================================================================

System uname: Linux-5.15.10-gentoo-x86_64-Intel-R-_Core-TM-_i9-10980HK_CPU_@_2.40GHz-with-glibc2.34

KiB Mem:    32470784 total,  29064520 free

KiB Swap:   41943036 total,  41943036 free

Timestamp of repository gentoo: Mon, 20 Dec 2021 13:30:01 +0000

Head commit of repository gentoo: 0da47d05cc2c7b04632cbf0490280237d7c923a5

sh bash 5.1_p12

ld GNU ld (Gentoo 2.37_p1 p1) 2.37

app-misc/pax-utils:        1.3.3::gentoo

app-shells/bash:           5.1_p12::gentoo

dev-java/java-config:      2.3.1::gentoo

dev-lang/perl:             5.34.0-r6::gentoo

dev-lang/python:           2.7.18_p13::gentoo, 3.9.9::gentoo, 3.10.1-r1::gentoo

dev-lang/rust:             1.57.0::gentoo

dev-util/cmake:            3.22.1::gentoo

dev-util/meson:            0.60.2-r1::gentoo

sec-policy/selinux-base:   2.20210908-r1::gentoo

sys-apps/baselayout:       2.8::gentoo

sys-apps/openrc:           0.44.9::gentoo

sys-apps/sandbox:          2.29::gentoo

sys-devel/autoconf:        2.13-r1::gentoo, 2.71-r1::gentoo

sys-devel/automake:        1.16.5::gentoo

sys-devel/binutils:        2.37_p1-r1::gentoo

sys-devel/binutils-config: 5.4::gentoo

sys-devel/clang:           13.0.0::gentoo

sys-devel/gcc:             11.2.1_p20211127::gentoo

sys-devel/gcc-config:      2.5-r1::gentoo

sys-devel/libtool:         2.4.6-r6::gentoo

sys-devel/lld:             13.0.0::gentoo

sys-devel/llvm:            13.0.0::gentoo

sys-devel/make:            4.3::gentoo

sys-kernel/linux-headers:  5.15-r1::gentoo (virtual/os-headers)

sys-libs/glibc:            2.34-r4::gentoo

sys-libs/libselinux:       3.3::gentoo

Repositories:

gentoo

    location: /var/db/repos/gentoo

    sync-type: rsync

    sync-uri: rsync://rsync.gentoo.org/gentoo-portage

    priority: -1000

    sync-rsync-verify-max-age: 24

    sync-rsync-verify-jobs: 1

    sync-rsync-extra-opts: 

    sync-rsync-verify-metamanifest: yes

steam-overlay

    location: /var/lib/layman/steam-overlay

    sync-type: laymansync

    sync-uri: https://github.com/anyc/steam-overlay.git

    masters: gentoo

    priority: 50

ACCEPT_KEYWORDS="amd64 ~amd64"

ACCEPT_LICENSE="*"

CBUILD="x86_64-pc-linux-gnu"

CFLAGS="-march=skylake -O2 -pipe -mmovbe -mmmx -msse -msse2 -msse3 -mssse3 -msse4.1 -msse4.2 -mpopcnt -mavx -mavx2 -maes -mpclmul -mfsgsbase -mrdrnd -mfma -mbmi -mbmi2 -mf16c -mrdseed -madx -mprefetchwt1 -mclflushopt -mxsavec -mxsaves"

CHOST="x86_64-pc-linux-gnu"

CONFIG_PROTECT="/etc /usr/lib64/libreoffice/program/sofficerc /usr/share/config /usr/share/gnupg/qualified.txt"

CONFIG_PROTECT_MASK="/etc/ca-certificates.conf /etc/dconf /etc/env.d /etc/fonts/fonts.conf /etc/gconf /etc/gentoo-release /etc/revdep-rebuild /etc/sandbox.d /etc/terminfo"

CXXFLAGS="-march=skylake -O2 -pipe -mmovbe -mmmx -msse -msse2 -msse3 -mssse3 -msse4.1 -msse4.2 -mpopcnt -mavx -mavx2 -maes -mpclmul -mfsgsbase -mrdrnd -mfma -mbmi -mbmi2 -mf16c -mrdseed -madx -mprefetchwt1 -mclflushopt -mxsavec -mxsaves"

DISTDIR="/var/cache/distfiles"

ENV_UNSET="CARGO_HOME DBUS_SESSION_BUS_ADDRESS DISPLAY GOBIN GOPATH PERL5LIB PERL5OPT PERLPREFIX PERL_CORE PERL_MB_OPT PERL_MM_OPT XAUTHORITY XDG_CACHE_HOME XDG_CONFIG_HOME XDG_DATA_HOME XDG_RUNTIME_DIR"

FCFLAGS="-march=skylake -O2 -pipe -mmovbe -mmmx -msse -msse2 -msse3 -mssse3 -msse4.1 -msse4.2 -mpopcnt -mavx -mavx2 -maes -mpclmul -mfsgsbase -mrdrnd -mfma -mbmi -mbmi2 -mf16c -mrdseed -madx -mprefetchwt1 -mclflushopt -mxsavec -mxsaves"

FEATURES="assume-digests binpkg-docompress binpkg-dostrip binpkg-logs buildpkg-live candy config-protect-if-modified distlocks ebuild-locks fixlafiles ipc-sandbox merge-sync multilib-strict network-sandbox news parallel-fetch preserve-libs protect-owned qa-unresolved-soname-deps sandbox selinux sesandbox sfperms strict unknown-features-warn unmerge-logs unmerge-orphans userfetch userpriv usersandbox usersync xattr"

FFLAGS="-march=skylake -O2 -pipe -mmovbe -mmmx -msse -msse2 -msse3 -mssse3 -msse4.1 -msse4.2 -mpopcnt -mavx -mavx2 -maes -mpclmul -mfsgsbase -mrdrnd -mfma -mbmi -mbmi2 -mf16c -mrdseed -madx -mprefetchwt1 -mclflushopt -mxsavec -mxsaves"

GENTOO_MIRRORS="http://gentoo.mirrors.ovh.net/gentoo-distfiles/ https://mirrors.aliyun.com/gentoo/ http://ftp.free.fr/mirrors/ftp.gentoo.org/"

LANG="fr_FR.UTF-8"

LC_ALL="C"

LDFLAGS="-Wl,-O1 -Wl,--as-needed"

MAKEOPTS="-j16"

PKGDIR="/var/cache/binpkgs"

PORTAGE_CONFIGROOT="/"

PORTAGE_RSYNC_OPTS="--recursive --links --safe-links --perms --times --omit-dir-times --compress --force --whole-file --delete --stats --human-readable --timeout=180 --exclude=/distfiles --exclude=/local --exclude=/packages --exclude=/.git"

PORTAGE_TMPDIR="/var/tmp"

SHELL="/bin/bash"

USE="X aac acl acpi alsa amd64 audit bluetooth btrfs bzip2 caps compat crypt cryptsetup cups custom-cflags custom-optimization dbus device-mapper dri dri3 elogind experimental ffmpeg git glamor gstreamer hardened iconv ipv6 jpeg kde libglvnd libtirpc lvm mp3 mp4 mtp multilib ncurses networkmanager nls nptl ogg open_perms opengl openmp pam pcre peer_perms phonon pie plasma png policykit pulseaudio readline seccomp selinux split-usr ssl ssp svg tiff ubac udev udisks unconfined unicode uvm v4l vorbis vulkan wayland wifi wireless x264 x265 xattr xtpax zlib" ABI_X86="32 64" ADA_TARGET="gnat_2020" APACHE2_MODULES="authn_core authz_core socache_shmcb unixd actions alias auth_basic authn_alias authn_anon authn_dbm authn_default authn_file authz_dbm authz_default authz_groupfile authz_host authz_owner authz_user autoindex cache cgi cgid dav dav_fs dav_lock deflate dir disk_cache env expires ext_filter file_cache filter headers include info log_config logio mem_cache mime mime_magic negotiation rewrite setenvif speling status unique_id userdir usertrack vhost_alias" CALLIGRA_FEATURES="karbon sheets words" COLLECTD_PLUGINS="df interface irq load memory rrdtool swap syslog" CPU_FLAGS_X86="aes avx avx2 f16c fma3 mmx mmxext pclmul popcnt rdrand sse sse2 sse3 ssse3 sse4_1 sse4_2" ELIBC="glibc" GPSD_PROTOCOLS="ashtech aivdm earthmate evermore fv18 garmin garmintxt gpsclock greis isync itrax mtk3301 nmea ntrip navcom oceanserver oldstyle oncore rtcm104v2 rtcm104v3 sirf skytraq superstar2 timing tsip tripmate tnt ublox ubx" GRUB_PLATFORMS="efi-64" INPUT_DEVICES="libinput synaptics" KERNEL="linux" L10N="fr fr-FR" LCD_DEVICES="bayrad cfontz cfontz633 glk hd44780 lb216 lcdm001 mtxorb ncurses text" LIBREOFFICE_EXTENSIONS="presenter-console presenter-minimizer" LLVM_TARGETS="NVPTX" LUA_SINGLE_TARGET="lua5-1" LUA_TARGETS="lua5-1" OFFICE_IMPLEMENTATION="libreoffice" PHP_TARGETS="php7-3 php7-4" POSTGRES_TARGETS="postgres12 postgres13" PYTHON_SINGLE_TARGET="python3_9" PYTHON_TARGETS="python3_9" QEMU_SOFTMMU_TARGETS="arm x86_64" QEMU_USER_TARGETS="x86_64" RUBY_TARGETS="ruby26 ruby27" USERLAND="GNU" VIDEO_CARDS="intel i965 iris nvidia" XTABLES_ADDONS="quota2 psd pknock lscan length2 ipv4options ipset ipp2p iface geoip fuzzy condition tee tarpit sysrq proto steal rawnat logmark ipmark dhcpmac delude chaos account"

Unset:  ADDR2LINE, AR, ARFLAGS, AS, ASFLAGS, CC, CCLD, CONFIG_SHELL, CPP, CPPFLAGS, CTARGET, CXX, CXXFILT, ELFEDIT, EMERGE_DEFAULT_OPTS, EXTRA_ECONF, F77FLAGS, FC, GCOV, GPROF, INSTALL_MASK, LD, LEX, LFLAGS, LIBTOOL, LINGUAS, MAKE, MAKEFLAGS, NM, OBJCOPY, OBJDUMP, PORTAGE_BINHOST, PORTAGE_BUNZIP2_COMMAND, PORTAGE_COMPRESS, PORTAGE_COMPRESS_FLAGS, PORTAGE_RSYNC_EXTRA_OPTS, RANLIB, READELF, RUSTFLAGS, SIZE, STRINGS, STRIP, YACC, YFLAGS
```

Selinux Config file:

```
# This file controls the state of SELinux on the system on boot.

# SELINUX can take one of these three values:

#       enforcing - SELinux security policy is enforced.

#       permissive - SELinux prints warnings instead of enforcing.

#       disabled - No SELinux policy is loaded.

SELINUX=permissive

# SELINUXTYPE can take one of these four values:

#       targeted - Only targeted network daemons are protected.

#       strict   - Full SELinux protection.

#       mls      - Full SELinux protection with Multi-Level Security

#       mcs      - Full SELinux protection with Multi-Category Security 

#                  (mls, but only one sensitivity level)

SELINUXTYPE=mcs
```

Just please ask me if you need more informations, because I'm not a selinux expert, and I don't know what files you need to see exactly

But just for you all, I'm able to boot with graphical session if I disable selinux by kernel command line, I putted: "selinux=0"

----------

## alamahant

Try

```

ausearch -m AVC

```

to see what auditd has to say about the denials.

Then use this gradation:

Set sebool->set file and/or port contexts->Write policy modules.

 *Quote:*   

> 
> 
> I'm not a selinux expert
> 
> 

 

My sincere advice to you would be NOT to run selinux on a DE.Or at least keep it in "permisive".

 *Quote:*   

> 
> 
> # This file controls the state of SELinux on the system on boot.
> 
> # SELINUX can take one of these three values:
> ...

 

You do have it in permissive.

Strange.....

Edit

```

SELINUXTYPE=targeted

```

and see it it works.

----------

## Fulgurance

```
  root  /  home  zohran  1  LC_ALL=C ausearch -m AVC

Error opening /var/log/audit/audit.log (No such file or directory)
```

And I don't understand your second request sorry   :Sad: 

----------

## alamahant

Selinux needs auditd daemon.

Plz in make.conf add USE="audit" and rebuild @world.

Then

mkdir /var/log/audit

touch /var/log/audit/audit.log

Enable and start "auditd"

Before you can fix it you need to find out what is the problem.

You can also try

```

grep -i  "selinux is preventing" /var/log/messages

or

grep -i "avc: .denied" /var/log/messages

```

But tou WILL need audit for writing policy modules if-need-be.

----------

## Fulgurance

I enabled already audit, It's fine, I just enabled auditd service.

For the first command, I have nothing, but for the second one   :Laughing: 

https://textup.fr/603748Yr

I will restart with the bug to have the audit file

----------

## Fulgurance

And now the result for: 

```
ausearch -m AVC 
```

https://textup.fr/603749oT

----------

## alamahant

You have thousands.

Plz run

```

audit2allow -w -a

```

to see reason for denial and apply appropriate action.

To brute-force yourself beyond these errors

```

ausearch -m AVC  | audit2allow -a -M my_policy-1 #### to generate policy module

semodule -i my_policy-1.pp #### to install policy module

```

Yet again a very bad idea.

BUT you shouldnt be having any problems since you are running "permissive"

Maybe some selinux adept can help you more.

Generally it is a bad idea to run selinux if you dont understand what it does.

I dont so i dont run it.

 :Smile: 

----------

## Fulgurance

If somebody can learn me how to do that without brute force, I would like.

Permissive is secure, or not at all ?

----------

## alamahant

 *Quote:*   

> 
> 
> Permissive is secure, or not at all ?
> 
> 

 

not at all.

It records the errors without blocking anything.

In other systems there is a fantastic tool called setroubleshoot-server

This will tell you for every infraction how to remedy.

Usually this involves

1.sebooleans

```

getsebool -a

setsebool (-P) <boolean-name> on|off

```

2.

```

semanage fcontext(port) -a -t <type> /path/to/file|port-number 

restorecon -R <path-to-file|dir>

```

3.write policy.

Lacking this tool you will need to decrypt audit messages and intuit what you need to do.

Start with

```

audit2allow -w -a 

```

this will tell you the "why?" of your selinux errors.

Selinux is a  MAC framework ie

<who> can have <what-kind of access> on <what>.

I think.

----------

## Fulgurance

Hi again. I continue to try to understand why selinux in permissive block my graphical session. It's very strange definitely. Somebody have an idea about the reason ?

I understood gentoo actually don't have all of the Red Hat tools to decrypt the selinux denial message. But are there another way to understand what I have to do ? I would like to write my policy please.

For example, just for this denied access:

```
Dec 7 00:01:59 alienware-m17-r3 kernel: audit: type=1400 audit(1638831719.141:847): avc: denied { read } for pid=25311 comm="nvidia-modprobe" name="modprobe" dev="proc" ino=70343 scontext=system_u:system_r:kernel_t tcontext=system_u:object_r:sysctl_modprobe_t tclass=file permissive=1
```

The command process nvidia-modprobe had denied access okay, but what is exactly the problem in this case ?

----------

## Fulgurance

Okay guys, I done a test to check what happened exactly.

When I start my gentoo with selinux=0 (so fully disabled), I can execute 

```
dbus-run-session startplasma-wayland
```

.

Plasma start properly

But if I start my gentoo with selinux enabled, and in permissive (the most strange thing actually), when I run 

```
dbus-run-session startplasma-wayland
```

, my cursor appear on a black screen, and nothing more. I can't move the cursor as well. It's like the screen froze. It's strange because normally selinux in permissive mode don't stop anything, but it look like ...

Somebody have an idea ?

----------

## pjp

Maybe try audit2why? According to Portage File List, it is part of sys-apps/selinux-python.

That might provide better information about errors.

After that, I think it's going to be looking for examples and trying to match enough details to create a solution.

----------

## Fulgurance

I think definitely something is wrong with selinux or the tools. When I try to use audit2why tool, I have this strange result:

```
alienware-m17-r3 /home/zohran # audit2why -p /var/log/audit/audit.log 

libsepol.policydb_read: policydb magic number 0x65707974 does not match expected magic number 0xf97cff8c or 0xf97cff8d

ValueError: invalid binary policy /var/log/audit/audit.log

The above exception was the direct cause of the following exception:

Traceback (most recent call last):

  File "/usr/lib/python-exec/python3.10/audit2allow", line 381, in <module>

    app.main()

  File "/usr/lib/python-exec/python3.10/audit2allow", line 363, in main

    audit2why.init(self.__options.policy)

SystemError: <built-in function init> returned a result with an exception set

[ble: exit 1]
```

Same without options:

```
alienware-m17-r3 /home/zohran # audit2why /var/log/audit/audit.log 

ValueError: You must specify the -p option with the path to the policy file.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):

  File "/usr/lib/python-exec/python3.10/audit2allow", line 381, in <module>

    app.main()

  File "/usr/lib/python-exec/python3.10/audit2allow", line 365, in main

    audit2why.init()

SystemError: <built-in function init> returned a result with an exception set

[ble: exit 1]
```

I seen in some forum I can specify the audit.log file with the -i option, but it doesn't work for me. What is wrong / I made wrong ?

Maybe a problem with my python version ?

----------

## pjp

As what user are you running audit2why, and what are the permissions for the audit log file (and directory if one exists)? I could be thinking of another log file, but I believe it is only accessible by root.

----------

## Fulgurance

It was as root (sudo su command).

This is the audit.log file permission:

```
alienware-m17-r3 /home/zohran # ls -la /var/log/audit

total 3340

drwx------. 1 root root      68 Jul 17 19:07 .

drwxr-xr-x. 1 root root     448 Jul 27 09:56 ..

-rw-------. 1 root root 3418066 Jul 27 23:23 audit.log

-rw-r--r--. 1 root root       0 Jul  5 23:21 .keep_sys-process_audit-0
```

Any idea about the problem ?

----------

## pjp

You could try as root (sudo /bin/su -), but I wouldn't expect that to be the problem. Occasionally some stuff doesn't like sudo.

I was going to suggest uninstalling and reinstalling selinux, but seeing that it is a profile, I can't recommend that as I have no idea what impact that might have.

Otherwise, i recommend reading about SELinux and how i works. You could disable it now and work with it in a VM until you're more comfortable with it. But do realize it is complicated and I've never heard it recommended for desktop use. Maybe someone out there has done it and documented their efforts?

It's one of those subjects I've put on my "someday" list, but it isn't enough of a personal priority.

----------

## Fulgurance

The same error with: 

```
sudo /bin/su
```

I think disable and enable selinux is not a solution at all. I done that already, but this solve nothing. I think it's just because we don't know something about the selinux configuration or something like that. I need an selinux user...

Do you think the problem can come from my python version maybe ?

----------

## alamahant

 *Quote:*   

> 
> 
> Otherwise, i recommend reading about SELinux and how i works. You could disable it now and work with it in a VM until you're more comfortable with it. But do realize it is complicated and I've never heard it recommended for desktop use. Maybe someone out there has done it and documented their efforts?
> 
> 

 

Fedora and centos do it just fine.

But they use "targeted" policy, not "strict" and they have more mature selinux policy--they created the damn thing,and more tools to help the user such as

setroubleshoot-server

What is your

```

cat /etc/selinux/config

```

?

Relabeling the filesystem is a god place to start.

----------

## pjp

I'll second the suggestion to try "SELINUXTYPE=targeted".

 *Fulgurance wrote:*   

> The same error with: 
> 
> ```
> sudo /bin/su
> ```
> ...

  For clarity, /bin/su and /bin/su - are not equivalent, though I wouldn't expect it to make a difference in this case. Except of course with selinux set to permissive, it theoretically shouldn't be interfering.

 *Fulgurance wrote:*   

> I think disable and enable selinux is not a solution at all.

  I didn't suggest that it was. My original thought was to uninstall and reinstall it. However, since selinux is configured via profile, I didn't want to recommend that attempt as uninstalling critical components can cause critical problems ;)

 *Fulgurance wrote:*   

> I think it's just because we don't know something about the selinux configuration or something like that. I need an selinux user...

  Well, yes. That's the point of reading about it to become more familiar with it. My input has solely been directed at attempts to eliminate basic problem areas. Must curious of course being why permissive mode seems to have an impact when it presumably shouldn't.

I would be surprised if an selinux user didn't recommend against using it on a desktop / GUI environment. If one appears, I'd certainly defer to their knowledge.

 *Fulgurance wrote:*   

> Do you think the problem can come from my python version maybe ?

  With audit2why, possibly. In general, I doubt it, but anything is possible until the solution is identified.

----------

## Fulgurance

Okay, I done the

```
 sudo /bin/su -
```

, but unfortunately, same result again  :Crying or Very sad: 

You asked me to try targeted ? Okay I will.

For the python version, what can I try to do ?

Is it normal when I perform this:

```
alienware-m17-r3 /home/zohran # seinfo

Statistics for policy file: /etc/selinux/mcs/policy/policy.33

Policy Version:             33 (MLS enabled)

Target Policy:              selinux

Handle unknown classes:     allow

  Classes:             134    Permissions:         425

  Sensitivities:         1    Categories:         1024

  Types:              1343    Attributes:          112

  Users:                 6    Roles:                 8

  Booleans:             68    Cond. Expr.:          59

  Allow:             13786    Neverallow:            0

  Auditallow:            1    Dontaudit:          3085

  Type_trans:          689    Type_change:          12

  Type_member:           6    Range_trans:           7

  Role allow:           11    Role_trans:            0

  Constraints:         133    Validatetrans:         0

  MLS Constrain:        71    MLS Val. Tran:         0

  Permissives:           0    Polcap:                5

  Defaults:              0    Typebounds:            0

  Allowxperm:            0    Neverallowxperm:       0

  Auditallowxperm:       0    Dontauditxperm:        0

  Ibendportcon:          0    Ibpkeycon:             0

  Initial SIDs:         27    Fs_use:               30

  Genfscon:             93    Portcon:             487

  Netifcon:              0    Nodecon:               0
```

It show a file to mcs policy (/etc/selinux/mcs/policy/policy.33), but after it's write Policy Version:             33 (MLS enabled), because MLS and MCS are differents

----------

## pjp

 *Fulgurance wrote:*   

> For the python version, what can I try to do ?

  Good question, I've not previously tried.

According to  python-exec Local implementation overrides, this appears to work (replace python --version with the command you want to run): 

```
$ python --version

Python 3.10.5

$ EPYTHON=python3.9 python --version

Python 3.9.13

$ EPYTHON=python3.10 python --version

Python 3.10.5
```

 Using python --version was the only test I could think of to demonstrate whether or not it "worked". Seems to.

 *Fulgurance wrote:*   

> Is it normal when I perform this:

  I'll make the small leap that seinfo is short for SELinux Information, so anything it outputs (aside from corrupt data) would be normal. I can't comment on specific values.

 *Fulgurance wrote:*   

> It show a file to mcs policy (/etc/selinux/mcs/policy/policy.33), but after it's write Policy Version:             33 (MLS enabled), because MLS and MCS are differents

  I noticed that too, but I've only used SELinux set to "targeted", and not recently enough to remember anything about the output of seinfo. Comparing the output after you've set "targeted" may or may not be useful.

And that's where reading as much as you can find might come in handy. A search for Gentoo SELinux produces at least a lot of Gentoo referenced items to get you started. I'm sure some of it won't have much technical, but starting begins with a single step. SELinux - Gentoo Wiki

SELinux/Installation - Gentoo Wiki

SELinux/Tutorials - Gentoo Wiki

SELinux/FAQ - Gentoo Wiki

Project:SELinux - Gentoo Wiki

SELinux/Gentoo profiles - Gentoo Wiki

SELinux/Quick introduction - Gentoo Wiki

selinux – Gentoo Packages

GitHub - ColOfAbRiX/selinux-summary: A summary of the Gentoo SELinux ... 

Hardened Gentoo - Gentoo Wiki

----------

## Fulgurance

I'm switching actually to the strict policy, to see if I can see any difference. I'm actually relabelling the system, I forgot everytime I label the system, I have this error:

```
alienware-m17-r3 /home/zohran # setfiles /etc/selinux/strict/contexts/files/file_contexts /{dev,home,proc,run,sys,tmp} 

Warning no default label for /proc

setfiles: Could not set context for /proc/19678/task/19678/fd/3:  No such file or directory

setfiles: Could not set context for /proc/19678/task/19678/fdinfo/3:  No such file or directory

setfiles: Could not set context for /proc/19678/fd/3:  No such file or directory

setfiles: Could not set context for /proc/19678/fdinfo/3:  No such file or directory

setfiles: Could not set context for /proc/19680:  No such file or directory

setfiles: Could not read /proc/19680: No such file or directory.

alienware-m17-r3 /home/zohran # rlpkg -a -r

Relabeling filesystem types: btrfs encfs ext2 ext3 ext4 ext4dev f2fs gfs gfs2 gpfs jffs2 jfs lustre xfs zfs

Running /sbin/setfiles -F /etc/selinux/strict/contexts/files/file_contexts / /boot

Scanning for shared libraries with text relocations...

/usr/lib/python3.10/subprocess.py:959: RuntimeWarning: line buffering (buffering=1) isn't supported in binary mode, the default buffer size will be used

  self.stdout = io.open(c2pread, 'rb', bufsize)

scanelf: /usr/lib/metasploit9999/vendor/ruby/2.7.0/gems/metasploit_payloads-mettle-1.0.18/build/s390x-linux-musl/bin/sniffer.bin: Invalid section header info (2)

scanelf: /usr/lib/metasploit9999/vendor/ruby/2.7.0/gems/metasploit_payloads-mettle-1.0.18/build/s390x-linux-musl/bin/mettle.bin: Invalid section header info (2)

scanelf: /usr/lib/metasploit9999/vendor/ruby/2.7.0/gems/metasploit_payloads-mettle-1.0.18/build/powerpc64le-linux-musl/bin/mettle.bin: Invalid section header info (2)

scanelf: /usr/lib/metasploit9999/vendor/ruby/2.7.0/gems/metasploit_payloads-mettle-1.0.18/build/powerpc-linux-muslsf/bin/sniffer.bin: Invalid section header info (2)

scanelf: /usr/lib/metasploit9999/vendor/ruby/2.7.0/gems/metasploit_payloads-mettle-1.0.18/build/powerpc-linux-muslsf/bin/mettle.bin: Invalid section header info (2)

scanelf: /usr/lib/metasploit9999/vendor/ruby/2.7.0/gems/metasploit_payloads-mettle-1.0.18/build/powerpc-e500v2-linux-musl/bin/mettle.bin: Invalid section header info (2)

scanelf: /usr/lib/metasploit9999/vendor/ruby/2.7.0/gems/metasploit_payloads-mettle-1.0.18/build/mipsel-linux-muslsf/bin/sniffer.bin: Invalid section header info (2)

scanelf: /usr/lib/metasploit9999/vendor/ruby/2.7.0/gems/metasploit_payloads-mettle-1.0.18/build/mipsel-linux-muslsf/bin/mettle.bin: Invalid section header info (2)

scanelf: /usr/lib/metasploit9999/vendor/ruby/2.7.0/gems/metasploit_payloads-mettle-1.0.18/build/mips64-linux-muslsf/bin/sniffer.bin: Invalid section header info (2)

scanelf: /usr/lib/metasploit9999/vendor/ruby/2.7.0/gems/metasploit_payloads-mettle-1.0.18/build/mips64-linux-muslsf/bin/mettle.bin: Invalid section header info (2)

scanelf: /usr/lib/metasploit9999/vendor/ruby/2.7.0/gems/metasploit_payloads-mettle-1.0.18/build/mips-linux-muslsf/bin/sniffer.bin: Invalid section header info (2)

scanelf: /usr/lib/metasploit9999/vendor/ruby/2.7.0/gems/metasploit_payloads-mettle-1.0.18/build/mips-linux-muslsf/bin/mettle.bin: Invalid section header info (2)

scanelf: /usr/lib/metasploit9999/vendor/ruby/2.7.0/gems/metasploit_payloads-mettle-1.0.18/build/i486-linux-musl/bin/sniffer.bin: Invalid section header info (2)

scanelf: /usr/lib/metasploit9999/vendor/ruby/2.7.0/gems/metasploit_payloads-mettle-1.0.18/build/i486-linux-musl/bin/mettle.bin: Invalid section header info (2)

scanelf: /usr/lib/metasploit9999/vendor/ruby/2.7.0/gems/metasploit_payloads-mettle-1.0.18/build/armv5l-linux-musleabi/bin/sniffer.bin: Invalid section header info (2)

scanelf: /usr/lib/metasploit9999/vendor/ruby/2.7.0/gems/metasploit_payloads-mettle-1.0.18/build/armv5l-linux-musleabi/bin/mettle.bin: Invalid section header info (2)

scanelf: /usr/lib/metasploit9999/vendor/ruby/2.7.0/gems/metasploit_payloads-mettle-1.0.18/build/armv5b-linux-musleabi/bin/sniffer.bin: Invalid section header info (2)

scanelf: /usr/lib/metasploit9999/vendor/ruby/2.7.0/gems/metasploit_payloads-mettle-1.0.18/build/armv5b-linux-musleabi/bin/mettle.bin: Invalid section header info (2)

scanelf: /usr/lib/metasploit9999/vendor/ruby/2.7.0/gems/metasploit_payloads-mettle-1.0.18/build/aarch64-linux-musl/bin/sniffer.bin: Invalid section header info (2)

scanelf: /usr/lib/metasploit9999/vendor/ruby/2.7.0/gems/metasploit_payloads-mettle-1.0.18/build/aarch64-linux-musl/bin/mettle.bin: Invalid section header info (2)

0 libraries with text relocations, 0 not relabeled.

Scanning for PIE binaries with text relocations...

0 binaries with text relocations detected.
```

----------

## Fulgurance

So yes, selinux work in the strict mode

----------

## Fulgurance

So now, I try to make the enforcing mode working when I enable it. It's almost good, I generate some policies for the required services. I just have one or two problems persisting actually:

https://www.zupimages.net/up/22/30/jmry.jpg

The things I don't know how to fix it is the failed to mount /tmp and failed to make symbolic link error.

When I perform a search, I have nothing relevant:

```
alienware-m17-r3 /home/zohran # ausearch -m avc --start recent | grep ln

type=AVC msg=audit(1659164109.812:509): avc:  denied  { read } for  pid=7311 comm="thunderbird" name="lock" dev="dm-2" ino=12546555 scontext=staff_u:staff_r:staff_t tcontext=user_u:object_r:user_home_t tclass=lnk_file permissive=1

type=AVC msg=audit(1659164109.812:510): avc:  denied  { unlink } for  pid=7311 comm="thunderbird" name="lock" dev="dm-2" ino=12546555 scontext=staff_u:staff_r:staff_t tcontext=user_u:object_r:user_home_t tclass=lnk_file permissive=1

alienware-m17-r3 /home/zohran # ausearch -m avc --start recent | grep mtab

[ble: exit 1]

alienware-m17-r3 /home/zohran # ausearch -m avc --start recent | grep /tmp

[ble: exit 1]

alienware-m17-r3 /home/zohran # ausearch -m avc --start recent | grep mount

type=PATH msg=audit(1659164104.768:489): item=0 name="/run/mount/utab" nametype=UNKNOWN cap_fp=0 cap_fi=0 cap_fe=0 cap_fver=0 cap_frootid=0

type=AVC msg=audit(1659164104.768:489): avc:  denied  { search } for  pid=4871 comm="firefox" name="mount" dev="tmpfs" ino=587 scontext=staff_u:staff_r:mozilla_t tcontext=system_u:object_r:mount_runtime_t tclass=dir permissive=1
```

I generated yet policies for postgresql, but it's look like problems with postgresql persist.

Any idea ?

I generate my policies after I read the audit.log like that: 

```
ausearch -c "ModemManager" --raw | audit2allow -M ModemManager-policy
```

----------

## pjp

Read documentation.

The main reason to use "targeted" is due to the likelihood of being able to find relevant information, primarily RedHat related since they use targeted. When you get it working with targeted, maybe it "just works" with other modes, or experience makes it easier to solve.

I personally have only investigated using SELinux for one environment and came to the conclusion that it wasn't viable. To do properly would require substantial effort to produce a working solution with documentation that included implementation and maintenance. It's a nice idea, in theory. I prefer being a generalist to hyper-specializing in some niche corner, or worse, "rarities and oddities."

----------

## Fulgurance

So somebody know how to fix the mtab issue ?

----------

## alamahant

 *Quote:*   

> 
> 
> I generate my policies after I read the audit.log like that:
> 
> Code:
> ...

 

Plz try

```

ausearch -c "ModemManager" --raw | audit2allow -a -M ModemManager-policy #to create policy

or better

ausearch -m AVC | grep -i  "ModemManager" | audit2allow -a -M ModemManager-policy #to create policy

semodule -i ModemManager-policy.pp #to load the created module.

```

Furthermore plz familiarize yourself with

```

semanage <fcontext> <port>

and

setsebool <-P> <selinux-boolean> =<on|off>

and

getsebool -a

```

Only resort to creating custom policy when the above tools dont help you.

Also better parallel to your Gentoo selinux musings,install also a fedora workstation and study how fedora does things.

If

```

setroubleshoot-server

```

were available in Gentoo it would be much easier to play with selinux.

But as it stands now the odds are against you.

Try lobbying the Gentoo selinux team to make this tool available.

It would be fantastic.

Because this tool will tell you exactly how to remedy each selinux denial in detail.

See

https://wiki.gentoo.org/wiki/SELinux/Tutorials/Where_to_find_SELinux_permission_denial_details#sealert

and

https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/security-enhanced_linux/sect-security-enhanced_linux-fixing_problems-sealert_messages

But NOT available.

----------

## Fulgurance

I found this information with audit2allow about the problem I have:

```
type=AVC msg=audit(1659372910.490:1273): avc:  denied  { setattr } for  pid=17520 comm="cpio" name="fstab" dev="dm-2" ino=14421948 scontext=staff_u:sysadm_r:sysadm_t tcontext=staff_u:object_r:unlabeled_t tclass=file permissive=1

        Was caused by:

                Unknown - would be allowed by active policy

                Possible mismatch between this policy and the one under which the audit message was generated.

                Possible mismatch between current in-memory boolean settings vs. permanent ones.

type=AVC msg=audit(1659372910.490:1274): avc:  denied  { create } for  pid=17520 comm="cpio" name="mtab" scontext=staff_u:sysadm_r:sysadm_t tcontext=staff_u:object_r:unlabeled_t tclass=lnk_file permissive=1

        Was caused by:

                Unknown - would be allowed by active policy

                Possible mismatch between this policy and the one under which the audit message was generated.

                Possible mismatch between current in-memory boolean settings vs. permanent ones.

type=AVC msg=audit(1659372910.490:1275): avc:  denied  { setattr } for  pid=17520 comm="cpio" name="mtab" dev="dm-2" ino=14421957 scontext=staff_u:sysadm_r:sysadm_t tcontext=staff_u:object_r:unlabeled_t tclass=lnk_file permissive=1

        Was caused by:

                Unknown - would be allowed by active policy

                Possible mismatch between this policy and the one under which the audit message was generated.

                Possible mismatch between current in-memory boolean settings vs. permanent ones.
```

So maybe I need to enable some selinux bool

----------

## alamahant

Try  this

```

ausearch -m AVC | grep -E "fstab|mtab" | audit2allow  -a

```

What does it say?

What command did you try to run?As which user

Try 

```

id -Z

semanage login -m -s sysadm_u $USER

```

----------

## Fulgurance

I have that:

```
alienware-m17-r3 /home/zohran # ausearch -m AVC | grep -E "fstab|mtab" | audit2allow  -a

#============= staff_t ==============

allow staff_t etc_t:file watch;

allow staff_t initrc_exec_t:file execute;

#============= sysadm_t ==============

#!!!! This avc is allowed in the current policy

allow sysadm_t unlabeled_t:file { create open setattr write };

allow sysadm_t unlabeled_t:file { append unlink };

allow sysadm_t unlabeled_t:lnk_file { read unlink };

#!!!! This avc is allowed in the current policy

allow sysadm_t unlabeled_t:lnk_file { create setattr };

#============= xdm_t ==============

#!!!! This avc is allowed in the current policy

allow xdm_t etc_t:file watch;
```

But I'm in permissive mode actually. Do you need the result of this command in a enforcing mode ?

----------

## alamahant

```

But I'm in permissive mode actually. Do you need the result of this command in a enforcing mode ?

```

No its the same.Permissive records the denials but does not block.

Basically this is the problem

```

#============= staff_t ==============

allow staff_t etc_t:file watch;

allow staff_t initrc_exec_t:file execute;

```

So plz change to sysadm_u as mentioned above

```

id -Z

semanage login -m -s sysadm_u $USER

```

Ie you have to map your linux user to the top privileged selinux user.

----------

## Fulgurance

So now my user is privileged:

```
zohran@alienware-m17-r3 ~ $ id -Z

sysadm_u:sysadm_r:sysadm_t
```

But I have again the error "ln: failed to create the symbolic link /etc/mtab: permission denied" (boot time) and mount & umount command for tmp failed again (boot time as well)

As well, something else very strange, when I run the enforcing mode and I login in my account, when I try to run sudo su, I have an error saying my account is not in the sudoers file, but I don't have this error without the enforcing mode.

The result I have now with the same command (if you need):

```
alienware-m17-r3 /home/zohran # ausearch -m AVC | grep -E "fstab|mtab" | audit2allow  -a

#============= staff_t ==============

allow staff_t etc_t:file watch;

allow staff_t initrc_exec_t:file execute;

#============= sysadm_t ==============

allow sysadm_t etc_t:file watch;

allow sysadm_t unlabeled_t:file { append unlink };

#!!!! This avc is allowed in the current policy

allow sysadm_t unlabeled_t:file { create setattr };

allow sysadm_t unlabeled_t:lnk_file { read unlink };

#!!!! This avc is allowed in the current policy

allow sysadm_t unlabeled_t:lnk_file { create setattr };
```

Actually, because I followed the instructions about selinux with Gentoo, I have one file /etc/sudoers.d/wheel, and inside it's like that:

```
%wheel ALL=(ALL) TYPE=sysadm_t ROLE=sysadm_r ALL
```

I didn't change my /etc/sudoers.

----------

## alamahant

Plz see

https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/selinux_users_and_administrators_guide/sect-security-enhanced_linux-targeted_policy-confined_and_unconfined_users

about sudo and su.

Also see about

unconfined_u

Maybe your root should be unconfined.

Then plz read the whole selinux content

https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/selinux_users_and_administrators_guide/part_i-selinux

Ah by the way

```

But I have again the error "ln: failed to create the symbolic link /etc/mtab: permission denied" (boot time) and mount & umount command for tmp failed again (boot time as well)

```

i see.your problem is during boot.Not when you as a user try to run a command.My mistake.

Then jist write a policy for

```

#============= staff_t ==============

allow staff_t etc_t:file watch;

allow staff_t initrc_exec_t:file execute;

```

Try creating mtabslink.te filr containing

```

policy_module(mtabslink, 1.0)

gen_require(`

  type staff_t;

  type etc_t;

  type initrc_exec_t:

')

#============= staff_t ==============

allow staff_t etc_t:file watch;

allow staff_t initrc_exec_t:file execute;

```

Then

```

make -f /usr/share/selinux/strict/include/Makefile mtabslink.pp

semodule -i mtabslink.pp

```

See

https://wiki.gentoo.org/wiki/SELinux/Tutorials/Creating_your_own_policy_module_file#The_structure_of_a_SELinux_policy_module

But to be honest with you if the init process can not create a symlink during boot then something is really really wrong with your selinux policy.

----------

## Fulgurance

I will try all of that , I will come back if I have questions. Do you think I have to emerge again some selinux ebuild if it’s like that ? Or maybe it’s like that because I use a testing Gentoo ?

I think I found a starting point with this:

```
Login Name                SELinux User             

__default__               user_u                   

root                      root                     

zohran                    sysadm_u
```

Because I think maybe root need to be unconfined.

EDIT: I tried with the root account unconfined, but the same problem. I will study a little bit the red hat documentation. It's very interesting

But just one question, if something don't work at boot time because of denied permission, is it because of a wrong configuration of the root account ? And is it possible some boot process are not allowed because of a selinux bool disabled ?

I have that actually :

```
alienware-m17-r3 /home/zohran # getsebool -a

allow_execheap --> off

allow_execmem --> off

allow_execmod --> off

allow_execstack --> off

allow_httpd_anon_write --> off

allow_httpd_git_script_anon_write --> off

allow_httpd_mod_auth_pam --> off

allow_httpd_squid_script_anon_write --> off

allow_httpd_sys_script_anon_write --> off

allow_httpd_user_script_anon_write --> off

allow_java_execstack --> off

allow_kerberos --> off

allow_mount_anyfile --> off

allow_polyinstantiation --> off

allow_ptrace --> off

allow_raw_memory_access --> off

allow_rsync_anon_write --> off

allow_ssh_keysign --> off

allow_user_mysql_connect --> off

allow_user_postgresql_connect --> off

allow_write_xshm --> off

allow_ypbind --> off

authlogin_nsswitch_use_ldap --> off

authlogin_pam --> on

chronyd_hwtimestamp --> off

console_login --> on

cron_can_relabel --> off

cron_manage_all_user_content --> off

cron_manage_generic_user_content --> off

cron_read_all_user_content --> off

cron_read_generic_user_content --> on

cron_userdomain_transition --> off

dbus_broker_run_transient_units --> off

dbus_broker_system_bus --> off

dbus_pass_tuntap_fd --> off

dhcpc_manage_samba --> off

fcron_crond --> off

git_cgi_enable_homedirs --> off

git_cgi_use_cifs --> off

git_cgi_use_nfs --> off

git_client_manage_all_user_home_content --> off

git_session_bind_all_unreserved_ports --> off

git_session_send_syslog_msg --> off

git_session_users --> off

git_system_enable_homedirs --> off

git_system_use_cifs --> off

git_system_use_nfs --> off

global_ssp --> off

gpg_agent_env_file --> off

gpg_agent_use_card --> off

gpg_manage_all_user_content --> off

gpg_manage_generic_user_content --> off

gpg_read_all_user_content --> off

gpg_read_generic_user_content --> on

hiawatha_httpd --> off

httpd_builtin_scripting --> off

httpd_can_check_spam --> off

httpd_can_network_connect --> off

httpd_can_network_connect_cobbler --> off

httpd_can_network_connect_db --> off

httpd_can_network_connect_ldap --> off

httpd_can_network_connect_memcache --> off

httpd_can_network_connect_zabbix --> off

httpd_can_network_relay --> off

httpd_can_sendmail --> off

httpd_dbus_avahi --> off

httpd_enable_cgi --> off

httpd_enable_ftp_server --> off

httpd_enable_homedirs --> off

httpd_execmem --> off

httpd_gpg_anon_write --> off

httpd_graceful_shutdown --> off

httpd_manage_ipa --> off

httpd_mod_auth_ntlm_winbind --> off

httpd_read_user_content --> off

httpd_setrlimit --> off

httpd_ssi_exec --> off

httpd_tmp_exec --> off

httpd_tty_comm --> off

httpd_unified --> off

httpd_use_cifs --> off

httpd_use_fusefs --> off

httpd_use_gpg --> off

httpd_use_nfs --> off

init_daemons_use_tty --> off

init_mounton_non_security --> off

init_upstart --> off

java_manage_all_user_content --> off

java_manage_generic_user_content --> off

java_read_all_user_content --> off

java_read_generic_user_content --> on

mail_read_content --> off

mmap_low_allowed --> off

mozilla_bind_all_unreserved_ports --> off

mozilla_execstack --> off

mozilla_manage_all_user_content --> off

mozilla_manage_generic_user_content --> off

mozilla_plugin_connect_all_unreserved --> off

mozilla_read_all_user_content --> off

mozilla_read_generic_user_content --> on

nfs_export_all_ro --> off

nfs_export_all_rw --> off

nscd_use_shm --> off

openvpn_can_network_connect --> off

openvpn_enable_homedirs --> off

portage_enable_test --> off

portage_mount_fs --> off

portage_read_user_content --> off

portage_use_nfs --> off

pulseaudio_execmem --> off

rsync_client --> off

rsync_export_all_ro --> off

rsync_use_cifs --> off

rsync_use_fusefs --> off

rsync_use_nfs --> off

secure_mode --> off

secure_mode_insmod --> off

secure_mode_policyload --> off

secure_mode_setbool --> off

sepgsql_enable_users_ddl --> off

sepgsql_transmit_client_label --> off

sepgsql_unconfined_dbadm --> off

shutdown_allow_user_exec_domains --> off

squid_connect_any --> off

squid_use_pinger --> on

squid_use_tproxy --> off

ssh_sysadm_login --> off

ssh_use_gpg_agent --> off

su_allow_user_exec_domains --> off

sudo_all_tcp_connect_http_port --> off

sudo_allow_user_exec_domains --> off

sysadm_allow_rw_inherited_fifo --> off

systemd_logind_get_bootloader --> off

systemd_networkd_dhcp_server --> off

systemd_nspawn_labeled_namespace --> off

systemd_socket_proxyd_bind_any --> off

systemd_socket_proxyd_connect_any --> off

systemd_tmpfiles_manage_all --> off

tmpfiles_manage_all_non_security --> on

use_lpd_server --> off

use_nfs_home_dirs --> off

use_samba_home_dirs --> off

user_direct_mouse --> off

user_dmesg --> off

user_exec_noexattrfile --> off

user_ping --> off

user_rw_noexattrfile --> off

user_tcp_server --> off

user_ttyfile_stat --> off

user_udp_server --> off

user_write_removable --> off

wireshark_manage_all_user_content --> off

wireshark_manage_generic_user_content --> off

wireshark_read_all_user_content --> off

wireshark_read_generic_user_content --> on

xdm_sysadm_login --> off

xserver_allow_dri --> off

xserver_gnome_xdm --> off

xserver_object_manager --> off
```

----------

