Python Flask kết hợp với uWSGI Nginx ssl Cerbot

Bình thường khi viết xong app Python Flask thì chúng ta thường chạy bằng lệnh:
python3 myproject.py



Giờ, chúng ta sẽ chạy qua uWSGI và Nginx sử dụng SSL cho nó...chuẩn!

Phần I: Chạy web với HTTP thuần

 
Step 1: Cài các gói cần thiết và chạy thử Python Flask App
Đầu tiên, cần cài các gói cần thiết:

yum install epel-release

Nếu dùng centos8/Rocky Linux thì có thể cài qua lệnh:
dnf install epel-release

yum install python-pip python-devel gcc nginx


Tạo Python Virtual Environment:
pip install virtualenv
mkdir ~/myproject
cd ~/myproject
virtualenv myprojectenv
source myprojectenv/bin/activate


Cài đặt Flask và uWSGI:
pip install uwsgi flask


Tạo cái app mẫu nào:
vim ~/myproject/myproject.py


Nội dung:
from flask import Flask
application = Flask(__name__)

@application.route("/")
def hello():
    return "<h1 style='color:blue'>Hello There!</h1>"

if __name__ == "__main__":
    
    application.run(host='0.0.0.0', port=5001)


Chạy test:
python3 myproject.py


Truy cập thử web với port:5001 nếu ra "Hello There!"  là ok, chưa ok thì xem mở port trong firewalld...

Nếu chưa mở port thì mở như sau:
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

Tạo WSGI Entry Point:

vim ~/myproject/wsgi.py

from myproject import application

if __name__ == "__main__":
    application.run()


Chạy thử uWSGI Serving:

uwsgi --socket 0.0.0.0:5001 --protocol=http -w wsgi


Truy cập thử web với port:5001 nếu ra "Hello There!"  là ok.
Xong, sứ mệnh của virtual environment đã kết thúc, tắt nó:
deactivate


Step 2: Tạo các cấu hình chạy dịch vụ cho uWSGI

- Tạo file cấu hình cho uWSGI:
vim ~/myproject/myproject.ini


Nội dung:
[uwsgi]
module = wsgi

master = true
processes = 5

socket = myproject.sock
chmod-socket = 660
vacuum = true

die-on-term = true

 

Tạo file chạy service:
vim /etc/systemd/system/myproject.service

[Unit]
Description=uWSGI instance to serve myproject
After=network.target

[Service]
User=webuser
Group=nginx
WorkingDirectory=/home/user/myproject
Environment="PATH=/home/user/myproject/myprojectenv/bin"
ExecStart=/home/user/myproject/myprojectenv/bin/uwsgi --ini myproject.ini

[Install]
WantedBy=multi-user.target


- Khởi chạy dịch vụ:

systemctl daemon-reload
sudo systemctl start myproject
sudo systemctl enable myproject


Step 3:  Cấu hình Nginx Proxy

vim /etc/nginx/conf.d/lecuong.info.conf


Nội dung:

server {
    listen 80;
    server_name lecuong.info;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/home/user/myproject/myproject.sock;
    }
}

Thêm webuser vào nhóm nginx
sudo usermod -a -G webuser nginx

chmod 710 /home/webuser   # ko chay lenh nay khi truy cap web se ra loi: 502 Bad Gateway



- Kiểm tra cấu hình Nginx
sudo nginx -t

Nếu nó không lòi ra lỗi gì, thì ngon lành rồi đó! Còn nếu có lỗi thì...tìm cách sửa đi :))

Khởi chạy dịch vụ Nginx:
sudo systemctl start nginx
sudo systemctl enable nginx


Rồi, xong rồi đó. Truy cập web ngon lành nha!
(*) phần này cần tham khảo chi tiết thì xem ở đây


Phần II: Chạy web với HTTPS cho nó bảo mật nha :))

Step 1:  Cài đặt cerbot và Nginx plugin dùng cho cerbot

sudo dnf install certbot python3-certbot-nginx


- Tiến hành tạo Cert:
sudo certbot --nginx -d lecuong.info -d www.lecuong.info
Nếu chỉ cần tạo cert cho 1 dommain duy nhất thì gõ:
sudo certbot --nginx -d your_domain


Nếu thành công thì certbot nó sẽ thông báo dạng "Congratulations! Your certificate and chain have been saved at:"
Còn nếu lỗi gì đó, thì debug từ từ giải quyết thôi :))

- Cấu hình tự động renew cert SSL (vì mặc định cert sẽ hết hạn sau 90 ngày.):

Test thử xem việc renew có ok ko?
certbot renew --dry-run


Nếu ok thì cài đặt job cho nó tự renew:
crontab -e

dán vô:
* */12 * * * root /usr/bin/certbot renew >/dev/null 2>&1


Step 2: cấu hình SSL vô web
Mặc định certbot nó ghi sẵn vô /etc/nginx/nginx.conf rồi, nhưng tôi thích dùng file cấu hình riêng hơn!

vim /etc/nginx/conf.d/lecuong.info.conf


    server {
    server_name lecuong.info;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/home/user/myproject/myproject.sock;
    }
    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/lecuong.info/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/lecuong.info/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

}


- Khởi động lại dịch vụ Flask web và Nginx

systemctl restart myproject
systemctl restart nginx


Nhiêu đó là xong rồi.
Từ giờ, chúng ta có thể truy cập web với https://

Cơm thêm:  Nếu bạn nào dùng dịch vụ CloudFlare, và có bật Proxy thì cần đổi cấu hình thì mới chạy được!

Chia sẻ file cấu hình nè: ngix_proxy_behind_cloudflare.conf

 Thêm nữa là nếu chạy test renew certbot lỗi thì nên thêm các page rule trên Cloudflare

# This is a Cloudflare issue as it's caching the response.

*yourdomain.com/.well-known/acme-challenge/*

Cache Level: Bypass, Automatic HTTPS Rewrites: Off, Disable Performance

Chúc các bạn may mắn. :))



Đọc tiếp

Quick install SSL - Let’s Encrypt Apache/ Python3 ~ Centos7

 yum install httpd

systemctl enable httpd
vim /etc/httpd/conf.d/domain.com.conf
Add the following lines:
<VirtualHost *:80>
    ServerAdmin admin@domain.com
    DocumentRoot "/var/www/html"
    DirectoryIndex index.html
    ServerName domain.com
    ErrorLog "/var/log/httpd/domain.com.error_log"
    CustomLog "/var/log/httpd/domain.com.access_log" common
</VirtualHost>
vim /var/www/html/index.html
Add:
<html>
Test - Welcome to The Apache Web Server.
</html>
sudo python3 -m venv /opt/certbot/
sudo /opt/certbot/bin/pip install --upgrade pip

sudo /opt/certbot/bin/pip install certbot

sudo ln -s /opt/certbot/bin/certbot /usr/bin/certbot

sudo certbot certonly --standalone
Test the renewal process manually with the following command.
certbot renew --dry-run
To do so, edit the crontab with the following command:

crontab -e

Add the following line:

* */12 * * * root /usr/bin/certbot renew >/dev/null 2>&1

[Monthly] Upgrade certbot
It's important to occasionally update Certbot to keep it up-to-date. To do this, run the following command on the command line on the machine.

sudo /opt/certbot/bin/pip install --upgrade certbot

Move to another server:

You can copy the entire dir /etc/letsencrypt/ and restore it on your new server.

Old server (as root):

tar zpcvf backup_etc-letsencrypt_2018-Nov-20.tar.gz /etc/letsencrypt/
Now transfer the file to the new server.

New server (as root):
tar zxvf backup_etc-letsencrypt_2018-Nov-20.tar.gz -C /

And you have all the certificates, renewal confs, etc. on your new server.
 

 Allow user bind privileged port
For some reason no one mention about lowering sysctl net.ipv4.ip_unprivileged_port_start to the value you need. Example: We need to bind our app to 443 port.

sysctl net.ipv4.ip_unprivileged_port_start=443
Some may say, there is a potential security problem: unprivileged users now may bind to the other privileged ports (444-1024). But you can solve this problem easily with iptables, by blocking other ports:
iptables -I INPUT -p tcp --dport 444:1024 -j DROP
iptables -I INPUT -p udp --dport 444:1024 -j DROP

#----------

https://dade2.net/kb/how-to-install-and-configure-certbot-on-apache-centos/
https://certbot.eff.org/lets-encrypt/pip-other

https://stackoverflow.com/questions/413807/is-there-a-way-for-non-root-processes-to-bind-to-privileged-ports-on-linux

Đọc tiếp

Hướng dẫn này cài đặt Python 3.6.3 trên Centos/Fedora/Redhat

Python là một ngôn ngữ lập trình dễ học. Ứng dụng của Python rất lớn, chương trình viết bằng python chạy trên nhiều nền tảng (Windows, Linux, OS X,...)
Python hiện nay ứng dụng nhiều trong:

  • lập trình web
  • phân tích dữ liệu, số liệu (big data)
  • xử lý toán học (Pynum)
  • tạo biểu đồ, hình hoá số liệu (visualization)
  • bảo mật mạng và máy tính
  • tự động hoá (tự động crawl data chẳng hạn)
  • scripting trong các engine (Blender 3D, Maya Scripting...)
  • scripting trong game (nhiều game online dùng scripting bằng Python)
  • xử lý đồ hoạ, ảnh kĩ thuật số.
 Ngoài ra, Python được sử dụng nhiều để...hack! @@


Trong bài viết này, tôi sẽ hướng dẫn cài đặt Python 3.6.3

Download:

# cd /usr/src
# wget https://www.python.org/ftp/python/3.6.3/Python-3.6.3.tgz

Giải nén:
# tar xzf Python-3.6.3.tgz

Tiến hành cài đặt Python 3.6

# cd Python-3.6.3
# ./configure
# make altinstall
 Sử dụng "make altinstall" để tránh ghi đè phiên bản python mặc định trên hệ thống tại /usr/bin/python .

Xóa file cài đặt
# rm Python-3.6.3.tgz
Kiểm tra phiên bản Python:

# python3.6 -V

Bây giờ trong hệ thống của bạn sẽ vừa có Python2 và Python3 để test ứng dụng, lập trình...và hack cái gì đó ^^!


Nếu quá trình cài đặt có lỗi : zipimport.ZipImportError: can't decompress data; zlib not available
#yum install zlib-devel


------------------------------------------------------ THE END ------------------------------------------


Chúc may mắn ^^!

Đọc tiếp

[SVN] How to Setup an Apache Subversion (SVN) Server on CentOS 7

[1].Chuẩn bị:

- Disable Firewall và Selinux
- Update server

[2].Cài đặt httpd:

 [root@svn-dev ~]#yum install httpd
 [root@svn-dev ~]#systemctl start httpd
 [root@svn-dev ~]#systemctl enable httpd
 [root@svn-dev ~]#vim /etc/httpd/conf/httpd.conf
               Sửa lại dòng 95=> ServerName 192.168.11.180:80

[3]. Cài đặt SVN và mod_dav_svn module:
 [root@svn-dev ~]#yum install subversion mod_dav_svn

[4].Cấu hình SVN configuration file:
 [root@svn-dev ~]#vim /etc/httpd/conf.modules.d/10-subversion.conf
      LoadModule dav_svn_module modules/mod_dav_svn.so
      LoadModule authz_svn_module modules/mod_authz_svn.so

      DAV svn
      SVNParentPath /var/www/svn
      Satisfy Any
      AuthType Basic
      AuthName "SVN Authentication"
      AuthUserFile /etc/svn-auth-accounts
      AuthzSVNAccessFile /etc/svn-auth-file
      SVNPathAuthz On
      Require valid-user
      Order allow,deny
      Allow from all

[5]. Tạo SVN repo:

 [root@svn-dev ~]#mkdir /var/www/svn
 [root@svn-dev ~]#cd /var/www/svn
 [root@svn-dev svn]#svnadmin create nhaccuatuitv
 [root@svn-dev svn]#chown -R apache:apache nhaccuatuitv
 [root@svn-dev svn]#chcon -R -t httpd_sys_content_t /var/www/svn/nhaccuatuitv/
 [root@svn-dev svn]#chcon -R -t httpd_sys_rw_content_t /var/www/svn/nhaccuatuitv/

[6].Tạo user SVN:

[root@svn-dev svn]#htpasswd -cm /etc/svn-auth-accounts quocha => nct@1234
[root@svn-dev svn]#htpasswd -m /etc/svn-auth-accounts cuongpt => nct@12345

[7]. Add quyền cho user:

[root@svn-dev svn]# cp nhaccuatuitv/conf/authz /etc/svn-auth-file
[root@svn-dev svn]#vim /etc/svn-auth-file
 [groups]
 admin=cuongpt
 repo1_user=quocha
 repo1_trainee=user003_no

 [/]
 @admin=rw

 [nhaccuatuitv:/]
 @repo1_user=rw

 [repo2:/]
 @repo1_trainee=rw

[root@svn-dev svn]# systemctl restart httpd.service

[8].Checkout SVN trên Windows: trên google đầy

[9].Checkout trên SVN Server:

[root@svn-dev ~]#mkdir -p /home/nhaccuatuitv/
[root@svn-dev ~]#svn co http://192.168.11.180/svn/nhaccuatuitv/ /home/nhaccuatuitv/ --username quocha
=> nhập pass và kiểm tra file

[10] More, Tạo crontab cho checkout

#vim /home/Notes/scripts/svn-co.sh
 svn co --username quocha --password nct@1234 http://192.168.11.180/svn/nhaccuatuitv/ /home/nhaccuatuitv/
 [root@svn-dev scripts]# chmod +x svn-co.sh
 
Crontab cho 1 phut check out
 #crontab -e
 * * * * * /home/Notes/scripts/svn-co.sh >/dev/null 2>&1

Đọc tiếp

Giải pháp giám sát hạ tầng mạng miễn phí

Chào các bạn,

Tiếp theo loại bài về GIẢI PHÁP GIÁM SÁT HẠ TẦNG MẠNG MIỄN PHÍ với:

  • Nagios
  • PNP4nagios
  • Check_mk
  • ....

Trong bài viết này, tôi sẽ giới thiệu về việc Tích hợp các dữ liệu monitoring vào database.

Để thực hiện việc này, chúng ta sử dụng một addon có tên là NDOUtils
Sau đây là các bước tích hợp:

  • Cài đặt & cấu hình MySQL
  • Thay đổi các thông số kernel
  • Cài đặt và cấu hình ndoutils-2.1.3
  • Khai báo Ndoutils vào Nagios
  • Kiểm tra

1/ Cài đặt & cấu hình MySQL

Installing MySQL

===== CentOS 5.x / 6.x | RHEL 5.x / 6.x | Oracle Linux 5.x / 6.x =====

yum install -y mysql mysql-server mysql-devel
 Install MariaDB
===== CentOS 7.x | RHEL 7.x =====

yum install -y mariadb mariadb-server mariadb-devel

Start And Configure MySQL / MariaDB

service mysqld start
systemctl start mariadb.service
Configure it to start when the system boots:
chkconfig --add mysqld
chkconfig mysqld on
systemctl start mariadb.service
systemctl enable mariadb.service
Set root password for MySQL / MariaDB

/usr/bin/mysqladmin -u root password 'mypassword'

Create Database

Tôi sẽ tạo tạo database với các thông tin như sau:

  • Database name: nagios
  • User: ndoutils
  • Password: 'ndoutils_password

Kết nối vào db:
mysql -u root -p'mypassword'
 Thực hiện các lệnh sau:

CREATE DATABASE nagios DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE USER 'ndoutils'@'localhost' IDENTIFIED BY 'ndoutils_password';
GRANT USAGE ON *.* TO 'ndoutils'@'localhost' IDENTIFIED BY 'ndoutils_password' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ; 
GRANT ALL PRIVILEGES ON nagios.* TO 'ndoutils'@'localhost' WITH GRANT OPTION ; 
\q

Test thử kết nối:
echo 'show databases;' | mysql -u ndoutils -p'ndoutils_password' -h localhost


Kết quả kiểu vầy là ok:
Database
information_schema
nagios
test
2/ Thay đổi các thông số kernel

Chúng ta cần thay đổi một vài thông số kernel để Ndoutils có thể hoạt động tốt.

Backup file cũ:
cp /etc/sysctl.conf /etc/sysctl.conf_backup
Tiến hành sửa một vài thông số, gõ lần lượt các lệnh sau:

sed -i '/msgmnb/d' /etc/sysctl.conf
sed -i '/msgmax/d' /etc/sysctl.conf
sed -i '/shmmax/d' /etc/sysctl.conf
sed -i '/shmall/d' /etc/sysctl.conf
printf "\n\nkernel.msgmnb = 131072000\n" >> /etc/sysctl.conf
printf "kernel.msgmax = 131072000\n" >> /etc/sysctl.conf
printf "kernel.shmmax = 4294967295\n" >> /etc/sysctl.conf
printf "kernel.shmall = 268435456\n" >> /etc/sysctl.conf
 Kiểm tra lại thông số:
sysctl -e -p /etc/sysctl.conf
Kết quả kiểu như vầy:
net.ipv4.ip_forward = 0
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
kernel.sysrq = 0
kernel.core_uses_pid = 1
net.ipv4.tcp_syncookies = 1
kernel.msgmnb = 131072000
kernel.msgmax = 131072000
kernel.shmmax = 4294967295
kernel.shmall = 268435456
 3/ Cài đặt và cấu hình ndoutils-2.1.3

Download:

cd /tmp
wget -O ndoutils.tar.gz https://github.com/NagiosEnterprises/ndoutils/releases/download/ndoutils-2.1.3/ndoutils-2.1.3.tar.gz
tar xzf ndoutils.tar.gz

Compile NDOUtils:
cd /tmp/ndoutils-2.1.3/
./configure
make all
make install

Tích hợp vào database

cd db/
./installdb -u 'ndoutils' -p 'ndoutils_password' -h 'localhost' -d nagios
cd .. 

Cấu hình ndoutils:

Có 2 file lưu trữ cấu hình của ndoutils:

  • /usr/local/nagios/etc/ndomod.cfg
  • /usr/local/nagios/etc/ndo2db.cfg

Chúng ta cần khai báo các thông số kết nối database:

  • db_user=ndoutils
  • db_pass=ndoutils_password

Sử dụng các lệnh sau:
make install-config
mv /usr/local/nagios/etc/ndo2db.cfg-sample /usr/local/nagios/etc/ndo2db.cfg
sed -i 's/^db_user=.*/db_user=ndoutils/g' /usr/local/nagios/etc/ndo2db.cfg
sed -i 's/^db_pass=.*/db_pass=ndoutils_password/g' /usr/local/nagios/etc/ndo2db.cfg
mv /usr/local/nagios/etc/ndomod.cfg-sample /usr/local/nagios/etc/ndomod.cfg

Cấu hình startup
make install-init
Start dịch vụ

===== CentOS 6.x | RHEL 6.x
service ndo2db start
===== CentOS 7.x | RHEL 7.x
systemctl enable ndo2db.service
4/ Khai báo Ndoutils vào Nagios

Sau khi cấu hình xong ndoutils thì cần phải thông báo cho Nagios biết về sự có mặt của em í ^^!
Sử dụng đoạn lệnh sau:
printf "\n\n# NDOUtils Broker Module\n" >> /usr/local/nagios/etc/nagios.cfg
printf "broker_module=/usr/local/nagios/bin/ndomod.o config_file=/usr/local/nagios/etc/ndomod.cfg\n" >> /usr/local/nagios/etc/nagios.cfg 
Khởi động lại Nagios:
service nagios restart
systemctl restart nagios.service
service ndo2db restart
systemctl restart ndo2db.service
5/ Kiểm tra:

Kiểm tra thử NDO module có tích hợp thành công vào Nagios hay không?
grep ndo /usr/local/nagios/var/nagios.log

Query thử dữ liệu trên database:

echo 'select * from nagios.nagios_logentries;' | mysql -u ndoutils -p'ndoutils_password'

------------------------------------------------------ THE END ------------------------------------------


Chúc may mắn ^^!




Đọc tiếp

[Solution] Giải pháp Audit hạ tầng IT

Chắc hẳn các bạn đã từng phân vân khi lựa chọn phần mềm audit trong hệ thống. Có rất nhiều tool để làm việc đó - quan trọng là thấy cái nào phù hợp với nhu cầu của mình.

Mình xin giới thiệu các phần mềm Netwrix (https://www.netwrix.com/).

Bài viết này mình hướng dẫn trên bản 8.5 (bản mới nhất là 9)

- Bạn chọn file cài đặt



- Nhấn Install














- Giao diện khi đã cài đặt thành công






Đọc tiếp