Skip to content

Instantly share code, notes, and snippets.

@arpanpal010
Last active August 1, 2017 11:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save arpanpal010/a90c8c0a16a3f92decc7 to your computer and use it in GitHub Desktop.
Save arpanpal010/a90c8c0a16a3f92decc7 to your computer and use it in GitHub Desktop.
Raspberry Pi configurations

##Configurations for Raspberry Pi Home Server## #####Using Raspbian##### (although the procedures are similar/compatible with most debian based systems.)

###Added###

  • [sysctl.conf mods] (#file-sysctl-md)
  • [Firewall config] (#file-firewall-md)
  • [DNS Server] (#file-dns-md)
  • [Dynamic Dns] (#file-dyndns-md)
  • [Git Server] (#file-git-server-md)
  • [Nginx with ssl] (#file-nginx-ssl-md)

###TOWRITE###

mumble server
web server with nginx and django/uwsgi/python
seafile firefox sync server 1.5

###TODO###

squid proxy
etherpad
yourls
openvpn
kareha imageboard

###DNS Server for local caching dns-queries###

DNS servers are queried everytime we visit a site, for the IP-adress of the site, so by caching such requests (and storing them persistently) help reduce network footprint, as well as a little boost in speed.

Used pdnsd for persistence (documentation: http://members.home.nl/p.a.rombouts/pdnsd/doc.html)

#install pdnsd
sudo apt-get install pdnsd resolvconf;
#start the service
sudo service pdnsd start;

(if given warning abut pdnsd daemon being disabled, just set the following in /etc/default/pdnsd)

START_DAEMON=yes  

Remember to open port 53/udp in firewall config

#####Sample configuration (located at /etc/pdnsd.conf)#####

#global settings
global {
    	perm_cache=16384; #16MB
    	cache_dir="/var/cache/pdnsd";
    	run_as="pdnsd";
    	server_ip = eth0;  // Use eth0 here if you want to allow other
                            // machines on your network to query pdnsd.
    	status_ctl = on;
    	paranoid=on;
//      query_method=tcp_udp;   // pdnsd must be compiled with tcp
                            	// query support for this to work.
    	min_ttl=15m;       // Retain cached entries at least 15 minutes.
    	max_ttl=1w;        // One week.
    	timeout=10;        // Global timeout option (10 seconds).

        // Don't enable if you don't recurse yourself, can lead to problems
        // delegation_only="com","net";
    	neg_rrs_pol=on; #reduces outgoing overhead by caching queries that return negetice response, to be used with proxy
    	par_queries=1; #number of queries per dns server, if more than one specified
    	debug=off; #turn on to monitor behaviour
}

/* with status_ctl=on and resolvconf installed, this will work out from the box
this is the recommended setup for mobile machines */
/* server {
	label="resolvconf"; #not used
}
*/

#server settings
server {
        label = "root-servers";
        root_server=on;
        ip =	46.151.208.154
        ,	128.199.248.105
        ,	213.183.57.55
	,	178.17.170.67
//above are from http://www.opennicproject.org/nearest-servers/    
//google dns
        ,	8.8.8.8
        ,       4.4.4.4
//add your own here
        ;
        timeout = 5;
        uptest = query;
        interval = 30m;      // Test every half hour.
        ping_timeout = 300;  // 30 seconds.
//      proxy_only=on; #set this on only for multiple dns servers
        purge_cache = off;
        exclude = .localdomain;
        policy = included;
        preset = off;
}	

#name blocking - create a new neg section
/* neg {
        name=doubleclick.net;
        types=domain;   // This will also block xxx.doubleclick.net, etc.
}
*/

###ddclient configuration with dnsdynamic.org###

#install
sudo apt-get install ddclient; #has multiple socket and io perl dependencies

#when asked for the dynamic dns imfornation
#provide own values, (see examples...)
#or choose to do manual config later

#start service
sudo service ddclient start;

#####Sample config (at /etc/ddclient.conf) - taken from dnsdyanmic#####

daemon=600 				#check every 10mins for ip address change
syslog=yes 				#enabled logging
mail=root 				# mail all msgs to root
mail-failure=root 			# mail failed update msgs to root
pid=/var/run/ddclient.pid 		# record PID in file.
ssl=yes 				# use ssl-support.  Works with ssl-librar
use=web, web=myip.dnsdynamic.com        # get ip from server.
server=www.dnsdynamic.org               # default server
login=user@gmail.com                    # default login
password=password                       # default password
server=www.dnsdynamic.org,              \
protocol=dyndns2                        \
your-dyndns-uri.here #e.g awesome.dnsdynamic.com

###Basic firewall configuration with iptables###

#####Installation#####

$ sudo apt-get install iptables;

#####Create default config#####

$ sudo bash -c 'iptables-save > /etc/network/iptables.rules';

#####Check configuration#####

$ sudo iptables -nvL;

#####Load firewall config#####

$ sudo iptables-restore < /etc/network/iptables.rules;

#####Load everytime before network starts##### For most cases just enable the iptables service, or create a file /etc/network/if-pre-up.d/firewall with the content

#!/bin/sh
/sbin/iptables-restore < /etc/network/iptables.rules

Make it executable

sudo chmod +x /etc/network/if-pre-up.d/firewall;

Sample configuration (located at /etc/network/if-pre-up.d/firewall)

#(this is no way usable for production, but is a good starting point)
*filter

#default policies chains
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
:IN_SSH - [0:0]
:LOGGING - [0:0]

#loopback allowed
-A INPUT -i lo -j ACCEPT

#invalid packets dropped
-A INPUT   -m state --state INVALID -j DROP
-A FORWARD -m state --state INVALID -j DROP
-A OUTPUT  -m state --state INVALID -j DROP

#ping allowed
-A INPUT -p icmp --icmp-type 8 -j ACCEPT

#connections already established allowed
#be careful to set this, otherwise you will be locked out when reloading the firewall
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

#ssh chain with limit
-A INPUT -p tcp --dport ssh -m conntrack --ctstate NEW -j IN_SSH
-A IN_SSH -m recent --name sshbf --rttl --update --hitcount 5 --seconds 20 -j DROP
-A IN_SSH -m recent --name sshbf --rttl --update --hitcount 10 --seconds 1800 -j DROP
-A IN_SSH -m recent --name sshbf --set -j ACCEPT

#dns
-A INPUT -p tcp -m tcp --dport 53 -j ACCEPT
-A INPUT -p udp --dport 53 -j ACCEPT

#http(s)
-A INPUT -p tcp -m tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 8080 -m state --state NEW,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 8081 -m state --state NEW,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT

#linux compliance
#-A INPUT -p udp -j REJECT --reject-with icmp-port-unreachable;
#-A INPUT -p tcp -j REJECT --reject-with tcp-rst;

#drop everything else
-A INPUT -j DROP
-A FORWARD -j DROP

#drop logged
-A INPUT -j LOGGING
-A LOGGING -m limit --limit 2/min -j LOG --log-prefix "IPTables Packet Dropped: " --log-level 6
-A LOGGING -j DROP

COMMIT

###Private GIT server###

This is a local git repository(s) to host codes, and setup a version control system. Using Git,codes can be pulled, uploaded or cloned over ssh (every contributor needs their own public key added to the server) or via http (clone only, also insecure).

#####Authentication##### Create a single user 'git' and add the contributors' public keys to .ssh/authorized_keys of the git user. This user can be secured by limiting access and setting up permission.

or

For small/personal use, just add the public keys to the default 'pi' user.

#####Authorization#####

  • If the repo will be used over internet, dont forget to disable password based logins and root logins,

  • Modify firewall setting and install fail2ban or sshguard for enhances security.

  • Disable shell access to git users by specifying user shell for the git user in /etc/passwd as /usr/bin/git-shell (or which git-shell to get the path)

[tip: Generate keys with ssh-keygen and copy it over with ssh-copy-id]

#####Create a bare repository#####

#all repos end in .git which isnt an extension
#add --shared flag to give group write access to repo
$ git in        it --bare /path/to/git/container/directory/$reponame.git

This will create an empty repository.

#####Now clone the repository#####

$ git clone git@raspberrypi:/path/to/git/container/directory/$reponame.git
#or if the project exists just add the remote by:
$ git remote add raspberrypi git@raspberrypi:/path/to/git/container/directory/$reponame.git

From here, use the repository as you would with github, although, the users will have to be able to authenticate themselves with the password or key based authentication to push to this repository.

#####Display the code##### The bare repository has the actual codes obfuscated/encrypted. To host a copy of the code elsewhere or view/download single files from server use the post-receive hook to checkout the repo at some directory and make that directory available to the server.

Create a file /location/to/git-bare-repo/hooks/post-receive with the content

#!/bin/sh
GIT_WORK_TREE=/path/where/repo/files/should/be/extracted/ git checkout -f

Make it executable

$ chmod a+x git-bare-repo/hooks/post-receive

[tip: If displaying the codes online, make sure the server has read ac cess to the directory]

#in git container folder
$ chgrp -R $server-username /git-container/ 

#####Allow public access##### To allow people to clone the repo from the web, make the directory containing the code publicy accessible and enable the post-update hook

Create a file /location/to/git-bare-repo/hooks/post-update with the content

#!/bin/sh
exec git-update-server-info

Make it executable

$ chmod a+x git-bare-repo/hooks/post-update

###Creating and Using SSL cetificate to Nginx###

#####Creating the private key and certificate (self-signed)##### Create certificate with openssl using default location /etc/nginx with keysize=2048 bit RSA encryption

$ sudo openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -outform PEM -out /etc/nginx/httpserver.pem;

Set permission with $ chmod 600 /etc/nginx/httpserver.pem

Issue signing request

$ sudo openssl req -new -key /etc/nginx/httpserver.pem -out /etc/nginx/httpserver.csr;
#fields -  fill as needed. common name=FQDN or IP or . (blank)

Remove passphrase - otherwise enter it everytime nginx reloads

$ sudo cp /etc/nginx/{httpserver.pem,actualserver.pem} #actualserver.pem is the key with passphrase
$ sudo openssl rsa -in /etc/nginx/actualserver.pem -out /etc/nginx/httpserver.pem

Sign the certificate - change days if needed

$ sudo openssl x509 -req -days 365 -in /etc/nginx/httpserver.csr -signkey /etc/nginx/httpserver.pem -out /etc/nginx/httpserver.crt;

#####Add the key to nginx##### Copy the keys to somewhere nginx has read access to e.g /etc/nginx/
Example config /etc/nginx/nginx.conf (from nginx docs)

server {
	listen              443 ssl;
	keepalive_timeout   70;
	
	ssl_protocols       SSLv3 TLSv1 TLSv1.1 TLSv1.2;
	ssl_ciphers         AES128-SHA:AES256-SHA:RC4-SHA:DES-CBC3-SHA:RC4-MD5;
	ssl_certificate     /etc/nginx/httpserver.crt;
	ssl_certificate_key /etc/nginx/httpserver.pem;
	ssl_session_cache   shared:SSL:10m;
	ssl_session_timeout 10m;
	
	#other stuff below
}

[tip: Dont forget to open port 443 of firewall]

###Optimizing Kernel Parameters###

(edit /etc/sysctl.conf)

Enable Spoof protection (reverse-path filter)

net.ipv4.conf.default.rp_filter=1
net.ipv4.conf.all.rp_filter=1

Enable TCP/IP SYN cookies

net.ipv4.tcp_syncookies=1

Ignore ICMP broadcasts

net.ipv4.icmp_echo_ignore_broadcasts = 1

Ignore bogus ICMP errors

net.ipv4.icmp_ignore_bogus_error_responses = 1

Do not accept ICMP redirects (prevent MITM attacks)

net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.eth0.accept_redirects = 0

Do not send ICMP redirects (really important for our single NIC gateway)

net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.conf.eth0.send_redirects = 0

Do not accept IP source route packets

net.ipv4.conf.all.accept_source_route = 0

Log Martian Packets

net.ipv4.conf.all.log_martians = 1

Router function (important1!!)

net.ipv4.ip_forward = 1

Avoid running Out Of Memory

vm.min_free_kbytes=8192
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment