Showing posts with label System - Linux - Security. Show all posts
Showing posts with label System - Linux - Security. Show all posts

PAM rejected by account configuration[7]: Authentication failure

one of the user can’t login to the system, even you have reset the password, account was not locked by observing the shadow file.
[root@stpdb log]# grep abc /etc/shadow
abc:$1$.6KFA6pB$Z7AgIDAF3nvMh0LX.lTPh.:16870:0:99999:14:7::

[root@stpdb log]# chage -l abc
Minimum:        0
Maximum:        99999
Warning:        14
Inactive:       7
Last Change:            Mar 10, 2016
Password Expires:       Never
Password Inactive:      Never
Account Expires:        Never

Then you found this
[root@stpdb pam.d]# grep -i pam_tally /var/log/messages
Mar 10 17:46:33 stpdb pam_tally[4865]: user afiza (786) tally 20, deny 5
..

[root@stpdb pam.d]# grep -i abc /var/log/secure
Mar 10 17:40:15 stpdb sshd[4648]: Failed password for abc from 172.20.42.249 port 3034 ssh2
Mar 10 17:40:15 stpdb sshd[4648]: Failed none for abc from 172.20.42.249 port 3034 ssh2
Mar 10 17:40:15 stpdb sshd[4648]: Failed keyboard-interactive for abc from 172.20.42.249 port 3034 ssh2
..

[root@stpdb log]# faillog
Username   Failures  Maximum  Latest
root             64        0  Thu Apr 24 20:26:06 +0800 2014 on 172.30.5.10
abc             20        0  Thu Mar 10 19:16:15 +0800 2016 on 172.30.4.38

[root@stpdb pam.d]# grep pam_tally /etc/pam.d/system-auth
auth        required      /lib/security/pam_tally.so no_magic_root
account     required      /lib/security/pam_tally.so deny=5 reset no_magic_root

This case, the user has been locked because of the “deny 5” setting, as you can check from the “faillog” command. To reset the user failure count, use below:
[root@stpdb log]# pam_tally --user=afiza –reset
[root@stpdb log]# faillog
Username   Failures  Maximum  Latest
root             64        0  Thu Apr 24 20:26:06 +0800 2014 on 172.30.5.10
abc             0        0  Thu Mar 10 19:16:15 +0800 2016 on 172.30.4.38


Remove weak ciphers from SSH Server

Use nmap to check current loaded ciphers.

local nmap = require "nmap"
local shortport = require "shortport"
local stdnse = require "stdnse"
local string = require "string"
local table = require "table"

local openssl = stdnse.silent_require "openssl"
local ssh2 = stdnse.silent_require "ssh2"

description = [[
Reports the number of algorithms (for encryption, compression, etc.) that
the target SSH2 server offers. If verbosity is set, the offered algorithms
are each listed by type.

If the "client to server" and "server to client" algorithm lists are identical
(order specifies preference) then the list is shown only once under a combined
type.
]]

---
-- @usage
-- nmap --script ssh2-enum-algos target
--
-- @output
-- PORT   STATE SERVICE
-- 22/tcp open  ssh
-- | ssh2-enum-algos:
-- |   kex_algorithms (4)
-- |       diffie-hellman-group-exchange-sha256
-- |       diffie-hellman-group-exchange-sha1
-- |       diffie-hellman-group14-sha1
-- |       diffie-hellman-group1-sha1
-- |   server_host_key_algorithms (2)
-- |       ssh-rsa
-- |       ssh-dss
-- |   encryption_algorithms (13)
-- |       aes128-ctr
-- |       aes192-ctr
-- |       aes256-ctr
-- |       arcfour256
-- |       arcfour128
-- |       aes128-cbc
-- |       3des-cbc
-- |       blowfish-cbc
-- |       cast128-cbc
-- |       aes192-cbc
-- |       aes256-cbc
-- |       arcfour
-- |       rijndael-cbc@lysator.liu.se
-- |   mac_algorithms (6)
-- |       hmac-md5
-- |       hmac-sha1
-- |       hmac-ripemd160
-- |       hmac-ripemd160@openssh.com
-- |       hmac-sha1-96
-- |       hmac-md5-96
-- |   compression_algorithms (2)
-- |       none
-- |_      zlib@openssh.com
--
-- @xmloutput
--
--   ecdh-sha2-nistp256
--   ecdh-sha2-nistp384
--   ecdh-sha2-nistp521
--   diffie-hellman-group-exchange-sha256
--   diffie-hellman-group-exchange-sha1
--   diffie-hellman-group14-sha1
--   diffie-hellman-group1-sha1
--
--
--   ssh-rsa
--   ecdsa-sha2-nistp256
--
--
--   aes128-ctr
--   aes192-ctr
--   aes256-ctr
--   aes128-cbc
--   3des-cbc
--   blowfish-cbc
--   cast128-cbc
--   aes192-cbc
--   aes256-cbc
--
--
--   hmac-sha1
--   umac-64@openssh.com
--   hmac-ripemd160
--   hmac-sha2-256
--   hmac-sha2-512
--
--
--   none
--   zlib@openssh.com
--

author = "Kris Katterjohn"

license = "Same as Nmap--See http://nmap.org/book/man-legal.html"

categories = {"safe", "discovery"}


portrule = shortport.port_or_service(22, "ssh")

-- Build onto lists{} and possibly modify parsed{} based on whether the
-- algorithm name-lists are identical between the server-to-client and
-- client-to-server types.  Note that this simply modifies the passed tables.
local combine_types = function(parsed, lists)
  local doubles = {
    "encryption_algorithms",
    "mac_algorithms",
    "compression_algorithms"
  }

  for _, i in ipairs(doubles) do
    local c2s = i .. "_client_to_server"
    local s2c = i .. "_server_to_client"

    if parsed[c2s] == parsed[s2c] then
      parsed[i] = parsed[c2s]
      parsed[c2s] = nil
      parsed[s2c] = nil
      table.insert(lists, i)
    else
      table.insert(lists, c2s)
      table.insert(lists, s2c)
    end
  end
end

-- Build and return the output table
local output = function(parsed, lists)
  local out = stdnse.output_table()

  for _, l in ipairs(lists) do
    local v = parsed[l]
    local a = v:len() > 0 and stdnse.strsplit(",", v) or {}
    if nmap.verbosity() > 0 then
      setmetatable(a, {
        __tostring = function(t)
          return string.format("(%d)\n      %s", #t, table.concat(t, "\n      "))
        end
      })
    else
      setmetatable(a, {
        __tostring = function(t)
          return string.format("(%d)", #t)
        end
      })
    end
    out[l] = a
  end

  return out
end

action = function(host, port)
  local sock = nmap.new_socket()
  local status = sock:connect(host, port)

  if not status then
    return
  end

  status = sock:receive_lines(1)
  if not status then
    sock:close()
    return
  end

  status = sock:send("SSH-2.0-Nmap-SSH2-Enum-Algos\r\n")
  if not status then
    sock:close()
    return
  end

  local ssh = ssh2.transport

  -- I would think that the server would send its kex data right after
  -- receiving and verifying our protocol id string above, then we could
  -- just use it here, but I've seen no definitive documentation saying
  -- that we don't ever send ours first.  All I've seen is that if the
  -- server doesn't care about compatibility with older clients then it
  -- MAY send its kex data after the protocol id string.  So I guess I'll
  -- send it here until I know for sure (removing this send works against
  -- OpenSSH though).
  local pkt = ssh.build(ssh.kex_init())

  status = sock:send(pkt)
  if not status then
    sock:close()
    return
  end

  local status, response = ssh.receive_packet(sock)

  sock:close()

  if not status then
    return
  end

  local parsed = ssh.parse_kex_init(ssh.payload(response))

  local lists = {
    "kex_algorithms",
    "server_host_key_algorithms"
    -- Other types will be added below in combine_types()
  }

  -- Modifies tables
  combine_types(parsed, lists)

  return output(parsed, lists)
end

Run the command.
[root@localhost ~]# nmap --script ssh2-enum-algo.nse localhost

Starting Nmap 6.40 ( http://nmap.org ) at 2015-10-04 02:47 EDT
mass_dns: warning: Unable to determine any DNS servers. Reverse DNS is disabled. Try using --system-dns or specify valid servers with --dns-servers
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000010s latency).
Other addresses for localhost (not scanned): 127.0.0.1
Not shown: 998 closed ports
PORT   STATE SERVICE
22/tcp open  ssh
| ssh2-enum-algo:
|   kex_algorithms: (7)
|       ecdh-sha2-nistp256
|       ecdh-sha2-nistp384
|       ecdh-sha2-nistp521
|       diffie-hellman-group-exchange-sha256
|       diffie-hellman-group-exchange-sha1
|       diffie-hellman-group14-sha1
|       diffie-hellman-group1-sha1
|   server_host_key_algorithms: (2)
|       ssh-rsa
|       ecdsa-sha2-nistp256
|   encryption_algorithms: (15)
|       aes128-ctr
|       aes192-ctr
|       aes256-ctr
|       arcfour256
|       arcfour128
|       aes128-gcm@openssh.com
|       aes256-gcm@openssh.com
|       aes128-cbc
|       3des-cbc
|       blowfish-cbc
|       cast128-cbc
|       aes192-cbc
|       aes256-cbc
|       arcfour
|       rijndael-cbc@lysator.liu.se
|   mac_algorithms: (19)
|       hmac-md5-etm@openssh.com
|       hmac-sha1-etm@openssh.com
|       umac-64-etm@openssh.com
|       umac-128-etm@openssh.com
|       hmac-sha2-256-etm@openssh.com
|       hmac-sha2-512-etm@openssh.com
|       hmac-ripemd160-etm@openssh.com
|       hmac-sha1-96-etm@openssh.com
|       hmac-md5-96-etm@openssh.com
|       hmac-md5
|       hmac-sha1
|       umac-64@openssh.com
|       umac-128@openssh.com
|       hmac-sha2-256
|       hmac-sha2-512
|       hmac-ripemd160
|       hmac-ripemd160@openssh.com
|       hmac-sha1-96
|       hmac-md5-96
|   compression_algorithms: (2)
|       none
|_      zlib@openssh.com
25/tcp open  smtp

Nmap done: 1 IP address (1 host up) scanned in 2.46 seconds

Load only what is needed

Now we specify the only ciphers that we need to load, hence removing those considered weak.
In sshd_config
Ciphers aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour
MACs hmac-md5,hmac-sha1,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96

Test it

Restart sshd and run the nmap script again to cross check, to diagnose,
$ ssh -vv -oCiphers=aes128-cbc,3des-cbc,blowfish-cbc
$ ssh -vv -oMACs=hmac-md5
If you are testing with the ciphers or MACs that you have removed, you should be getting something like this

no matching mac found: client hmac-sha1-etm@openssh.com server hmac-md5,hmac-sha1,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96

POODLE: SSLv3 vulnerability (CVE-2014-3566)


WHAT IS THIS CVE ABOUT?


POODLE stands for Padding Oracle On Downgraded Legacy Encryption. This vulnerability allows a man-in-the-middle attacker to decrypt ciphertext using a padding oracle side-channel attack. More details are available in the upstream OpenSSL advisory.

POODLE affects older standards of encryption, specifically Secure Socket Layer (SSL) version 3. It does not affect the newer encryption mechansim known as Transport Layer Security (TLS).

AM I AFFECTED?

This CVE is not Operating System centric, you will need to check on your application whether it was running in Linux or Windows platform.

Test online


Test offline

Save this file under a linux server, and run the test as below:
# example of a server that is not vulnerable
$ bash poodle.sh foobar.example.com 443 foobar.example.com:443 - Not vulnerable. Failed to establish SSLv3 connection. 

# example of a server that is vulnerable
$ bash poodle.sh foobar.example.com 443 foobar.example.com:443 - Vulnerable! SSLv3 connection established using SSLv3/$CIPHER

CONSIDERATION

For non HTTPs clients:
Disabling SSLv3 in favor of at least a TLS connection is recommended. However in disabling SSL it is important to understand that certain applications that do not support TLS could default to plain-text transmission which would be worse from a security perspective than the vulnerable SSL protocol. Before disabling SSL on services, please carefully consider these measures.

HOW TO FIX?

Please identify your affected application (that runs SSL), and follow the general guidelines here for the fix

ANY DOWNTIME NEEDED?

Depends on your application, normally an application restart is needed.

REFERENCE



OpenSSL HeartBleed (CVE-2014-0160)

Was my OpenSSL affected by the OpenSSL HeartBleed Bug (CVE-2014-0160)?

http://support.f5.com/kb/en-us/solutions/public/15000/100/sol15159.html
http://www.inmotionhosting.com/support/website/security/protect-data-fix-openssl-heartbleed-bug
https://www.nccgroup.com/en/blog/2014/04/heartbleed-openssl-vulnerability/


It really depends on your SSL termination setup.
If the SSL being terminated directly on your Apache server, then you should make sure your version being patch or not in the affected version.

Else if your SSL being terminated in Network Load Balancer like F5 LTM, you will need to check on the model you are using and the SSL mode being used.

You may find links above for steps on how to check.

How to test from remote?
Run below from client machine, if it returns “safe” means your version was not affected.
$ openssl s_client -connect www.coursera.org:443  -tlsextdebug 2>&1 | grep 'server extension "heartbeat" (id=15)' || echo safe

safe

Or you can download the script from below and run:
https://gist.github.com/takeshixx/10107280

[root@rhel6 test]# ./hb-test.py -p 443 www.hlb.com.my
Connecting...
Sending Client Hello...
Waiting for Server Hello...
 ... received message: type = 22, ver = 0302, length = 53
 ... received message: type = 22, ver = 0302, length = 3234
 ... received message: type = 22, ver = 0302, length = 4
Sending heartbeat request...
Unexpected EOF receiving record header - server closed connection
No heartbeat response received, server likely not vulnerable

More detailed info from Redhat can be fine here:

https://access.redhat.com/site/articles/786463



Redhat Enterprise Linux enable core dump

1. To check current configuration for core dump. Zero means core dump was disabled.

$ ulimit -c
0

2. To enable system wide core dump, edit /etc/profile as below:

# No core files by default
#ulimit -S -c 0 > /dev/null 2>&1
ulimit -S -c unlimited > /dev/null 2>&1

3. specify core dump file location
Add it to /etc/sysctl.conf, and make sure to reload the config using "sysctl -p"

kernel.core_pattern = /tmp/core

4. To limit users from having unlimited core dump that causes file system full.
Edit /etc/security/limits.conf as below (value was in KB), disable all users, only allow for specific users with size limit:

*         hard    core            0
userA hard    core            512000

5. To confirm the configuration, log out from current session, relogin and try below.
start a new process or just edit a file using vim, grep the PID and check below (you need to have a new process to have this new setup):

(userA process)
[root@server1 ~]# cat /proc/8865/limits 
Limit                     Soft Limit           Hard Limit           Units     
Max cpu time              unlimited            unlimited            seconds   
Max file size             unlimited            unlimited            bytes     
Max data size             unlimited            unlimited            bytes     
Max stack size            10485760             unlimited            bytes     
Max core file size        0                    524288000            bytes     
Max resident set          unlimited            unlimited            bytes     
Max processes             unlimited            unlimited            processes 
Max open files            1024                 1024                 files     
Max locked memory         32768                32768                bytes     
Max address space         unlimited            unlimited            bytes     
Max file locks            unlimited            unlimited            locks     
Max pending signals       40960                40960                signals   
Max msgqueue size         819200               819200               bytes     
Max nice priority         0                    0                    
Max realtime priority     0                    0   

(Other user process)
[root@server1 ~]# cat /proc/30376/limits 
Limit                     Soft Limit           Hard Limit           Units     
Max cpu time              unlimited            unlimited            seconds   
Max file size             unlimited            unlimited            bytes     
Max data size             unlimited            unlimited            bytes     
Max stack size            10485760             unlimited            bytes     
Max core file size        0                    0                    bytes     
Max resident set          unlimited            unlimited            bytes     
Max processes             40960                40960                processes 
Max open files            1024                 1024                 files     
Max locked memory         32768                32768                bytes     
Max address space         unlimited            unlimited            bytes     
Max file locks            unlimited            unlimited            locks     
Max pending signals       40960                40960                signals   
Max msgqueue size         819200               819200               bytes     
Max nice priority         0                    0                    

Max realtime priority     0                    0  


Reference:
https://access.redhat.com/site/solutions/5352
https://access.redhat.com/site/solutions/4058
http://linuxtechres.blogspot.com/2011/09/how-to-enable-core-dump-for-application.html

Differences Between IPTables and IPChains


Both ipchains and iptables use chains of rules that operate within the Linux kernel to filter packets based on matches with specified rules or rule sets. However, iptables offers a more extensible way of filtering packets, giving the administrator greater control without building undue complexity into the system.

You should be aware of the following significant differences between ipchains and iptables:

Using iptables, each filtered packet is processed using rules from only one chain rather than multiple chains.
For example, a FORWARD packet coming into a system using ipchains would have to go through the INPUT, FORWARD, and OUTPUT chains to continue to its destination. However, iptables only sends packets to the INPUT chain if they are destined for the local system, and only sends them to the OUTPUT chain if the local system generated the packets. It is therefore important to place the rule designed to catch a particular packet within the chain that actually handles the packet.

The DENY target has been changed to DROP.
In ipchains, packets that matched a rule in a chain could be directed to the DENY target. This target must be changed to DROP in iptables.

Order matters when placing options in a rule.
In ipchains, the order of the rule options does not matter.

The iptables command has a stricter syntax. The iptables command requires that the protocol (ICMP, TCP, or UDP) be specified before the source or destination ports.

Network interfaces must be associated with the correct chains in firewall rules.
For example, incoming interfaces (-i option) can only be used in INPUT or FORWARD chains. Similarly, outgoing interfaces (-o option) can only be used in FORWARD or OUTPUT chains.

In other words, INPUT chains and incoming interfaces work together; OUTPUT chains and outgoing interfaces work together. FORWARD chains work with both incoming and outgoing interfaces.

OUTPUT chains are no longer used by incoming interfaces, and INPUT chains are not seen by packets moving through outgoing interfaces.

hping3 error "-DBYTE_ORDER_(BIG|LITTLE)_ENDIAN""


If you are getting error below during ./configure of hping3

OS:

[root@localhost hping3-20051105]# uname -a
Linux localhost.localdomain 2.6.32-279.2.1.el6.x86_64 #1 SMP Fri Jul 20 01:55:29 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
[root@localhost hping3-20051105]# cat /etc/redhat-release
CentOS release 6.3 (Final)

Symptom:


[root@localhost hping3-20051105]#./configure
bytesex.h:22:3: error: #error can not find the byte order for this architecture, fix bytesex.h

In file included from rapd.c:11:
ars.h:190:2: error: #error "Please, edit Makefile and add -DBYTE_ORDER_(BIG|LITTLE)_ENDIAN"
ars.h:254:2: error: #error "Please, edit Makefile and add -DBYTE_ORDER_(BIG|LITTLE)_ENDIAN"
ars.h:323:2: error: #error "Please, edit Makefile and add -DBYTE_ORDER_(BIG|LITTLE)_ENDIAN"
In file included from ars.h:20,
                 from split.c:11:
bytesex.h:22:3: error: #error can not find the byte order for this architecture, fix bytesex.h
In file included from split.c:11:
ars.h:190:2: error: #error "Please, edit Makefile and add -DBYTE_ORDER_(BIG|LITTLE)_ENDIAN"
ars.h:254:2: error: #error "Please, edit Makefile and add -DBYTE_ORDER_(BIG|LITTLE)_ENDIAN"
ars.h:323:2: error: #error "Please, edit Makefile and add -DBYTE_ORDER_(BIG|LITTLE)_ENDIAN"
now you can try `make'

To resolve:
Since this was a x86_64 architecture, and it was not in the bytesex.h you just need to add in a line as below  and ./configure again.

[root@localhost hping3-20051105]# cat bytesex.h
/* Original code from the Linux C library */
/* Copyright (C) 2000,2001 Salvatore Sanfilippo
 * This code is under the original GNU C library license (GPL) */

/* $Id: bytesex.h,v 1.1.1.1 2003/08/31 17:23:48 antirez Exp $ */

#ifndef ARS_BYTESEX_H
#define ARS_BYTESEX_H

#if     defined(__i386__) \
        || defined(__alpha__) \
        || defined(__x86_64__) \
        || (defined(__mips__) && (defined(MIPSEL) || defined (__MIPSEL__)))
#define BYTE_ORDER_LITTLE_ENDIAN
#elif   defined(__mc68000__) \
        || defined (__sparc__) \
        || defined (__sparc) \
        || defined (__PPC__) \
        || defined (__BIG_ENDIAN__) \
        || (defined(__mips__) && (defined(MIPSEB) || defined (__MIPSEB__)))
#define BYTE_ORDER_BIG_ENDIAN
#else
# error can not find the byte order for this architecture, fix bytesex.h
#endif

#endif /* ARS_BYTESEX_H */


/var/lib/php/session

If you are running any PHP application that requires writing of session files in the server but it fails like in the Apache log below:


[Thu Oct 27 09:41:02 2011] [error] [client 171.4.87.27] PHP Warning:  Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/var/lib/php/session) in

Please check whether you have this directory in place, create it if it hasn't there.
Change the permission to 777, and try run it again.

If you were able to see session files being written, then you are good.
Now make sure the file permission for those session files in this directory was not readable and writable by other users.

[root@server apache2]# ll  /var/lib/php/session/
total 4
-rw------- 1 userb userb 40 Oct 27 09:39 sess_3bsrvlkc291l7jlsakvtknv3v0
-rw------- 1 usera usera  30 Oct 27 09:39 sess_3s95nd55qs44s0uslsai2ghlu7



DDoS

Good article about DDoS.

http://www.linuxsecurity.com/content/view/121960/49/

Hardening the TCP/IP stack to SYN attacks

How to detect a SYN attack

It is very simple to detect SYN attacks. The netstat command shows us how many connections are currently in the half-open state. The half-open state is described as SYN_RECEIVED in Windows and as SYN_RECV in Unix systems.

# netstat -n -p TCP tcp        0      0 10.100.0.200:21            237.177.154.8:25882     SYN_RECV    - tcp        0      0 10.100.0.200:21            236.15.133.204:2577     SYN_RECV    - tcp        0      0 10.100.0.200:21            127.160.6.129:51748     SYN_RECV    - tcp        0      0 10.100.0.200:21            230.220.13.25:47393     SYN_RECV    - tcp        0      0 10.100.0.200:21            227.200.204.182:60427   SYN_RECV    - tcp        0      0 10.100.0.200:21            232.115.18.38:278       SYN_RECV    - tcp        0      0 10.100.0.200:21            229.116.95.96:5122      SYN_RECV    - tcp        0      0 10.100.0.200:21            236.219.139.207:49162   SYN_RECV    - tcp        0      0 10.100.0.200:21            238.100.72.228:37899    SYN_RECV    - ... 
We can also count how many half-open connections are in the backlog queue at the moment. In the example below, 769 connections (for TELNET) in the SYN RECEIVED state are kept in the backlog queue.

# netstat -n -p TCP | grep SYN_RECV | grep :23 | wc -l 769 
The other method for detecting SYN attacks is to print TCP statistics and look at the TCP parameters which count dropped connection requests. While under attack, the values of these parameters grow rapidly.
In this example we watch the value of the TcpHalfOpenDrop parameter on a Sun Solaris machine.

# netstat -s -P tcp | grep tcpHalfOpenDrop         tcpHalfOpenDrop     =   473 
It is important to note that every TCP port has its own backlog queue, but only one variable of the TCP/IP stack controls the size of backlog queues for all ports.

The backlog queue

The backlog queue is a large memory structure used to handle incoming packets with the SYN flag set until the moment the three-way handshake process is completed. An operating system allocates part of the system memory for every incoming connection. We know that every TCP port can handle a defined number of incoming requests. The backlog queue controls how many half-open connections can be handled by the operating system at the same time. When a maximum number of incoming connections is reached, subsequent requests are silently dropped by the operating system.
As mentioned before, when we detect a lot of connections in the SYN RECEIVED state, host is probably under a SYN flooding attack. Moreover, the source IP addresses of these incoming packets can be spoofed. To limit the effects of SYN attacks we should enable some built-in protection mechanisms. Additionally, we can sometimes use techniques such as increasing the backlog queue size and minimizing the total time where a pending connection in kept in allocated memory (in the backlog queue).

Built-in protection mechanisms

Operating system: Windows 2000
The most important parameter in Windows 2000 and also in Windows Server 2003 is SynAttackProtect. Enabling this parameter allows the operating system to handle incoming connections more efficiently. The protection can be set by adding a SynAttackProtect DWORD value to the following registry key:

HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters 
In general, when a SYN attack is detected the SynAttackProtect parameter changes the behavior of the TCP/IP stack. This allows the operating system to handle more SYN requests. It works by disabling some socket options, adding additional delays to connection indications and changing the timeout for connection requests.
When the value of SynAttackProtect is set to 1, the number of retransmissions is reduced and according to the vendor, the creation of a route cache entry is delayed until a connection is made. The recommended value of SynAttackProtect is 2, which additionally delays the indication of a connection to the Windows Socket until the three-way handshake is completed. During an attack, better performance in handling connections is achieved by disabling the use of a few parameters (these parameters are usually used by the system during the process of creating new connections). The TCPInitialRTT parameter, which defines the time of the first retransmission, will no longer work. It's impossible to negotiate the window size value. Also, the scalable windows option is disabled on any socket.
As we can see, by enabling the SynAttackProtect parameter we don't change the TCP/IP stack behavior until under a SYN attack. But even then, when SynAttackProtect starts to operate, the operating system can handle legitimate incoming connections.
The operating system enables protection against SYN attacks automatically when it detects that values of the following three parameters are exceeded. These parameters are TcpMaxHalfOpenTcpMaxHalfOpenRetried and TcpMaxPortsExhausted.
To change the values of these parameters, first we have to add them to the same registry key as we made for SynAttackProtect.
The TcpMaxHalfOpen registry entry defines the maximum number of SYN RECEIVED states which can be handled concurrently before SYN protection starts working. The recommended value of this parameter is 100 for Windows 2000 Server and 500 for Windows 2000 Advanced Server.
TcpMaxHalfOpenRetried defines the maximum number of half-open connections, for which the operating system has performed at least one retransmission, before SYN protection begins to operate. The recommended value is 80 for Windows 2000 Server, and 400 for Advanced Server.
The TcpMaxPortsExhausted registry entry defines the number of dropped SYN requests, after which the protection against SYN attacks starts to operate. Recommended value is 5.
Operating system: Linux RedHat
RedHat, like other Linux operating systems, has implemented a SYN cookies mechanism which can be enabled in the following way:

# echo 1 > /proc/sys/net/ipv4/tcp_syncookies 
Note that to make this change permanent we need to create a startup file that sets this variable. We must do the same operation for other UNIX variables described in this paper because the values for these variables will return to default upon system reboot.
SYN cookies protection is especially useful when the system is under a SYN flood attack and source IP addresses of SYN packets are also forged (a SYN spoofing attack). This mechanism allows construction of a packet with the SYN and ACK flags set and which has a specially crafted initial sequence number (ISN), called a cookie. The value of the cookie is not a pseudo-random number generated by the system but instead is the result of a hash function. This hash result is generated from information like: source IP, source port, destination IP, destination port plus some secret values. During a SYN attack the system generates a response by sending back a packet with a cookie, instead of rejecting the connection when the SYN queue is full. When a server receives a packet with the ACK flag set (the last stage of the three-way handshake process) then it verifies the cookie. When its value is correct, it creates the connection, even though there is no corresponding entry in the SYN queue. Then we know that it is a legitimate connection and that the source IP address was not spoofed. It is important to note that the SYN cookie mechanism works by not using the backlog queue at all, so we don't need to change the backlog queue size. More information about SYN cookies can be found athttp://cr.yp.to/syncookies.html.
Also note that the SYN cookies mechanism works only when the CONFIG_SYNCOOKIES option is set during kernel compilation.
The next section will describe other useful methods of protection against SYN attacks. I would like to emphasize that under heavy SYN attacks (like Distributed SYN flooding attack) these methods may help but still not solve the problem.

Increasing the backlog queue

Under a SYN attack, we can modify the backlog queue to support more connections in the half-open state without denying access to legitimate clients. In some operating systems, the value of the backlog queue is very low and vendors often recommend increasing the SYN queue when a system is under attack.
Increasing the backlog queue size requires that a system reserve additional memory resources for incoming requests. If a system has not enough memory for this operation, it will have an impact on system performance. We should also make sure that network applications like Apache or IIS can accept more connections.
Operating system: Windows 2000
Aside from described above TcpMaxHalfOpen and TcpMaxHalfOpenRetried variables, in Windows 2000 the number of connections handled in the half-open state can be set through a dynamic backlog. Configuration of this dynamic backlog is accomplished via the AFD.SYS driver. This kernel-mode driver is used to support Windows Socket applications like FTP and Telnet. To increase the number of half-open connections, AFD.SYS provides four registry entries. All of these values, corresponding to AFD.SYS, are located under the following registry key:

HKLM\System\CurrentControlSet\Services\AFD\Parameters
The EnableDynamicBacklog registry value is a global switch to enable or disable a dynamic backlog. Setting it to 1 enables the dynamic backlog queue.
MinimumDynamicBacklog controls the minimum number of free connections allowed on a single TCP port. If the number of free connections drops below this value, then additional free connections are created automatically. Recommended value is 20.
The MaximumDynamicBacklog registry value defines the sum of active half-open connections and the maximum number of free connections. When this value is exceeded, no more free connections will be created by a system. Microsoft suggests that this value should not exceed 20000.
The last DynamicBacklogGrowthDelta parameter controls the number of free connections to be created when additional connections are necessary. Recommended value: 10.
The table below shows the recommended values for the AFD.SYS driver:

Subkey Registry Value EntryFormatValue
EnableDynamicBacklogDWORD1
MinimumDynamicBacklogDWORD20
MaximumDynamicBacklogDWORD20000
DynamicBacklogGrowthDeltaDWORD10
Operating system: Linux
tcp_max_syn_backlog variable defines how many half-open connections can be kept by the backlog queue. For instance 256 is a total number of half-open connections handled in memory by Linux RedHat 7.3. The TCP/IP stack variables can be configured by sysctl or standard Unix commands. The following example shows how to change the default size of the backlog queue by the sysctl command:

# sysctl -w net.ipv4.tcp_max_syn_backlog="2048" 
Operating system: Sun Solaris
In Sun Solaris there are two parameters which control the maximum number of connections. The first parameter controls the total number of full connections. The second tcp_conn_req_max_q0 parameter defines how many half-open connections are allowed without the dropping of incoming requests. In Sun Solaris 8, the default value is set to 1024. Using the ndd command we can modify this value.

# ndd -set /dev/tcp tcp_conn_req_max_q0 2048 
Operating system: HP-UX
In HP-UX, a tcp_syn_rcvd_max TCP/IP stack variable is responsible for control of the maximum number of half-open connections in the SYN RECEIVE state. In HP-UX 11.00 this value is set to 500. We can change this value by using the ndd command, similar to the one used in a Sun Solaris system.

# ndd -set /dev/tcp tcp_syn_rcvd_max 2048 

Decreasing total time of handling connection request

As we know, SYN flooding/spoofing attacks are simply a series of SYN packets, mostly from forged IP addresses. In the last section we tried to increase the backlog queue. Now that our systems can handle more SYN requests, we should decrease the total time we keep half-open connections in the backlog queue. When a server receives a request, it immediately sends a response with the SYN and ACK flags set, puts this half-open connection into the backlog queue, and then waits for a packet with the ACK flag set from the client. When no response is received from the client, the server retransmits a response packet (with the SYN and ACK flags set) several times (depending on default value in each operating system) by giving the client a chance to send the ACK packet again. It is clear that when the source IP address of client was spoofed, the ACK packet will never arrive. After a few minutes the server removes this half-open connection. We can speed up this time of removing connections in the SYN RECEIVED state from the backlog queue by changing time of first retransmission and by changing the total number of retransmissions.
Another technique of protection against SYN attacks is switching off some TCP parameters that are always negotiated during the three-way handshake process. Some of these parameters are automatically turned off by mechanisms described in the first section (SynAttackProtect and Syncookies).
Now, I will describe TCP/IP stack variables which allow a decrease in the time half-open connections are kept in the backlog queue.
Operating system: Windows 2000
In Windows 2000, the default time for a first retransmission is set to 3 seconds (3000 milliseconds) and can be changed by modifying the value of the TcpInitialRtt registry entry (for every interface). For example, to decrease time of a first retransmission to 2 seconds we have to set this registry value to 2000 milliseconds in decimal format. The number of retransmissions (packets with the SYN and ACK flags set) is controlled by a TcpMaxConnectResponseRetransmissions registry parameter which has to be added to HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters registry key.
The table below contains a few examples of values and corresponding times for keeping half-open connections in the backlog queue (the time of a first retransmission is set to 3 seconds).

ValueTime of retransmissionTotal time to keep half-open connections in the backlog queue
1in 3rd second9 seconds
2in 3rd and 9th second21 seconds
3in 3rd , 9th and 21st second45 seconds
We can set this registry value to 0, whereby Windows doesn't try to retransmit packets at all. In this case, the system sends only one response and cancels the half-open connection after 3 seconds. This setting is ignored when its value is equal or greater than 2 and when SynAttackProtect is enabled.
Operating system: Linux RedHat
tcp_synack_retries variable is responsible for controlling the number of retransmissions in Linux operating system. Its default value is set to 5 for most Linux operating systems, which causes the half-open connection to be removed after 3 minutes. In the below table there are calculations for other values.

ValueTime of retransmissionTotal time to keep half-open connections in the backlog queue
1in 3rd second9 seconds
2in 3rd and 9th second21 seconds
3in 3rd , 9th and 21st second45 seconds
Operating system: Sun Solaris
In this operating system it is impossible to turn off retransmissions of packets directly using the ndd command. Moreover, in Sun Solaris there are parameters which are non-configurable by ndd and which control the number of retransmissions (at least 3) and total time of packet retransmissions (at least 3 minutes). More information about these parameters can be found in the "Solaris 2.x - Tuning Your TCP/IP stack and More" document.
Operating system: HP-UX
For HP-UX, the time spent handling half-open connections in the backlog queue is controlled by the tcp_ip_abort_cinterval parameter. By using the ndd command we can define how long a HP-UX operating system will be waiting for the ACK packet. We can control how many retransmissions will be performed indirectly by changing this value. Have a look at the table below.

ValueTime of retransmissionTotal time to keep half-open connections in the backlog queue
1000-1 second
5000in 2nd second5 seconds
10000in 2nd and 5th second10 seconds
60000In 2nd, 5th, 11th, 23rd and 47th second1 minute
We can change the time of a first retransmission by modifying tcp_rexmit_interval_initial. Intervals of subsequent retransmissions are controlled by two parameters: tcp_rexmit_interval and tcp_rexmit_interval_min. These three variables are the same as in a Sun Solaris operating system.

Summary

The methods of hardening the TCP/IP stack that are presented in this article make servers more resistant to SYN flooding and SYN spoofing - Denial of Service attacks. A modification of your default TCP/IP stack settings is also recommended during the process of securing of the operating system.