среда, 12 сентября 2012 г.

Ubuntu (CentOS 6) + SVN

В общем встала задача поднять svn сервер по https.

Долго мучился искал какой дистрибутив linux взять за основу, что бы был свежий svn. В итоге найдя интересный сайт забил на поиск поставил ubuntu 12.04. А сайт интересен тем, что у него лежат скрипты для установки свежей версии svn на любую ОСь :)


Сама компания мне не понравилась по той причине, что у них на сайте есть ссылки с названием СКАЧАЙТЕ СЕЙЧАС, а на деле после заполнения анкеты вы ни получаете ни хрена - передаю по буква: Николай Илья Харитон Ульяна... в общении с ними через почту мне сообщили: позвоните нам, расскажите кто вы что вы и что хотите и мы может быть вам вышлем демо версию програмки... ебаа****ь как я люблю америкосов :) но я отвлёкся :)

Скачать скрипты можно тут. Делаете его исполняемым, запускаете и вуаля у вас свежий стабильный релиз svn. (к сожалению они закрыли свободный доступ к скачиванию этих файлов, а заполнение анкеты ни к чему хорошему не приводит, поэтому в самом низу я приведу текст скачанного мною файлика для CentOS 6, он скачивался для версии 1.7.6 но установил мне свежую на момент установки версию 1.7.7)

Апача он тоже по моему впаяет вам. Затем создаём папочку под названием svn где нибудь в opt-е. Так же если вы хотите, что бы svn пускал ваших программеров через ldap/ad нужно установить ещё пакет libapache2-mod-ldap-userdir , для убунты я ставил именно его.

     sudo apt-get install libapache2-mod-ldap-userdir

Так же его надо активировать.

     sudo a2enmod authnz_ldap

Далее нам надо запилить сертификаты, что бы заработал https.
Далее буду периодически копипастить, а в конце статьи вы найдёте ссылки на весь материал который я использовал.


Активируем соответствующий модуль Apache2, сделать это в любимом дистрибутиве можно так:
sudo a2enmod ssl

Создаём свой ключ для шифрования:
sudo openssl genrsa -des3 -out server.key 1024

В конце потребуется пару раз ввести (задать и подтвердить) пароль для вашего ключа. Тут всё стандартно: не забывайте свой пароль, но и не записывайте его на стикере в углу монитора. Минимально допустимая длина пароля тут — 4 символа, но рекомендуется задать пароль в 8+ символов, да такой, чтоб он содержал буквы разных регистров и цифры.

Можно создать не шифрованную копию ключа вот так (это делать обязательно и дальше прыгать от этого ключа иначе апач перед каждым стартом будет просить пароль):
sudo openssl rsa -in server.key -out server.key.insecure

И для удобства это лучше сделать: иначе при каждой (ре-)активации хоста с SSL потребуется вводить пароль.

Плюс вот в чём: не придётся вводить пароль при запуске сервера.

Теперь будем создавать CSR, это тоже просто:
sudo openssl req -new -key server.key -out server.csr

Вас попросят сообщить информацию о себе, в принципе (поскольку сертификат мы создаём самоподписной) можно ничего не сообщать, тупо вводя пустые ответы. Но если вы захотите получить «настоящий» сертификат CA, то все данные, конечно, надо заполнить, притом указывая достоверные значения.

Но перейдём к процессу самоподписания:
sudo openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt


Далее приведу код моего файлика в папке sites-available в апаче


<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerAdmin webmaster@localhost

# DocumentRoot /var/www
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
# <Directory /var/www/>
# Options Indexes FollowSymLinks MultiViews
# AllowOverride None
# Order allow,deny
# allow from all
# </Directory>

<Location />
DAV svn
SVNParentPath /opt/svn
SVNListparentPath on

AuthName "Name's repository"
AuthType Basic
AuthBasicProvider file ldap
AuthLDAPUrl "ldap://12.23.34.45:3210/DC=name,DC=com?samAccountName?sub?(objectClass=user)"
AuthUserFile /opt/svn/etc/.htpasswd
AuthzSVNAccessFile /opt/svn/etc/.htsvnpolicy
AuthLDAPBindDN "SVNAdmin@name.com"
AuthLDAPBindPassword "SVNAdmin"
AuthzLDAPAuthoritative off

Require valid-user

</Location>

# ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
# <Directory "/usr/lib/cgi-bin">
# AllowOverride None
# Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
# Order allow,deny
# Allow from all
# </Directory>

ErrorLog /var/log/apache2/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog /var/log/apache2/ssl_access.log combined

# Alias /doc/ "/usr/share/doc/"
# <Directory "/usr/share/doc/">
# Options Indexes MultiViews FollowSymLinks
# AllowOverride None
# Order deny,allow
# Deny from all
# Allow from 127.0.0.0/255.0.0.0 ::1/128
# </Directory>

#   SSL Engine Switch:
#   Enable/Disable SSL for this virtual host.
SSLEngine on

#   A self-signed (snakeoil) certificate can be created by installing
#   the ssl-cert package. See
#   /usr/share/doc/apache2.2-common/README.Debian.gz for more info.
#   If both key and certificate are stored in the same file, only the
#   SSLCertificateFile directive is needed.
SSLCertificateFile    /etc/apache2/ssl/ssl.crt    # вот они ключи которые
SSLCertificateKeyFile /etc/apache2/ssl/ssl.key  # мы создавали

#   Server Certificate Chain:
#   Point SSLCertificateChainFile at a file containing the
#   concatenation of PEM encoded CA certificates which form the
#   certificate chain for the server certificate. Alternatively
#   the referenced file can be the same as SSLCertificateFile
#   when the CA certificates are directly appended to the server
#   certificate for convinience.
#SSLCertificateChainFile /etc/apache2/ssl.crt/server-ca.crt

#   Certificate Authority (CA):
#   Set the CA certificate verification path where to find CA
#   certificates for client authentication or alternatively one
#   huge file containing all of them (file must be PEM encoded)
#   Note: Inside SSLCACertificatePath you need hash symlinks
#         to point to the certificate files. Use the provided
#         Makefile to update the hash symlinks after changes.
#SSLCACertificatePath /etc/ssl/certs/
#SSLCACertificateFile /etc/apache2/ssl.crt/ca-bundle.crt

#   Certificate Revocation Lists (CRL):
#   Set the CA revocation path where to find CA CRLs for client
#   authentication or alternatively one huge file containing all
#   of them (file must be PEM encoded)
#   Note: Inside SSLCARevocationPath you need hash symlinks
#         to point to the certificate files. Use the provided
#         Makefile to update the hash symlinks after changes.
#SSLCARevocationPath /etc/apache2/ssl.crl/
#SSLCARevocationFile /etc/apache2/ssl.crl/ca-bundle.crl

#   Client Authentication (Type):
#   Client certificate verification type and depth.  Types are
#   none, optional, require and optional_no_ca.  Depth is a
#   number which specifies how deeply to verify the certificate
#   issuer chain before deciding the certificate is not valid.
#SSLVerifyClient require
#SSLVerifyDepth  10

#   Access Control:
#   With SSLRequire you can do per-directory access control based
#   on arbitrary complex boolean expressions containing server
#   variable checks and other lookup directives.  The syntax is a
#   mixture between C and Perl.  See the mod_ssl documentation
#   for more details.
#<Location />
#SSLRequire (    %{SSL_CIPHER} !~ m/^(EXP|NULL)/ \
#            and %{SSL_CLIENT_S_DN_O} eq "Snake Oil, Ltd." \
#            and %{SSL_CLIENT_S_DN_OU} in {"Staff", "CA", "Dev"} \
#            and %{TIME_WDAY} >= 1 and %{TIME_WDAY} <= 5 \
#            and %{TIME_HOUR} >= 8 and %{TIME_HOUR} <= 20       ) \
#           or %{REMOTE_ADDR} =~ m/^192\.76\.162\.[0-9]+$/
#</Location>

#   SSL Engine Options:
#   Set various options for the SSL engine.
#   o FakeBasicAuth:
#     Translate the client X.509 into a Basic Authorisation.  This means that
#     the standard Auth/DBMAuth methods can be used for access control.  The
#     user name is the `one line' version of the client's X.509 certificate.
#     Note that no password is obtained from the user. Every entry in the user
#     file needs this password: `xxj31ZMTZzkVA'.
#   o ExportCertData:
#     This exports two additional environment variables: SSL_CLIENT_CERT and
#     SSL_SERVER_CERT. These contain the PEM-encoded certificates of the
#     server (always existing) and the client (only existing when client
#     authentication is used). This can be used to import the certificates
#     into CGI scripts.
#   o StdEnvVars:
#     This exports the standard SSL/TLS related `SSL_*' environment variables.
#     Per default this exportation is switched off for performance reasons,
#     because the extraction step is an expensive operation and is usually
#     useless for serving static content. So one usually enables the
#     exportation for CGI and SSI requests only.
#   o StrictRequire:
#     This denies access when "SSLRequireSSL" or "SSLRequire" applied even
#     under a "Satisfy any" situation, i.e. when it applies access is denied
#     and no other module can change it.
#   o OptRenegotiate:
#     This enables optimized SSL connection renegotiation handling when SSL
#     directives are used in per-directory context.
#SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
<FilesMatch "\.(cgi|shtml|phtml|php)$">
SSLOptions +StdEnvVars
</FilesMatch>
<Directory /usr/lib/cgi-bin>
SSLOptions +StdEnvVars
</Directory>

#   SSL Protocol Adjustments:
#   The safe and default but still SSL/TLS standard compliant shutdown
#   approach is that mod_ssl sends the close notify alert but doesn't wait for
#   the close notify alert from client. When you need a different shutdown
#   approach you can use one of the following variables:
#   o ssl-unclean-shutdown:
#     This forces an unclean shutdown when the connection is closed, i.e. no
#     SSL close notify alert is send or allowed to received.  This violates
#     the SSL/TLS standard but is needed for some brain-dead browsers. Use
#     this when you receive I/O errors because of the standard approach where
#     mod_ssl sends the close notify alert.
#   o ssl-accurate-shutdown:
#     This forces an accurate shutdown when the connection is closed, i.e. a
#     SSL close notify alert is send and mod_ssl waits for the close notify
#     alert of the client. This is 100% SSL/TLS standard compliant, but in
#     practice often causes hanging connections with brain-dead browsers. Use
#     this only for browsers where you know that their SSL implementation
#     works correctly.
#   Notice: Most problems of broken clients are also related to the HTTP
#   keep-alive facility, so you usually additionally want to disable
#   keep-alive for those clients, too. Use variable "nokeepalive" for this.
#   Similarly, one has to force some clients to use HTTP/1.0 to workaround
#   their broken HTTP/1.1 implementation. Use variables "downgrade-1.0" and
#   "force-response-1.0" for this.
BrowserMatch "MSIE [2-6]" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
# MSIE 7 and newer should be able to use keepalive
BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown

</VirtualHost>
</IfModule>


Как видите ваши репозитории будут доступны сразу https://address.com/repo1
Так же авторизация двойная и через домен и через файлик, что бы не заводить левых людей в домен. Подробно о создании этого файлика


Сосздадим файл пользователей и паролей для авторизации
1.# htpasswd -c /var/www/svn/conf/htpasswd test
2.New password:
3.Re-type new password:
4.Adding password for user test
После можно добавлять туда пользователей уже без ключа -c
1.# htpasswd /var/www/svn/conf/htpasswd test
Теперь сделаем файл прав доступа заведенным пользователям
1.# vi /var/www/svn/conf/svn-access
В нем распишем, что доступ ко всем репозиториям любым пользователям запрещен,
а нашему новому пользователю test разрешена запись и чтение из всех репозиториев
[/]
* =
test = rw


Теперь назначим всей папке svn и вложенным подпапкам и файлам пользователя apache, а иначе он не сможет получить доступ до репозиториев и всё что мы получим, это сообщение об ошибке “You don’t have permission to access /svn/ on this server.”
1.# chown -R apache:apache /var/www/svn
Вот и всё теперь сервер готов к использованию.

Затем возникли небольшие, но для меня критичные проблемы и было решено переставить свн на CentOS, на сколько сильно я "люблю" CentOS можно прочитать в предыдущих постах. В любом случае тут рассказ обрывается, но вы уже имеете готовый СВН с доменно-файловой авторизацией. СВН на CentOSe будет чуть позже, там будет поднят вопрос зеркала. Svndomp не подходит, был выбран Pushmi, а там посмотрим до чего дойдём :)



а теперь код скачанного мною файлика для установки свн под CentOS6 (хоть и написано 1.7.6, но ставит самые новые версии, мне поставил 1.7.7)

#!/bin/bash
# staging.opensource.wandisco.com
echo WANdisco Subversion Installer for CentOS 6
echo Please report bugs or feature suggestions to staging.opensource.wandisco.com
echo 
echo Gathering some information about your system...

MINVERSION='1'
SVNVER='1.7.6'
NOW=$(date +"%b-%d-%y%s")

#functions

gather_info () {
        ARCH=`uname -m`
        SVNSTATUS=`rpm -qa|grep ^subversion-[0-9]|awk 'BEGIN { FS = "-" } ; { print $1 }'`
}
check_tools () {
        COMMANDS="yum wget rpm"
        for C in $COMMANDS; do
                if [ -z "$(which $C)" ] ; then
                        echo "This installer uses the $C command which was not found in \$PATH."
                        exit 1
                fi
        done
}



check_centos_version ()
{
       if [ ! -e /etc/redhat-release ]; then
                echo "No /etc/redhat-release file, exiting"
                echo "You are most likely not using CentOS."
                echo "Installers for other operating systems are available from our downloads page:"
                echo "http://www.wandisco.com/subversion/download"
echo "Exiting.."
                exit 1
        fi;
cat /etc/redhat-release |grep -e 6.[0-9]
if [ $? == 0 ]; then
echo "CentOS version 6.x confirmed.."
else
                echo "You are most likely using an incompatible version of CentOS."
echo "This installer is made for CentOS 5.x"
                echo "Installers for other operating systems are available from our downloads page:"
                echo "http://www.wandisco.com/subversion/download"
                exit 1
fi;
}


check_is_root ()
{
if [[ $EUID -ne 0 ]]; then
    echo "This script must be run as root" 1>&2
    exit 1
fi
}
svn_remove_old ()
{
if [ -f /etc/httpd/conf.d/subversion.conf ]; then
echo Backing up /etc/httpd/conf.d/subversion.conf to /etc/httpd/conf.d/subversion.conf.backup-$NOW
cp /etc/httpd/conf.d/subversion.conf /etc/httpd/subversion.conf.backup-$NOW
fi
echo Removing old packages...
yum -y remove mod_dav_svn subversion subversion-devel subversion-perl subversion-python subversion-tools &>/dev/null
}
add_repo_config ()
{
        echo Adding repository configuration to /etc/yum.repos.d/
        if [ -f /etc/yum.repos.d/WANdisco-1.7.repo ]; then
rm /etc/yum.repos.d/WANdisco-1.7.repo
fi;
echo " ------ Installing yum repo ------"
echo "
[WANdisco]
name=WANdisco Repo
enabled=1
baseurl=http://staging.opensource.wandisco.com/rhel/6/svn-1.7/RPMS/$ARCH/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-WANdisco
" > /etc/yum.repos.d/WANdisco-1.7.repo
echo "Importing GPG key"
wget http://staging.opensource.wandisco.com/RPM-GPG-KEY-WANdisco -O /tmp/RPM-GPG-KEY-WANdisco &>/dev/null
rpm --import /tmp/RPM-GPG-KEY-WANdisco
rm -rf /tmp/RPM-GPG-KEY-WANdisco
echo " ------ Installing yum repo: Done ------"
}
install_svn ()
{
        echo Checking to see if you already have Subversion installed via rpm...
        if [[ "$SVNSTATUS" =~ subversion ]]; then
        echo Subversion is already installed on the system.
        echo Do you wish to replace the version of subversion currently installed with the WANdisco version? 
echo This action will remove the previous version from your system 
echo "[y/n]"
read svn_install_confirm
if [ "$svn_install_confirm" == "y" -o "$svn_install_confirm" == "Y" ]; then
svn_remove_old
add_repo_config
echo
echo Installing Subversion $SVNVER
echo
yum -y install subversion.$ARCH subversion-perl.$ARCH subversion-python.$ARCH subversion-tools.$ARCH
  echo Would you like to install apache and the apache SVN modules?
echo "[y/n]"
read dav_svn_confirm
if [ "$dav_svn_confirm" == "y" -o "$dav_svn_confirm" == "Y" ]; then
echo Installing apache and subversion modules
yum -y install mod_dav_svn.$ARCH httpd
echo "Installation complete."
echo "You can find the subversion configuration file for apache HTTPD at /etc/httpd/conf.d/subversion.conf"
echo "By default, the modules are commented out in subversion.conf."
echo "To enable the modules, please edit subversion.conf and remove the # infront of the LoadModule lines."
echo "You should then restart httpd (/etc/init.d/httpd restart)"
fi
      else
echo "Install Cancelled"
exit 1
fi

else
# Install SVN
echo "Subversion is not currently installed"
echo "Starting installation, are you sure you wish to continue?"
echo "[y/n]"
read svn_install_confirm
                if [ "$svn_install_confirm" == "y" -o "$svn_install_confirm" == "Y" ]; then
add_repo_config
                        echo
                        echo Installing Subversion $SVNVER
                        echo
yum -y install subversion.$ARCH subversion-perl.$ARCH subversion-python.$ARCH subversion-tools.$ARCH
                        echo Would you like to install apache HTTPD and the apache SVN modules?
echo "[y/n]"
                        read dav_svn_confirm
                        if [ "$dav_svn_confirm" == "y" -o "$dav_svn_confirm" == "Y" ]; then
                                echo Installing apache and subversion modules
yum -y install mod_dav_svn.$ARCH httpd
                                echo "Installation complete."
                                echo "You can find the subversion configuration file for apache HTTPD at /etc/httpd/conf.d/subversion.conf"
                                echo "By default, the modules are commented out in subversion.conf."
                                echo "To enable the modules, please edit subversion.conf and remove the # infront of the LoadModule lines."
                                echo "You should then restart httpd (/etc/init.d/httpd restart)"
                        fi

                else
                        echo "Install Cancelled"
                        exit 1
                fi
        fi
}

install_32 ()
{
        echo Installing for $ARCH
install_svn
}
install_64 ()
{
        echo Installing for $ARCH
install_svn
}

#Main
check_is_root
check_centos_version
check_tools
gather_info

echo Checking your system arch
if [ "$ARCH" == "i686" -o "$ARCH" == "i386" ]; then
if [ "$ARCH" == "i686" ]; then
ARCH="i686"
fi;
install_32
elif [ "$ARCH" == "x86_64" ];
then
install_64
else 
echo Unsupported platform: $ARCH
exit 1
fi










что я использовал:
http://www.aboutubuntu.ru/apache-ssl-https-ubuntu.html
http://dandreev.com/blog/administrirovanie/svoj-svn-server-ustanovka-subversion-na-centos/

Комментариев нет:

Отправить комментарий