Мы в http://www.quantilope.com активно пользуемся метеоритами и любим кадиру! Мы постоянно пользуемся кадирой и, к сожалению, не можем использовать mdg's galaxy. Поэтому мы вставили код kadira с открытым исходным кодом и немного исправили его, чтобы вы могли легко запускать его и на своем сервере! Мы также планируем выпустить образы докеров в будущем. Итак, давайте начнем с настройки сервера Ubuntu!

Это серия из 3 частей, так что ждите 2 и 3 части!

Это скорее минимальное руководство, а не полное руководство по усилению защиты вашего сервера ubuntu!

Требования

  • Запуск экземпляра MongoDB с хотя бы одной установленной репликой.
  • Глобально установленный пакет npm pick-mongo-primary
  • Установлен git

Установка на Ubuntu Server 16.04

Создать нового пользователя

  • Создайте нового пользователя с именем kadira
adduser kadira
  • Добавьте kadira в группу sudo, чтобы получить права root
usermod -aG sudo kadira
  • Проверьте, можете ли вы войти в систему как этот пользователь
su - kadira
  • проверьте, есть ли у вас root-доступ
sudo ls -la /root
  • Клонировать репо
cd ; git clone [email protected]:lampe/kadira-server.git
  • Установить ufw
sudo apt-get install ufw
  • Разрешить openSSH (sshd) в ufw
sudo ufw allow OpenSSH
  • Включить ufw
sudo ufw enable
  • Проверить статус
sudo ufw status
  • Он должен вывести что-то вроде этого
Status: active
To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere
OpenSSH (v6)               ALLOW       Anywhere (v6)

Установить MongoDB

Добавить репозиторий MongoDB

  • Добавьте ключ
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927
  • Добавить репо к источникам
echo "deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list
  • Обновите кеш ваших пакетов
sudo apt-get update

Установить MongoDB

  • Установите MongoDB и nano
sudo apt-get install -y mongodb-org nano
  • Создайте модуль для systemD
sudo nano /etc/systemd/system/mongodb.service
  • Вставьте это в mongodb.service файл
[Unit]
Description=High-performance, schema-free document-oriented database
After=network.target
[Service]
User=mongodb
ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf
[Install]
WantedBy=multi-user.target
  • включить настройку реплики
mongo admin --eval 'rs.initiate({_id: "rs0", members:[{_id : 0, host : "localhost:27017"},]})'
mongo admin --eval 'rs.slaveOk()'

Запустить MongoDB

  • Запустить MongoDB
sudo systemctl start mongodb
  • Проверить статус
sudo systemctl status mongodb
  • Если все в порядке, включите mongodb, чтобы он запустился автоматически
sudo systemctl enable mongodb

Оптимизировать MonogDB

Отключить прозрачные огромные страницы

  • Создайте файл init.d
sudo nano /etc/init.d/disable-transparent-hugepages
  • Вставьте это в disable-transparent-hugepages файл
#!/bin/bash
### BEGIN INIT INFO
# Provides:          disable-transparent-hugepages
# Required-Start:    $local_fs
# Required-Stop:
# X-Start-Before:    mongod mongodb-mms-automation-agent
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Disable Linux transparent huge pages
# Description:       Disable Linux transparent huge pages, to improve
#                    database performance.
### END INIT INFO
case $1 in
  start)
    if [ -d /sys/kernel/mm/transparent_hugepage ]; then
      thp_path=/sys/kernel/mm/transparent_hugepage
    elif [ -d /sys/kernel/mm/redhat_transparent_hugepage ]; then
      thp_path=/sys/kernel/mm/redhat_transparent_hugepage
    else
      return 0
    fi
    echo 'never' > ${thp_path}/enabled
    echo 'never' > ${thp_path}/defrag
    re='^[0-1]+$'
    if [[ $(cat ${thp_path}/khugepaged/defrag) =~ $re ]]
    then
      # RHEL 7
      echo 0  > ${thp_path}/khugepaged/defrag
    else
      # RHEL 6
      echo 'no' > ${thp_path}/khugepaged/defrag
    fi
    unset re
    unset thp_path
    ;;
esac
  • Сделайте его исполняемым
sudo chmod 755 /etc/init.d/disable-transparent-hugepages
  • Включить при загрузке
sudo update-rc.d disable-transparent-hugepages defaults
  • Перезагрузите систему, чтобы изменения вступили в силу.
sudo reboot now

настроить nginx

  • Установить nginx
sudo apt-get install nginx
  • Удалите сайты nginx по умолчанию
sudo rm /etc/nginx/sites-enabled/default
  • Создайте новый серверный блок для kadira-ui
sudo nano /etc/nginx/sites-available/kadira
  • Настройте nginx для перенаправления с 80 на порт 4000, где работает kadira-ui
server_tokens off; # for security-by-obscurity: stop displaying nginx version
# this section is needed to proxy web-socket connections
map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
}
# HTTP
server {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;
        # pass requests to Meteor
        location / {
            proxy_pass http://127.0.0.1:4000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade; #for websockets
            proxy_set_header Connection $connection_upgrade;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Host $host;
        }
}
# HTTPS server
server {
    listen 443 default_server ssl http2; # we enable SPDY here
    server_name [::]:443 default_server; # this domain must match Common Name (CN) in the SSL certificate
    root html; # irrelevant
    index index.html; # irrelevant
    ssl_certificate /etc/nginx/ssl/kadira.pem; # full path to SSL certificate and CA certificate concatenated together
    ssl_certificate_key /etc/nginx/ssl/kadira.key; # full path to SSL key
    # performance enhancement for SSL
    ssl_stapling on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 5m;
    # config to enable HSTS(HTTP Strict Transport Security) https://developer.mozilla.org/en-US/docs/Security/HTTP_Strict_Transport_Security
    # to avoid ssl stripping https://en.wikipedia.org/wiki/SSL_stripping#SSL_stripping
    add_header Strict-Transport-Security "max-age=31536000;";
    # If your application is not compatible with IE <= 10, this will redirect visitors to a page advising a browser update
    # This works because IE 11 does not present itself as MSIE anymore
    if ($http_user_agent ~ "MSIE" ) {
        return 303 https://browser-update.org/update.html;
    }
    # pass all requests to Meteor
    location / {
        proxy_pass http://127.0.0.1:4000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade; # allow websockets
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header X-Forwarded-For $remote_addr; # preserve client IP
        # this setting allows the browser to cache the application in a way compatible with Meteor
        # on every applicaiton update the name of CSS and JS file is different, so they can be cache infinitely (here: 30 days)
        # the root path (/) MUST NOT be cached
        if ($uri != '/') {
            expires 30d;
        }
    }
}
  • Включите новый пользовательский интерфейс kadira
sudo ln -s /etc/nginx/sites-available/kadira /etc/nginx/sites-enabled/
  • Протестируйте конфигурацию nginx
sudo nginx -t
  • Создайте новый серверный блок для kadira-engine
sudo nano /etc/nginx/sites-available/kadira-engine
  • Настройте nginx для пересылки с 80 на порт 4000, если выполняется kadira-ui
# this section is needed to proxy web-socket connections
map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
}
# HTTPS server
server {
    listen 543 default_server ssl http2; # we enable SPDY here
    server_name [::]:543 default_server; # this domain must match Common Name (CN) in the SSL certificate
    root html; # irrelevant
    index index.html; # irrelevant
    ssl_certificate /etc/nginx/ssl/kadira.pem; # full path to SSL certificate and CA certificate concatenated together
    ssl_certificate_key /etc/nginx/ssl/kadira.key; # full path to SSL key
    # performance enhancement for SSL
    ssl_stapling on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 5m;
    # config to enable HSTS(HTTP Strict Transport Security) https://developer.mozilla.org/en-US/docs/Security/HTTP_Strict_Transport_Security
    # to avoid ssl stripping https://en.wikipedia.org/wiki/SSL_stripping#SSL_stripping
    add_header Strict-Transport-Security "max-age=31536000;";
    # If your application is not compatible with IE <= 10, this will redirect visitors to a page advising a browser update
    # This works because IE 11 does not present itself as MSIE anymore
    if ($http_user_agent ~ "MSIE" ) {
        return 303 https://browser-update.org/update.html;
    }
    # pass all requests to Meteor
    location / {
        proxy_pass http://127.0.0.1:11011;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade; # allow websockets
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header X-Forwarded-For $remote_addr; # preserve client IP
        # this setting allows the browser to cache the application in a way compatible with Meteor
        # on every applicaiton update the name of CSS and JS file is different, so they can be cache infinitely (here: 30 days)
        # the root path (/) MUST NOT be cached
        if ($uri != '/') {
            expires 30d;
        }
    }
}
  • Включите новый движок kadira
sudo ln -s /etc/nginx/sites-available/kadira-engine /etc/nginx/sites-enabled/
  • Протестируйте конфигурацию nginx
sudo nginx -t
  • если все в порядке, перезапустите nginx
sudo systemctl restart nginx