Thursday, February 18, 2016

Optimizing HTTPS on Nginx

Step 1: Connection credentials caching

Almost all of the overhead with SSL/TLS is during the initial connection setup, so by caching the connection parameters for the session, will drastically improve subsequent requests (or in the case of SPDY, requests after the connection have closed – like a new page load).
All we need is these two lines:
ssl_session_cache shared:SSL:20m;
ssl_session_timeout 180m;
This will create a cache shared between all worker processes. The cache size is specified in bytes (in this example: 20 MB). According to the Nginx documentation can 1MB store about 4000 sessions, so for this example, we can store about 80000 sessions, and we will store them for 180 minutes. If you expect more traffic, increase the cache size accordingly.
I usually don’t recommend lowering the ssl_session_timeout to below 10 minutes, but if your resources are sparse and your analytics tells you otherwise, go ahead. Nginx is supposedly smart enough to not use up all your RAM on session cache, even if you set this value too high, anyways.

Step 2: Disable SSL

– Say, what?
Techically SSL (Secure Sockets Layer) is actually superseded by TLS (Transport Layer Security). I guess it is just out of old habit and convention we still talk about SSL.
SSL contains several weaknesses, there have been various attacks on implementations and it is vulnerable to certain protocol downgrade attacks.
The only browser or library still known to mankind that doesn’t support TLS is of course IE 6. Since that browser is dead (should be, there is not one single excuse in the world), we can safely disable SSL.
The most recent version of TLS is 1.2, but there are still modern browsers and libraries that use TLS 1.0.
So, we’ll add this line to our config then:
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
That was easy, now on to something more complicated (which I made easy for you):

Step 3: Optimizing the cipher suites

The cipher suites are the hard core of SSL/TLS. This is where the encryption happens, and I will really not go into any of that here. All you need to know is that there are very secure suits, there are unsafe suites and if you thought browser compatibility issues were big on the front-end, this is a whole new ballgame. Researching what cipher suites to use, what not to use and in what order takes a huge amount of time to research. Luckily for you, I’ve done it.
First you need to configure Nginx to tell the client that we have a preferred order of available cipher suites:
ssl_prefer_server_ciphers on;
Next we have to provide the actual list of ciphers:
ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:!ADH:!AECDH:!MD5
All of these suites use forward secrecy, and the fast cipher AES is the preferred one. You’ll lose support for all versions of Internet Explorer on Windows XP. Who cares?

Step 4: Generate DH parameters

If you want an explanation, read the DHE handshake and dhparam part on the Mozilla wiki. I’m not doing that here.
Create the DH parameters file with 2048 bit long safe prime:
$ openssl dhparam 2048 -out /etc/nginx/cert/dhparam.pem
And add it to your Nginx config:
ssl_dhparam /etc/nginx/cert/dhparam.pem;
Note that Java 6 doesn’t support DHParams with primes longer than 1024 bit. If that really matters to you, something is a bit wrong somewhere.

Step 5: Enable OCSP stapling

Online Certificate Status Protocol (OCSP) is a protocol for checking the revocation status of the presented certificate. When a proper browser is presented a certificate, it will contact the issuer of that certificate to check that it hasn’t been revoked. This, of course, adds overhead to the connection initialization and also presents a privacy issue involving a 3rd party.
Enter OCSP stapling:
The web server can at regular intervals, contact the certificate authority’s OCSP server to get a signed response and staple it on to the handshake when the connection is set up. This provides for a much more efficient connection initialization and keeps the 3rd party out of the way.
To make sure the response from the CA is not tampered with, we also set up Nginx to verify response using the CA’s root and the intermediate certificates, similar to what we did when we first to enable HTTPS on Nginx (remember the order here is important):
cat AddTrustExternalCARoot.crt PositiveSSLCA2.crt > trustchain.crt
I am using a Positive SSL certificate so AddTrustExternalCARoot.crt is the root certificate and PositiveSSLCA2.crt is the intermediate. Replace with your issuer’s certificates accordingly. If you don’t have your CA’s root certificate, it should be available from their web site or you have to contact them.
Next, enable stapling and verification:
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/nginx/cert/trustchain.crt;
resolver 8.8.8.8 8.8.4.4;
You also need to provide one or more DNS servers for Nginx to use. Here I’m using Google’s public DNS servers, but you are free to use whichever works for you (if you don’t like Google or are worried about privacy, OpenDNS might be a good option for you). The resolvers are used in a round-robin fashion, so make sure all of them are good ones.

Step 6: Strict Transport Security

Even though you already should have made all regular HTTP requests redirect to HTTPS when you enabled SPDY, you do want to enable Strict Transport Security (STS or HSTS) to avoid having to do those redirects. STS is a nifty little feature enabled in modern browsers. All the server does is to set the response header Strict-Transport-Security with a max-age value.
If the browser have seen this header, it will not try to contact the server over regular HTTP again for the given time period. It will actually interpret all requests to this hostname as HTTPS, no matter what. You can even tell the browser to enable the same behaviour on all subdomains. It will make MITM attacks with SSLstrip harder to do.
All you need is this little line in your config:
add_header Strict-Transport-Security "max-age=31536000" always;
The max-age is set in seconds. 31536000 seconds is equivalent to 365 days.
If you want HSTS to apply to all subdomains, you use this config instead:
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
That’s it.

Wrap-up

I know how annoying it is to follow guides like this. You just want the config, right?
Well, here it is:
server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;

        ssl_certificate /etc/nginx/cert/bjornjohansen.no.certchain.crt;
        ssl_certificate_key /etc/nginx/cert/bjornjohansen.no.key;

        ssl_session_cache shared:SSL:20m;
        ssl_session_timeout 60m;

        ssl_prefer_server_ciphers on;

        ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:!ADH:!AECDH:!MD5;

        ssl_dhparam /etc/nginx/cert/dhparam.pem;

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

        ssl_stapling on;
        ssl_stapling_verify on;
        ssl_trusted_certificate /etc/nginx/cert/trustchain.crt;
        resolver 8.8.8.8 8.8.4.4;

        #add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
        add_header Strict-Transport-Security "max-age=31536000" always;

        # Rest of your regular config goes here:
        # […]
}
Now that you’re done, go check your site on Qualsys SSL Labs test. You should have an «A+» rating.
Have fun, be safe, encrypt everything!
BTW: Now that you have HTTPS properly set up, it is time to look at HTTP Public Key Pinning (HPKP).

Source https://bjornjohansen.no/optimizing-https-nginx

Monday, January 11, 2016

Mẹo tính toán cực hay mà sách giáo khoa chưa bao giờ dạy bạn



1. Đổi từ độ F sang độ C và ngược lại (con số tương đối)
 
mẹo tính toán, toán học, học toán

2. Bí quyết đơn giản với các phép nhân lớn
mẹo tính toán, toán học, học toán

3. Bí quyết khi nhân với 11
mẹo tính toán, toán học, học toán

4. Bí quyết để nhớ được giá trị của số Pi
Bạn có thể nhớ được giá trị của số Pi bằng cách đếm các chữ cái trong câu: “May I have a large container of coffee” (3,1415926).
mẹo tính toán, toán học, học toán

5. Mẹo tính cộng trừ bằng phương pháp hình con bướm
mẹo tính toán, toán học, học toán

6. Bảng cửu chương nhân 9 có qui luật ngược chiều
mẹo tính toán, toán học, học toán

7. Cách nhân của học sinh Nhật Bản
mẹo tính toán, toán học, học toán

8. Cách tính phân số
mẹo tính toán, toán học, học toán

(sưu tầm)

Monday, December 28, 2015

Vì sao trẻ vừa lọt lòng không nên cho tắm ngay?

(ĐSPL) - Ở những giờ đầu tiên sau khi sinh, không nên tắm ngay cho trẻ sơ sinh, bởi nó sẽ ảnh hưởng đến sức đề kháng của trẻ và một số những hệ lụy khác.
Thông thường một đứa trẻ sinh ra, việc làm đầu tiên là bé được tắm rửa sạch sẽ. Nhưng hiện nay, theo xu thế sinh nở mới nhất, trẻ sinh ra không nên tắm luôn mà để đến vài ngày sau. Điều này giống cũng như việc cắt dây rốn muộn.
Vì sao trẻ vừa lọt lòng không nên cho tắm ngay? - Ảnh 1

Nên bỏ qua lần tắm đầu tiên cho trẻ vừa chào đời (trong khoảng 24h sau sinh). Ảnh minh họa.

Dưới đây là những lý do bạn không nên tắm cho trẻ sơ sinh quá sớm trong những giờ đầu tiên mới sinh sau.

Duy trì lớp da bảo vệ tự nhiên cho bé

Được biết, khi ở trong bụng mẹ, bé được bao bọc bởi nước ối. Điều này khiến da bé được phủ một lớp màu trắng để bảo vệ bé khỏi môi trường ngoài, lớp màu trắng này được gọi là vernix. Đó là một trong những lý do bạn không nên tắm ngay cho trẻ sơ sinh.
Giúp da bé thêm khỏe mạnh và dẻo dai
Theo các nghiên cứu, chất venix có tính miễn dịch cao và đây là lợi thế rất lớn của em bé mới sinh. Nó đồng thời là kem dưỡng ẩm giữ cho làn da bé mềm mại và dẻo dai cũng ngăn vi khuẩn xâm nhập.
Đây là nguyên nhân giải thích tại sao trong khoảng 24 giờ sau lần tắm đầu tiên của bé, có những lớp màu trắng đục bong ra. Toàn bộ cơ thể của bé sẽ được lột sạch lớp vernix (nhất là ở trên bàn tay và bàn chân).

Nước ối có vai trò cung cấp vitamin K cho trẻ

Sau khi sinh cơ thể trẻ vẫn còn dính lớp nước ối. Trong nước ối có chứa nhiều loại vi khuẩn có lợi giúp sản xuất vitamin K cung cấp cho trẻ. Vì vậy khi trẻ mới sinh ra, mẹ không nên tắm luôn mà hãy để lại lớp nước ối còn dính trên người bé.
Tăng sự liên kết giữa mẹ và bé
Khi bé chào đời, cần được gần gũi với mẹ, gần nguồn thức ăn nơi bé có thể nghe, ngửi hơi ấm của người mẹ. Vì vậy, nếu tắm cho trẻ quá sớm có thể làm gián đoạn quá trình em bé nhận biết mẹ, bé cảm thấy mất an toàn và có thể ảnh hưởng đến những cữ bú quan trọng đầu tiên.
Vì sao trẻ vừa lọt lòng không nên cho tắm ngay? - Ảnh 2
Ảnh minh họa.

Giúp ổn định nhiệt độ cơ thể

Trẻ vừa mới lọt lòng mẹ đang tìm cách duy trì nhiệt độ cơ thể mình. Nếu cho bé tắm quá sớm, có thể làm cho bé chới với với nhiệt độ mới. Vì điều này, có một số trường hợp, em bé sơ sinh cần đặt dưới đèn nhiệt để lấy lại nhiệt độ sau khi tắm.
Thay vào đó, hãy trì hoãn thời gian tắm, để bé tiếp xúc với mẹ thời gian vừa đủ và quen với nhiệt độ bên ngoài.

Tránh tăng đường huyết và hoóc-môn stress

Khi sinh ra, trẻ đã bị tách khỏi mẹ để đi tắm, trẻ có thể sẽ khóc. Điều này làm cơ thể sản sinh một loại hoóc-môn gây stress để đáp ứng tình hình thực tế. Việc cơ thể phải làm việc căng thẳng hơn khi bé đi tắm cũng khiến bé dễ bị tuột đường huyết. Khi được ở bên mẹ đủ lâu, các cơ quan trong cơ thể bé có khuynh hướng thực hiện tốt chức năng của chúng hơn.
Một số lưu ý khác:
Tốt nhất, cha mẹ nên bỏ qua lần tắm đầu tiên từ sau khi con chào đời (trong khoảng sau khi sinh). Từ lần tắm thứ 2, mẹ hãy tắm chung cùng bé giúp bé cảm thấy rất an toàn khi không bị tách khỏi mẹ. Mẹ nên ôm con cùng ngồi trong bồn tắm, chớ nên thả bé một mình sẽ gây cho bé sự chới với và đơn độc.
Khi tắm, lưu ý sử dụng găng tay để ngăn chặn những vi trùng, vi khuẩn ở môi trường bệnh viện. Một nghiên cứu cho thấy, sử dụng găng tay với trẻ sơ sinh ngay cả khi tắm có tỷ lệ nhiễm trùng rất ít.

http://www.doisongphapluat.com/doi-song/suc-khoe-lam-dep/vi-sao-tre-vua-lot-long-khong-nen-cho-tam-ngay-a126435.html

Friday, December 25, 2015

Tuning Apache2 prefork MaxClients ServerLimit

Apache prefork settings, per apache performance tuning guidelines
quote:
The single biggest hardware issue affecting webserver performance is RAM.
A webserver should never ever have to swap, as swapping increases the latency
of each request beyond a point that users consider "fast enough". 
This causes users to hit stop and reload, further increasing the load.
You can, and should, control the MaxClients setting so that your server does
not spawn so many children it starts swapping. This procedure for doing this
is simple: determine the size of your average Apache process, by looking at
your process list via a tool such as top, and divide this into your total 
available memory, leaving some room for other processes.
you should set it up like this based on your input to:
  • Total Memory : 128 GB 
  • -10% memory for everything except apache: 115 GB
  • Now we need to figure out how much single apache process is using. 
To calculate this you can use following script :
pgrep apache2 | xargs -n1 -I{} cat /proc/{}/smaps | \
  awk '{if ($0 ~ /stack/) {pids+=1} else if ($0 ~/^Shared_/) 
    {shared+=$2} else if ($0 ~ /^Pss:/) {priv+=$2}} END {
      printf "%.2f MB\n",(priv+shared/(pids*pids))/1024}'
This is best estimate of how much single apache process is using memory while trying to proportionally dividing shared usage per number of active apache processes and adding it on top of Pss (proportional set size)
Finally you divide 115 GB with this figure and you get MaxClients/ServerLimit. From here you can relatively calculate other figures like 
  • StartServers 30% of MaxClients
  • MinSpareServers 5% of MaxClients
  • MaxSpareServers 10% of MaxClients
  • ServerLimit == MaxClients
  • MaxRequestsPerChild 10000 (as conservative alternative to address possible problem with memory leaky apps)
http://serverfault.com/questions/644622/tuning-apache2-prefork-maxclients-serverlimit

Saturday, October 10, 2015

delete client connections in redis using lua

Here are Lua script run in redis 2.6

>eval " local str_tmp = redis.call('client', 'list') for k,v in string.gmatch(str_tmp, '(addr)=(IP:%d+)') do redis.call('client', 'kill', v) end return" 0
>script flush

Tuesday, September 29, 2015

Recover MySQL root password

Step # 1 : Stop the MySQL service:
# /etc/init.d/mysql stop
Output:
Stopping MySQL database server: mysqld.
Step # 2: Start the MySQL server w/o password:
# mysqld_safe --skip-grant-tables &
Output:
[1] 5988
Starting mysqld daemon with databases from /var/lib/mysql
mysqld_safe[6025]: started
Step # 3: Connect to the MySQL server using the MySQL client:
# mysql -u root
Output:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1 to server version: 4.1.15-Debian_1-log

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>
Step # 4: Set a new MySQL root user password:
mysql> use mysql;
mysql> update user set password=PASSWORD("NEW-ROOT-PASSWORD") where User='root';
mysql> flush privileges;
mysql> quit
Step # 5: Stop the MySQL server:
# /etc/init.d/mysql stop
Output:
Stopping MySQL database server: mysqld
STOPPING server from pid file /var/run/mysqld/mysqld.pid
mysqld_safe[6186]: ended

[1]+  Done                    mysqld_safe --skip-grant-tables
Start the MySQL server and test it:
# /etc/init.d/mysql start
# mysql -u root -p

Source: https://www.howtoforge.com/setting-changing-resetting-mysql-root-passwords

Friday, September 11, 2015

mongo replica with authentication

- Have not to create anything before
- connect to mongod using the localhost exception

>use admin
>db.createUser(
    {
      user: "superuser",
      pwd: "12345678",
      roles: [ {role: "userAdminAnyDatabase", db: "admin"}, "root" ]
    }
)

=========To create use in database===========
>use another_database
>db.createUser({user: "name", pwd: "password", roles: ['read', 'readWrite', 'dbAmin', 'dbOwner', 'userAdmin', ... http://docs.mongodb.org/v2.6/reference/built-in-roles/ ]})
====================End======================
- Close mongod
 
- Create keyFile
#openssl rand -base64 741 > mongodb-keyfile
#chmod 600 mongodb-keyfile
 
- Copy key file to each member of replica set
 
- Start mongod: mongod --auth --setParameter enableLocalhostAuthBypass=0 --setParameter enableTestCommands=0 --dbpath /your/path --replSet rs0 --smallfiles --oplogSize 128 --keyFile /path/to/mongodb-keyfile 
  Or edit in file config

dbpath=/var/lib/mongodb
logpath=/var/log/mongodb/mongod.log
logappend=true
bind_ip = 127.0.0.1
auth = true
smallfiles = true
oplogSize = 128
keyFile = /path/to/mongodb-keyfile
replSet = rs0
setParameter=enableLocalhostAuthBypass=0
setParameter=enableTestCommands=0

- Connect to mongod
#./mongo
>use admin
>db.auth('superuser', '12345678');
>rs.initiate()
- Add secondaries 
>rs.add('host:port')

================================================================================
db.getCollectionNames().forEach(function(c) { if (c.indexOf("system.") == -1) db[c].drop();