вторник, 1 июля 2014 г.

Fresh u-boot images (01 july 2014) for atheros-based routers


I revised original's sources for pepe2k's u-boot mod (https://github.com/pepe2k/u-boot_mod) for atheros-bases routers and dev-boards.
And i decided to recompile fresh u-boot images for all capable routers. Here they are:

uboot_for_tp-link_tl-wr740n_v4.bin https://app.box.com/s/3pxe21ar1rsbi9b7ne1i
uboot_for_tp-link_tl-wr720n_v3_CH.bin https://app.box.com/s/epcyt2vpo435uklug5uh
uboot_for_tp-link_tl-wr710n.bin https://app.box.com/s/2q2uvhvfsnpwol5b2evb
uboot_for_tp-link_tl-wr703n.bin https://app.box.com/s/z13rrr8v8vdu70la67jn
uboot_for_tp-link_tl-mr3220_v2.bin https://app.box.com/s/v6jclan4ycu8mhphqrpf
uboot_for_tp-link_tl-mr3040.bin https://app.box.com/s/a0nw5w2hlmoz7giy8ll7
uboot_for_tp-link_tl-mr3020.bin https://app.box.com/s/yk395fpy7d2ukmd4tvgf
uboot_for_tp-link_tl-mr13u.bin https://app.box.com/s/ztfqxrdje9i36sw0edca
uboot_for_tp-link_tl-mr10u.bin https://app.box.com/s/kq1jqtb041em8uwzhfki
uboot_for_gs-oolite_v1_dev.bin https://app.box.com/s/o9blybah1xsnxt4bs0w1
uboot_for_dragino_v2_ms14.bin https://app.box.com/s/lw8cl6fzzouk6ilyxrkx
uboot_for_d-link_dir-505.bin https://app.box.com/s/fguydczy84zbahv3vtke
uboot_for_8devices_carambola2.bin https://app.box.com/s/9k2peuxxjjgb8mcxbrxb

вторник, 29 апреля 2014 г.

Your own certificate authority(CA) with EasyRSA 3.0


You always can buy certificate for your Webserver/VPN or even order free one from StartSSL. But what if you can do everything by yourself? Create your CA, create signed server certificates, create client certificates, use client ssl-certs to authorize on your servers? Sounds cool, let's do it, step by step.

Clone project from github.
# git clone https://github.com/OpenVPN/easy-rsa

Take directory from git tree and make copy of it.
# cp -a easy-rsa/easyrsa3/ test-ca/

Modify settings for fit your needs.
# cd test-ca/
# cp vars.example vars
# $EDITOR vars

(will look like this)
if [ -z "$EASYRSA_CALLER" ]; then
 echo "You appear to be sourcing an Easy-RSA 'vars' file." >&2
 echo "This is no longer necessary and is disallowed. See the section called" >&2
 echo "'How to use this file' near the top comments for more details." >&2
 return 1
fi
set_var EASYRSA "$PWD"
set_var EASYRSA_PKI  "$EASYRSA/pki"
set_var EASYRSA_DN "cn_only"
set_var EASYRSA_REQ_COUNTRY "RU"
set_var EASYRSA_REQ_PROVINCE "Moscow"
set_var EASYRSA_REQ_CITY "Moscow"
set_var EASYRSA_REQ_ORG  "OOO Roga and Kopyta"
set_var EASYRSA_REQ_EMAIL "noc@rogaandkopyta.ru"
set_var EASYRSA_REQ_OU  "Devops department"
set_var EASYRSA_KEY_SIZE 2048
set_var EASYRSA_ALGO  rsa
set_var EASYRSA_CA_EXPIRE 3650
set_var EASYRSA_CERT_EXPIRE 3650
set_var EASYRSA_CRL_DAYS 180

Init pki
# ./easyrsa init-pki

Build CA
# ./easyrsa build-ca


Note: using Easy-RSA configuration from: ./vars
Generating a 2048 bit RSA private key
......................+++
...................................+++
writing new private key to '/root/test-ca/pki/private/ca.key'
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----
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.
-----
Common Name (eg: your user, host, or server name) [Easy-RSA CA]:ca.rogaandkopyta.ru

CA creation complete and you may now import and sign cert requests.
Your new CA certificate file for publishing is at:
/root/test-ca/pki/ca.crt

Create certificate sign request(csr) (WITHOUT password)

./easyrsa gen-req wildcard.rogaandkopyta.ru nopass

Note: using Easy-RSA configuration from: ./vars

Generating a 2048 bit RSA private key
...........................................+++
................................+++
writing new private key to '/root/test-ca/pki/private/wildcard.rogaandkopyta.ru.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.
-----
Common Name (eg: your user, host, or server name) [wildcard.rogaandkopyta.ru]:*.rogaandkopyta.ru

Keypair and certificate request completed. Your files are:
req: /root/test-ca/pki/reqs/wildcard.rogaandkopyta.ru.req
key: /root/test-ca/pki/private/wildcard.rogaandkopyta.ru.key

Sign csr and create certificate

# ./easyrsa sign-req server wildcard.rogaandkopyta.ru

Note: using Easy-RSA configuration from: ./vars

You are about to sign the following certificate.
Please check over the details shown below for accuracy. Note that this request
has not been cryptographically verified. Please be sure it came from a trusted
source or that you have verified the request checksum with the sender.

Request subject, to be signed as a server certificate for 3650 days:

subject=
    commonName                = *.rogaandkopyta.ru

Type the word 'yes' to continue, or any other input to abort.
  Confirm request details: yes
Using configuration from /root/test-ca/openssl-1.0.cnf
Enter pass phrase for /root/test-ca/pki/private/ca.key:
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName            :T61STRING:'*.rogaandkopyta.ru'
Certificate is to be certified until Apr 25 13:40:38 2024 GMT (3650 days)

Write out database with 1 new entries
Data Base Updated

Certificate created at: /root/test-ca/pki/issued/wildcard.rogaandkopyta.ru.crt

All done, your server certificate now awaits at pki/issued/wildcard.rogaandkopyta.ru.crt. Key for this certificate is at pki/private/wildcard.rogaandkopyta.ru.key
Put these two files to your web-server. If you need to access web-server via client certs, you need ca.crt too.
Example part for nginx's vhost config
 ssl on;
        server_name test.rogaandkopyta.ru;
        ssl_certificate          /etc/nginx/ssl/wildcard.rogaandkopyta.ru.crt;
        ssl_certificate_key      /etc/nginx/ssl/wildcard.rogaandkopyta.ru.key;
        #ssl_client_certificate /etc/nginx/ssl/ca.crt;
        #ssl_verify_client on;

EasyRSA 3.0 Удостоверяющий центр


Можно всегда заказать за денюшку сертификат для собственного веб- или openvpn-сервера, даже можно заказать бесплатный сертификат от StartSSL. Но ведь можно сделать всё и самостоятельно, особенно если этих самых сертификатов придется генерить очень много. Расскажу про создание своего удостоверяющего центра и создадим сертификат для веб-сервера. Поехали.

Клонируем репо с гитхаба.
# git clone https://github.com/OpenVPN/easy-rsa

Делаем копию нужной нам директории, чтобы потом можно было сделать git pull и обновиться.
# cp -a easy-rsa/easyrsa3/ test-ca/

Настраиваем под себя.
# cd test-ca/
# cp vars.example vars
# $EDITOR vars

Файл vars должен выглядеть примерно так
if [ -z "$EASYRSA_CALLER" ]; then
 echo "You appear to be sourcing an Easy-RSA 'vars' file." >&2
 echo "This is no longer necessary and is disallowed. See the section called" >&2
 echo "'How to use this file' near the top comments for more details." >&2
 return 1
fi
set_var EASYRSA "$PWD"
set_var EASYRSA_PKI  "$EASYRSA/pki"
set_var EASYRSA_DN "cn_only"
set_var EASYRSA_REQ_COUNTRY "RU"
set_var EASYRSA_REQ_PROVINCE "Moscow"
set_var EASYRSA_REQ_CITY "Moscow"
set_var EASYRSA_REQ_ORG  "OOO Roga and Kopyta"
set_var EASYRSA_REQ_EMAIL "noc@rogaandkopyta.ru"
set_var EASYRSA_REQ_OU  "Devops department"
set_var EASYRSA_KEY_SIZE 2048
set_var EASYRSA_ALGO  rsa
set_var EASYRSA_CA_EXPIRE 3650
set_var EASYRSA_CERT_EXPIRE 3650
set_var EASYRSA_CRL_DAYS 180

Инициализируем pki
# ./easyrsa init-pki

Создаем CA
# ./easyrsa ./easyrsa build-ca


Note: using Easy-RSA configuration from: ./vars
Generating a 2048 bit RSA private key
......................+++
...................................+++
writing new private key to '/root/test-ca/pki/private/ca.key'
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----
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.
-----
Common Name (eg: your user, host, or server name) [Easy-RSA CA]:ca.rogaandkopyta.ru

CA creation complete and you may now import and sign cert requests.
Your new CA certificate file for publishing is at:
/root/test-ca/pki/ca.crt

Создадим запрос на подписывание сертификата(csr) (БЕЗ пароля)

./easyrsa gen-req wildcard.rogaandkopyta.ru nopass

Note: using Easy-RSA configuration from: ./vars

Generating a 2048 bit RSA private key
...........................................+++
................................+++
writing new private key to '/root/test-ca/pki/private/wildcard.rogaandkopyta.ru.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.
-----
Common Name (eg: your user, host, or server name) [wildcard.rogaandkopyta.ru]:*.rogaandkopyta.ru

Keypair and certificate request completed. Your files are:
req: /root/test-ca/pki/reqs/wildcard.rogaandkopyta.ru.req
key: /root/test-ca/pki/private/wildcard.rogaandkopyta.ru.key

Подписываем сертификат для веб-сервера

# ./easyrsa sign-req server wildcard.rogaandkopyta.ru

Note: using Easy-RSA configuration from: ./vars

You are about to sign the following certificate.
Please check over the details shown below for accuracy. Note that this request
has not been cryptographically verified. Please be sure it came from a trusted
source or that you have verified the request checksum with the sender.

Request subject, to be signed as a server certificate for 3650 days:

subject=
    commonName                = *.rogaandkopyta.ru

Type the word 'yes' to continue, or any other input to abort.
  Confirm request details: yes
Using configuration from /root/test-ca/openssl-1.0.cnf
Enter pass phrase for /root/test-ca/pki/private/ca.key:
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName            :T61STRING:'*.rogaandkopyta.ru'
Certificate is to be certified until Apr 25 13:40:38 2024 GMT (3650 days)

Write out database with 1 new entries
Data Base Updated

Certificate created at: /root/test-ca/pki/issued/wildcard.rogaandkopyta.ru.crt

Готово, сертификат для web-сервера лежит в pki/issued/wildcard.rogaandkopyta.ru.crt. Ключ к нему - pki/private/wildcard.rogaandkopyta.ru.key
Нужно закинуть эти два файла к веб-серверу. Если нужен еще и доступ по клиентским сертификатам, то понадобится еще и файлик ca.crt.
Примерный кусок конфига для nginx(проверка клиентских сертоф закомменчена)
 ssl on;
        server_name test.rogaandkopyta.ru;
        ssl_certificate          /etc/nginx/ssl/wildcard.rogaandkopyta.ru.crt;
        ssl_certificate_key      /etc/nginx/ssl/wildcard.rogaandkopyta.ru.key;
        #ssl_client_certificate /etc/nginx/ssl/ca.crt;
        #ssl_verify_client on;

Secure your mac with your bluetooth-enabled phone, auto-lock it when you're away.


Some time ago i though about security of my laptop. When I'm not at home, at work, for example, i often go away from my macbook and wanted to be sure no one will look at my screen when i'm away. I'm running mac os x, so i found free Proximity app. Get it here
Create new file and type it's full path in Out of Range Script field.
/usr/local/bin/screensaver.scpt
tell application "System Events"
    set ss to screen saver "Random"
    start ss
end tell

All done, now you can walk away from your mac and when you're back - mac is protected with screensaver.

Блокировка mac с помощью мобильного телефона. Bluetooth.


Решил заморочиться с безопасностью ноута. На работе часто бывает, что отходишь от ноута и хочется быть уверенным что лишние глаза не смотрят в твой экран во время твоего отсутствия. На просторах интернета было найдено бесплатное приложение Proximity. Скачать можно тут
Создаем файлик и указываем полный путь до него в настройках в поле Out of Range Script field.
/usr/local/bin/screensaver.scpt
tell application "System Events"
    set ss to screen saver "Random"
    start ss
end tell

Готово! Теперь можно отойти от ноутбука и монитор защищен скринсейвером.

среда, 26 февраля 2014 г.

VLC 2.2 http lua interface || nginx basic auth upstream


Yesterday i updated VLC from version 2.0.8 to 2.2 nightie. As i expected, this broken some things. Developers of http lua interface decided that i NEED to have password to access web-interface of VLC. Good idea, but why they didn't done this before? On the days of version 2.0 i came to same idea, and added nginx proxy in front of vlc remote http interface. And auth was done on nginx behalf. Another bad thing - you can only set http interface password, but not login. Login will be always blank. And i told all the users login/password combination and not wanted to tell everyone new combinaton of ""/password. SO! I'll do basic auth at nginx upstream section.
/etc/nginx/sites-enabled/vlc
server {

  listen   0.0.0.0:80;

  server_name  _;

  location / {
    proxy_pass        http://127.0.0.1:8080/;
    proxy_redirect    off;
    proxy_set_header  Host             $http_host;
    proxy_set_header  X-Real-IP        $remote_addr;
    proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_set_header Authorization "Basic OjEyMzQ1Ng==";
    auth_basic            "closed site";
    auth_basic_user_file  htpasswd;
  }
}
Interested line in config is:
proxy_set_header Authorization "Basic OjEyMzQ1Ng==";
OjEyMzQ1Ng== - is a hash from login:password, you can generate it in console window:
$ echo ":123456" | base64
OjEyMzQ1Ngo=
But vlc doesn't accept that hash, so i will sniff http trafic from my browser to vlc interface, directly, without nginx:
# tcpdump -n -w - -i en0 host 10.12.34.56 | strings | grep -i Basic
tcpdump: listening on en0, link-type EN10MB (Ethernet), capture size 65535 bytes
Authorization: Basic OjEyMzQ1Ng==
Don't know why is it so, but in this hash there is one char less and additional = char in the end of string.
Example vlc runit script, just in case: /etc/sv/vlc/run
#!/bin/bash
PLAYLIST="/home/vlc/playlist.m3u"
killall vlc
killall cvlc

exec 2>&1

exec /bin/su - vlc -l -c "taskset 8 cvlc --http-password=123456 -vv -I http $PLAYLIST"
taskset 8(process will be assigned to 4rd core, 2^3) is workaround for old bug that exist in VLC(or, at least, existed earlier): VLC player with high uptime, when linux kernel scheduler moves vlc process from core to another core and back, sound output becomes stuttering. This workaround fixes this.

VLC 2.2 http lua interface || nginx basic auth upstream


Случилось тут вдруг обновить VLC с 2.0.8 на ночную сборку 2.2. Был неприятно удивлен, умные разработчики внезапно внедрили ОБЯЗАТЕЛЬНУЮ защиту паролем веб-интерфейса. Спасибо, конечно! Но пользователь не предусмотрен, только пароль. Но что мешало сделать это раньше, из-за чего пришлось колхозить перед vlc nginx с basic авторизацией по логин-паролю? А т.к. теперь у всех есть комбинация login/password для морды и всем сообщать новые реквизиты для входа не хотелось, то будем делать авторизацию на уровне upstream в nginx! /etc/nginx/sites-enabled/vlc
server {

  listen   0.0.0.0:80;

  server_name  _;

  location / {
    proxy_pass        http://127.0.0.1:8080/;
    proxy_redirect    off;
    proxy_set_header  Host             $http_host;
    proxy_set_header  X-Real-IP        $remote_addr;
    proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_set_header Authorization "Basic OjEyMzQ1Ng==";
    auth_basic            "closed site";
    auth_basic_user_file  htpasswd;
  }
}
Интересующая строчка тут:
proxy_set_header Authorization "Basic OjEyMzQ1Ng==";
OjEyMzQ1Ng== - это хеш от пары login:password, их можно сгенерить и ручками в консоли:
$ echo ":123456" | base64
OjEyMzQ1Ngo=
Вот только vlc не прожевывает такой хеш, поэтому пришлось снифать что передает браузер если обратиться к vlc напрямую, без nginx:
# tcpdump -n -w - -i en0 host 10.12.34.56 | strings | grep -i Basic
tcpdump: listening on en0, link-type EN10MB (Ethernet), capture size 65535 bytes
Authorization: Basic OjEyMzQ1Ng=
Не знаю, почему, но на один символ оказалось меньше и с дополнительным знаком = в конце. Ну и заодно оставлю тут примерный ранит-скрипт для vlc: /etc/sv/vlc/run
#!/bin/bash
PLAYLIST="/home/vlc/playlist.m3u"
killall vlc
killall cvlc

exec 2>&1

exec /bin/su - vlc -l -c "taskset 8 cvlc --http-password=123456 -vv -I http $PLAYLIST"
taskset 8(указание что процесс будет привязан к 4-му ядру, 2^3) тут не просто так - существует(по крайней мере, раньше существовал) известный баг, который проявляется при большом аптайме vlc - когда шедулер ядра начинает швырять vlc с ядра на ядро, vlc сносит крышу и звук начинает заикаться.