вторник, 16 сентября 2014 г.

Использование putty и ssh ключей в Windows

Скачиваем архив putty отсюда putty.zip
1. Распаковываем и запускаем ssh-keygen

Выбираем ключ ssh-rsa и длину 2048 бит. Жмем «Generate».


Ключ готов, заполняем кодовую фразу и комментарий к нему. Сохраняем приватный ключ как mykey.ppk и публичный как id_rsa.pub

2. Далее необходимо скопировать наш публичный ключ на сервер. Для этого запускаем psftp.
psftp: no hostname specified; use «open host.name» to connect
psftp> open myserver
The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 2048 XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX
If you trust this host, enter «y» to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter «n».
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n) y
login as: root
root@myserver's password:
Remote working directory is /root
psftp>put id_rsa.pub /tmp/id_rsa.pub
local:id_rsa.pub => remote:/tmp/id_rsa.pub
psftp>


3. Ключ скопировался, теперь нужно добавить его в /root/.ssh/authorized_keys
Для этого логинимся еще раз по паролю, через putty и выполняем
ssh-keygen -i -f /tmp/id_rsa.pub >> /root/.ssh/authorized_keys

Теперь осталось добавить наш ключ в ssh-agent'a. После запуска он сидит в трее, чтобы добавить ключ кликаем правой кнопкой на «Add Key»


Вводим кодовую фразу:


Теперь логинимся в putty:
login as: root
Authenticating with public key "rsa-key-20080908" from agent


Практически все, чтобы устранить проблемы с кодировками, с кривым отображением mc в путти, исправляем локаль в настроках:

понедельник, 16 июня 2014 г.

Rails CSRF Protection + Angular.js

I think reading CSRF-value from DOM is not a good solution, it's just a workaround.
Here is a document form angularJS official website http://docs.angularjs.org/api/ng.$http :
Since only JavaScript that runs on your domain could read the cookie, your server can be assured that the XHR came from JavaScript running on your domain.
To take advantage of this (CSRF Protection), your server needs to set a token in a JavaScript readable session cookie called XSRF-TOKEN on first HTTP GET request. On subsequent non-GET requests the server can verify that the cookie matches X-XSRF-TOKEN HTTP header
Here is my solution based on those instructions:
First, set the cookie:
 
# app/controllers/application_controller.rb

# Turn on request forgery protection
protect_from_forgery

after_filter :set_csrf_cookie_for_ng

def set_csrf_cookie_for_ng
  cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery?
end
 
Then, we should verify the token on every non-GET request.
Since Rails has already built with the similar method, we can just simply override it to append our logic:
# app/controllers/application_controller.rb

protected

  def verified_request?
    super || form_authenticity_token == request.headers['X-XSRF-TOKEN']
  end

source: http://stackoverflow.com/questions/14734243/rails-csrf-protection-angular-js-protect-from-forgery-makes-me-to-log-out-on

четверг, 29 мая 2014 г.

Bounced Message "retry time not reached for any host after a long failure period" или Exim не хочет отправлять почту

Решить проблему можно следующим образом:

1.  RHEL :

cd /var/spool/exim/db
rm -f retry retry.lockfile
rm -f wait-remote_smtp wait-remote_smtp.lockfile
service exim restart

2. Debian/Ubuntu/etc.
 
 
cd /var/spool/exim4/db
rm -f retry retry.lockfile
rm -f wait-remote_smtp wait-remote_smtp.lockfile
service exim4 restart

среда, 28 мая 2014 г.

Enable Active Directory / LDAP authentication in Apache

If you already have a central directory of users installed (AD or LDAP) you can configure most applications to use that directory instead of a local database for each application and make the user management much easier. Apache supports that so here are instructions on how to password protect a site or location using LDAP directory.
In squeeze, the Apache LDAP module is already installed with the Apache common package. You just need to enable the module and configure.
1. Enable the LDAP module
a2enmod authnz_ldap

2. Add Auth config variables to the site or directory that should be password protected (ex. pico /etc/apache2/sites-enabled/000-default). In this example, the “/protected” relative location will be password protected. You can protect any Location or Directory using the same method.
<Location /protected>
AuthType Basic
AuthBasicProvider ldap
AuthzLDAPAuthoritative on
AuthName "Password protected. Enter your AD username and password."
AuthLDAPURL "ldap://{host_or_ip}/CN=Users,DC=example,DC=org?sAMAccountName?sub?(objectClass=*)"
AuthLDAPBindDN "{username}@example.org"
AuthLDAPBindPassword {password}
Require valid-user
</Location>

Replace {host_or_ip} with the AD/LDAP server hostname or IP address. Change example.org to your domain. Enter username and password for a user that has access to the domain.
The last line, “Require valid-user” will allow any user in the directory to login. To allow only certain users, change that line to:
Require ldap-user user1 user2

To allow only users from a specific group, change “Require valid-user” to:
Require ldap-group CN={group},CN=Users,dc=example,dc=org

Replace {group} to the name of a group and type correct domain name instead of example.org.
3. Restart Apache
/etc/init.d/apache2 restart

P.S.: How to find AD DC server in local network:
On any computer, that has DNS configured to use AD's DNS server do:
Start -> Run -> nslookup    
set type=all
_ldap._tcp.dc._msdcs.DOMAIN_NAME
Replace DOMAIN_NAME with actual domain name i.e. contoso.com.

пятница, 18 апреля 2014 г.

The Heartbleed Bug

The Heartbleed Bug

OpenSSL is one of the most ubiquitous components in a secure network environment. In fact, chances are good that if you accessed the Internet today your browser communicated with a number of servers running OpenSSL. Today, an announcement was made describing a critical flaw in the OpenSSL source code.

The Problem

According to heartbleed.com (which goes into quite a bit of detail):
The Heartbleed bug ... allows stealing the information protected, under normal conditions, by the SSL/TLS encryption used to secure the Internet.
What does this mean? If you are viewing a website that encrypts traffic (look for the "https://" protocol in the address bar), it may be possible under certain conditions for an attacker to obtain the remote server's private key and decrypt content exchanged between you and the website you are viewing.

The Solution

Update: Ubuntu has issued a USN containing updated packages for Ubuntu 14.04, 13.10, 12.10, and 12.04. In other words, check for updates and install them.
This bug has now been fixed and a new version of OpenSSL released (v1.0.1g). Unfortunately this hasn't hit the archives yet, so if you are really in desperate need of a patched copy of the library, do not despair!
We have a PPA:
ppa:george-edison55/openssl-heartbleed-fix
Currently, we have packages for the following series:
  • Precise Pangolin
  • Saucy Salamander
  • Trusty Tahr
You can install everything with the following three commands:
sudo add-apt-repository ppa:george-edison55/openssl-heartbleed-fix
sudo apt-get update
sudo apt-get upgrade
Now you can breathe a sigh of relief.
If you are running into errors running "add-apt-repository" on Ubuntu 12.04, install the "python-software-properties" package with the following command and try again: sudo apt-get install python-software-properties

четверг, 27 февраля 2014 г.

Production сервер для Ruby on Rails

Начнем, пожалуй! =)
Нужно выбрать веб-сервер, который мы будем использовать. Для целей разработки в Rails есть встроенный Webrick, который запускает написанное приложение на http://localhost:3000
Но это же несерьезно, использовать его на production сервере =)
В итоге я выбрал связку Nginx и Passenger. Можно спросить, почему? Просто она дает бОльшую производительность (в настройках по default), чем Apache + Passenger и менее сложна в настройке, чем Nginx + Unicorn. Во всяком случае, мне так кажется =)
Доступ по SSH. Консоль, откройся!
1
2
apt-get update
apt-get upgrade
Только что мы обновили все пакеты в системе. Теперь остановим и удалим Apache (если он есть), раз уж ставим вместо него Nginx.
1
/etc/init.d/apache2 stop && apt-get purge apache2*
Теперь займемся установкой rvm (контроль версий Ruby)
1
2
apt-get install curl
\curl -L https://get.rvm.io | bash -s stable --rails
В конце установки rvm даст правильную команду для своего запуска. У меня это было:
1
source /usr/local/rvm/scripts/rvm
Теперь поставим зависимости rvm. Команда
1
rvm requirements
Подскажет нам, что же именно еще нужно установить. Это длинный список разных пакетов.
1
/usr/bin/apt-get install build-essential openssl libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev automake libtool bison subversion pkg-config
Запускаем и ждем, покуда все установится =)
Установим Ruby (версия у Вас может быть и новее) и укажет, какую версию мы будем использовать в системе по умолчанию.
1
2
rvm install 1.9.3
rvm use 1.9.3 --default
Далее установим RubyGems
1
rvm rubygems current
и рельсы
1
gem install rails
Теперь займемся, собственно, сервером.
Ставим Passenger
1
gem install passenger
В качестве модуля для Passenger устанавливаем Nginx.
1
rvmsudo passenger-install-nginx-module
Инсталлер nginx скажет нам, если ему чего-нибудь не хватает. Мне не хватало одного пакета:
1
apt-get install libcurl4-openssl-dev
Если все зависимости установлены, в меню установки nginx выбираем «1″ для быстрой установки.
Примечание: init.d (файл для запуска) для nginx при такой установке не создается, так что тырим его с linode.com =)
1
2
3
4
wget -O init-deb.sh http://library.linode.com/assets/660-init-deb.sh
sudo mv init-deb.sh /etc/init.d/nginx
sudo chmod +x /etc/init.d/nginx
sudo /usr/sbin/update-rc.d -f nginx defaults
Далее стартуем nginx.
1
sudo service nginx start
Теперь зайдя на адрес нашего vps мы можем увидеть стандартную заглушку nginx. Это значит, что все идет хорошо =)
Лишним не будет установить node.js
1
sudo apt-get install nodejs
Теперь настроим nginx. Для этого нужно подредактировать его файл nginx.conf (у меня он был в /opt/nginx/conf/nginx.conf). Его расположение зависит, конечно, от директории, в которую nginx установился.
1
nano /opt/nginx/conf/nginx.conf
Найдите в файле участок «server { тут настройки по-умолчанию }». Придадим ему следующий вид:
1
2
3
4
5
6
7
8
9
10
server {
        listen      80;
        server_name имя_вашего_сервера;
        rails_env production;
        passenger_use_global_queue on;
        root /var/www/название_вашего_приложения/public;
        passenger_enabled on;
        error_page  404              /404.html;
        error_page   500 502 503 504  /50x.html;
    }
В строке root должен быть путь к папке public вашего приложения.
После правки не забываем перезапустить сервер nginx.
1
service nginx restart
И не забывайте, что теперь мы работаем не с development базой данных, а с production.
Возможно, еще придется сделать:
1
rake assets:precompile
Пока я не ставил Capistrano для нормального деплоя приложений…
Если будут вопросы — задавайте их в комментариях =)

воскресенье, 23 февраля 2014 г.

Установка PHP 5.5.x на Debian

vim /etc/apt/sources.list.d/dotdeb.list


deb http://packages.dotdeb.org wheezy-php55 all
deb-src http://packages.dotdeb.org wheezy-php55 all

Если есть прокси:
export http_proxy='101.198.130.118:3128'
wget http://www.dotdeb.org/dotdeb.gpg
sudo apt-key add dotdeb.gpg
apt-key add dotdeb.gpg
apt-get update

Для apache :
apt-get install php5

или lighttpd :
apt-get install php5-cgi

php -v || php-cgi -v
Оригинал: http://www.dev-metal.com/setup-latest-version-php-5-5-debian-wheezy-7-07-1-fix-gpg-key-error/

среда, 22 января 2014 г.

Установка Ruby on Rails на Debian

Установка

Перед установкой Rails вам придется поставить Apache и MySQL. Для установки пакета Apache обратитесь к разделу руководства HTTPD - Apache2 интернет сервер. Для инструкций по установке MySQL смотрите раздел MySQL.
Как только пакеты Apache и MySQL установлены, вы готовы к установке пакета Ruby on Rails.
Чтобы установить базовые пакеты Ruby и Ruby on Rails, вы можете выполнить следующую команду в терминале:

$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo apt-get install rails
$ sudo apt-get install ruby
$ sudo apt-get install ruby-dev
$ export http_proxy=127.0.0.1:3128
$ sudo gem  install rails --verbose
$ sudo apt-get install libsqlite3-dev
$ sudo gem install sqlite3 --verbose
$ sudo gem install libv8 --verbose -- --with-system-v8
$ sudo gem install execjs --verbose
$ rails new blog
$ cd ./blog/ 
 
upd: Полезные гемы:
 gem install rspec --verbose
 gem install capybara --verbose
 gem install spork-rails
 gem install guard-spork --verbose
 gem install 'bootstrap-sass' -v '2.3.2.0' --verbose
 gem install net-ping --verbose
 gem install net-snmp --verbose
 gem install net-ssh --verbose
 gem install pony --verbose
После этого при попытке запустить rails server , мы получим ошибку. Требуется установить nodejs . Но если вы используете Ubuntu, то у вас есть проблема: в стандартных репозиториях такого пакета нет. А значит, что вам придётся собирать, устанавливать и настраивать nodejs самостоятельно. Это не слишком сложно, но не очень очевидно. Решается подключением репозитория sid debian ( http://packages.debian.org/ru/sid/i386/nodejs/download ) : 
echo 'deb http://ftp.de.debian.org/debian sid main' >> /etc/apt/source.conf .

После этого выполняем :
$ sudo apt-get update
$ sudo apt-get install nodejs

Не забудьте удалить подключенный репозиторий из /etc/apt/source.conf и сделать apt-get update .

Настройка

Измените файл настроек /etc/apache2/sites-available/default для настройки ваших доменов.
Первое, что стоит изменить, это инструкция DocumentRoot:
DocumentRoot /path/to/rails/application/public
Затем измените секцию <Directory "/path/to/rails/application/public">:
<Directory "/path/to/rails/application/public">
        Options Indexes FollowSymLinks MultiViews ExecCGI
        AllowOverride All
        Order allow,deny
        allow from all
        AddHandler cgi-script .cgi
</Directory>
Вы также можете разрешить модуль mod_rewrite для Apache. Для включения модуля mod_rewrite введите, пожалуйста, следующую команду в терминале:
sudo a2enmod rewrite
Наконец вам потребуется изменить владельца каталогов /path/to/rails/application/public и /path/to/rails/application/tmp на пользователя, который используется для запуска процесса Apache:
sudo chown -R www-data:www-data /path/to/rails/application/public
sudo chown -R www-data:www-data /path/to/rails/application/tmp
 
Использованные ресурсы:
http://habrahabr.ru/sandbox/49699/ 

вторник, 14 января 2014 г.

Сборка Squid3 с SSL в Debian

apt-get update
apt-get install openssl
apt-get install devscripts build-essential libssl-dev

apt-get source squid3
apt-get build-dep squid3
cd squid3-3.1.20
vim debian/rules
 

Находим секцию DEB_CONFIGURE_EXTRA_FLAGS . Добавляем :
--enable-ssl
--with-open-ssl="/etc/ssl/openssl.cnf"
 

Сохраняемся и выходим.
debuild -us -uc
cd ..
dpkg -i squid3_3.1.20-2.2_i386.deb