Tag: linux

What goes on behind the Network Time Protocol ?

Several times, I had discussions with friends on how NTP works! What is the logic behind NTP and its configurations? We noticed that there are several terms and calculations to grasp especially when it comes to debugging. Well, I decided to make a research on it and shed some ideas on NTP – Network Time Protocol. These recent days, we have noticed several vulnerabilities and attacks going on the NTP servers. NTP is a protocol designed to synchronize the clocks of computers over a network.

Photo credits: networktimefoundation.org
Photo credits: networktimefoundation.org

NTP is a utility where timestamps are used. Examples are logs, database replications, the time packets  exchanged in a network. NTP uses its own binary format and runs on port 123 UDP. RFC 1305 and RFC 2030 give detailed explanations of NTP.

The logic behind NTP

In brief, packets are exchanged between the NTP server and the client in the following order. It is to be noted that latency is an important issue when it comes to NTP:

  1. The NTP client will send a request with a timestamp.
  2. The NTP server will return the packet with 3 timestamps.
    • echo of the client timestamp
    • The timestamp of the received timestamp by the server
    • The timestamp response sent by the server.
  3. The client will then estimate the offset (the difference in timestamps between the client and the server)

A client may have several NTP servers configured, but will synchronize with only one NTP server. A server may also take some time to respond to a client depending when it is not busy. NTP packets are exchanged between 64 – 1024 seconds for each server. – This configurations are called “minpoll” and “maxpoll”

Some basic configuration on a CentOS 7 machine

The command timedatectl can be used to check if NTP is enabled or not

[[email protected] ~]# timedatectl | egrep -i ntp
     NTP enabled: yes
NTP synchronized: yes

You can also check if the service is running using the following command;

systemctl status chronyd.service

The configuration file is located by default at /etc/chrony.conf . You will notice that the NTP servers are configured by default in that file.

[[email protected] ~]# head -n 7 /etc/chrony.conf 

# Use public servers from the pool.ntp.org project.
# Please consider joining the pool (http://www.pool.ntp.org/join.html).
server 0.centos.pool.ntp.org iburst
server 1.centos.pool.ntp.org iburst
server 2.centos.pool.ntp.org iburst
server 3.centos.pool.ntp.org iburst

You can check if your machine are synchronised from the sources with the following command. The column Name/IP address are the location from where the time is being synchronized.

[[email protected] ~]# chronyc sources


210 Number of sources = 4
MS Name/IP address         Stratum Poll Reach LastRx Last sample
===============================================================================
^+ cpt-ntp.mweb.co.za            2   6   367    40    +29ms[  +29ms] +/-  151ms
^* cpto-afr-01.time.jpbe.de      2   7   377    43    +69ms[  +66ms] +/-  178ms
^+ ntp2.inx.net.za               2   6   377    43    +64ms[  +64ms] +/-  181ms
^+ ns.bitco.co.za                3   7   377   107    +79ms[  +77ms] +/-  199ms

A drift means a deviation. A drift happens when  the hardware clock is either fast or slow compared to the NTP server clock. The drift file contains 2 values. If it’s a positive number, it means the clock is fast from the NTP server whereas if it is a negative number, it means the clock is slow compared to the NTP server. Here i have a slow clock.

[[email protected] ~]# cat /var/lib/chrony/drift 

         -870.203668          1484.980507
The Maths - How the NTP client adjust its response from the NTP server

Now, we will get into the math behind the logic as discussed previously what happens when the NTP client request the time from the NTP server.

  1. NTP Client A send request to server X – Let’s assume A=100 where 100 is the time of the client
  2. NTP Server X received the request after some secs. – Let’s assume X= 150 where 150 is the time of the server.
  3. Being given that, the request from NTP client is not necessarily served immediately, there is lapse of time at this point. let’s assume that X is now 160
  4. We now have 3 values i.e; The time the client sent the request, the time (real time) the server received the request and the time the server want to respond back.
  5. Now the NTP client gets the request back at 120. This is because the NTP client has its own time.
  6. Client will now determine the time using the formulae B-A – (Y-X) which means 120-100-(160-150) = 10 seconds
  7. Client assumed that the time it took to get the response from server to client is 10/2 = 5 seconds. Assuming 5 seconds is the latency.
  8. Now the client adds 5 seconds to  the server time at the time it received the response which makes 160 +5 = 165 seconds.
  9. The client knows it needs to add 45 seconds to its clock. This is done by subtracting 165 – 120 = 45 seconds where 45 seconds is the difference between the client and the server clock to which the client will set forward its clock by 45 seconds. This indication will be given in the drift file in PPM – Parts Per Million.

TIPS:

  • If the iburst parameters are removed, communication between the server will 8 times faster.
  • You can also increase the verbosity of the command chronyc sources by adding the parameter -v to it and detailed explanation of the values will be given i.e; chronyc source -v
  • You can pick up different NTP servers from the NIST website and restart the NTP service (chronyd).
  • NTP was invented by David L. Mills in 1981 and it is based on Marzullo’s algorithm to get accurate time from several sources.
  • Timestamps of NTP are stored in seconds and it is 64 bit in size – 32 bit for number of seconds and 32 bit for fraction of seconds.
  • Number in drift file is measured in PPM – Parts per million
  • Offset – The difference in timestamps between the client and the server
  • Burst – The speed of communication between NTP client and NTP server will be 8 times more if “burst” is used.
  • The drift value is in PPM – Parts Per Million.
  • To convert into PPM is easy. Since we have 86,400 seconds in a day, therefore, 86,400 / 1,000,000 = 0.0864 PPM
  • If my drift file shows a value of Z  where Z = 30.3 simply do (30.3 x 0.0864) to get the drift file into milliseconds.

Web Security Fundamentals by Varonis

Some days back, i received an invitation to attend an online course by Varonis on Web Security Fundamentals which has been conducted by Troy Hunt. I should say though this course is for beginners, its worth watching and pretty interesting. Troy Hunt is a security developer and author of PluralSight tutorials. You can join the course at Web Security Fundamental on Varonis website.

Some world biggest data breach examples were enumerated at the beginning of the mini course followed by some statistics and the impact of web security. The following points were enumerated:

  1. SQL Injections
  2. Insufficient Transport Layer Security
  3. Insecure Password Storage
  4. Cross site Scripting (XSS)
  5. Weak account management

The course composed of the impact of the risk, how it works with examples and demos as well as defense techniques to be used to strengthen  the system.

SQL Injection

screenshot-from-2016-10-15-09-38-54
Photo credits: varonis.com

An example given using tool such as Havij to automate SQL injection. This tool is a GUI pretty straight forward such as to enter the URL, followed by the tables, columns etc.. to retrieve information from a database. This will result in leaking of information from a website is same is not secured. Several ways to defend against SQL injection attack is to :

  • Validate untrusted data – Has the user provided valid input to the system?
  • Parameterize queries – Seperate the query and the data
  • Lock down the Database permission – Apply the ‘principle of least permission’
  • Apply ‘Defence in depth’ – Web application firewall and cryptographic storage

 Transport Layer Security

screenshot-from-2016-10-15-09-56-00
Photo credits: varonis.com

This part was elaborated on the lack of encryption on network layer such as missing HTTPS security, especially how the risk manifest. An example of a key logger was used to retrieve information from a web page. Defense of such type of attacks were emphasized on the following points:

  • Apply TLS – Literally apply TLS to encrypt by default
  • Strengthen TLS – Ensure it is a strong implementation of TLS
  • Lock down Application – Use construct that disallow  communication over insecure connections.
  • Apply the same control internally – Attacks on the Transport layer can occur behind firewall too

Insecure Password Storage

screenshot-from-2016-10-15-10-07-12
Photo credits: varonis.com

Encryption and Decryption mechanism need to be mastered at this level as this is the basic concept of preventing attacks on insecure password storage. An example of brute force attack was demonstrated. One of the tool is Hashcat which was used as proof of concept. To prevent such types of attacks:

  • Always hash and never encrypt – This work on the assumption that the entire system may be compromised.
  • Choose the right algorithm – Get the balance between workload and performance right.
  • Enforce password rules – Stronger password are significantly harder to crack.
  • Encourage strong password – Do not place arbitrary limits on password strength

Cross-Site Scripting (XSS)

A demo was shown on this aspect using a “search” example on a website search engine. The aim is to search  mechanism that can be exploited.

screenshot-from-2016-10-15-10-18-04
Photo credits: varonis.com
  • Defense against such type of attacks were on the following points:
  • Validate untrusted data – Has the user provide valid input to the system?
  • Always Encore output – Ensure that any reflected input is rendered in the browser
  • Encode for the correct context – HTML / HTML attribute / CSS / JavaScript are all different
  • Protecting cookies – Flag cookies as ‘http only’ so they cannot be accessible by client script.

Weak Account Management

screenshot-from-2016-10-15-10-33-15
Photo credits: varonis.com

To manage weak accounts, the following factors need to be taken into consideration:

  • Poor password rules
  • Lack of brute force protection
  • Insecure ‘remember me’ feature
  • Vulnerable password change feature
  • Enumerable password resets

Here are some tips against account enumeration attacks:

  • Always respond identically – Return the same message to anonymous users
  • Use email for verification – Email the address and confirm or deny account existence there
  • Consider other enumeration vectors – Login and registration are other common channels for disclosure.
  • Consider the risk in context – Different application have different levels of privacy expectation.

To resume, its important to grasp the fact that good security is ‘defense in depth’. Security needs to be considered in the context of cost as well as usability as many of these attacks provide vectors into the internal network. Security goes well beyond. The tutorial ensures that questions are being asked at all levels to ensure security such as:

  • Is access to data logged and auditable?
  • Do you have visibility to resource accessible via access controls?
  • How many of these permissions excessive?
  • Is anyone actually reviewing entitlements?
  • How are you prioritizing security efforts?

 

A simple and fast Memcache implementation on WordPress

Memcache is an in-memory key-value pairs data store. The data store lives in the memory of the machine. That is why it is much faster compared to other data stores. The only thing that you can put in memcache are key-value pairs. You can also put anything that is serializable into memcache either as a key or a value. In general, there are two major use cases such as Caching and Sharing Data Cross App Instances. In caching, datastore query results are kept or a user authentication token and session data. There are also APIs call that can also be cached. URL fetching can also be kept in memcache. Content of a whole page can also be kept in memcache. 

Results can be ten times much faster as explained by this benchmark test carried out by Google Developers team some times back.

Photo credits: Google Developers Team
Photo credits: Google Developers Team

1.For installation on a wordpress website, thats simple straight forward. On CLI, simply do a

yum install memcached

2. By default, memcache configurations on Centos7 is found at /etc/sysconfig/memcached as follows

[[email protected] ~]# cat /etc/sysconfig/memcached 
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS=" "

3. To check if your memcache is running correctly, use the following command

echo stats | nc localhost 11211

4. Now, login to the plugin area and download the WP-FFPC plugin and activate it.

Screenshot from 2016-09-04 13-35-27

5. In the wp-config file of the wordpress CMS, define the following parameters

define('WP_CACHE', TRUE);

6. Save changes in the WP-FFPC plugins settings. On your server, you can now see the caching being done

[[email protected]]# echo stats | nc localhost 11211 | grep total_items
STAT total_items 32

And, here you are. A simple and fast memcache implementation on your WordPress website.

Note: By activating a wordpress plugin, you should make sure that proper auditing have been carried out as these days there are several vulnerabilities present on WordPress plugins.

Chef workstation and a basic cookbook

Since the main jobs of system administrator is to maintain systems, keep repeating ourselves which is kind boring as well as to dig into our memory of previous configurations that we have set up on a machine. No wonder, manual consistency configurations need to be checked on server configurations. It can be thousands of machines. Chef, is just another tool to get rid of these situations. It is a configuration management tool which is written in Ruby and Erlang for IT professional. Compared to Puppet which has only the Workstation and the Derver whilst Chef has three components that are the Chef Server, Chef workstation and Chef Node.

Photo credits: Linode.com
Photo credits: Linode.com

The cookbooks are written on the Workstation, and its then uploaded to the Chef server (service) which will be executed on the nodes. Chef nodes can be physical, virtual or directly on the cloud. Normally, chef nodes cannot communicate directly to the workstation. Let’s not focus on the installation.

Let’s first get into the workstation.

1.On the workstation download and install the Chef client from the client download page. In my case, i am on a Centos7 virtual machine.

[[email protected] ~]# wget https://packages.chef.io/stable/el/7/chef-12.12.15-1.el7.x86_64.rpm

2.After installation, you should notice the four utils already available: chef-apply chef-client chef-shell chef-solo

3. Now, we are going to create a cookbook. Since chef use the DSL – Domain specific language, the file created should end with the extension .rb Here is an example called file.rb. The first line means file resource which means a file is being created. The file resource will manage a file on the machine. The content of the file will be created with the line ‘Hello Tunnelix’

file 'file.txt' do
            content 'Hello Tunnelix'
 end

4. The tool chef-apply can be used to run it as follows:

Screenshot from 2016-08-07 21-49-07

5. You will also noticed that the file.txt has been created in the current directory as the path has not been specified.

Screenshot from 2016-08-07 21-50-24

Tips:

  • If the content of file.rb (refer to point 3) has not been modified and you fire a chef-apply again, you would notice a prompt that its already ‘up to date’ which means that it reduce the disk IO as well as the bandwidth. 
  • A string must be enclosed  in double quotes when using variables. You cannot use a single quote into another single quote. It won’t work!

Chef always check and refer to the resource and attributes in the cookbook to execute an order ; ie to cook a food. The thing is that Chef focus on the DSL with the aim to what the modifications need to be. Chef allows servers to be in a consistent state.

HTTPoxy – Is your nginx affected?

httpoxy is a set of vulnerabilities that affect application code running in CGI, or CGI-like environments. It comes down to a simple namespace conflict:

  • RFC 3875 (CGI) puts the HTTP Proxy header from a request into the environment variables as HTTP_PROXY
  • HTTP_PROXY is a popular environment variable used to configure an outgoing proxy

This leads to a remotely exploitable vulnerability. If you’re running PHP or CGI, you should block the Proxy header now.httpoxy.org

httpoxy is a vulnerability for server-side web applications. If you’re not deploying code, you don’t need to worry. A number of CVEs have been assigned, covering specific languages and CGI implementations:

Screenshot from 2016-07-20 22-45-54

After receiving the updates from hackers.mu, i immediately started some heavy research. For Nginx users, to defeat the attack, modifications can be carried out in the fastcgi_params file.

1.Create a file called test.php containing the following codes in the source code.

[[email protected]]# cat test.php

<?php
 echo getenv ('HTTP_PROXY')
 ?>

2. Launch a CURL as follows:

As you can see its “Affected”

[[email protected]]# curl -H 'Proxy: AFFECTED' http://127.0.0.1:/test.php
 AFFECTED

3. Add the following parameters in the /etc/nginx/fastcgi_params file

 fastcgi_param  HTTP_PROXY  "";

4. Stop and start the Nginx Service

5. Conduct the test again. You should be vulnerable by now.

Several links available already explaining this vulnerability :

References:

  • https://www.nginx.com/blog/mitigating-the-httpoxy-vulnerability-with-nginx/
  • https://www.kb.cert.org/vuls/id/797896
  • https://access.redhat.com/solutions/2442861
  • https://httpoxy.org/#history
  • http://www.theregister.co.uk/2016/07/18/httpoxy_hole/
  • https://blogs.akamai.com/2016/07/akamai-mitigates-httpoxy-vulnerability.html
  • http://www.zdnet.com/article/15-year-old-httpoxy-flaw-causes-developer-patch-scramble/
  • https://access.redhat.com/solutions/2435541