msgbartop
Blog di Dino Ciuffetti (Bernardino in realtà)
msgbarbottom

30 Ott 14 WPA2 connection without NetworkManager in Debian linux

This is a memo that I can use to remember how to enable WPA2 protected WiFI connections with debian without using NetworkManager.

All that you have to do is:

  • create the file /etc/wpa_supplicant/wpa_supplicant.conf with the following content:

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=0
country=IT
ap_scan=2

network={
ssid=”My WiFI SSID”
psk=”mysupersecret password”
bssid=””
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP TKIP
group=TKIP
}

  • if you want to set a static IP, add the following content to the file /etc/network/interfaces

iface wlan0 inet static
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
address 192.168.100.7
netmask 255.255.255.0
network 192.168.100.0
broadcast 192.168.100.255

  • if, instead, you want a dynamic address assigned by a DHCP server, add the following to /etc/network/interfaces

iface wlan0 inet dhcp
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

  • now, setup the connection with this command by root (sudo before the command if you are on ubuntu):

ifup wlan0

  • when you have finisched with the connection, close it up with the command by root (sudo before the command if you are on ubuntu)

ifdown wlan0

 

28 Ott 14 Best rsync options to mirror a remote directory

If you want to mirror a remote directory via SSH, you may want to use the wonderful rsync command.

The rsync executable has many options, so, which is the correct option list to make an exact copy of a remote directory, maintaining permissions, ownerships, timestampts, copying only the modified files, and updating only the pieces of modified files?

Let me begin with an example. We want to full mirror the directory /mystuff on server 1.2.3.4 into /mystufflocal. The files deleted on 1.2.3.4 from the previous rsync will be removed locally too, so pay attention! If you don’t want to locally remove deleted files you can remove the “–delete” option.
If you want to compress the stream in transit you can add the “-z” option.
All we have to do is:

rsync -vartuh –inplace –delete –progress –stats -e “ssh -carcfour128” root@1.2.3.4:/mystuff/ /mystufflocal/

The trailing slashes are important because are used by rsync to understand precisely what should be transferred and where.

27 Ago 14 Squid: how to get rid of “All url_rewriter processes are busy”

If you check your squid forward (transparent or not) proxy log files you may found errors like those:

WARNING: All url_rewriter processes are busy.
WARNING: up to 6 pending requests queued

This is true if you use the directive “url_rewrite_program”, for example with SquidGuard.
In this case, squid tells you that it cannot spawn more helper processes to externally scan your requests in parallel, so it’s queuing your requests.
This is not a great problem, but you may be annoyed to see this stuff in your log files, or there are cases in which the default may be too low!

You may raise this limit with the parameter called url_rewrite_children.

To solve, add something like this to your squid.conf configuration file, and restart squid:

url_rewrite_children 32

Ciao, Dino.

21 Ago 14 How to enable apache NameVirtualHost with SSL

If you want to create name based virtualhosts in apache with SSL Certificates, you need openssl with SNI and TLS support (0.9.8f or better) and good apache 2.2.X version.

It’s a simple task, after you’ve read this official article: https://wiki.apache.org/httpd/NameBasedSSLVHostsWithSNI

12 Giu 14 How to declare a read only variable in bash

I didn’t know that it was possible to declare a read only variable in bash.

It’s as simple as to run the following statement:

declare -r a=10

This will create a read only variable called $a with value 10 that you cannot overwrite or unset.
Cool!!

02 Apr 14 Adafruit 4-Digit 7-Segment Display Backpack on raspberry pi in C

In my previous blog post I published a TSL2561 light sensor driver in C for Raspberry PI. In this article I will publish a user space C driver for Adafruit 4-digit 7-segment display.

This is based on a HT16K33 led driver IC, that it’s a I2C driven RAM mapping 16*8 LED controller driver.

The driver I’m posting it’s valid for the adafruit circuit only, since it’s completely based on the electronic schematic they realized.
Don’t use the driver with other circuits, since the display could not function properly.
Basically the adafruit 7-segment backpack (http://www.adafruit.com/products/879) uses 8 (rows) * 5 (columns) HT16K33 lines to drive its leds. The column number 1 is dedicated to the first digit, the second column is dedicated to the second digit, the third column is attached to the colon sign in the middle of the 4 digits, the fourth column is attached to the third digit, and the fifth colum to the fourth display digit.

adafruit_7seg_schematic

While each row drives a single led of the given column.

The display columns 0, 1, 3, 4 can show numbers and some letters (A-F, n, o, i, l, L, etc…) plus a decimal point, while the column 2 can only show a colon sign (:).
A number or a letter for each digit is composed by 7 led segments, so the possibilities are few… but not so few after all (check 7seg.txt file attachment for more details on letter composition).

So, now comes the fun. How can I access the led driver memory to light display digits in C? Adafruit releases proof of concept libraries in C and python, but they don’t seem to run on my raspberry pi.
Since I am too lazy to port their code with external dependencies, I decided to write my own library in C.

#include "7seg_bp_ada.h"

/* prepare the backpack driver
(the first parameter is the raspberry pi i2c master controller attached to the HT16K33, the second is the i2c selection jumper)
The i2c selection address can be one of HT16K33_ADDR_01 to HT16K33_ADDR_08
*/
HT16K33 led_backpack1 = HT16K33_INIT(1, HT16K33_ADDR_01);

/* initialize the backpack */
rc = HT16K33_OPEN(&led_backpack1);

/* power on the ht16k33 */
HT16K33_ON(&led_backpack1);

/* make it shining bright */
HT16K33_BRIGHTNESS(&led_backpack1, 0x0F);

/* make it not blinking */
HT16K33_BLINK(&led_backpack1, HT16K33_BLINK_OFF);

/* power on the display */
HT16K33_DISPLAY(&led_backpack1, HT16K33_DISPLAY_ON);

/* Say hello */
HT16K33_UPDATE_DIGIT(&led_backpack1, 0, 'H', 0); // first digit
HT16K33_UPDATE_DIGIT(&led_backpack1, 1, 'E', 0); // second digit
// turn off the colon sign in the middle of the 4 digits
HT16K33_UPDATE_DIGIT(&led_backpack1, 2, HT16K33_COLON_OFF, 0);
HT16K33_UPDATE_DIGIT(&led_backpack1, 3, '#', 0); // third digit
HT16K33_UPDATE_DIGIT(&led_backpack1, 4, 'o', 0); // fourth digit
HT16K33_COMMIT(&led_backpack1); // commit to the display memory

// call this if you want to shut down the device (power saving mode)
// HT16K33_OFF(&led_backpack1);

/* close things (the display remains in the conditions left) */
HT16K33_CLOSE(&led_backpack1);

I decided to release the software with the liberal apache 2 license, so feel free to use this software inside your commercial, non free software / firmware.

Below you will find the files .c and .h that you can embed into your project.
It’s helpful for me, and I hope it will be helpful for you.

Ciao, Dino.

Note: on Raspberry PI OS (and debian) you need libi2c-dev (apt install libi2c-dev) before compiling.

gcc -Wall -O2 -o 7seg_bp_ada.o -c 7seg_bp_ada.c
gcc -Wall -O2 -o 7seg_bp_ada_test.o -c 7seg_bp_ada_test.c
gcc -Wall -O2 -o 7seg_bp_ada_test 7seg_bp_ada.o -li2c 7seg_bp_ada_test.o

7seg_bp_ada.c
7seg_bp_ada.h
7seg_bp_ada_test.c

21 Feb 14 HOWTO generate a SAN (Subject Alternative Names) SSL CSR with OpenSSL

There is a cool SSLv3 protocol extension that’s called SAN (Subject Alternative Names). With this extension you can create a single SSL X509 certificate that is valid for several domain names, instead of a classic certificate that’s valid for one domain name only.

You can ofcourse create this kind of certificate with OpenSSL. We are now going to see how to do that.
Fist you have to create a file called openssl.cnf and put it for example into a temporary dir. The file should begin with:

[req]
distinguished_name = req_distinguished_name
req_extensions = v3_req

This is to enable SSLv3 req extensions.
Now, you have to add your custom informations to the openssl.cnf file: those informations will be reflected on the next steps.
Add something like this to openssl.cnf:

[req_distinguished_name]
countryName = Country Name (2 letter code)
countryName_default = IT
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = Italy
localityName = Locality Name (eg, city)
localityName_default = Rome
organizationName = Organization name
organizationName_default = My company name Srl
organizationalUnitName = Organizational Unit Name (eg, section)
organizationalUnitName_default = System Techies
commonName = Common Name (eg, YOUR name)
commonName_max = 64
#commonName_default = www.myfirstdomain.it
emailAddress = Email Address
emailAddress_max = 40

The informations above are used by the “openssl req” command to ask you data to generate your certificate request.
Then, add this block of informations into the openssl.cnf file:

[v3_req]
keyUsage = nonRepudiation, digitalSignature, keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth, clientAuth
subjectAltName = @alt_names

Those informations will enable some extra useful things on your certificate request that will hopefully became valid on your brand new SSLv3 certificate. For example you are requesting your Certification Authority to release a X509 SSLv3 certificate with server and client authentication purposes, plus other certificate goodies.

Now the cool part: this is where you are asking your CA to release a certificate with Alternative Names (certificate valid for several domains). Append this stuff in openssl.cnf:

[alt_names]
DNS.1   = www.myfirstdomain.it
DNS.2   = myfirstdomain.it
DNS.3   = www.myalternativedomain.it
# you could also specify IP addresses like this:
# IP.1 = 1.2.3.4

OK. You are almost ready to create your CSR, but first you have to generate your private key.
NOTE that many CA are now requesting a private key of 2048 bits or more. Warned: a key of 1024 bits is not recommended!
To generate a 2048 bits private key, as usual, execute this command:

openssl genrsa -out server.key 2048

Perfect. It’s time to create the Certificate Request (PKCS#10) with SSLv3 extensions:

openssl req -new -out server.csr -key server.key -config openssl.cnf

Now, send your new server.csr file to your Certification Authority that will hopefully accept the request and relase a valid X509 SSLv3 certificate with SAN.

Good luck and enjoy.

22 Gen 14 Alta affidabilità o bilanciamento di carico su OpenLDAP 2.4.x?

Come saprete, l’ultimo filone di openldap (2.4.x) supporta una varietà di meccanismi di replica utili per la realizzazione dell’alta affidabilità. Si trovano in rete vari documenti su cui potete osservare i vari meccanismi e i loro pro e contro. Ne riporto un paio tra i più rappresentativi (in lingua inglese):
http://www.openldap.org/doc/admin24/replication.html
http://www.synetis.com/en/2012/09/03/replication-openldap

Faccio presente che non esistono configurazioni di ldap che permettono una gestione trasparente dell’alta affidabilità, infatti tutte le configurazioni hanno bisogno di un bilanciatore di carico o un sistema di cluster manager per poter gestire il flusso di dati verso il server ldap attivo, la replica ha il solo scopo di mantenere aggiornati tutto il tempo gli ldap server.

In particolare, se vi è la disponibilità di soli due server e la volontà di realizzare l’alta affidabilità, vorrei consigliare la modalità di replica di opendap 2.4.X chiamata MIRROR MODE, di cui riporto pro e contro come indicato nel documento “http://www.synetis.com/en/2012/09/03/replication-openldap/”:

A mirror is composed of only two nodes. Both nodes are configured in both master and slave. In this mode, both nodes are identical at all times. They are writable and it is possible to update either one or the other.

Advantages:
If a node is down, on his return, it automatically updates;
– If the data files of a node is destroyed, when it restarts, it will synchronize completely from the other node;
A node is configured as a master. It is possible to connect consumers.

Disadvantages:
– Mass treatment of update of a node are longer in fashion provider / consumers, because the two nodes are updated simultaneously and in full mode.

Sebbene in questa modalità sia prevista l’operatività sia in scrittura che in lettura di entrambi i nodi ldap, il documento ufficiale di openldap “http://www.openldap.org/doc/admin24/replication.html”, relativamente al paragrafo 18.2.3, specifica che la corretta configurazione è quella di utilizzare in scrittura un nodo per volta.

Riporto il testo del paragrafo in questione:

MirrorMode is a hybrid configuration that provides all of the consistency guarantees of single-master replication, while also providing the high availability of multi-master. In MirrorMode two providers are set up to replicate from each other (as a multi-master configuration), but an external frontend is employed to direct all writes to only one of the two servers. The second provider will only be used for writes if the first provider crashes, at which point the frontend will switch to directing all writes to the second provider. When a crashed provider is repaired and restarted it will automatically catch up to any changes on the running provider and resync.

Il fatto che le scrittura debbano essere spedite ad un master per volta è necessario (come in un qualsiasi sistema multi master) ad evitare l’accesso concorrente alla stessa risorsa (record).
Questo tipo di configurazione infatti risolve a priori qualsiasi conflitto di concorrenza a livello di record e allo stesso tempo garantisce l’alta affidabilità.

A questo punto è possibile ipotizzare un paio di configurazioni architetturali per identificare quale sarà il frontend esterno che dovrà gestire le richieste in scrittura su uno dei nodi ldap:
1) l’utilizzo di un bilanciatore di carico hardware a livello TCP/IP, impostato non in modalità round robind ma in modalità Active/Standby con controllo della risorsa (porta TCP/389);
2) l’utilizzo di un gestore di cluster come Linux HA (http://www.linux-ha.org/wiki/Main_Page) che gestisca lo switch dell’IP di erogazione del servizio ldap su uno dei nodi ldap in replica incrociata, erogato sul server supersite in caso di fault di uno dei due nodi.

Se si sceglie la prima ipotesi, volendo, si potrebbe prevedere una terza possibilità utile al mantenimento dell’alta affidabilità in lettura/scrittura e allo stesso tempo per ottenere il bilanciamento di carico per le richieste in sola lettura sui due nodi. Quest’ultima possibilità prevede l’utilizzo di due indirizzi IP, uno in HA da utilizzarsi per le sole scritture, nelle modalità indicate al punto 1 di cui sopra, e l’altro IP che bilancia il traffico in lettura sui due nodi, tramite una configurazione in modalità round robin verso i due nodi ldap.

Per riassumere, considerando che le macchine sono linux redhat 6, se si sceglie la prima ipotesi (letture e scritture LDAP in HA su uno dei due nodi tramite utilizzo di un bilanciatore hardware), la lista della spesa è:

– installazione di OpenLDAP 2.4.X su tutti e due i nodi. I processi devono sempre essere mantenuti attivi contemporaneamente;
– configurazione di un indirizzo IP (VIP) da associare all’erogazione del servizio che viene impostato sul bilanciatore di carico;
– configurazione dei due nodi LDAP in modalità MirrorMode

Se si sceglie la seconda ipotesi (utilizzo di un gestore di cluster per ottenere letture e scritture LDAP in HA), la lista è:
– installazione di OpenLDAP 2.4.X su tutti e due i nodi. I processi devono sempre essere mantenuti attivi contemporaneamente;
– installazione e configurazione di un cluster manager come linux-ha (http://www.linux-ha.org/wiki/Main_Page) sui due nodi;
– configurazione di un indirizzo IP (VIP) da associare all’erogazione del servizio che viene impostato sul cluster manager;
– configurazione dei due nodi LDAP in modalità MirrorMode

La terza ipotesi (utilizzo di due IP su bilanciatore hardware, con scritture in HA su uno dei due nodi e letture in bilanciamento di carico) prevede la seguente lista della spesa:
– installazione di OpenLDAP 2.4.X su tutti e due i nodi. I processi devono sempre essere mantenuti attivi contemporaneamente;
– configurazione di due indirizzi IP (VIP), uno da associare all’erogazione del servizio di sole letture che viene impostato sul bilanciatore di carico in modalità round robin, l’altro da associare all’erogazione del servizio di lettura e scrittura che viene impostato sul bilanciatore di carico in modalita’ active/standby con controllo della risorsa;
– configurazione dei due nodi LDAP in modalità MirrorMode

Sono tutte e tre valide, anche se secondo me la migliore è la terza perchè permette HA + bilanciamento di carico in lettura, HA in scrittura, e soprattutto la divisione logica dei flussi di scrittura e lettura.

Ciao, Dino Ciuffetti.

05 Dic 13 As you can see, this site is reachable via IPv6!

If you are using IPv6 (like me) you can see that this blog is reachable via IPv6. Pretty cool!

ipv6 ready

14 Nov 13 LVM Hot backups with snapshot

As you may know, LVM make it possible to create live snapshots of running logical volumes.
Imagine a guest virtual machine that has its virtual disk backed on a LVM logical volume on the host system.
You may create a live hot backup of your virtual machine on the fly, while it is working.

To do this, I created a small script that makes a compressed backup of all the logical volumes on the /dev/vg0 volume group.
The script make use of the standard LVM utilities to have the snapshot, the pv utility to get a cool progress bar and pigz utility to compress (gzip) using all of your processors.
If everything went ok, when the script finishes you’ll find your LVM hot backups on the /backups directory, and the temporary lvm snapshots removed.

This is how I make hot backups of some of my virtual machines (lvm_hot_backup.sh):

#!/bin/bash

for lv in `lvdisplay /dev/vg0 | grep ‘LV Name’ | awk ‘{print $3}’`
do
LV_SIZE=”`lvs –units m –noheadings –nosuffix $lv | cut -d’ ‘ -f7 | cut -d. -f 1`” # LV size in MB
LV_UUID=”`lvdisplay $lv | grep ‘LV UUID’ | awk -F’LV UUID’ ‘{print $2}’ | sed ‘s/^ *//g’`”
LV_SNAPNAME=”SNAP_`basename $lv`”

echo “LVM Logical Volume: $lv”
echo “Size: $LV_SIZE MB”
echo “UUID: $LV_UUID”
echo “Snapshot name: $LV_SNAPNAME”
echo “Removing old snapshot (if any)…”
lvremove -f “/dev/vg0/$LV_SNAPNAME”
echo “Creating snapshot…”
lvcreate -L+2G –snapshot -n”$LV_SNAPNAME” “$lv”
sleep 4
echo “Backing up snapshot…”
dd if=”/dev/vg0/$LV_SNAPNAME” bs=512k of=/dev/stdout | pv -pterbW -i 2 –buffer-size 512k –size “$LV_SIZE”m | /usr/bin/pigz -9 -b 256 > “/backups/$LV_SNAPNAME.lv.gz”
echo “Removing snapshot…”
lvremove -f “/dev/vg0/$LV_SNAPNAME”
echo “–”
done