Project “Find My Device”

Since I use LineageOS without any google services some important feature was still missing to find my phone once I lost it. The idea was simple. Gain persistent access, call API requests to get the needed information and send it back to my Nextcloud. I noticed that being able to access the API directly you could actually start to script your own little snippets but we will get to this later.

Lets start with the transport problem. Somehow we have to get access to our smartphone at any time punching holes through firewalls. First method would be to use your own VPN like Wireguard or OpenVPN. But a much more convenient (but battery draining method) would be to use a tor hidden service maybe even using bridges to obfuscate its real intention (Maybe “Orbot”).

Install Termux, Termux:API and Termux:Boot on your Android.
Lets setup the SSH Server and install some dependencies we need later:

Open Termux on your phone and type in:

pkg install root-repo
pkg update
pkg upgrade
pkg install openssh termux-api jq zip
# this will set the password for first login but it is highly advised to use pub-key authentication for your later ssh session
passwd
sshd

Now you should be able to access your phones Termux environment by ssh’ing into it from your Notebook:

ssh root@your.mobile -p 8022

Lets make the ssh session persistent over boot and change some settings (I’ll just show you the content of my setup):

cd ~

~ $ cat /data/data/com.termux/files/usr/etc/ssh/sshd_config
PrintMotd yes
# set this to yes if you want to enable password authentication
PasswordAuthentication no
Subsystem sftp /data/data/com.termux/files/usr/libexec/sftp-server

~ $ cat ~/.termux/boot/start-sshd
#!/data/data/com.termux/files/usr/bin/sh
termux-wake-lock
sshd

After that you should open Termux:Boot once on your phone. Maybe reboot your phone to check if everything works so far. (ssh should be available after reboot)

Well, let us start to have some fun.

Go to app permission settings of your android and give all permissions to Termux:API.

Now ssh into your phone and execute:

termux-setup-storage

tabbing “termux-” will actually show all your tools you can use to control your phone. Should look like this:

~ $ termux-
termux-audio-info            termux-fix-shebang           termux-open                  termux-telephony-deviceinfo
termux-battery-status        termux-info                  termux-open-url              termux-toast
termux-brightness            termux-infrared-frequencies  termux-reload-settings       termux-torch
termux-call-log              termux-infrared-transmit     termux-reset                 termux-tts-engines
termux-camera-info           termux-job-scheduler         termux-sensor                termux-tts-speak
termux-camera-photo          termux-keystore              termux-setup-storage         termux-usb
termux-change-repo           termux-location              termux-share                 termux-vibrate
termux-chroot                termux-media-player          termux-sms-inbox             termux-volume
termux-clipboard-get         termux-media-scan            termux-sms-list              termux-wake-lock
termux-clipboard-set         termux-microphone-record     termux-sms-send              termux-wake-unlock
termux-contact-list          termux-nfc                   termux-speech-to-text        termux-wallpaper
termux-dialog                termux-notification          termux-storage-get           termux-wifi-connectioninfo
termux-download              termux-notification-list     termux-telephony-call        termux-wifi-enable
termux-fingerprint           termux-notification-remove   termux-telephony-cellinfo    termux-wifi-scaninfo

From this point it’s really up to the limitations of your imagination. Some examples could be…

Capture all telemetry and send it to your Nextcloud:

cd ~

~ $ cat scripts/get_telemetry
date="$(date +'%d-%m-%y_%H-%M-%S')"
path="/data/data/com.termux/files/home/records/$date"
echo "create dir..."
mkdir -p $path/txt
echo "get wifi..."
termux-wifi-scaninfo > $path/txt/wifi.txt
echo "get cellinfo..."
termux-telephony-cellinfo > $path/txt/cell.txt
echo "get all sensor data..."
termux-sensor -a -n 1 > $path/txt/sensor.txt
echo "get location..."
while :
do
        echo "trying..."
        termux-location > $path/txt/location.txt
        if [ -s $path/txt/location.txt ]
        then
                echo "got location..."
                break
        fi
done
echo "export to nextcloud..."
zip -r $path/$date.zip $path/txt >&- 2>&-
curl -u USERNAME:GENERATE_YOUR_NEXTCLOUD_APP_KEY -T $path/$date.zip https://cloud.53c70r.de/remote.php/dav/files/sector/termux/

Play presidential alert:

cd ~

~ $ cat scripts/presidential_alert
lat=$(termux-location | jq -r ".latitude")
long=$(termux-location -r last | jq -r ".longitude")
termux-notification -c 'SEE EMERGENCY INFORMATION' -t "LOST DEVICE"
setsid -f sh -c "while true; do termux-volume music 15; sleep 1; done"
termux-torch on
termux-vibrate -f -d 2000
sleep 2
termux-media-player play /data/data/com.termux/files/home/scripts/data/eas.mp3
sleep 11
termux-torch off
termux-tts-speak -s MUSIC "GPS coordinates. latitude: $lat, longitude: $long. WARNING. This system is for the use of authorized users only. Individuals using this computer system without authority or in excess of their authority are subject to having all their activities on this system monitored and recorded by system personnel. Anyone using this system expressly consents to such monitoring and is advised that if such monitoring reveals possible evidence of criminal activity system personal may provide the evidence of such monitoring to law enforcement officials."
killall sh

Some loud alarm:

cd ~

~ $ cat scripts/loud_alarm
setsid -f sh -c "while true; do termux-volume music 15; sleep 1; done"
setsid -f sh -c "while true; do termux-torch on; sleep 1; termux-torch off; sleep 1; done"
termux-media-player play /data/data/com.termux/files/home/scripts/data/alarm.mp3
termux-torch off
killall sh

Persistent ssh root backdoor on android

Tested on Android 10.
Get a root shell to your android via adb and execute;

remount
ssh-keygen -A
mkdir /root
cp -r /data/ssh /root
cp /etc/ssh/sshd_config /root
chmod 740 /root
chmod 700 /root/ssh
touch /root/ssh/authorized_keys
chmod 600 /root/ssh/authorized_keys
chown root:root -R /root

Add your ssh pub-key to “/root/ssh/authorized_keys” than execute:

sed -i 's/\/data\//\/root\//g' /etc/ssh/sshd_config
echo "HostKey /root/ssh/ssh_host_ed25519_key" >> /etc/ssh/sshd_config

Add the file “/root/start” with content;

#!/bin/sh
/bin/sshd -f /root/sshd_config

Add our daemon under “/system/etc/init/sshd.rc”;

service sshd /system/bin/sh /root/start
    user root
    group root
    oneshot
    seclabel u:r:su:s0

on property:sys.boot_completed=1 && property:sys.logbootcomplete=1
    start sshd

Reboot your device, done.

(On LineageOS 18.1 sshd will crash at the moment)
https://gitlab.com/LineageOS/issues/android/-/issues/3437

signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0
Cause: null pointer dereference
    x0  0000000000000000  x1  0000007b0bd1dfb8  x2  0000000000000008  x3  0000000000000010
    x4  0000000000000000  x5  8080808080808080  x6  fefefefefefefeff  x7  7f7f7f7f7f7f7f7f
    x8  0101010101010101  x9  ffffff84f42e2047  x10 0000000000000068  x11 000000000b52b678
    x12 000000004f1d3b2b  x13 0000007ff25268cb  x14 0000007b0b6ddd42  x15 0000ffff00000fff
    x16 00000058c010e3f8  x17 0000007b0b66bb30  x18 0000007b0c578000  x19 0000000000000000
    x20 00000058c0110000  x21 000000791b5241f0  x22 000000791b5248e0  x23 0000000000000000
    x24 00000058c00d9e8d  x25 0000007b0baa6ae0  x26 0000000000000001  x27 0000000000000003
    x28 00000058c0111000  x29 0000007ff2527910
    lr  00000058c01071c8  sp  0000007ff2527330  pc  0000007b0b66bb40  pst 0000000080000000

backtrace:
      #00 pc 000000000004ab40  /apex/com.android.runtime/lib64/bionic/libc.so (strlen_default+16) (BuildId: be9c72fe4db37cd191b589b74d090d13)
      #01 pc 00000000000361c4  /system/bin/sshd (main+1720) (BuildId: 610e2671bc203f1b61ef273d60564a86)
      #02 pc 000000000004988c  /apex/com.android.runtime/lib64/bionic/libc.so (__libc_init+108) (BuildId: be9c72fe4db37cd191b589b74d090d13)

NGINX with ModSecurity and Fail2ban

cat /etc/fail2ban/filter.d/modsecurity.conf

# Fail2Ban filter for modsecurity
#
[Definition]

failregex = ^<HOST> \- \S+ \[\] \"(.*)\S+\" 444 .+$

will check for HTTP status code 444.

Add this to your “/etc/fail2ban/jail.local”:

[modsecurity]
port = http,https
logpath = %(nginx_access_log)s
enabled = true

SELinux Murmur Server Policy for Fedora

sudo -i
mkdir ~/selinux/murmur
cd ~/selinux/murmur
sepolgen --inetd /usr/sbin/murmurd -n murmur -u system_u

Add this to murmur.te:

# Add Port defenition
type murmur_port_t;
corenet_port(murmur_port_t)

Run

semanage dontaudit off
./murmur.sh
semanage port -a -t murmur_port_t 64738 -p tcp
semanage port -a -t murmur_port_t 64738 -p udp
systemctl start murmur.service

Login to your server, restart it, generate some system calls…
Than execute and check if the policy is restrictive enough:

./murmur.sh --update

Clean up your audit log

> /var/log/audit/audit.log
rm -rf /var/log/audit/audit.log.*

Generate system calls again and rerun “–update”.
If murmur does not generate any more violations your policy is good to go.

Set it to enforcing by removing “#” before “permissive murmur_t;” in “murmur.te”.

Rerun

./murmur.sh

Restart murmur and check if everything is working as expected.

Finally enable “don’t audit” again:

semanage dontaudit on

WordPress on SELinux enforced systems

First of all SELinux is your friend not your enemy.
Hosting WordPress on SELinux enforced systems like Centos8 will mostly ruin your security concept since the majority would straight away disable SELinux leaving the system open to all other nasty exploitation attacks against running services.

TL;DR
Please don’t forget to adjust your WordPress root path.
For more information read the man page semanage-fcontext(8).

semanage fcontext -a -t httpd_sys_rw_content_t "/usr/share/nginx/html/wordpress/wp-content"
semanage fcontext -a -t httpd_sys_rw_content_t "/usr/share/nginx/html/wordpress/wp-content/plugins(/.*)?"
semanage fcontext -a -t httpd_sys_rw_content_t "/usr/share/nginx/html/wordpress/wp-content/themes(/.*)?"
semanage fcontext -a -t httpd_sys_rw_content_t "/usr/share/nginx/html/wordpress/wp-content/upgrade(/.*)?"
semanage fcontext -a -t httpd_sys_rw_content_t "/usr/share/nginx/html/wordpress/wp-content/uploads(/.*)?"
semanage fcontext -a -t httpd_sys_rw_content_t "/usr/share/nginx/html/wordpress/wp-content/wflogs(/.*)?"

Make sure your default label for e.g. /usr/share/nginx/ is “httpd_sys_content_t”.

[root@53c70r wordpress]# semanage fcontext -l | grep /usr/share/nginx/
/usr/share/nginx/html(/.*)?                        all files          system_u:object_r:httpd_sys_content_t:s0

This will cause all other files not defined by our own file context to be read only.
Finaly execute

restorecon -RFv /usr/share/nginx/

After the command being executed labeling should look as follow:

[root@53c70r wordpress]# ll -Z
total 208
-rw-r--r--.  1 nginx nginx system_u:object_r:httpd_sys_content_t:s0      405 Apr 17 23:32 index.php
-rw-r--r--.  1 nginx nginx system_u:object_r:httpd_sys_content_t:s0    19915 Aug 27 23:24 license.txt
-rw-r--r--.  1 nginx nginx system_u:object_r:httpd_sys_content_t:s0     7278 Sep 23 00:56 readme.html
-rw-r--r--.  1 nginx nginx system_u:object_r:httpd_sys_content_t:s0     7101 Aug 27 23:24 wp-activate.php
drwxr-xr-x.  9 nginx nginx system_u:object_r:httpd_sys_content_t:s0     4096 Jan 19  2020 wp-admin
-rw-r--r--.  1 nginx nginx system_u:object_r:httpd_sys_content_t:s0      351 Apr 17 23:32 wp-blog-header.php
-rw-r--r--.  1 nginx nginx system_u:object_r:httpd_sys_content_t:s0     2332 Aug 27 23:24 wp-comments-post.php
-rw-r--r--.  1 nginx nginx system_u:object_r:httpd_sys_content_t:s0     2897 Jan 19  2020 wp-config.php
-rw-r--r--.  1 nginx nginx system_u:object_r:httpd_sys_content_t:s0     2913 Apr 17 23:32 wp-config-sample.php
drwxr-xr-x.  7 nginx nginx system_u:object_r:httpd_sys_rw_content_t:s0    96 Sep 23 00:57 wp-content
-rw-r--r--.  1 nginx nginx system_u:object_r:httpd_sys_content_t:s0     3940 Apr 17 23:32 wp-cron.php
drwxr-xr-x. 24 nginx nginx system_u:object_r:httpd_sys_content_t:s0     8192 Aug 27 23:24 wp-includes
-rw-r--r--.  1 nginx nginx system_u:object_r:httpd_sys_content_t:s0     2496 Apr 17 23:32 wp-links-opml.php
-rw-r--r--.  1 nginx nginx system_u:object_r:httpd_sys_content_t:s0     3300 Apr 17 23:32 wp-load.php
-rw-r--r--.  1 nginx nginx system_u:object_r:httpd_sys_content_t:s0    48761 Aug 27 23:24 wp-login.php
-rw-r--r--.  1 nginx nginx system_u:object_r:httpd_sys_content_t:s0     8509 Jun 17 12:56 wp-mail.php
-rw-r--r--.  1 nginx nginx system_u:object_r:httpd_sys_content_t:s0    20181 Aug 27 23:24 wp-settings.php
-rw-r--r--.  1 nginx nginx system_u:object_r:httpd_sys_content_t:s0    31159 Aug 27 23:24 wp-signup.php
-rw-r--r--.  1 nginx nginx system_u:object_r:httpd_sys_content_t:s0     4755 Apr 17 23:32 wp-trackback.php
-rw-r--r--.  1 nginx nginx system_u:object_r:httpd_sys_content_t:s0     3236 Aug 27 23:24 xmlrpc.php

[root@53c70r wordpress]# ll -Z wp-content/
total 4
-rw-r--r--. 1 nginx nginx system_u:object_r:httpd_sys_content_t:s0     28 Jan 19  2020 index.php
drwxr-xr-x. 7 nginx nginx system_u:object_r:httpd_sys_rw_content_t:s0 129 Sep 23 00:49 plugins
drwxr-xr-x. 4 nginx nginx system_u:object_r:httpd_sys_rw_content_t:s0  56 Aug 27 23:17 themes
drwxr-xr-x. 2 nginx nginx system_u:object_r:httpd_sys_rw_content_t:s0   6 Sep 23 00:56 upgrade
drwxr-xr-x. 6 nginx nginx system_u:object_r:httpd_sys_rw_content_t:s0  68 Jan 19  2020 uploads
drwxr-xr-x. 2 nginx nginx system_u:object_r:httpd_sys_rw_content_t:s0 224 Jan 19  2020 wflogs

If you want to upgrade your WordPress later just execute this before

setsebool httpd_unified 1

And when your upgrade is finished

setsebool httpd_unified 0

NGINX ModSecurity with coreruleset on Fedora

Recently I migrated my infrastructure from Apache to NGINX and noticed that it lacks packaging for ModSecurity and a proper rule set like the coreruleset from OWASP.
So I decided to start packaging the necessary components to get the coreruleset running.
 
This link will redirect you to the repository.
 
After installation you may edit “/etc/nginx/modsecurity.d/coreruleset/crs-setup.conf” and change

#SecDefaultAction "phase:1,log,auditlog,pass"
#SecDefaultAction "phase:2,log,auditlog,pass"

to

SecDefaultAction "phase:1,log,auditlog,deny,status:403"
SecDefaultAction "phase:2,log,auditlog,deny,status:403"

notice you could change the http status code to anything else e.g. 444.
 

Add your expetions to this files:

cp /etc/nginx/modsecurity.d/coreruleset/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf.example /etc/nginx/modsecurity.d/coreruleset/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf
cp /etc/nginx/modsecurity.d/coreruleset/rules/RESPONSE-999-EXCLUSION-RULES-AFTER-CRS.conf.example /etc/nginx/modsecurity.d/coreruleset/rules/RESPONSE-999-EXCLUSION-RULES-AFTER-CRS.conf

P.S. I compiled my own libmodsecurity because the default one includes LMDB which caused segfaults on my machine so I just removed it completely.

Minecraft Server with SELinux on Fedora

This blog post will show you how to host a Minecraft Server on a Fedora Server sandboxed by SELinux and systemd.

Let us consider “/data/minecraft” will be our Minecraft Server root.

mkdir -p /data/minecraft

Download and extract the server.jar to the root.

groupadd minecraft
adduser --shell=/sbin/nologin --no-create-home minecraft
usermod -G minecraft -a minecraft
semanage login -a -s user_u minecraft
touch /data/minecraft/start
chmod +x /data/minecraft/start

Add the following content to “start” and adjust the start command as needed. My setup uses spigot.

#!/bin/bash
java -Xms1G -Xmx8G -jar server.jar nogui

Later we will use the “start” file for transition to our SELinux Minecraft domain.

chown -R minecraft:minecraft /data/minecraft

I like to put all generated SELinux policies to the path /root/selinux/

mkdir -p /root/selinux/minecraft_server/
cd /root/selinux/minecraft_server

Now we generate our SELinux policy:

sepolgen --inetd /data/minecraft/start -n minecraft_server -w /data/minecraft -u user_u

We disable the “don’t audit” rule of SELinux.

semanage dontaudit off

Append this to minecraft_server.te:

# Add Port defenition
type minecraft_port_t;
corenet_port(minecraft_port_t)
./minecraft_server.sh
semanage port -a -t minecraft_port_t 25565 -p tcp

Create “/usr/lib/systemd/system/minecraft.service” and add the content:

[Unit]
Description=Minecraft Server
Documentation=

Wants=network.target
After=network.target

[Service]
User=minecraft
Group=minecraft
SuccessExitStatus=130
PrivateMounts=yes
RemoveIPC=true
ProtectHome=true
ProtectSystem=strict
PrivateDevices=true
NoNewPrivileges=true
PrivateTmp=true
ProtectControlGroups=yes
ProtectKernelModules=yes
ProtectKernelTunables=yes
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
LockPersonality=yes
InaccessibleDirectories=/root /sys /srv -/opt /media -/lost+found
ReadWriteDirectories=/data/minecraft
WorkingDirectory=/data/minecraft
TimeoutStopSec=60
KillSignal=SIGINT
ExecStart=/data/minecraft/start

[Install]
WantedBy=multi-user.target
restorecon -Fv /usr/lib/systemd/system/minecraft.service
systemctl daemon-reload
cd /root/selinux/minecraft_server
./minecraft_server.sh
systemctl enable --now minecraft

You should now see something like this:

[root@53c70r ~]# ls -Z /data/minecraft/
  system_u:object_r:minecraft_server_rw_t:s0 banned-ips.json
  system_u:object_r:minecraft_server_rw_t:s0 banned-players.json
  system_u:object_r:minecraft_server_rw_t:s0 bukkit.yml
  system_u:object_r:minecraft_server_rw_t:s0 commands.yml
  system_u:object_r:minecraft_server_rw_t:s0 crash-reports
  system_u:object_r:minecraft_server_rw_t:s0 debug
  system_u:object_r:minecraft_server_rw_t:s0 eula.txt
  system_u:object_r:minecraft_server_rw_t:s0 help.yml
  system_u:object_r:minecraft_server_rw_t:s0 logs
  system_u:object_r:minecraft_server_rw_t:s0 ops.json
  system_u:object_r:minecraft_server_rw_t:s0 permissions.yml
  system_u:object_r:minecraft_server_rw_t:s0 plugins
  system_u:object_r:minecraft_server_rw_t:s0 server.jar
  system_u:object_r:minecraft_server_rw_t:s0 server.properties
  system_u:object_r:minecraft_server_rw_t:s0 spigot.yml
  system_u:object_r:minecraft_server_exec_t:s0 start
  system_u:object_r:minecraft_server_rw_t:s0 timings
  system_u:object_r:minecraft_server_rw_t:s0 usercache.json
  system_u:object_r:minecraft_server_rw_t:s0 wepif.yml
  system_u:object_r:minecraft_server_rw_t:s0 whitelist.json
  system_u:object_r:minecraft_server_rw_t:s0 world
  system_u:object_r:minecraft_server_rw_t:s0 world_nether
  system_u:object_r:minecraft_server_rw_t:s0 world_the_end

And our running process:

[root@53c70r ~]# ps xaZ | grep minecraft
system_u:system_r:minecraft_server_t:s0 95956 ?  Ss     0:00 /bin/bash /data/minecraft/start
system_u:system_r:minecraft_server_t:s0 95957 ?  Sl     9:42 java -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -XX:+CMSIncrementalPacing -XX:ParallelGCThreads=7 -XX:+AggressiveOpts -Xms1G -Xmx8G -jar server.jar nogui

Let the Server run now for a while and try to interact with it as much as possible e.g. connect to it and disconnect, playing on it yada yada…

The idea is to collect as much logs as possible how the server interacts with the system to catch all system calls we want to whitelist.

If you think you caught all possible system calls execute:

cd /root/selinux/minecraft_server/
./minecraft_server.sh --update

Confirm with “y”.

To set the policy finally to enforcing mode just change the files content of “minecraft_server.te”

permissive minecraft_server_t;

to

#permissive minecraft_server_t;

and re-execute our script.

./minecraft_server.sh

Restart the Minecraft Server and see if everything works smoothly.

systemctl restart minecraft

If not do “–update” again and see if it found new violations. This process can be repeated as many times as you want.

Finally we can enable the “don’t audit” rule again.

Keep in mind that I did not add a port specific domain like I did in this post.

semanage dontaudit on

Congratulations.

You now own a Military Grade Minecraft Server.