Setup-Raspi-Mobile

From Coolscript
Jump to navigation Jump to search

Disk

  • Expand the filesystem after fresh installation
raspi-config - Advanced - Expand Filesystem

Delete docs to get more disk space

sudo rm -rf /usr/share/doc/
sudo rm -rf /usr/share/man/
sudo rm -rf /usr/share/locale/

APT

apt-get update
#apt-get upgrade
#or better
apt-get full-upgrade
  • Shrink journal
journalctl --vacuum-size=20M
journalctl --vacuum-time=3d
  • View packages
dpkg-query -Wf '${Installed-Size}\t${Package}\n' | sort -n

  • Remove and clean
apt-get remove libraspberrypi-doc --purge
apt-get clean
apt-get purge
apt autoremove
  • Good on Debian 11 Bullseye
apt-get remove firmware-libertas --purge
apt-get remove firmware-atheros --purge
apt-get remove rpi-eeprom --purge
apt-get remove gcc-10 --purge
apt-get remove iso-codes --purge
apt-get remove cpp-10  --purge
apt-get clean
apt-get purge
apt autoremove
root@raspberrypi:~# df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/root       1.6G  1.3G  177M  89% /
devtmpfs        776M     0  776M   0% /dev
tmpfs           937M     0  937M   0% /dev/shm
tmpfs           375M  1.7M  373M   1% /run
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
/dev/mmcblk0p1  253M   49M  204M  20% /boot
tmpfs           188M     0  188M   0% /run/user/1000


  • Install additional packages needed for this project
apt-get install mc autofs iptraf samba samba-common nftables apache2 locate tcpdump ncdu
apt-get install hostapd wireless-tools dnsmasq iw bridge-utils cloud-utils lsof nmap tcpdump

Apapter

  • Turn on WiFi and leave Bluetooth off
root@raspberrypi:~# rfkill unblock 0
root@raspberrypi:~# rfkill block 1
root@raspberrypi:~# rfkill
ID TYPE      DEVICE      SOFT      HARD
 0 wlan      phy0   unblocked unblocked
 1 bluetooth hci0     blocked unblocked

sysctl

  • /etc/sysctl.conf
net.ipv4.ip_forward=1
  • Activate
sysctl -p


User/Group

addgroup sambagrp
usermod -a -G sambagrp pi

Samba

  • Set a password for the pi user
smbpasswd -a pi
  • /etc/samba/smb.conf
[global]
 workgroup = WORKGROUP
 server string = %h server (Linux)
 #interfaces = eth0
 bind interfaces only = yes
 log file = /var/log/samba/log.%m
 panic action = /usr/share/samba/panic-action %d
 server role = standalone server
 obey pam restrictions = Yes
 passwd program = /usr/bin/passwd %u
 passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .
 pam password change = Yes
 map to guest = Bad User
 #log level = 4 #To be used for debugging purposes
 local master = no
 disable netbios = yes

[automnt]
 comment = automnt
 path = /automnt
 valid users = @sambagrp
 browsable = yes
 writable = yes
 read only = no
 create mask = 0660
  • Enable and start smbd, disable nmbd
systemctl enable smbd 
systemctl restart smbd 
systemctl stop nmbd
systemctl disable nmbd
systemctl mask nmbd

AUTOFS/UDEV

touch /etc/auto.rbusb
  • Add to the end of auto.master
echo '/automnt /etc/auto.rbusb --timeout=5 --ghost' >> /etc/auto.master
  • Restart
systemctl restart autofs
  • Get autofs helper script (automount helper, auto shutdow on usb flash device)
wget https://coolgeo.org:/download/scripts/autofs-config.pl -O /usr/local/bin/autofs-config.pl
chmod u+x /usr/local/bin/autofs-config.pl
  • Add udev rule
echo 'ACTION=="add", SUBSYSTEM=="block", KERNEL=="sd*", ATTRS{vendor}=="*", RUN+="/usr/bin/perl /usr/local/bin/autofs-config.pl"' > /etc/udev/rules.d/90-local.rules
  • Reload udev
udevadm control --reload-rules && udevadm trigger
  • TEST USB

Apache2/WebDAV

  • /etc/apache2/sites-available/000-default.conf
DavLockDB /var/www/DavLock
<Directory "/automnt/">
 Options +Indexes
 Order allow,deny
 Allow from all
 Require all granted
</Directory>
<VirtualHost *:80>
   ServerAdmin webmaster@localhost
   DocumentRoot /automnt
   Alias /automnt /automnt
   <Directory /automnt>
    DAV On
   </Directory>
   <Directory "/automnt">
    AuthType Basic
    AuthName "Restricted Content"
    AuthUserFile /etc/apache2/.htpasswd
    Require valid-user
   </Directory>
</VirtualHost>
  • Enable WebDAV Mod
a2enmod dav_fs
  • Restart
systemctl restart apache2
  • Add the PI user to WebDAV
htpasswd -c /etc/apache2/.htpasswd pi

HOSTS

  • /etc/hosts
192.168.4.1     raspi raspberry raspberrypi raspap

INIT

Check fro Update 2022

  • /etc/systemd/system/rbinit.service
[Unit]
Description=RaspiMobile Init Script
#After=network.target
After=hostapd.service

[Service]
Type=oneshot
ExecStart=/usr/sbin/rbinit

[Install]
WantedBy=multi-user.target
  • /usr/sbin/rbinit
#!/bin/bash
#Workaround for Ipdads
logger "rbinit set if"
/sbin/ip addr add 192.168.5.1/24 dev eth0:0
#not needed as nftables loads at startup
#/sbin/nft -f /etc/nftables.conf
logger "rbinit start openvpn"
systemctl start openvpn
  • Apply the new init script
chmod 755 /usr/sbin/rbinit
systemctl enable rbinit.service
systemctl start rbinit

NFT

Check fro Update 2022

  • /etc/nftables.conf
#!/usr/sbin/nft -f

flush ruleset

table inet filter {
       chain input {
               type filter hook input priority 0; policy accept;
       }
       chain forward {
               type filter hook forward priority 0; policy accept;
       }
       chain output {
               type filter hook output priority 0; policy accept;
       }
}
table ip nat {
       chain PREROUTING {
               type nat hook prerouting priority -100; policy accept;
       }

       chain INPUT {
               type nat hook input priority 100; policy accept;
       }

       chain POSTROUTING {
               type nat hook postrouting priority 100; policy accept;
               oif "eth0" masquerade comment "masq for eth0"
               #oif "wlan0" masquerade comment "masq for wlan0"
       }

       chain OUTPUT {
               type nat hook output priority -100; policy accept;
       }
}
  • Apply
systemctl enable nftables
systemctl start nftables

DHCPCD

/etc/dhcpcd.conf

hostname
clientid
persistent
option rapid_commit
option domain_name_servers, domain_name, domain_search, host_name
option classless_static_routes
option ntp_servers
require dhcp_server_identifier
slaac private
nohook lookup-hostname

#wlan0 configuration
interface wlan0
static ip_address=192.168.4.1/24
static routers=192.168.4.1
gateway
  • Apply changes
systemctl daemon-reload
systemctl restart dhcpcd.service


DNSMASQ

  • /etc/dnsmasq.d/090_wlan0.conf
#---------------------------------------------------------
#Raspi-Mobile wlan0 configuration
interface=wlan0
dhcp-range=192.168.4.50,192.168.4.255,255.255.255.0,30d 
#---------------------------------------------------------
  • Apply
systemctl enable dnsmasq
systemctl restart dnsmasq

HOSTAPD

  • /etc/hostapd/hostapd.conf
driver=nl80211
ctrl_interface=/var/run/hostapd
ctrl_interface_group=0
auth_algs=1
wpa_key_mgmt=WPA-PSK
beacon_int=100
ssid=raspi-mobile
channel=1
hw_mode=g
ieee80211n=0
wpa_passphrase=raspberry
interface=wlan0
wpa=2
wpa_pairwise=CCMP
country_code=DE
ignore_broadcast_ssid=0 


  • Apply
systemctl unmask hostapd
systemctl enable hostapd
systemctl restart hostapd


Workaround if hostapd does not start

  • /etc/systemd/system/rbautostart.service
[Unit]
Description=RaspiMobile automatic tasks at startup only
After=network.target auditd.service

[Service]
Type=oneshot
ExecStart=/usr/sbin/rbautstart

[Install]


  • /usr/sbin/rbautstart
#!/bin/bash

#restart hostapd at startup
systemctl restart hostapd

WiFi Scan

  • Check your neighbourhood
iwlist wlan0 scan

Disable syslog

  • Save disk space and avoid corruptions on the sd card
systemctl stop syslog.socket rsyslog.service
systemctl disable syslog.socket rsyslog.service

Optional keepalive logging

  • This is simple logging script to see if the device is up and write into a log, used eg for battery live testing.
root@raspberrypi:/# cat /home//pi/rbkeepalive.sh
#!/bin/bash
backup_time=$(date +'%H:%M:%S')
log_date=$(date +'%Y%m%d')
backup_dir="/tmp/"
alive_suffix="-alive.txt"
echo "$backup_dir$log_date$alive_suffix Keepalive $backup_time" >> $backup_dir$log_date$alive_suffix
  • Perms
chmod 755 /home//pi/rbkeepalive.sh
  • Crontab, all 10 Minutes
root@raspberrypi:/# crontab -l | grep rbkeepalive.sh
*/10 * * * * /home/pi/rbkeepalive.sh

RaspAP

raspi-config
  • Invoke RaspAP's Quick Installer:
curl -sL https://install.raspap.com | bash
  • Configure Website, for port 8080 and set the pi user as admin

OnetTime Disk Expand

  • /etc/systemd/system/rbexpanddisk.service
[Unit]
Description=RaspiMobile one time disk expand
After=network.target

[Service]
Type=oneshot
ExecStart=/usr/sbin/rbexpand

[Install]
WantedBy=multi-user.target
  • Enable the one time service
root@raspberrypi:~# systemctl enable rbexpanddisk
  • /usr/sbin/rbexpand
#!/bin/bash
#Script to expand the Raspi filesystem. The script checks for the file /tmp/raspi-mobile and will run if the file exists.
#After the first run the script will disable its own service (rbexapnddisk.service) and delete /tmp/raspi-mobile
PATH=/sbin:/usr/sbin/:/usr/local/sbin:/bin:/usr/local/bin:/usr/bin:
declare LS="Raspi-Mobile:"  #LS = LogSuffix
declare TriggerFile="/tmp/raspi-mobile"
if [ -f $TriggerFile ]; then
 systemctl enable syslog.socket rsyslog.service
 systemctl start syslog.socket rsyslog.service
 logger "$LS Start expanding disk"
 logger "$LS growpart /dev/mmcblk0 2"
 growpart /dev/mmcblk0 2 | logger
 logger "$LS resize2fs /dev/mmcblk0p2"
 resize2fs /dev/mmcblk0p2 | logger
 logger "$LS Disable rbexpanddisk.service"
 systemctl disable rbexpanddisk.service | logger
 rm $TriggerFile >/dev/null 2>&1
 logger "$LS Disable syslog"
 #Disable syslog as this is a security protection against data loss, you may turn it on any time again
 systemctl stop syslog.socket rsyslog.service | logger
 systemctl disable syslog.socket rsyslog.service | logger
else
 logger "$LS Expanding is disabled"
fi
chmod u+x /usr/sbin/rbexpand
systemctl daemon-reload
systemctl enable rbexpanddisk
touch /tmp/raspi-mobile

Features

  • Neofetch Banner
apt-get install neofetch
bash -c $'echo "neofetch" >> /etc/profile.d/mymotd.sh && chmod +x /etc/profile.d/mymotd.sh'
  • Add to /etc/profile.d/mymotd.sh
echo "See here too: https://coolscript.org/index.php/Raspi-Mobile"


  • RaspAP
curl -sL https://install.raspap.com | bash


bashrc

# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples

# If not running interactively, don't do anything
case $- in
   *i*) ;;
     *) return;;
esac

# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth

# append to the history file, don't overwrite it
shopt -s histappend

# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize
 
# If set, the pattern "**" used in a pathname expansion context will
# match all files and zero or more directories and subdirectories.
#shopt -s globstar
 
# make less more friendly for non-text input files, see lesspipe(1)
#[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
    xterm-color|*-256color) color_prompt=yes;;
esac

# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
force_color_prompt=yes

if [ -n "$force_color_prompt" ]; then
   if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
       # We have color support; assume it's compliant with Ecma-48
       # (ISO/IEC-6429). (Lack of such support is extremely rare, and such
       # a case would tend to support setf rather than setaf.)
       color_prompt=yes
   else
       color_prompt=
   fi
fi

if [ "$color_prompt" = yes ]; then
   PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w \$\[\033[00m\] '
else
   PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
   PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
   ;;
*)
   ;;
esac

# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
   test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
   alias ls='ls --color=auto'
   #alias dir='dir --color=auto'
   #alias vdir='vdir --color=auto'

   alias grep='grep --color=auto'
   alias fgrep='fgrep --color=auto'
   alias egrep='egrep --color=auto'
fi

# colored GCC warnings and errors
#export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'

# some more ls aliases
#alias ll='ls -l'
#alias la='ls -A'
#alias l='ls -CF'

# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if ! shopt -oq posix; then
 if [ -f /usr/share/bash-completion/bash_completion ]; then
   . /usr/share/bash-completion/bash_completion
 elif [ -f /etc/bash_completion ]; then
   . /etc/bash_completion
 fi
fi

Last Step

Last step is to delete the logs and shut down

touch /home/pi/raspi-mobile
systemctl enable rbexpanddisk
systemctl stop autofs.service
systemctl stop apache2 nmbd smbd
rm /etc/auto.rbusb
touch /etc/auto.rbusb
rm  -rf /var/log/apache2/*
rm  -rf /var/log/samba/*
rm  /var/log/*
: > /root/.bash_history
: > /home/pi/.bash_history
history -c
systemctl stop autofs
#Used for debugging
#systemctl enable syslog.socket rsyslog.service 
systemctl disable syslog.socket rsyslog.service 

Then

- history -c

Then CTRL D

- history -c

Beta OpenVPN

Check from Update 2022

  • Script to alternate interface - etc/openvpn/ovpn2nft.pl
#!/bin/perl
#Script to alternate the nft POSTROUTING chain between eth0 and tun0. The script is used together with OpenVPN.
#Arg up : delete eth0 and set tun0 to be masquerading
#Arg down : delete tun0 and set eth0 to be masquerading
use strict;
my $mode = $ARGV[0];
my $ethArg="oif \"eth0\"";
my $nftlistcmd="/sbin/nft -a list chain ip nat POSTROUTING";
my $nftdeletecmd="/sbin/nft delete rule ip nat POSTROUTING handle ";
my $nftaddTun="/sbin/nft add rule nat POSTROUTING oif tun0 counter masquerade comment \\\"Masq for tun0\\\"";
my $nftReset="/sbin/nft -f /etc/nftables.conf";
#my $id=`id`;
#syslog("Check nft along openvpn, mode: $mode id: $id");
if (uc($mode) eq "UP") {
 my @nflist = `$nftlistcmd`;
 foreach (@nflist) {
  chomp;
  #syslog ("DEB $_");
  if (/$ethArg.*handle (\d+)/){
   $nftdeletecmd.="$1";
   syslog("Found and delete eth0 rule on handle $1");
   my $nftret=`$nftdeletecmd`;
   if ($nftret) {
    syslog ("Error $nftret");
    exit 1;
   }
  syslog("Set tun0 rule");
   my $nftret=`$nftaddTun`;
   if ($nftret) {
    syslog ("Error $nftret");
    exit 1;
   }
   exit 0;
  }   #if (/$ethArg.*handle (\d+)/)
 }    #foreach (@nflist) {
}     #if (uc($mode) eq "UP")


if (uc($mode) eq "DOWN") {
 syslog ("Reset nft");
 my $nftret=`$nftReset`;
 if ($nftret) {
  syslog ("Error $nftret");
  exit 1;
 }
}     #if (uc($mode) eq "DOWN")




sub syslog {
 #print "$_[0]\n";
 my $logger="logger \"($0) NFT $_[0]\"";
 `$logger`;
}

To be used in client conf of openvpn:

script-security 2
up "/etc/openvpn/ovpn2nft.pl up"
down "/etc/openvpn/ovpn2nft.pl down"

Model3 vs Model4

  • Model4
root@raspberrypi:~# lscpu
Architecture: armv7l
Byte Order: Little Endian
CPU(s): 4
On-line CPU(s) list: 0-3
Thread(s) per core: 1
Core(s) per socket: 4
Socket(s): 1
Vendor ID: ARM
Model: 3
Model name: Cortex-A72


  • Modell 3
root@raspberrypi:~# lscpu
Architecture: armv7l
Byte Order: Little Endian
CPU(s): 4
On-line CPU(s) list: 0-3
Thread(s) per core: 1
Core(s) per socket: 4
Socket(s): 1
Vendor ID: ARM
Model: 4
Model name: Cortex-A53


Function Test

  • Plugin Media USB Stick, check automount
  • Wlan connect
  • Connect Ethernet
  • Test Internet
  • Test RaspAP Web
  • Connect (samba) via local ip and hostname (raspi)
  • Connect (webdav) via local ip and hostname (raspi)
  • Connect (sftp) via local ip and hostname (raspi)
  • Disconnect Ethernet
  • Connect (samba) via hostname (raspi)
  • Connect (webdav) via hostname (raspi)
  • Connect (sftp) via hostname (raspi)
  • Test Auto Shutdown USB Stick
  • Test Access via LAN

Interesting commands

  • iwlist wlan0 scan | grep ESSID
  • iwlist wlan0 scan | grep Frequency | sort | uniq -c | sort -n

Systemctl

  • systemctl cat service
  • systemctl cat rc-local.service
  • systemd-analyze blame
  • systemd-analyze time

Known Problems

Problem:
In case of unplugging eth0 while wlan0 is active then it can happen that the SID is no more visible eve after reboot
Solution
Shut down the Raspi and start again without eth0, then shutdown again, plugin eth0 and start again.