Showing posts with label raspberry-pi. Show all posts
Showing posts with label raspberry-pi. Show all posts

Friday, 3 June 2016

Using a raspberry pi (or any Debian based computer) to set up an open VPN server

Why

There are many howto's explaining the set-up of an OpenVPN server. The majority of what I have seen, provide instructions about setting up a tunnel device. This allows you to gain access to the OpenVPN server itself, but requires a lot more customisation if you want to access other computers on the remote LAN.

Using a tap device is much easier, and allows the OpenVPN client to be able to access not only the server but all other computers connected to the same LAN.

The basic idea is that you create an Ethernet bridge on the VPN server. Each time clients connect, the server taps them to that bridge and so clients behave as if they are physically connected to the remote LAN.

How

I would advice starting your setup with a clean fresh install. Before proceeding to follow the instructions below, issue:

pi@gabriella:~ $ sudo apt-get update && sudo apt-get dist-upgrade 

Install the bridge

The first step is to set up our bridge:

pi@gabriella:~ $ sudo apt-get install bridge-utils uml-utilities 

After the bridge-utils package is installed, we need to change the server's network configuration file in order to activate the bridge.The actual file is:/etc/network/interfaces and the definition of the bridge is :

# interfaces(5) file used by ifup(8) and ifdown(8)

# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf'

# Include files from /etc/network/interfaces.d:
source-directory /etc/network/interfaces.d

auto lo
iface lo inet loopback

iface eth0 inet manual
iface tap0 inet manual

# Our bridge initially contains just the ethernet interface and is configured to use DHCP
auto br0
  iface br0 inet dhcp
  bridge_ports eth0

# You can delete these lines if you do not whish to use Wi-fi 
allow-hotplug wlan0
iface wlan0 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

allow-hotplug wlan1
iface wlan1 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

This setup uses DHCP for the bridge. Setting up a static IP is explained in the Network Configuration section of the Debian Wiki. The same pages provide more information and details about bridging. The actual link is here.

At this point a server reboot is required in order to verify the bridge setup. When the server is up again you can check that the bridge is working by examining the outcome of the ip addr command which should be similar to this:

pi@gabriella:/etc/openvpn $ ip addr
1: lo:  mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0:  mtu 1500 qdisc pfifo_fast master br0 state UP group default qlen 1000
    link/ether b8:27:eb:b2:d8:f2 brd ff:ff:ff:ff:ff:ff
    inet 169.254.30.59/16 brd 169.254.255.255 scope global eth0
       valid_lft forever preferred_lft forever
3: br0:  mtu 1500 qdisc noqueue state UP group default qlen 1000
    link/ether b8:27:eb:b2:d8:f2 brd ff:ff:ff:ff:ff:ff
    inet 10.0.1.240/24 brd 10.0.1.255 scope global br0
       valid_lft forever preferred_lft forever
    inet 10.0.1.205/24 brd 10.0.1.255 scope global secondary br0
       valid_lft forever preferred_lft forever
    inet6 fe80::ba27:ebff:feb2:d8f2/64 scope link 
       valid_lft forever preferred_lft forever

install openvpn

With the bridge working the next step will be installation and configuration of the OpenVPN server itself. Before we proceed with the server installation we will lay out the necessary fact about the network the server is on:

  • Our network is a class C net with a broadcast address of 10.0.1.0/24
  • Default gateway is 10.0.1.1
  • Network DNS is 10.0.1.152
  • The target network uses DHCP. We have set aside the range between 10.0.1.32 and 10.0.1.39 to be used by our clients,

Having clear our theses fact we may begin our installation.

pi@gabriella:~ $ sudo apt-get install openvpn easy-rsa 

Since all the commands that we will type from now on will require root privileges, it is wise to do a :

pi@gabriella:~ $ sudo su -
root@gabriella:~# cd /etc/openvpn/
root@gabriella:/etc/openvpn#

We will create a new server configuration file. This file is /etc/openvpn/server.conf with the following contents

# --------------------------------------------------------------------------------
# OpenVPN bridging configuration file.
# Adopted from the Ubuntu Community Page at https://help.ubuntu.com/community/OpenVPN
# Date may -15th 2016
# --------------------------------------------------------------------------------
mode server
tls-server

local 10.10.1.240       ## ip/hostname of server
port 1194               ## default openvpn port
proto udp

# --------------------------------------------------------------------------------
# Bidging directive
# --------------------------------------------------------------------------------
dev tap0 

script-security 2       ## allow calling up.sh and down.sh
up "/etc/openvpn/up.sh br0 tap0 1500"
down "/etc/openvpn/down.sh br0 tap0"

persist-key
persist-tun

# --------------------------------------------------------------------------------
# certificates and encryption
# --------------------------------------------------------------------------------
ca ca.crt
cert server.crt
key server.key          # This file should be kept secret
dh dh2048.pem
tls-auth ta.key 0       # This file is secret

cipher BF-CBC           # Blowfish (default)
comp-lzo

# Allow multiple clients to connect using the same client keys
# duplicate-cn

# --------------------------------------------------------------------------------
# DHCP Information
# --------------------------------------------------------------------------------
ifconfig-pool-persist ipp.txt
# The first address is the bridge address of the server the second is the netmask to use
# and the next twoo addresses are the range that should be assigned to clients
server-bridge 10.0.1.240 255.255.255.0 10.0.1.32 10.0.1.39
push "dhcp-option DNS 10.0.1.152"
push "dhcp-option DOMAIN simsons"
max-clients 8           ## set this to the max number of clients that should be connected at a time

# --------------------------------------------------------------------------------
# log and security
# --------------------------------------------------------------------------------
user nobody
group nogroup
keepalive 10 120
status openvpn-status.log
verb 3

Next we will need to create the two scripts that hook and unhook our tap device to the server bridge. These files should be called up.sh and down.sh (These are the names in server.conf file) with the following contents.

#!/bin/sh
# File up.sh adds a device to a bridge with a specified MTU

BR=$1    # bridge to add device to
DEV=$2   # actual device to add
MTU=$3   # MTU value

/sbin/ip link set "$DEV" up promisc on mtu "$MTU"
/sbin/brctl addif $BR $DEV
and
#!/bin/sh
# file down.sh remove a device from a bridge

BR=$1
DEV=$2

/sbin/brctl delif $BR $DEV
/sbin/ip link set "$DEV" down

Do not forget, to make both scripts executable

root@gabriella:/etc/openvpn# chmod +x up.sh down.sh 

Having done all that, it's time for a break. We will create our own DH 2048 bit file.

root@gabriella:/etc/openvpn# openssl dhparam -out dh2048.pem 2048
Generating DH parameters, 2048 bit long safe prime, generator 2
This is going to take a long time
................+........................................................................................................+.........................................

Even on a four core Raspberry-PI2 model B board, this takes well over 40 minutes, so sit back and relax

Create the Certificates

With the dh2048.pem file in place, we will start creating our server and client certificates by first copying the easy-rsa scripts to our servers setup directory and next creating the folder that will host our keys.

In order to make things a bit more secure we will create an additional tls-auth directive and the related key

root@gabriella:/etc/openvpn# openvpn --genkey --secret ta.key
root@gabriella:/etc/openvpn# cp -r /usr/share/easy-rsa/ /etc/openvpn
root@gabriella:/etc/openvpn# cd easy-rsa/
root@gabriella:/etc/openvpn/easy-rsa# mkdir keys

The Easy-RSA package that comes with the latest version of Rasbian (June-2019) provides three openssl.conf files depending on the installed version of the openssl package. Raspberry pi uses openssl 1.0 so, we need to link the correct version configuation file to openssl.conf.

# ln -sf openssl-1.0.0.cnf openssl.cnf

Next step is the creation of the actual server certificates. Open file /etc/openvpn/easy-rsa/vars and fill in the details accordingly.

root@gabriella:/etc/openvpn# vim /etc/openvpn/easy-rsa/vars 

Change the lines (first one is line 64 in my version) that refer to the certificate creation parameters, so they look similar to this:

# These are the default values for fields
# which will be placed in the certificate.
# Don't leave any of these fields blank.
export KEY_COUNTRY="gr"
export KEY_PROVINCE="Rodope"
export KEY_CITY="Komotini"
export KEY_ORG="Aryballos"
export KEY_EMAIL="admin@aryballos.gr"
export KEY_OU="Aryballos-IT-Services"

# X509 Subject Field
export KEY_NAME="server"
# Add this for Debian Stretch. ./build-ca will not work otherwise
export KEY_ALTNAMES="server"

Save, exist, run the file ... and do a clean-all to start fresh.

root@gabriella:/etc/openvpn/easy-rsa# . ./vars 
NOTE: If you run ./clean-all, I will be doing a rm -rf on /etc/openvpn/easy-rsa/keys
root@gabriella:/etc/openvpn/easy-rsa# ./clean-all

The next command will build the required certificate authorities for the server (Hit ENTER when there is a prompt).

root@gabriella:/etc/openvpn/easy-rsa# ./build-ca
Generating a 2048 bit RSA private key
...........................................................................................................+++
..............................................+++
writing new private key to 'ca.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [gr]:
State or Province Name (full name) [Rodope]:
Locality Name (eg, city) [Komotini]:
Organization Name (eg, company) [Aryballos]:
Organizational Unit Name (eg, section) [Aryballos-IT-Services]:
Common Name (eg, your name or your server's hostname) [Aryballos CA]:
Name [server]:
Email Address [admin@aryballos.gr]:
root@gabriella:/etc/openvpn/easy-rsa# 

Now it's time to build the actual server key.

root@gabriella:/etc/openvpn/easy-rsa# ./build-key-server server
Generating a 2048 bit RSA private key
.................................................................................................................................+++
....................................................+++
writing new private key to 'server.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [gr]:
State or Province Name (full name) [Rodope]:
Locality Name (eg, city) [Komotini]:
Organization Name (eg, company) [Aryballos]:
Organizational Unit Name (eg, section) [Aryballos-IT-Services]:
Common Name (eg, your name or your server's hostname) [server]:
Name [server]:
Email Address [admin@aryballos.gr]:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /etc/openvpn/easy-rsa/openssl-1.0.0.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'gr'
stateOrProvinceName   :PRINTABLE:'Rodope'
localityName          :PRINTABLE:'Komotini'
organizationName      :PRINTABLE:'Aryballos'
organizationalUnitName:PRINTABLE:'Aryballos-IT-Services'
commonName            :PRINTABLE:'server'
name                  :PRINTABLE:'server'
emailAddress          :IA5STRING:'admin@aryballos.gr'
Certificate is to be certified until May 13 14:09:17 2026 GMT (3650 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
root@gabriella:/etc/openvpn/easy-rsa# 

Copy the certificates to their designated place.

root@gabriella:/etc/openvpn/easy-rsa# cp /etc/openvpn/easy-rsa/keys/{server.crt,server.key,ca.crt} /etc/openvpn

Yes we are ready fire up the openvpn server!

root@gabriella:/etc/openvpn/easy-rsa# service openvpn start
root@gabriella:/etc/openvpn/easy-rsa# service openvpn status
● openvpn.service - OpenVPN service
   Loaded: loaded (/lib/systemd/system/openvpn.service; enabled)
   Active: active (exited) since Sun 2016-05-15 17:13:53 EEST; 4s ago
  Process: 2009 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
 Main PID: 2009 (code=exited, status=0/SUCCESS)

May 15 17:13:53 gabriella systemd[1]: Started OpenVPN service

At this point it would be very wise to switch to your ISP's router or firewall setup page and enable port 1194 forwarding between the external IP address of your router and the internal IP address of the OpenVPN server.

The final step will be to generate keys for the client. OpenVPN will not allow two clients with the same key to log on simultaneously, unless you add a line with duplicate-cn in the server.conf parameter file. Client certificates are build the same way as the server's, only this time you get to use the build-key script

root@gabriella:/etc/openvpn/easy-rsa# ./build-key client
Generating a 2048 bit RSA private key
..................+++
................+++
writing new private key to 'client.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [gr]:
State or Province Name (full name) [Rodope]:
Locality Name (eg, city) [Komotini]:
Organization Name (eg, company) [Aryballos]:
Organizational Unit Name (eg, section) [Aryballos-IT-Services]:
Common Name (eg, your name or your server's hostname) [client]:
Name [server]:
Email Address [admin@aryballos.gr]:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /etc/openvpn/easy-rsa/openssl-1.0.0.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'gr'
stateOrProvinceName   :PRINTABLE:'Rodope'
localityName          :PRINTABLE:'Komotini'
organizationName      :PRINTABLE:'Aryballos'
organizationalUnitName:PRINTABLE:'Aryballos-IT-Services'
commonName            :PRINTABLE:'client'
name                  :PRINTABLE:'server'
emailAddress          :IA5STRING:'admin@aryballos.gr'
Certificate is to be certified until May 13 14:31:07 2026 GMT (3650 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
root@gabriella:/etc/openvpn/easy-rsa# 

You may create a different key for each of the clients you want to allow access. Otherwise enable the duplicate-cn option on your server configuration file to allow multiple clients to connect with the same key.

Client setup

Each client must have the openvpn package installed. After installation move to the /etc/openvpn folder create a file named client.conf and enter the following:

### Client configuration file for OpenVPN

# Specify that this is a client
client

# Same setting as on server
script-security 3

# Bridge device setting
dev tap
proto udp

# Host name and port for the server (default port is 1194)
# note: replace with the correct values your server set up
remote  extennal_ip.of.openvpn.server 1194

# Client does not need to bind to a specific local port
nobind

user nobody
group nogroup

# Keep trying to resolve the host name of OpenVPN server.
## The windows GUI seems to dislike the following rule. 
##You may need to comment it out.
resolv-retry infinite

# Preserve state across restarts
persist-key
persist-tun
mute-replay-warnings

# SSL/TLS parameters - files created previously
ca /etc/openvpn/ca.crt
cert /etc/openvpn/client.crt
key /etc/openvpn/client.key
ns-cert-type server

# Since we specified the tls-auth for server, we need it for the client
# note: 0 = server, 1 = client
tls-auth /etc/openvpn/diaamath/ta.key 1

# Specify same cipher as server
cipher BF-CBC

# Use compression
comp-lzo

# Log verbosity (to help if there are problems)
verb 3

up /etc/openvpn/update-resolv-conf
down /etc/openvpn/update-resolv-conf

Next, copy the files ta.key, ca.crt, client.crt and client.key from the the server to the clients /etc/openvpn. directory.

Disable autostart of the OpenVPN service.

sudo update-rc.d openvpn disable

Reboot the client. (The OpenVPn setup usually fires up the OpenVPN service) And finally connect

sudo openvpn /etc/openvpn.client.conf

That should do it!

Links

This howto has been assembled using various sources. Most important being:

  1. The Ubuntu Community OpenVPN Wiki
  2. The Digital Ocean Tutorail about setting up an Open VPN Server on Debian 9
  3. The OpenVPN howto on the Debian Wiki

Friday, 14 June 2013

Using a raspberrypi as an sftp server

Following a previous post regarding how to use your raspberry-pi device as a file server, we are going to continue amd set up sftp service on the same pi device, so that it may be accessible over WAN.

The complete guide comes from a Mark Van den Borre posting available through this link.In our case however the steps are fewer, since raspberry has already the openssh server set up and running and if you have followed from the previous port we already have a user (bill) and a group (microsoft) to use for sftp service.

To get started let;s give our friend Bill a password:

pi@xena ~ $ sudo passwd bill 
Enter new UNIX password: 
Retype new UNIX password: 
passwd: password updated successfully

Next step will be to prevent Bill from interactively logging in. The usual remedy to this problem to use the sftp server as a login shell. After the post is over bill will not be able to access our pi from ssh either

pi@xena ~ $ sudo chsh bill 
Changing the login shell for bill
Enter the new value, or press ENTER for the default
        Login Shell [/usr/lib/tftp-server]: /usr/lib/sftp-server
pi@xena ~ $ 

Now for the sftp configuration itself. (Copying, pasting and adjusting from Mark's post we have something like this:) Open the default OpenSSH server configuration for editing:

pi@xena ~ $ sudo vi /etc/ssh/sshd_config

: and change the default sftp server from:

Subsystem sftp /usr/lib/openssh/sftp-server

to

Subsystem sftp internal-sftp

Some users can only use sftp, but not other OpenSSH features like remote login. Let's create a rule for that group of users. Add the following section to the bottom of /etc/ssh/sshd_config:

Match group microsoft
ChrootDirectory /mnt/SFTP-Data
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp
Reboot...

Wednesday, 10 April 2013

Using a raspberry-pi as a UPS server with nut

In this post we will try to install the Network UPS tools on a Raspberry-Pi device, attach a USB connected UPS and use it as a UPS server that will allow all machines sharing the same UPS to shut-down correctly when the UPS runs out of power. Our server will look after two clients; one running EL5 and the other openSUSE 11.4.

At the end of the post we will demonstrate how easy it is to set up your clients once the server is up and running and provide additional instructions for setting up the client software on Fedora 18 and EL6.

Update 2014-02-02: Meanwhile things here at the office have changed. The openSUSE machine is now gone and has been replaced by one running Debian 7. I have now revised the client setup guides for Fedora and EL5, 6 and I also have added one for Debian. The openSUSE "howto" is left as is but I can no longer verify if it works or not :) ..

Server Setup

Before we begin I would like to confess that my first attempt to install a no-name made in China UPS resulted to total failure, so eventually I got an expensive APC BackUPS Pro, that worked without any problems from the beginning, so unless your UPS is one supported by the UPS network tools project drivers, don't even try to follow the tutorial.

A second remark, is that if you are following the tutorial as the standard pi user you will need to prefix almost all commands with sudo. To become root on a standard Raspbian and follow along, you will need to issue sudo su-. (Thanks Derek for pointing it out)

root@raspbx:~# apt-get install nut-client nut-server
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following extra packages will be installed:
  libupsclient1
Suggested packages:
  nut-cgi nut-snmp nut-dev nut-xml
The following NEW packages will be installed:
  libupsclient1 nut-client nut-server
0 upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
Need to get 1,583 kB of archives.
After this operation, 3,217 kB of additional disk space will be used.
Do you want to continue [Y/n]? y
Get:1 http://archive.raspbian.org/raspbian/ wheezy/main libupsclient1 armhf 2.6.4-2.3 [106 kB]
Get:2 http://archive.raspbian.org/raspbian/ wheezy/main nut-client armhf 2.6.4-2.3 [191 kB]
Get:3 http://archive.raspbian.org/raspbian/ wheezy/main nut-server armhf 2.6.4-2.3 [1,286 kB]
Fetched 1,583 kB in 2s (562 kB/s)     
debconf: delaying package configuration, since apt-utils is not installed
Selecting previously unselected package libupsclient1.
(Reading database ... 37855 files and directories currently installed.)
Unpacking libupsclient1 (from .../libupsclient1_2.6.4-2.3_armhf.deb) ...
Selecting previously unselected package nut-client.
Unpacking nut-client (from .../nut-client_2.6.4-2.3_armhf.deb) ...
Selecting previously unselected package nut-server.
Unpacking nut-server (from .../nut-server_2.6.4-2.3_armhf.deb) ...
Processing triggers for man-db ...
Setting up libupsclient1 (2.6.4-2.3) ...
Setting up nut-client (2.6.4-2.3) ...
[info] nut-client disabled, please adjust the configuration to your needs.
[info] Then set MODE to a suitable value in /etc/nut/nut.conf to enable it.
Setting up nut-server (2.6.4-2.3) ...
[info] nut-server disabled, please adjust the configuration to your needs.
[info] Then set MODE to a suitable value in /etc/nut/nut.conf to enable it.
root@raspbx:~# 

Don't worry about the nut-server information we shall deal with it later on. Now an optional step that will allow us to to use the lsusb utility will be to install the usbutils package, assuming that it is not already there. So:

root@raspbx:~# apt-get install usbutils

.. and then -- blame me for my Windows habits, I firmly suggest a reboot. When the system is back on, we will make sure that out USB device is nιcely plugged in...

root@raspbx:~# lsusb
Bus 001 Device 002: ID 0424:9512 Standard Microsystems Corp. 
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. 
Bus 001 Device 004: ID 051d:0002 American Power Conversion Uninterruptible Power Supply
root@raspbx:~# 

Our UPS is there so let's set up the driver for the nut server. Open file /etc/nut/ups.conf and append the following lines at the end.

[apc1200]
        driver = usbhid-ups
        port = auto
        desc = "APC Back UPS Pro 1200VA supporting the two network servers"

You can name your ups anything you like, as far as the driver is concerned my advice is to browse through the official Network UPS Tools drivers list.

Setting up the UPS name and driver is not enough. I have not tested this on any other Debian box, but on raspberry-pi we need an extra step in order to create the /var/run/nut folder and set correct permissions to it.

root@raspbx:~# mkdir /var/run/nut
root@raspbx:~# chown root.nut /var/run/nut/
root@raspbx:~# chmod 770 /var/run/nut/

Now we are ready to test the UPS driver.

root@raspbx:~# upsdrvctl start
Network UPS Tools - UPS driver controller 2.6.4
Network UPS Tools - Generic HID driver 0.37 (2.6.4)
USB communication driver 0.31
Using subdriver: APC HID 0.95
root@raspbx:~# 

Our next step will be to configure upsd and upsmon. The network UPS tools design dictates that upsd communicates with the UPS driver that we just started and upsmon communicates with upsd and actually shuts down the machine in the event of a power failure. By providing this extra level of indirection, nut allows for multiple instances of upsmon to run on different machines. That way they can allow share the same physical UPS and this is what we said that we are going to demonstrate in this posting.

So to enable accessing the upsd via the network, edit the file /etc/nut/upsd.conf and place the following LISTEN directives.

LISTEN 127.0.0.1 3493
LISTEN 192.168.1.137 3493

192.168.1.137, is my pi's IP address -- replace that with your own. Next, we will need to add some kind of security and the next file that we will need to tamper with will be the /etc/nut/upsd.users. Edit it with your text editor and set up the following users

[admin]
        password = myadmpass
        actions = SET
        instcmds = ALL

#
# --- Configuring for a user who can execute tests only
#
[testuser]
        password  = pass  
        instcmds  = test.battery.start
        instcmds  = test.battery.stop

#
# --- Configuring for upsmon
#
# To add a user for your upsmon, use this example:
#
[upsmon_local]
        password  = local_pass
        upsmon master
[upsmon_remote]
        password  = remote_pass
        upsmon slave

Finally the local UPS monitor daemon will need to specify the UPS to monitor and the user credentials from upsd.users file. Open the /etc/nut/upsmon.conf file, locate the monitor section and add the following line:

MONITOR apc1200@localhost 1 upsmon_local local_pass master 

The number 1 after the ups name and host is the power value. The man page for upsd states clearly that:

The "current overall power value" is the sum of all UPSes that are currently able to supply power to the system hosting upsmon. Any UPS that is either on line or just on battery contributes to this number. If a UPS is critical (on battery and low battery) or has been put into "forced shutdown" mode, it no longer contributes.
A "power value" on a MONITOR line in the config file is the number of power supplies that the UPS runs on the current system.

Final steps: Open the /etc/nut/nut.conf file and change the value of Mode to netserver -- making sure that there are no spaces between each side of the = sign. (See NOTE at end of file) and issue the following commands:

root@raspbx:/etc/nut# service nut-server start
[ ok ] Starting NUT - power devices information server and drivers:  driver(s). upsd.
root@raspbx:/etc/nut# service nut-client start
[ ok ] Starting NUT - power device monitor and shutdown controller: nut-client.
root@raspbx:/etc/nut# 

As a last check, verify that both services will start automatically on system (using the update-rc.d command) reboot and yes, our server is ready! ...

root@raspbx:~# ps -ef | grep ups
nut       3275     1  0 Apr09 ?        00:08:24 /lib/nut/usbhid-ups -a apc1200
nut       3278     1  0 Apr09 ?        00:00:19 /sbin/upsd
root      3312     1  0 Apr09 ?        00:00:00 /sbin/upsmon
nut       3314  3312  0 Apr09 ?        00:00:09 /sbin/upsmon
root      4721  4711  0 18:44 pts/1    00:00:00 grep ups
root@raspbx:~#

Clients

Client setup requires more or less three things: One will be to edit the nut.conf file and set the mode variable value to netclient. Next will be to place the correct MONITOR line in the upsmon.conf file and the third will be to start the upsmon daemon.

openSUSE

Our first client is an openSUSE 11.4 machine that I keep saying that I must upgrade. To install nut on openSUSE we need to issue the following command as root.

zypper install nut

openSUSE nut stores the configuration files /etc/ups. By the way the file /usr/share/doc/packages/nut/README.SUSE offer excellent detailed and precise information on how to do things right. So to get things started:

  • Add the line MODE=netclient at the end of the /etc/ups/nut.conf file
  • Add MONITOR apc1200@asterisk "UPS supporting the main Servers" to /etc/hosts.conf
  • Comment out any reference to any UPS at the end of /etc/ups/ups.conf
  • Add MONITOR apc1200@asterisk 1 upsom_remote remote_pass slave
  • Start the service with etc/init.d/upsd start. (The reload option can be used to reread updated configuration files
  • Finally change the system config so that the service starts every time you start your system using the following command: chkconfig upsd on

Reboot and verify :

atlas:~ # ps -ef | grep ups
root      2958     1  0 18:06 ?        00:00:00 /usr/sbin/cupsd -C /etc/cups/cupsd.conf
root      3374     1  0 18:06 ?        00:00:00 /usr/sbin/upsmon
upsd      3376  3374  0 18:06 ?        00:00:00 /usr/sbin/upsmon
root      4776  4732  0 18:13 pts/0    00:00:00 grep ups

You might probably want to test the configuration and whether the upsmon daemon can shut-down your server, so go ahead and ...

atlas:~ # upsmon -c fsd
Network UPS Tools upsmon 2.6.0
                                                                               
Broadcast Message from upsd@atlas                                              
        (somewhere) at 13:57 ...                                               
                                                                               
Executing automatic power-fail shutdown                                        
                                                                               
                                                                              

Broadcast message from root@atlas (Wed Apr 10 13:57:06 2013):

The system is going down for system halt NOW!

Debian/Ubuntu

Perhaps the easiest setup is on a Debian system. You only need four steps:

  1. Install just the client: sudo apt-get install nut-client.
  2. Edit the file/etc/nut/nut.conf and set the mode to netclient. MODE=netclient (mind that there must be no spaces around the equals sign).
  3. Add the monitor MONITOR apc900@xena 1 upsom_remote remote_pass slave command in the /etc/nut/upsmon.conf.
  4. Restart the nut-client service
    service nut-client restart
  5. Update the system to start the service automatically update-rc.d nut-client defaults

Fedora and CentOS versions 5 & 6

Fedora also stores the nut related data in /etc/ups. Again here we need to perform the three steps we mentioned before, but this time we will need to start the upsmon daemon by hand. So to set up our fedora box as a network client:

  • Install the software using yum install nut-client
  • Add MONITOR apc1200@asterisk 1 upsom_remote remote_pass slave
  • Add /usr/sbin/upsmon start in /etc/rc.d/rc.local to verify that the monitor program will start again after reboot.
    Note: On my Fedora 20 system the file was not present so I had to create it, turn it into a shell script by adding !/bin/sh at the first line and make it executable.

Verify:

[thanassis@skymnos ~]$ ps -ef | grep upsmon
root      1898     1  0 17:37 ?        00:00:00 /usr/sbin/upsmon start
nut       1900  1898  0 17:37 ?        00:00:00 /usr/sbin/upsmon start
500       2142  2118  0 17:38 pts/0    00:00:00 grep upsmon

NUT Monitor

A very good GUI based tool to help test the ups servers. It can be easily installed using the package manager of your distribution -- just search for the nut-monitor package and after you install and run it, it looks like this:

Windows

Winnut is a Windows client, that runs as a 32bit service on Windows 7. The project has not been updated since February 24, 2011. I did install the software on a Windows machine but have not been able to do any serious testing. The program's configuration follows the same rules as the Linux clients. The only thing you have to is click the edit configuration file button

and then add the correct MONITOR Line in the upsmon.conf file that will appear loaded into notepad. On 64bit systems you will also need to change the line

NOTIFYCMD "\"c:\\Program Files\\WinNUT\\alertPopup.exe\""

to

NOTIFYCMD "\"c:\\Program Files (x86)\\WinNUT\\alertPopup.exe\""

Thursday, 6 December 2012

Using a raspberrypi as a file server

The idea came to me from a friend. I wanted to install a small network storage system to use merely as a file exchange repository at the office and I was looking to buy some kind of Ethernet disk, when he said to me why don't you do it with a raspberry and a USB flash drive?. The thought was intriguing -- to say the least, so here I am with all the little details:

I am not going to go through the entire process of downloading and preparing the raspberry SD card from the Raspberry Pi Downloads page. The cool thing with raspberry is that once you get it running for the first time, you get a real Debian Linux that does all you expect a descent OS to do.

A pleasant surprise with the raspberry image was that the default set-up registered itself to my dynamic DNS and I was able to log into raspberrypi the moment I plugged it into my LAN without touching a thing.

The first thing that I needed to do was change the hostname of the device. That way there would be no name conflicts when I add a fresh one for the next God knows what project that will come up...

Changing the host name is as simple as editing the file /etc/hostname, changing the single line with the word raspeberrypi to xena (Yes i wanted an ... epic name) and then rebooting. The DNS picked up the name change and logging into xina was as easy as typing ssh -l pi xena -X. (An even easier way to accomplish the task is to use raspi-config. Check the advanced options menu)

Next thing would be a plug the USB disk and make sure it gets mounted every time the system boots. I suppose that the proper way to make this work would be to tamper with /etc/fstab. I chose to do it a bit differently and ended up creating a file containing the last things that the system should do right after booting.

First create a mount point and mount the USB disk. In my case, I created /mnt/SFTP-Data and tested it with a:
mount /dev/sda1 /mnt/STFP-Data

The idea with executing commands right after boot is that we need to create a file, let's call it system-startup.sh that contains the above mount command, plua the necessary LSB comments, place it in /etc/init.d, make it executable and then run insserv to add this command as the last default runlevel action. The format of the comments section is :

#! /bin/sh
### BEGIN INIT INFO
# Provides: system-start.sh
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start up script after boot
# Description: Enable service provided by daemon.
### END INIT INFO
mount /dev/sda1 /mnt/STFP-Data

...and the actual command to make this work is:
sudo insserv /etc/init.d/system-startup.sh

Finally, it time to install and configure Samba. The Debian Administrator's handbook says it all. Just remember that raspebrry-pi only has 256MB of actual RAM so keep away from web configuration tools like swat and go with the debconf and manually editing the the smb.conf file option.

After Samba is up and running edit the file /etc/samba/smb.conf and fix the basic staff like work group name and server description. Mine looks like this:

[global]
## Browsing/Identification ###

# Change this to the workgroup/NT-domain name your Samba server will part of
   workgroup = aryballos

# server string is the equivalent of the NT Description field
   server string = %h Raspberry-PI Server

# Windows Internet Name Serving Support Section:
# WINS Support - Tells the NMBD component of Samba to enable its WINS Server
  wins support = yes

In order to create a read write share that anyone can use, we need to create a new user that has read/write access to the disk and then force that use and group everytime that someone accesses data through the Samba share.

pi@xena /etc/samba $ groupadd microsoft
pi@xena /etc/samba $ useradd -c "Samba user" -m -d /mnt/mdz-disk/shared/ -g microsoft bill

There are two things here. First Bill does not have a password so he can not log in interactively. Second Bill's home is the directory on the disk where I want everybody to have full read/write access. Telling this to the Samba server requires that the following section be placed at the end of the smb.comf file ...

[public]
   comment = Public data in the USB drive for our work-group
   read only = no
   path = /mnt//mnt/STFP-Data/public
   guest ok = yes
   force user = bill
   force group = microsoft

... the directory is made and permissions are set

pi@xena /mnt/SFTP-Data $ sudo mkdir public
pi@xena /mnt/SFTP-Data $ sudo chown bill.microsoft public/

... and finally the samba service is restarted...

pi@xena /etc/samba $ sudo service samba restart
[ ok ] Stopping Samba daemons: nmbd smbd.
[ ok ] Starting Samba daemons: nmbd smbd.
pi@xena /etc/samba $