Gentoo Websites Logo
Go to: Gentoo Home Documentation Forums Lists Bugs Planet Store Wiki Get Gentoo!
Bug 615270 - sec-policy/selinux-base-policy-2.20170204-r2: 'Failed to execute postinst' due to bridge_socket class dependency issue
Summary: sec-policy/selinux-base-policy-2.20170204-r2: 'Failed to execute postinst' du...
Status: RESOLVED FIXED
Alias: None
Product: Gentoo Linux
Classification: Unclassified
Component: SELinux (show other bugs)
Hardware: AMD64 Linux
: Normal normal (vote)
Assignee: Sven Vermeulen (RETIRED)
URL:
Whiteboard:
Keywords:
Depends on:
Blocks:
 
Reported: 2017-04-11 15:04 UTC by Mircea Sava
Modified: 2018-03-25 12:28 UTC (History)
3 users (show)

See Also:
Package list:
Runtime testing required: ---


Attachments
console update log - method 1 (update_method_1.txt.gz,19.81 KB, application/gzip)
2017-04-21 16:32 UTC, Alexander Wetzel
Details
console update log - method 2 (update_method_2.txt.gz,22.55 KB, application/gzip)
2017-04-21 16:32 UTC, Alexander Wetzel
Details

Note You need to log in before you can comment on or make changes to this bug.
Description Mircea Sava 2017-04-11 15:04:57 UTC
Package installs but fails in post installation phase.

Reproducible: Always

Steps to Reproduce:
1. emerge -u
2.
3.
Actual Results:  
 * Error messages for package sec-policy/selinux-base-policy-2.20170204-r2:

 * FAILED postinst: 1
 * ERROR: sec-policy/selinux-base-policy-2.20170204-r2::gentoo failed (postinst phase):
 *   Failed to load in base and modules application authlogin bootloader clock consoletype cron dmesg fstools getty hostname hotplug init iptables libraries locallogin logging lvm miscfiles modutils mount mta netutils nscd portage raid rsync selinuxutil setrans ssh staff storage su sysadm sysnetwork tmpfiles udev userdomain usermanage unprivuser xdg in the targeted policy store
 * 
 * Call stack:
 *     ebuild.sh, line 115:  Called pkg_postinst
 *   environment, line 395:  Called die
 * The specific snippet of code:
 *           semodule -s ${i} ${COMMAND} || die "Failed to load in base and modules ${MODS} in the $i policy store";


Portage 2.3.3 (python 2.7.12-final-0, hardened/linux/amd64/selinux, gcc-4.9.4, glibc-2.23-r3, 4.8.17-hardened-r2-gnu x86_64)
=================================================================
                         System Settings
=================================================================
System uname: Linux-4.8.17-hardened-r2-gnu-x86_64-Intel-R-_Core-TM-_i3-3110M_CPU_@_2.40GHz-with-gentoo-2.3
KiB Mem:    16296820 total,   4369288 free
KiB Swap:    2097148 total,   2096952 free
Timestamp of repository gentoo: Tue, 11 Apr 2017 00:45:01 +0000
sh bash 4.3_p48-r1
ld GNU ld (Gentoo 2.26.1 p1.0) 2.26.1
app-shells/bash:          4.3_p48-r1::gentoo
dev-java/java-config:     2.2.0-r3::gentoo
dev-lang/perl:            5.22.3_rc4::gentoo
dev-lang/python:          2.7.12::gentoo, 3.4.5::gentoo
dev-util/cmake:           3.7.2::gentoo
dev-util/pkgconfig:       0.28-r2::gentoo
sys-apps/baselayout:      2.3::gentoo
sys-apps/openrc:          0.23.2::gentoo
sys-apps/sandbox:         2.10-r3::gentoo
sys-devel/autoconf:       2.13::gentoo, 2.69::gentoo
sys-devel/automake:       1.11.6-r1::gentoo, 1.13.4::gentoo, 1.15::gentoo
sys-devel/binutils:       2.26.1::gentoo
sys-devel/gcc:            4.9.4::gentoo
sys-devel/gcc-config:     1.7.3::gentoo
sys-devel/libtool:        2.4.6-r3::gentoo
sys-devel/make:           4.2.1::gentoo
sys-kernel/linux-headers: 4.4::gentoo (virtual/os-headers)
sys-libs/glibc:           2.23-r3::gentoo
Repositories:

gentoo
    location: /usr/portage
    sync-type: webrsync
    sync-uri: rsync://rsync.gentoo.org/gentoo-portage
    priority: -1000

local
    location: /usr/local/portage
    masters: gentoo

ACCEPT_KEYWORDS="amd64"
ACCEPT_LICENSE="@FREE"
CBUILD="x86_64-pc-linux-gnu"
CFLAGS="-march=core-avx-i -O2 -pipe"
CHOST="x86_64-pc-linux-gnu"
CONFIG_PROTECT="/etc /etc/stunnel/stunnel.conf /usr/lib64/libreoffice/program/sofficerc /usr/share/config /usr/share/easy-rsa /usr/share/gnupg/qualified.txt /var/bind"
CONFIG_PROTECT_MASK="/etc/ca-certificates.conf /etc/dconf /etc/env.d /etc/fonts/fonts.conf /etc/gconf /etc/gentoo-release /etc/php/apache2-php7.0/ext-active/ /etc/php/cgi-php7.0/ext-active/ /etc/php/cli-php7.0/ext-active/ /etc/revdep-rebuild /etc/sandbox.d /etc/terminfo /etc/texmf/language.dat.d /etc/texmf/language.def.d /etc/texmf/updmap.d /etc/texmf/web2c"
CXXFLAGS="-march=core-avx-i -O2 -pipe"
DISTDIR="/usr/portage/distfiles"
FCFLAGS="-O2 -pipe"
FEATURES="assume-digests binpkg-logs config-protect-if-modified distlocks ebuild-locks fixlafiles merge-sync news parallel-fetch preserve-libs protect-owned sandbox selinux sesandbox sfperms strict unknown-features-warn unmerge-logs unmerge-orphans userfetch userpriv usersandbox usersync webrsync-gpg xattr"
FFLAGS="-O2 -pipe"
GENTOO_MIRRORS="ftp://ftp.swin.edu.au/gentoo ftp://gd.tuwien.ac.at/opsys/linux/gentoo/ rsync://gentoo.c3sl.ufpr.br/gentoo/ ftp://gentoo.c3sl.ufpr.br/gentoo/ ftp://ftp.las.ic.unicamp.br/pub/gentoo/ rsync://gentoo.gossamerhost.com/gentoo-distfiles/ ftp://mirrors.tera-byte.com/pub/gentoo rsync://mirrors.tera-byte.com/gentoo ftp://mirror.csclub.uwaterloo.ca/gentoo-distfiles/ rsync://ftp6.linux.cz/pub/linux/gentoo/ rsync://ftp.fi.muni.cz/pub/linux/gentoo/ ftp://ftp.fi.muni.cz/pub/linux/gentoo/ rsync://mirror.dkm.cz/gentoo/ ftp://mirror.dkm.cz/gentoo/ ftp://gentoo.mirror.web4u.cz/ rsync://trumpetti.atm.tut.fi/gentoo/ ftp://trumpetti.atm.tut.fi/gentoo/ rsync://mirror.eu.oneandone.net/gentoo/ ftp://ftp.wh2.tu-dresden.de/pub/mirrors/gentoo ftp://mirror.netcologne.de/gentoo/ rsync://mirror.netcologne.de/gentoo/ ftp://ftp.halifax.rwth-aachen.de/gentoo/ rsync://ftp.halifax.rwth-aachen.de/gentoo/ ftp://sunsite.informatik.rwth-aachen.de/pub/Linux/gentoo ftp://ftp.uni-erlangen.de/pub/mirrors/gentoo ftp://ftp-stud.hs-esslingen.de/pub/Mirrors/gentoo/ rsync://ftp-stud.hs-esslingen.de/gentoo/ ftp://ftp.heanet.ie/pub/gentoo/ rsync://ftp.heanet.ie/pub/gentoo/ ftp://mirror.isoc.org.il/gentoo/ rsync://ftp.iij.ad.jp/pub/linux/gentoo/ ftp://ftp.iij.ad.jp/pub/linux/gentoo/ rsync://ftp.jaist.ac.jp/pub/Linux/Gentoo/ ftp://ftp.jaist.ac.jp/pub/Linux/Gentoo/ rsync://mirror.leaseweb.com/gentoo/ ftp://mirror.leaseweb.com/gentoo/ ftp://ftp.snt.utwente.nl/pub/os/linux/gentoo rsync://ftp.snt.utwente.nl/gentoo rsync://gentoo.prz.rzeszow.pl/gentoo rsync://ftp.vectranet.pl/gentoo/ ftp://ftp.vectranet.pl/gentoo/ ftp://ftp.rnl.tecnico.ulisboa.pt/pub/gentoo/gentoo-distfiles/ rsync://ftp.rnl.tecnico.ulisboa.pt/pub/gentoo/gentoo-distfiles/ ftp://ftp.dei.uc.pt/pub/linux/gentoo/ ftp://mirror.mdfnet.se/gentoo ftp://mirror.switch.ch/mirror/gentoo/ ftp://mirror.bytemark.co.uk/gentoo/ rsync://mirror.bytemark.co.uk/gentoo/ ftp://ftp.mirrorservice.org/sites/distfiles.gentoo.org/ rsync://rsync.mirrorservice.org/distfiles.gentoo.org/ rsync://rsync.gtlib.gatech.edu/gentoo ftp://ftp.gtlib.gatech.edu/pub/gentoo ftp://ftp.ussg.iu.edu/pub/linux/gentoo ftp://lug.mtu.edu/gentoo/ ftp://gentoo.netnitco.net/pub/mirrors/gentoo/source/ ftp://gentoo.mirrors.pair.com/ rsync://mirrors.rit.edu/gentoo/ ftp://mirrors.rit.edu/gentoo/ ftp://mirror.iawnet.sandia.gov/pub/gentoo/ ftp://cosmos.illinois.edu/pub/gentoo/ rsync://gentoo.cs.uni.edu/gentoo-distfiles"
LANG="en_US.UTF8"
LDFLAGS="-Wl,-O1 -Wl,--as-needed"
MAKEOPTS="-j5 -l4"
PKGDIR="/usr/portage/packages"
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"
USE="X a52 aac aalib acl acpi alsa amd64 audiofile audit avahi bash-completion berkdb bindist blas bluetooth branding bzip2 cairo cdda cddb cdparanoia cdr clamav cli consolekit cracklib crypt css cups curl cxx dbus djvu dri dts dv dvd dvdr emboss encode exif fam fbcon ffmpeg fftw firefox flac fontconfig gdbm geoip geolocation gif gimp git gnuplot gphoto2 gpm gps graphviz gsl gstreamer hardened hddtemp hdf5 iconv icu imlib inotify ipv6 jack jbig jemalloc jpeg jpeg2k justify kde kerberos kolab kontact ladspa lapack lash latex lcms ldap libnotify libsamplerate lm_sensors lua lzma mad matroska memcached memlimit mime mms mng modplug modules mozilla mp3 mp4 mpeg mpi mplayer mtp multilib musepack musicbrainz mysql mysqli ncurses netcdf networkmanager nls nptl offensive ofx ogg open_perms openexr opengl openmp pam pax_kernel pcre pdf php pie plasma plotutils png policykit posix postgres postscript ppds python qml qt5 quicktime raw readline rss samba sasl scanner sctp sdl seccomp selinux semantic-desktop session smartcard smp sndfile snmp sockets socks5 sound sox speex spell sqlite ssl ssp startup-notification svg sybase syslog szip taglib tcl tcpd theora threads tiff tk tools truetype udev udisks unconfined unicode upower urandom usb utils v4l vaapi vcd vdpau vhosts vnc vorbis wavpack wayland webp wifi wmf wxwidgets x264 xattr xcb xcomposite xface xml xmlrpc xmp xmpp xpm xtpax xv xvid yaz zeroconf zlib" ABI_X86="64" ALSA_CARDS="hda-intel" 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="kexi words flow plan sheets stage tables krita karbon braindump author" CAMERAS="ptp2" COLLECTD_PLUGINS="df interface irq load memory rrdtool swap syslog" CPU_FLAGS_X86="avx mmx mmxext popcnt sse sse2 sse3 sse4_1 sse4_2 ssse3" ELIBC="glibc" GPSD_PROTOCOLS="ashtech aivdm earthmate evermore fv18 garmin garmintxt gpsclock isync itrax mtk3301 nmea ntrip navcom oceanserver oldstyle oncore rtcm104v2 rtcm104v3 sirf skytraq superstar2 timing tsip tripmate tnt ublox ubx" INPUT_DEVICES="evdev synaptics" KERNEL="linux" L10N="en en-US" LCD_DEVICES="bayrad cfontz cfontz633 glk hd44780 lb216 lcdm001 mtxorb ncurses text" LIBREOFFICE_EXTENSIONS="presenter-console presenter-minimizer" LINGUAS="en en_US" LLVM_TARGETS="X86" NGINX_MODULES_HTTP="access auth_basic auth_pam autoindex browser cache_purge charset empty_gif fancyindex fastcgi geo gzip limit_conn limit_req map memcached metrics proxy realip referer rewrite scgi secure_link security split_clients ssi stub_status upload_progress upstream_check upstream_ip_hash userid uwsgi xslt" NGINX_MODULES_MAIL="imap pop3 smtp" OFFICE_IMPLEMENTATION="libreoffice" PHP_TARGETS="php5-6" PYTHON_SINGLE_TARGET="python2_7" PYTHON_TARGETS="python2_7 python3_4" QEMU_SOFTMMU_TARGETS="aarch64 arm ppc64 x86_64" QEMU_USER_TARGETS="x86_64" RUBY_TARGETS="ruby21" SANE_BACKENDS="hp" USERLAND="GNU" VIDEO_CARDS="intel i965" XTABLES_ADDONS="quota2 psd pknock lscan length2 ipv4options ipset ipp2p iface geoip fuzzy condition tee tarpit sysrq steal rawnat logmark ipmark dhcpmac delude chaos account"
Unset:  CC, CPPFLAGS, CTARGET, CXX, EMERGE_DEFAULT_OPTS, INSTALL_MASK, LC_ALL, PORTAGE_BUNZIP2_COMMAND, PORTAGE_COMPRESS, PORTAGE_COMPRESS_FLAGS, PORTAGE_RSYNC_EXTRA_OPTS, USE_PYTHON

=================================================================
                        Package Settings
=================================================================

sec-policy/selinux-base-policy-2.20170204-r2::gentoo was built with the following:
USE="unconfined (-systemd)" ABI_X86="64"
Comment 1 Sven Vermeulen (RETIRED) gentoo-dev 2017-04-11 17:15:53 UTC
Hi Mircea,

Can you go towards /usr/share/selinux/targeted and run the following command:

~# semodule -i *.pp

This should try to load all built policy module files. It will probably fail again, but give an error message that might be more descriptive than the one we have here right now.
Comment 2 Mircea Sava 2017-04-11 17:52:39 UTC
It returns the following:

Failed to resolve typeattributeset statement at /var/lib/selinux/targeted/tmp/modules/400/apache/cil:350
semodule:  Failed!
Comment 3 Sven Vermeulen (RETIRED) gentoo-dev 2017-04-11 17:57:29 UTC
Can you check if all .pp files in the previously mentioned directory are all built around the same time? There might be a SELinux policy module not being updated. It doesn't necessarily mean that the apache.pp one is the culprit (it can be a dependency), and the file mentioned in the error message is cleaned up before we can take a look :-(

To see:

~# ls -ltr *.pp | head
Comment 4 Mircea Sava 2017-04-11 18:05:12 UTC
-rw-r--r--. 1 root root  328846 Apr 11 13:37 base.pp
-rw-r--r--. 1 root root  120889 Apr 11 13:38 dbus.pp
-rw-r--r--. 1 root root  207094 Apr 11 13:40 kerberos.pp
-rw-r--r--. 1 root root   79793 Apr 11 13:40 gpm.pp
-rw-r--r--. 1 root root  109186 Apr 11 13:41 ldap.pp
-rw-r--r--. 1 root root  144187 Apr 11 13:41 sasl.pp
-rw-r--r--. 1 root root  223788 Apr 11 13:42 postgresql.pp
-rw-r--r--. 1 root root  167216 Apr 11 13:42 lpd.pp
-rw-r--r--. 1 root root  109431 Apr 11 13:43 avahi.pp
-rw-r--r--. 1 root root  246347 Apr 11 13:43 policykit.pp
Comment 5 Sven Vermeulen (RETIRED) gentoo-dev 2017-04-11 18:27:02 UTC
OK, so no outdated modules. I've installed sec-policy/selinux-apache-2.20170204-r2 myself without problem. Let's see if the CIL file you already have on the system can help us.

Can you check /var/lib/selinux/targeted/active/modules/400/apache/cil around line 350? Not just that line, also the lines before and after that (because the current CIL file is not the one that fails, let's just hope the policy hasn't changed too much).

On my system, the CIL file (which is for the loadable -r2) has the following lines (middle one is line 350):

(typeattributeset cil_gen_require user_devpts_t)
(typeattributeset cil_gen_require fusefs_t)
(typeattributeset cil_gen_require nfsd_rw_t)
(typeattributeset cil_gen_require nfsd_ro_t)
(typeattributeset cil_gen_require ld_so_t)

Here, it might be a bad dependency on nfs related types (I do have NFS active, can't disable it for testing). However, I don't immediately see a wrong entry regarding its dependencies.

But let's not get ahead of ourselves first, let's see what the CIL file is at your system.

If it is similar (NFS requirement), can you run "getsebool -a | grep nfs" and give the output?
Comment 6 Mircea Sava 2017-04-11 18:47:06 UTC
I apparently don't have a 'cil' file, or even an 'apache' directory under '/var/lib/selinux/targeted/tmp/modules/400', which I find strange since sec-policy/selinux-apache is installed and up-to-date.

There is also the following warning in the package elog which is also present in sec-policy/selinux-alsa, sec-policy/selinux-bind, sec-policy/selinux-chromium, sec-policy/selinux-dbus, sec-policy/selinux-devicekit, 
sec-policy/selinux-fail2ban, sec-policy/selinux-java, sec-policy/selinux-logrotate, sec-policy/selinux-lpd, sec-policy/selinux-mozilla, sec-policy/selinux-mplayer, sec-policy/selinux-networkmanager, sec-policy/selinux-policykit, sec-policy/selinux-qemu, sec-policy/selinux-shutdown, sec-policy/selinux-slocate, sec-policy/selinux-sysstat, sec-policy/selinux-thunderbird, sec-policy/selinux-unconfined, sec-policy/selinux-virt, and sec-policy/selinux-xserver:

WARN: postinst
SELinux module load failed. Trying full reload...
Failed to reload SELinux policies.

If this is *not* the last SELinux module package being installed,
then you can safely ignore this as the reloads will be retried
with other, recent modules.

If it is the last SELinux module package being installed however,
then it is advised to look at the error above and take appropriate
action since the new SELinux policies are not loaded until the
command finished succesfully.

To reload, run the following command from within /usr/share/selinux/targeted:
  semodule -i base.pp -i $(ls *.pp | grep -v base.pp)
or
  semodule -i base.pp -i $(ls *.pp | grep -v base.pp | grep -v unconfined.pp)
depending on if you need the unconfined domain loaded as well or not.
Comment 7 Sven Vermeulen (RETIRED) gentoo-dev 2017-04-11 18:58:22 UTC
It is to be expected that you can't find anything in the mentioned .../tmp/ directory, as that directory is cleaned up (sadly, upstream hasn't enabled an option to not clean it up after failure).

Check in /var/lib/selinux/targeted/active/modules/400/apache/ for a "cil" file.

The warnings with the other ebuilds is also to be expected: as long as even the base module can't be loaded, none of the other modules can and the active SELinux policy will remain the "old" policy.
Comment 8 Mircea Sava 2017-04-11 19:08:13 UTC
This is the 348-352 line range in my '/var/lib/selinux/targeted/active/modules/400/apache/cil' file:

(typeattributeset cil_gen_require daemonpidfile)
(typeattributeset daemonpidfile (httpd_var_run_t ))
(allow httpd_t httpd_exec_t (file (entrypoint)))
(allow httpd_t httpd_exec_t (file (ioctl read getattr lock execute open)))
(allow initrc_t httpd_exec_t (file (read getattr execute open)))
Comment 9 Alexander Wetzel 2017-04-14 22:38:53 UTC
> Failed to resolve typeattributeset statement at
> /var/lib/selinux/targeted/tmp/modules/400/apache/cil:350
> semodule:  Failed!

I just opened a bug for that: Bug 615552 (Did not see it was mentioned in this one) But I'm pretty sure that is unrelated to this bug. You can get rid of the error by installing sec-policy/selinux-rpc.
Comment 10 Mircea Sava 2017-04-15 15:42:40 UTC
Indeed, installing sec-policy/selinux-rpc solves the issue and further re-emerging of sec-policy/selinux-base-policy worked without error.
Thank you!
Comment 11 Alexander Wetzel 2017-04-16 15:44:31 UTC
This got a bit long, so let's start with my conclusion: There seems to be some kind of circular dependency between sec-policy/selinux-base-policy and at least one more policy (selinux-apm for me). 
This is quite critical, since it can render a system unusable and - since relabeling will not work till sec-policy/selinux-base-policy is installed again - tricky to fix. 

For me selinux-base-policy seems to needs something (not identified) from sec-policy/selinux-apm and vice versa. 
The trick is, installing selinux-base-policy again after the problematic other selinux module.

The best procedure to update my (cloned test) system is:
1) emerge -1av sec-policy/selinux-apm
--> will also update sec-policy/selinux-base and sec-policy/selinux-base-policy and only then update sec-policy/selinux-apm
This causes the "normal" postinst errors for sec-policy/selinux-base-policy, but does not break existing lables. (Calling rlpkg or restorecon now WILL break the labeles. I assume that is exactly what one of the other selinux update scripts do during a normal update.)

2) Calling "emerge -1av sec-policy/selinux-base-policy"
--> This will now work without postinst error and make it save again to use restorecon/setfile/rlpkg.

3) Start the normal update

If that does not work a more generic procedure catching comparable errors in other modules would be to just reinstall sec-policy/selinux-base-policy and call "rlpkg -a -r"


Here the longer bug report, which lead to the conclusion above:

I'm also affected from the issue outlined in the initial bug report message here ("Failed to execute postinst"). When updating to the new stable selinux policy this issue seems to have rendered multiple of my systems unusable when booted without fixing the postinstall error first, as long as enforcing was enabled. But not all of my seven (very similar) systems were affected, so there is probably another unknown factor required (One idea would be the install order.)

The exact error varies, but I was not able to logon to any system affected by the bug via ssh or console, even if they were not restarted. In one case lvm startup was hanging forever, in other cases /bin/bash could not be executed. All these errors could be tracked down to wrong selinux file types. I've found several files with the wrong type set during debugging, but I focused on the worst one: /sbin/init was set to bin_t instead of init_exec_t.

Now the REALLY curious think here is, that once your system is affected by the problem restorecon and "rlpkg -a -r" won't help, in fact they will set init back to bin_t if fixed with chcon manually. But semanage fcontext -l" and also /etc/selinux/strict/contexts/files/file_contexts were still correct:
 /sbin/init(ng)? --      system_u:object_r:init_exec_t

Here an outline how a normal update will work and can be fixed:
1) Update all selinux policy packages to 2.20170204-r2 (I started from 2.20161023-r3)
--> sec-policy/selinux-base-policy fails in the install phase, but installation continues with other selinux packages.

2) After emerge is done "ls -lZ /sbin/init" shows bin_t instead of init_exec_t. Calling restorecon or rlpkg is NOT fixing the wrong label. "semodule fcontext -l" HAS the correct file/label mapping.
--> The system is damaged at this time. E.g. new login attempts and even a calling "shutdown -r now" may fail due to wrong file labels.

3) "emerge -1v sec-policy/selinux-base-policy" works on the second attempt but won't fix the broken labels

4) Calling "rlpkg -a -r" now works and is able to fix the labeling errors
--> System is now again in an usable state

I have btrfs snapshots and can reproduce the issue at will. If you need additional data I can provide basically anything with little efforts.

Here some debug data from the first (failing postinst) emerge of selinux-base-policy:

First, I aborted the emerge install attempt of sec-policy/selinux-base-policy during the normal update prior to the merge and can now reproduce the issue with ebuild. ebuilt install is still fine, calling ebuild qmerge throws the postinst error. At this stage I can reinstall the package as often as I want, I always get the same error message. NOTE: After a "normal update" you can't see this error. It's only visible prior to updating selinux-apm. For that reason I belive the orignal reporter was affected by the same or a very similar issue and the apache module error a distraction.)
Here the error message:

>>> Regenerating /etc/ld.so.cache...
>>> Original instance of package unmerged safely.
 * Inserting the following modules, with base, into the strict module store: application authlogin bootloader clock consoletype cron dmesg fstools getty hostname hotplug init iptables libraries locallogin logging lvm miscfiles modutils mount mta netutils nscd portage raid rsync selinuxutil setrans ssh staff storage su sysadm sysnetwork tmpfiles udev userdomain usermanage unprivuser xdg
Failed to resolve dontaudit statement at /var/lib/selinux/strict/tmp/modules/400/apm/cil:339
semodule:  Failed!
 * ERROR: sec-policy/selinux-base-policy-2.20170204-r2::gentoo failed (postinst phase):
 *   Failed to load in base and modules application authlogin bootloader clock consoletype cron dmesg fstools getty hostname hotplug init iptables libraries locallogin logging lvm miscfiles modutils mount mta netutils nscd portage raid rsync selinuxutil setrans ssh staff storage su sysadm sysnetwork tmpfiles udev userdomain usermanage unprivuser xdg in the strict policy store
 * 
 * Call stack:
 *     ebuild.sh, line 115:  Called pkg_postinst
 *   environment, line 319:  Called die
 * The specific snippet of code:
 *           semodule -s ${i} ${COMMAND} || die "Failed to load in base and modules ${MODS} in the $i policy store";
 * 
 * If you need support, post the output of `emerge --info '=sec-policy/selinux-base-policy-2.20170204-r2::gentoo'`,
 * the complete build log and the output of `emerge -pqv '=sec-policy/selinux-base-policy-2.20170204-r2::gentoo'`.
 * The complete build log is located at '/var/tmp/portage/sec-policy/selinux-base-policy-2.20170204-r2/temp/build.log'.
 * The ebuild environment file is located at '/var/tmp/portage/sec-policy/selinux-base-policy-2.20170204-r2/temp/environment'.
 * Working directory: '/usr/share/selinux/strict'
 * S: '/var/tmp/portage/sec-policy/selinux-base-policy-2.20170204-r2/work/'
 * FAILED postinst: 1

With "/usr/libexec/selinux/hll/pp /usr/share/selinux/strict/apm.pp >/tmp/cli" line 339 from /var/lib/selinux/strict/tmp/modules/400/apm/cil we can get the problematic line 339 (hopefully):
(dontaudit apmd_t domain (bridge_socket (getattr)))

Calling "cd /usr/share/selinux/strict/; semodule -i *.pp" gets us:
Failed to resolve dontaudit statement at /var/lib/selinux/strict/tmp/modules/400/apm/cil:339
semodule:  Failed!

(Again, that that will only show the error if selinux-apm was not updated, yet. Which probably only happens during debuging...)

Using "emerge -1av sec-policy/selinux-apm" to update selinux-apm out-of-emerge-order gets rid of the error message above and also allows us to merge selinux-base-policy with ebuild now... And now relabeling is again working correctly.

Here a emerge --info after the "postinst error, prior to fixing anything:

# emerge --info '=sec-policy/selinux-base-policy-2.20170204-r2::gentoo'
Portage 2.3.3 (python 2.7.12-final-0, hardened/linux/amd64/selinux, gcc-4.9.4, glibc-2.23-r3, 4.8.17-hardened-r2 x86_64)
=================================================================
                         System Settings
=================================================================
System uname: Linux-4.8.17-hardened-r2-x86_64-Intel_Core_Processor_-Haswell,_no_TSX-with-gentoo-2.3
KiB Mem:     2049516 total,   1647812 free
KiB Swap:    1951740 total,   1951740 free
Timestamp of repository gentoo: Thu, 13 Apr 2017 17:30:01 +0000
sh bash 4.3_p48-r1
ld GNU ld (Gentoo 2.26.1 p1.0) 2.26.1
app-shells/bash:          4.3_p48-r1::gentoo
dev-lang/perl:            5.22.3_rc4::gentoo
dev-lang/python:          2.7.12::gentoo, 3.4.5::gentoo
dev-util/pkgconfig:       0.28-r2::gentoo
sys-apps/baselayout:      2.3::gentoo
sys-apps/openrc:          0.23.2::gentoo
sys-apps/sandbox:         2.10-r3::gentoo
sys-devel/autoconf:       2.69::gentoo
sys-devel/automake:       1.15::gentoo
sys-devel/binutils:       2.26.1::gentoo
sys-devel/gcc:            4.9.4::gentoo
sys-devel/gcc-config:     1.7.3::gentoo
sys-devel/libtool:        2.4.6-r3::gentoo
sys-devel/make:           4.2.1::gentoo
sys-kernel/linux-headers: 4.4::gentoo (virtual/os-headers)
sys-libs/glibc:           2.23-r3::gentoo
Repositories:

gentoo
    location: /usr/portage
    sync-type: rsync
    sync-uri: rsync://rsync.gentoo.org/gentoo-portage
    priority: -1000

ACCEPT_KEYWORDS="amd64"
ACCEPT_LICENSE="* -@EULA"
CBUILD="x86_64-pc-linux-gnu"
CFLAGS="-march=native -O2 -pipe"
CHOST="x86_64-pc-linux-gnu"
CONFIG_PROTECT="/etc /var/bind"
CONFIG_PROTECT_MASK="/etc/ca-certificates.conf /etc/env.d /etc/gconf /etc/gentoo-release /etc/revdep-rebuild /etc/sandbox.d /etc/terminfo"
CXXFLAGS="-march=native -O2 -pipe"
DISTDIR="/usr/portage/distfiles"
FCFLAGS="-O2 -pipe"
FEATURES="assume-digests binpkg-logs config-protect-if-modified distlocks ebuild-locks fixlafiles merge-sync news parallel-fetch preserve-libs protect-owned sandbox selinux sesandbox sfperms strict unknown-features-warn unmerge-logs unmerge-orphans userfetch userpriv usersandbox usersync xattr"
FFLAGS="-O2 -pipe"
GENTOO_MIRRORS="http://gentoo.mirrors.ovh.net/gentoo-distfiles/"
LANG="C"
LDFLAGS="-Wl,-O1 -Wl,--as-needed"
MAKEOPTS="-j2"
PKGDIR="/usr/portage/packages"
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"
USE="acl amd64 berkdb bzip2 cli cracklib crypt cxx dri gdbm hardened iconv ipv6 justify modules multilib ncurses nls nptl open_perms openmp pam pax_kernel pcre pie readline seccomp selinux session ssl ssp tcpd unconfined unicode urandom xattr xtpax zlib" ABI_X86="64" ALSA_CARDS="ali5451 als4000 atiixp atiixp-modem bt87x ca0106 cmipci emu10k1x ens1370 ens1371 es1938 es1968 fm801 hda-intel intel8x0 intel8x0m maestro3 trident usb-audio via82xx via82xx-modem ymfpci" 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="kexi words flow plan sheets stage tables krita karbon braindump author" COLLECTD_PLUGINS="df interface irq load memory rrdtool swap syslog" CPU_FLAGS_X86="mmx mmxext popcnt sse sse2 sse3 sse4_1 sse4_2 ssse3" ELIBC="glibc" GPSD_PROTOCOLS="ashtech aivdm earthmate evermore fv18 garmin garmintxt gpsclock isync itrax mtk3301 nmea ntrip navcom oceanserver oldstyle oncore rtcm104v2 rtcm104v3 sirf skytraq superstar2 timing tsip tripmate tnt ublox ubx" GRUB_PLATFORMS="pc" INPUT_DEVICES="libinput keyboard mouse" KERNEL="linux" LCD_DEVICES="bayrad cfontz cfontz633 glk hd44780 lb216 lcdm001 mtxorb ncurses text" LIBREOFFICE_EXTENSIONS="presenter-console presenter-minimizer" OFFICE_IMPLEMENTATION="libreoffice" PHP_TARGETS="php5-6" PYTHON_SINGLE_TARGET="python2_7" PYTHON_TARGETS="python2_7 python3_4" RUBY_TARGETS="ruby21" USERLAND="GNU" VIDEO_CARDS="amdgpu fbdev intel nouveau radeon radeonsi vesa dummy v4l" XTABLES_ADDONS="quota2 psd pknock lscan length2 ipv4options ipset ipp2p iface geoip fuzzy condition tee tarpit sysrq steal rawnat logmark ipmark dhcpmac delude chaos account"
USE_PYTHON="2.7"
Unset:  CC, CPPFLAGS, CTARGET, CXX, EMERGE_DEFAULT_OPTS, INSTALL_MASK, LC_ALL, PORTAGE_BUNZIP2_COMMAND, PORTAGE_COMPRESS, PORTAGE_COMPRESS_FLAGS, PORTAGE_RSYNC_EXTRA_OPTS

=================================================================
                        Package Settings
=================================================================

sec-policy/selinux-base-policy-2.20170204-r2::gentoo was built with the following:
USE="unconfined (-systemd)" ABI_X86="64"
Comment 12 Sven Vermeulen (RETIRED) gentoo-dev 2017-04-20 14:37:14 UTC
OK, I'll track the rpc dependency (and the fix for it) through bug #615552. With the domain identified, we should be able to drill down the area where we can mark this as an optional statement (so it doesn't fail).

The apm dependency, I'll try to handle this on this bug further.
Comment 13 Sven Vermeulen (RETIRED) gentoo-dev 2017-04-20 15:38:10 UTC
The issue with apm is different from the rpc one (as now handled through bug #615552). Here, one or more modules are declaring rules regarding unused sockets, such as the bridge_socket class.

Support for these (unused) classes was removed from the policy in the following upstream change:

https://www.spinics.net/lists/selinux/msg21217.html

For Gentoo, this indeed means that the postinstallation phases will fail. However, this *should* have resolved itself as follows:

- selinux-base builds fine, no policy load (no postinst)
- selinux-base-policy builds fine, but postinst fails to load modules
- selinux-* builds fine, but postinst fails to load modules
- last selinux-* one builds fine, and postinst succeeds as well

This should have occurred, because the selinux eclass we use will first try to load the policy module. This will most likely fail because it has policy dependencies on other SELinux rules in the other (unloaded) modules. However, the eclass will continue to try and load the full set.

Now that should have succeeded, because all SELinux policy modules at that point have been rebuilt and no longer depend on bridge_socket (unless you have stale policy modules still left, but that shouldn't be the case by default).

Can you confirm that the problem still exists?

~# emerge -1 $(qlist -IC sec-policy)
Comment 14 Alexander Wetzel 2017-04-21 16:32:14 UTC
Created attachment 470578 [details]
console update log - method 1

I updated my test system to current, only holding back the selinux policies.
I've then created a new snapshot and updated the system both ways from that stage: One time using your command, the other time normal emerge.
(I'll upload the script log for both updates, so you can verify my findings. There are some additional commands in it to illustrate the issue and the fix.)

It looks like we are nearly there, things are starting to make sense.
The "gentoo update procedure" is failing due to two issues:

1) When installing a selinux policy the postinstall script relabels the files belonging to it, even when the new module could not be loaded

2) The selinux packages are assuming, that if a module load fails for one module it will fail for all subsequent ones. Till one is able to fix the problem with a FULL RELOAD. That assumption is wrong, after merging apm the normal module load is generally working again. So it can happen there is never a full reload, fixing the previous installed modules...

When updating with your command, there IS a policy reload after installing selinux-apm, triggered by selinux-bind. After that all modules can be inserted without a full reload. And only the files relabeled between selinux-base-policy and selinux-bind can/could get wrong labels.
Therefore rplkg is also working after updating with emerge -1v $(qlist -IC sec-policy). But that's also just plain luck, another install may well fail with that command also.

Chances are, that regardless of how you are updating some files will get labeled wrong. If you are lucky relabeling will work without a full policy reload, but I was not.

So the advise for any other users affected by the issue seems to be, to just force a full reload with
"cd /usr/share/selinux/<policy>; semodule -i base.pp -i $(ls *.pp | grep -v base.pp | grep -v unconfined.pp)"
and then call
"rlpkg -v $(qlist -IC sec-policy)" to fix all labels the update may have broken
Comment 15 Alexander Wetzel 2017-04-21 16:32:43 UTC
Created attachment 470580 [details]
console update log - method 2
Comment 16 Sven Vermeulen (RETIRED) gentoo-dev 2018-03-25 12:28:38 UTC
I'm going to close this with the workaround as suggested by Alexander in https://bugs.gentoo.org/615270#c14:

So the advise for any other users affected by the issue seems to be, to just force a full reload with
"cd /usr/share/selinux/<policy>; semodule -i base.pp -i $(ls *.pp | grep -v base.pp | grep -v unconfined.pp)"
and then call
"rlpkg -v $(qlist -IC sec-policy)" to fix all labels the update may have broken