Leaderboard (728 x 90)

Monday, October 29, 2012

how to disable esmtp inspection feature (Cisco)?


ESMTP TLS Configuration

Note: If you use Transport Layer Security (TLS) encryption for e-mail communication then the ESMTP inspection feature (enabled by default) in the PIX drops the packets. In order to allow the e-mails with TLS enabled, disable the ESMTP inspection feature as this output shows. Refer to Cisco bug ID CSCtn08326  (registered  customers only) for more information.

pix(config)#policy-map global_policy
pix(config-pmap)#class inspection_default
pix(config-pmap-c)#no inspect esmtp
pix(config-pmap-c)#exit
pix(config-pmap)#exit

Reference: http://www.cisco.com/en/US/products/hw/vpndevc/ps2030/products_configuration_example09186a00806745b8.shtml

Sunday, October 21, 2012

How to use wlctl command in router?


wlctl

Usage: wlctl [-a|i <adapter>] [-h] [-d|u|x] <command> [arguments]

-h
     this message
-a, -i
     adapter name or number
-d
     signed integer
-u
     unsigned integer
-x
     hexdecimal

ver
     get version information

cmds
     generate a short list of available commands

up
     reinitialize and mark adapter up (operational)

down
     reset and mark adapter down (disabled)

out
     mark adapter down but do not reset hardware(disabled). 
     On dualband cards, cards must be bandlocked before use.

clk
     set board clock state. return error for set_clk attempt if the driver is not down
     0: clock off
     1: clock on

restart
     Restart driver.  Driver must already be down.

reboot
     Reboot platform

ucflags
     Get/Set ucode flags

radio
     Set the radio on or off.
     "on" or "off"

dump
     print driver software state and chip registers to stdout

srdump
     print contents of SPROM to stdout

nvdump
     print nvram variables to stdout

nvset
     set an nvram variable
     name=value (no spaces around '=')

nvget
     get the value of an nvram variable

revinfo
     get hardware revision information

msglevel
     set driver console debugging message bitvector
     type 'wl msglevel ?' for values

PM
     set driver power management mode:
     0: CAM (constantly awake)
     1: PS  (power-save)
     2: FAST PS mode

wake
     set driver power-save mode sleep state:
     0: core-managed
     1: awake

promisc
     set promiscuous mode ethernet address reception
     0 - disable
     1 - enable

monitor
     set monitor mode
     0 - disable
     1 - enable active monitor mode (interface still operates)

frag
     Deprecated. Use fragthresh.

rts
     Deprecated. Use rtsthresh.

cwmin
     Set the cwmin.  (integer [1, 255])

cwmax
     Set the cwmax.  (integer [256, 2047])

srl
     Set the short retry limit.  (integer [1, 255])

lrl
     Set the long retry limit.  (integer [1, 255])

rate
     force a fixed rate:
     valid values for 802.11a are (6, 9, 12, 18, 24, 36, 48, 54)
     valid values for 802.11b are (1, 2, 5.5, 11)
     valid values for 802.11g are (1, 2, 5.5, 6, 9, 11, 12, 18, 24, 36, 48, 54)
     -1 (default) means automatically determine the best rate

mrate
     force a fixed multicast rate:
     valid values for 802.11a are (6, 9, 12, 18, 24, 36, 48, 54)
     valid values for 802.11b are (1, 2, 5.5, 11)
     valid values for 802.11g are (1, 2, 5.5, 6, 9, 11, 12, 18, 24, 36, 48, 54)
     -1 (default) means automatically determine the best rate

a_rate
     force a fixed rate for the A PHY:
     valid values for 802.11a are (6, 9, 12, 18, 24, 36, 48, 54)
     -1 (default) means automatically determine the best rate

a_mrate
     force a fixed multicast rate for the A PHY:
     valid values for 802.11a are (6, 9, 12, 18, 24, 36, 48, 54)
     -1 (default) means automatically determine the best rate

bg_rate
     force a fixed rate for the B/G PHY:
     valid values for 802.11b are (1, 2, 5.5, 11)
     valid values for 802.11g are (1, 2, 5.5, 6, 9, 11, 12, 18, 24, 36, 48, 54)
     -1 (default) means automatically determine the best rate

bg_mrate
     force a fixed multicast rate for the B/G PHY:
     valid values for 802.11b are (1, 2, 5.5, 11)
     valid values for 802.11g are (1, 2, 5.5, 6, 9, 11, 12, 18, 24, 36, 48, 54)
     -1 (default) means automatically determine the best rate

infra
     Set Infrastructure mode: 0 (IBSS) or 1 (Infra BSS)

ap
     Set AP mode: 0 (STA) or 1 (AP)

bssid
     Get the BSSID value, error if STA and not associated

channel
     Set the channel:
     valid channels for 802.11b/g (2.4GHz band) are 1 through 14
     valid channels for 802.11a  (5 GHz band) are:
          36, 40, 44, 48, 52, 56, 60, 64, 100, 104,
          108, 112, 116, 120, 124, 128, 132, 136,
          140, 149, 153, 157, 161,184, 188, 192,
          196, 200, 204, 208, 212, 216

tssi
     Get the tssi value from radio

txpwr
     Set tx power in milliwatts.  Range [1, 84].

txpwr1
     Set tx power in in various units. Choose one of (default: dbm): 
     -d dbm units
     -q quarter dbm units
     -m milliwatt units
Can be combined with:
     -o turn on override to disable regulatory and other limitations
Use wl txpwr -1 to restore defaults

txpathpwr
     Turn the tx path power on or off on 2050 radios

txpwrlimit
     Return current tx power limit

powerindex
     Set the transmit power for A band(0-63).
     -1 - default value

atten
     Set the transmit attenuation for B band. Args: bb radio txctl1.
     auto to revert to automatic control
     manual to supspend automatic control

phyreg
     Get/Set a phy register:
     offset [ value ] [ band ]

radioreg
     Get/Set a radio register:
     offset [ value ] [ band ]

shmem
     Get/Set a shared memory location:
     offset [ value ] [ band ]

macreg
     Get/Set any mac registers(include IHR and SB):
     macreg offset size[2,4] [value] [ band ]

ucantdiv
     Enable/disable ucode antenna diversity (1/0 or on/off)

antdiv
     Set antenna diversity for rx
     0 - force use of antenna 0
     1 - force use of antenna 1
     3 - automatic selection of antenna diversity

txant
     Set the transmit antenna
     0 - force use of antenna 0
     1 - force use of antenna 1
     3 - use the RX antenna selection that was in force during
     the most recently received good PLCP header

plcphdr
     Set the plcp header.
     "long" or "auto" or "debug"

phytype
     Get phy type

scbdump
     print driver scb state to stdout

rateparam
     set driver rate selection tunables
     arg 1: tunable id
     arg 2: tunable value

wepstatus
     Set or Get WEP status
     wepstatus [on|off]

primary_key
     Set or get index of primary key

addwep
     Set an encryption key.  The key must be 5, 13 or 16 bytes long, or
     10, 26, 32, or 64 hex digits long.  The encryption algorithm is
     automatically selected based on the key size. keytype is accepted
     only when key length is 16 bytes/32 hex digits and specifies
     whether AES-OCB or AES-CCM encryption is used. Default is ccm.
     addwep <keyindex> <keydata> [ocb | ccm] [notx] [xx:xx:xx:xx:xx:xx]

rmwep
     Remove the encryption key at the specified key index.

keys
     Prints a list of the current WEP keys

tsc
     Print Tx Sequence Couter for key at specified key index.

wsec_test
     Generate wsec errors
     wsec_test <test_type> <keyindex|xx:xx:xx:xx:xx:xx>
     type 'wl wsec_test ?' for test_types

tkip_countermeasures
     Enable or disable TKIP countermeasures (TKIP-enabled AP only)
     0 - disable
     1 - enable

wsec_restrict
     Drop unencrypted packets if WSEC is enabled
     0 - disable
     1 - enable

eap
     restrict traffic to 802.1X packets until 802.1X authorization succeeds
     0 - disable
     1 - enable

authorize
     restrict traffic to 802.1X packets until 802.1X authorization succeeds

deauthorize
     do not restrict traffic to 802.1X packets until 802.1X authorization succeeds

deauthenticate
     deauthenticate a STA from the AP with optional reason code (AP ONLY)

wsec
     wireless security bit vector
     1 - WEP enabled
     2 - TKIP enabled
     4 - AES enabled
     8 - WSEC in software

auth
     set/get 802.11 authentication type. 0 = OpenSystem, 1= SharedKey

wpa_auth
     Bitvector of WPA authorization modes:
     1
     WPA-NONE
     2
     WPA-802.1X/WPA-Professional
     4
     WPA-PSK/WPA-Personal
     64
     WPA2-802.1X/WPA2-Professional
     128
     WPA2-PSK/WPA2-Personal
     0
     disable WPA

wpa_cap
     set/get 802.11i RSN capabilities

set_pmk
     Set passphrase for PMK in driver-resident supplicant.

scan
     Initiate a scan.
     Default an active scan across all channels for any SSID.
     Optional arg: SSID, the SSID to scan.
     Options:
     -s S, --ssid=S
      SSID to scan
     -t ST, --scan_type=ST
     [active|passive] scan type
     --bss_type=BT
      [bss/infra|ibss/adhoc] bss type to scan
     -b MAC, --bssid=MAC
     particular BSSID MAC address to scan, xx:xx:xx:xx:xx:xx
     -n N, --nprobes=N
     number of probes per scanned channel
     -a N, --active=N
     dwell time per channel for active scanning
     -p N, --passive=N
     dwell time per channel for passive scanning
     -h N, --home=N
      dwell time for the home channel between channel scans
     -c L, --channels=L
     comma or space separated list of channels to scan

passive
     Puts scan engine into passive mode

regulatory
     Get/Set regulatory domain mode (802.11d). Driver must be down.

spect
     Get/Set 802.11h Spectrum Management mode.
     0 - Off
     1 - Loose interpretation of spec - may join non-11h APs
     2 - Strict interpretation of spec - may not join non-11h APs
     3 - Disable 11H and enable 11D

scanresults
     Return results from last scan.

assoc
     Print information about current network association.
     (also known as "status")

status
     Print information about current network association.
     (also known as "assoc")

disassoc
     Disassociate from the current BSS/IBSS.

chanlist
     Deprecated. Use channels.

channels
     Return valid channels for the current settings.

channels_in_country
     Return valid channels for the country specified.
     Arg 1 is the country abbreviation
     Arg 2 is the band(a or b)

curpower
     Return current tx power settings.
     -q (quiet): estimated power only.

txinstpwr
     Return tx power based on instant TSSI 

scansuppress
     Suppress all scans for testing.
     0 - allow scans
     1 - suppress scans

evm
     Start an EVM test on the given channel, or stop EVM test.
     Arg 1 is channel number 1-14, or "off" or 0 to stop the test.
     Arg 2 is optional rate (1, 2, 5.5 or 11)

rateset
     Returns or sets the supported and basic rateset, (b) indicates basic
     With no args, returns the rateset. Args are
     rateset "default" | "all" | <arbitrary rateset>
 
     default - driver defaults
 
     all - all rates are basic rates
 
     arbitrary rateset - list of rates
     List of rates are in Mbps and each rate is optionally followed
     by "(b)" or "b" for a Basic rate. Example: 1(b) 2b 5.5 11
     At least one rate must be Basic for a legal rateset.

roam_trigger
     Set the roam trigger RSSI threshold: roam_trigger [integer [, a/b]] 

roam_delta
     Set the roam candidate qualification delta. roam_delta [integer [, a/b]]

roam_scan_period
     Set the roam candidate qualification delta.  (integer)

suprates
     Returns or sets the 11g override for the supported rateset
     With no args, returns the rateset. Args are a list of rates,
     or 0 or -1 to specify an empty rateset to clear the override.
     List of rates are in Mbps, example: 1 2 5.5 11

scan_channel_time
     Get/Set scan channel time

scan_unassoc_time
     Get/Set unassociated scan channel dwell time

scan_home_time
     Get/Set scan home channel dwell time

scan_passive_time
     Get/Set passive scan channel dwell time

scan_nprobes
     Get/Set scan parameter for number of probes to use per channel scanned

prb_resp_timeout
     Get/Set probe response timeout

channel_qa
     Get last channel quality measurment

channel_qa_start
     Start a channel quality measurment

country
     Select Country code for use with 802.11d
     Use either long name or abbreviation from ISO 3166.
     Use 'wl country list [band(a or b)]' for the list of supported countries

locale
     OBSOLETE: use "wl country"
     Select the country:
     Worldwide
     Thailand
     Israel
     Jordan
     China
     Japan
     USA/Canada/ANZ
     Europe
     USAlow
     JapanHigh
     All

join
     Join a specified network SSID.
     Join syntax is: join <ssid> [key xxxxx] [imode bss|ibss] [amode open|shared|wpa|wpapsk|wpa2|wpa2psk|wpanone]

ssid
     Set or get a configuration's SSID.
     wl ssid [-C num]|[--cfg=num] [<ssid>]
     If the configuration index 'num' is not given, configuraion #0 is assumed and
     setting will initiate an assoication attempt if in infrastructure mode,
     or join/creation of an IBSS if in IBSS mode,
     or creation of a BSS if in AP mode.

mac
     Set or get the list of source MAC address matches.
     wl mac xx:xx:xx:xx:xx:xx [xx:xx:xx:xx:xx:xx ...]
     To Clear the list: wl mac none

macmode
     Set the mode of the MAC list.
     0 - Disable MAC address matching.
     1 - Deny association to stations on the MAC list.
     2 - Allow association to stations on the MAC list.

wds
     Set or get the list of WDS member MAC addresses.
     Set using a space separated list of MAC addresses.
  wl wds xx:xx:xx:xx:xx:xx [xx:xx:xx:xx:xx:xx ...]

lazywds
     Set or get "lazy" WDS mode (dynamically grant WDS membership to anyone).

noise
     Get noise (moving average) right after tx in dBm

fqacurcy
     Manufacturing test: set frequency accuracy mode.
     freqacuracy syntax is: fqacurcy <channel>
     Arg is channel number 1-14, or 0 to stop the test.

crsuprs
     Manufacturing test: set carrier suppression mode.
     carriersuprs syntax is: crsuprs <channel>
     Arg is channel number 1-14, or 0 to stop the test.

longtrain
     Manufacturing test: set longtraining mode.
     longtrain syntax is: longtrain <channel>
     Arg is A band channel number or 0 to stop the test.

band
     Returns or sets the current band
     auto - auto switch between available bands (default)
     a - force use of 802.11a band
     b - force use of 802.11b band

bands
     Return the list of available 802.11 bands

phylist
     Return the list of available phytypes

shortslot
     Get current 11g Short Slot Timing mode. (0=long, 1=short)

shortslot_override
     Get/Set 11g Short Slot Timing mode override. (-1=auto, 0=long, 1=short)

shortslot_restrict
     Get/Set AP Restriction on associations for 11g Short Slot Timing capable STAs.
     0 - Do not restrict association based on ShortSlot capability
     1 - Restrict association to STAs with ShortSlot capability

ignore_bcns
     AP only (G mode): Check for beacons without NONERP element (0=Examine beacons, 1=Ignore beacons)

pktcnt
     Get the summary of good and bad packets.

upgrade
     Upgrade the firmware on an embedded device

gmode
     Set the 54g Mode (LegacyB|Auto||GOnly|BDeferred|Performance|LRS)

gmode_protection
     Get G protection mode. (0=disabled, 1=enabled)

gmode_protection_control
     Get/Set 11g protection mode control alg. (0=always off, 1=monitor local association, 2=monitor overlapping BSS)

gmode_protection_cts
     Get/Set 11g protection type to CTS (0=disable, 1=enable)

gmode_protection_override
     Get/Set 11g protection mode override. (-1=auto, 0=disable, 1=enable)

legacy_erp
     Get/Set 11g legacy ERP inclusion (0=disable, 1=enable)

scb_timeout
     AP only: inactivity timeout value for authenticated stas

assoclist
     AP only: Get the list of associated MAC addresses.

rssi
     Get the current RSSI val, for an AP you must specify the mac addr of the STA

isup
     Get driver operational state (0=down, 1=up)

fasttimer
     Deprecated. Use fast_timer.

slowtimer
     Deprecated. Use slow_timer.

glacialtimer
     Deprecated. Use glacial_timer.

radar
     Enable/Disable radar

radarargs
     Get/Set Radar parameters in 
     order as npulses, ncontig, min_pw , max_pw, thresh0, thresh1

dfs_status
     Get dfs status

interference
     Get/Set interference mitigation mode. Choices are:
     0 = none
     1 = non wlan
     2 = wlan manual
     3 = wlan automatic

aciargs
     Get/Set various aci tuning parameters.  Choices are:
     enter:
     CRS glitch trigger level to start detecting ACI
     exit:
     CRS glitch trigger level to exit ACI mode
     glitch
     Seconds interval between ACI scans when glitchcount is continuously high
     spin:
     Num microsecs to delay between rssi samples
     Usage: wl aciargs [enter x][exit x][spin x][glitch x]

frameburst
     Disable/Enable frameburst mode

pwr_percent
     Get/Set power output percentage

wet
     Get/Set wireless ethernet bridging mode

bi
     Get/Set the beacon period (bi=beacon interval)

dtim
     Get/Set DTIM

wds_remote_mac
     Get WDS link remote endpoint's MAC address

wds_wpa_role_old
     Get WDS link local endpoint's WPA role (old)

wds_wpa_role
     Get/Set WDS link local endpoint's WPA role

authe_sta_list
     Get authenticated sta mac address list

autho_sta_list
     Get authorized sta mac address list

measure_req
     Send an 802.11h measurement request.
     Usage: wl measure_req <type> <target MAC addr>
     Measurement types are: TPC, Basic, CCA, RPI
     Target MAC addr format is xx:xx:xx:xx:xx:xx

quiet
     Send an 802.11h quiet command.
     Usage: wl quiet <TBTTs until start>, <duration (in TUs)>, <offset (in TUs)>

csa
     Send an 802.11h channel switch anouncement
     Usage wl csa <mode> <when (in TBTTs)> <channel>

constraint
     Send an 802.11h Power Constraint IE
     Usage: wl constraint 1-255 db

rm_req
     Request a radio measurement of type basic, cca, or rpi
     specify a series of measurement types each followed by options.
     example: wl rm_req cca -c 1 -d 50 cca -c 6 cca -c 11
     Options:
     -t n  numeric token id for measurement set or measurement
     -c n  channel
     -d n  duration in TUs (1024 us)
     -p    parallel flag, measurement starts at the same time as previous

     Each measurement specified uses the same channel and duration as the
     previous unless a new channel or duration is specified.

rm_rep
     Get current radio measurement report

join_pref
     Set/Get join target preferences.

assoc_pref
     Set/Get association preference.
Usage: wl assoc_pref [auto|a|b|g]

wme
     Set WME (Wireless Multimedia Extensions) mode (0=off, 1=on, -1=auto)

wme_ac
     wl wme_ac sta/ap [be, bk, vi, vo] [ecwmax, ecwmin, txop, aifsn, acm] value

wme_apsd
     Set APSD (Automatic Power Save Delivery) mode on AP (0=off, 1=on)

wme_apsd_sta
     Set APSD parameters on STA. Driver must be down.
Usage: wl wme_apsd_sta <max_sp_len> <be> <bk> <vi> <vo>
   <max_sp_len>: number of frames per USP: 0 (all), 2, 4, or 6
   <xx>: value 0 to disable, 1 to enable U-APSD per AC

wme_dp
     Set AC queue discard policy.
Usage: wl wme_dp <be> <bk> <vi> <vo>
   <xx>: value 0 for newest-first, 1 for oldest-first

wme_counters
     print WMM stats

reinit
     Reinitialize device

sta_info
     wl sta_info <xx:xx:xx:xx:xx:xx>

cap
     driver capabilities

malloc_dump
     debug malloc info

chan_info
     channel info

add_ie
     Add a vendor proprietary IE to 802.11 management packets
Usage: wl add_ie <pktflag> length OUI hexdata
<pktflag>: Bit 0 - Beacons
           Bit 1 - Probe Rsp
           Bit 2 - Assoc/Reassoc Rsp
           Bit 3 - Auth Rsp
Example: wl add_ie 3 10 00:90:4C 0101050c121a03
         to add this IE to beacons and probe responses

del_ie
     Delete a vendor proprietary IE from 802.11 management packets
Usage: wl del_ie <pktflag> length OUI hexdata
<pktflag>: Bit 0 - Beacons
           Bit 1 - Probe Rsp
           Bit 2 - Assoc/Reassoc Rsp
           Bit 3 - Auth Rsp
Example: wl del_ie 3 10 00:90:4C 0101050c121a03

list_ie
     Dump the list of vendor proprietary IEs

rand
     Get a 2-byte Random Number from the MAC's PRNG
Usage: wl rand

nvotpw
     Write nvram to on-chip otp
Usage: wl nvotpw file

bcmerrorstr
     errorstring

freqtrack
     Set Frequency Tracking Mode (0=Auto, 1=On, 2=OFF)

eventing
     set/get 128-bit hex filter bitmask for MAC event reporting up to application layer

event_msgs
     set/get 128-bit hex filter bitmask for MAC event reporting via packet indications

counters
     Return driver counter values

assoc_info
     Returns the assoc req and resp information [STA only]

autochannel
     auto channel selection: 
     1 to issue a channel scanning;
     2 to set channel based on the channel scanning result;
     without argument to only show the channel selected; 
     ssid must set to null before this process, RF must be up

csscantimer
     auto channel scan timer in minutes (0 to disable)

closed
     hides the network from active scans, 0 or 1.
     0 is open, 1 is hide

pmkid_info
     Returns the pmkid table

abminrate
     get/set afterburner minimum rate threshold

bss
     set/get BSS enabled status: up/down

closednet
     set/get BSS closed network attribute

diag
     diag testindex(1-interrupt, 2-loopback, 3-memory, 4-led); precede by 'wl down' and follow by 'wl up'

reset_d11cnts
     reset 802.11 MIB counters

Wednesday, October 3, 2012

VSFTPD installation


Contents 

This tutorial is split up into the following topics:
introduction
installation
base configuration
xinetd vs. standalone
PAM configuration
creating virtual users (PAM)
virtual user configuration
Appendixes:
vsftpd configuration options
xinetd configuration options
faq


Introduction

This tutorial has actually being written because more and more people are trying to setup a ftp service, but mainly choose software with a bad security history like wu-ftpd for that task. My personal suggestion for a ftp server is vsftpd because of it's security, performance and stability.

We will be using virtual users here since they do not have real privileges - unlike real system users. For additional information please consult the faq.


Installation 
Before we can start with the real topic of this tutorial, we need to install vsftpd of course. Since we want to run vsftpd with virtual users and a per-user configuration we require at least version 1.1.0 of vsftpd. I have been using a backport of vsftpd 1.2.1-1 when writing this tutorial.

If your distribution is Debian/GNU Linux, you need to either backport it yourself or use my backport of vsftpd, since currently vsftpd 1.0.0-2 is in stable and 1.2.1-1 in testing. For other distributions you should check with your distribution if you can rely on a pre-built vsftpd.


Base configuration 
We will not start using a bloated standard configuration and adopt that to our needs - which is the way most people set up their services - no, we will configure from scratch changing the default values only where required:

/etc/vsftpd.conf (without chmod capabilities)

# =========================================================================
# base configuration
# -------------------------------------------------------------------------
anon_world_readable_only=NO
anonymous_enable=NO
chroot_local_user=YES
guest_enable=YES
guest_username=ftp
hide_ids=YES
listen=YES
listen_address=192.168.0.1
local_enable=YES
max_clients=100
max_per_ip=1
nopriv_user=ftp
pam_service_name=ftp
pasv_max_port=65535
pasv_min_port=64000
session_support=NO
use_localtime=YES
user_config_dir=/etc/vsftpd/users
userlist_enable=YES
userlist_file=/etc/vsftpd/denied_users
xferlog_enable=YES
# -------------------------------------------------------------------------


# =========================================================================
# ftp settings
# -------------------------------------------------------------------------
anon_umask=0027
async_abor_enable=YES
connect_from_port_20=YES
dirlist_enable=NO
download_enable=NO
# =========================================================================



The above configuration in combination with the default values of vsftpd provides a pretty secure default configuration, which we will then override on a per-user basis.

However if you require the capability to chmod then the above configuration will not work since this is not allowed for anonymous users. You should only use the configuration file below if you do really require chmod capabilites. You would require chmod capabilites for instance when the users should be able to change the permissions of "sensitive" information from the default umask you have specified in the per-user configuration.

/etc/vsftpd.conf (with chmod capabilities)

# =========================================================================
# base configuration
# -------------------------------------------------------------------------
anonymous_enable=NO
chroot_local_user=YES
guest_enable=YES
guest_username=ftp
hide_ids=YES
listen=YES
listen_address=192.168.0.1
local_enable=YES
max_clients=100
max_per_ip=1
nopriv_user=ftp
pam_service_name=ftp
pasv_max_port=65535
pasv_min_port=64000
session_support=NO
use_localtime=YES
user_config_dir=/etc/vsftpd/users
userlist_enable=YES
userlist_file=/etc/vsftpd/denied_users
virtual_use_local_privs=YES
xferlog_enable=YES
# -------------------------------------------------------------------------


# =========================================================================
# ftp settings
# -------------------------------------------------------------------------
async_abor_enable=YES
connect_from_port_20=YES
dirlist_enable=NO
download_enable=NO
local_umask=0027
# =========================================================================



Now we need to:

create directory /etc/vsftpd
create directory /etc/vsftpd/users
write list of denied users to /etc/vsftpd/denied_users
I suggest adding every system user in /etc/vsftpd/denied_users so no system user is asked for submisson of the password in plaintext. Use cat /etc/passwd | cut -d ":" -f 1 | sort > /etc/vsftpd/denied_users for creating that file.

Now when a user, who is listed in /etc/vsftpd/denied_users attempts to login, the session will be terminated before prompting for the password like illustrated below:

example ftp session for denied user

Connected to 192.168.0.1.
220 (vsFTPd 1.2.0)
Name (192.168.0.1:root): root
530 Permission denied.
Login failed.
ftp> quit
221 Goodbye.




xinetd vs. standalone
If you like to use the power of xinetd, for instance to restrict the usage of the ftp server to a specified time range or a couple of ip addresses, you can launch vsftpd from xinetd.

For that purpose you will require to change the base configuration, in detail remove the listen and listen_address configuration option and configure your xinetd service:

/etc/xinetd.d/ftp

service ftp
{
   banner_fail   = /etc/vsftpd/busy_banner
   disable      = no
   instances      = 100
   log_on_failure   += HOST
   log_on_success   += PID HOST DURATION
   no_access      = 192.168.0.3
   only_from      = 192.168.0.0/28
   per_source   = 2
   server      = /usr/sbin/vsftpd
   socket_type   = stream
   user      = root
   wait      = no
}



The above configuration will of course need to be adjusted for your needs, like you probably want to limit the number of concurrent sessions (instances) even more or ban a couple of subnetworks (no_access).

The banner_fail file could look like:

/etc/vsftpd/busy_banner
421 Server busy, please try again later!


PAM configuration
After providing the username and verifiying it is not contained in /etc/vsftpd/denied_users, we still can not login since we have nothing left to authentificate against left - assuming our /etc/vsftpd/denied_users always contains all usernames from /etc/passwd.

Therefore we now need to configure our real authentification which will be based upon PAM. As example we can authentificate against a username/password file in common database format:

/etc/pam.d/ftp

auth    required /lib/security/pam_userdb.so db=/etc/vsftpd/accounts
account required /lib/security/pam_userdb.so db=/etc/vsftpd/accounts




creating virtual users (PAM)
Before being able to login, we need to create a valid user. Depending on the PAM authentification backend this steps could vary. For instance when using a database as authentification backend you would require addind that user to the specified table.

If you would like to follow from the above PAM sample configuration, you will need the db_load program for creating the file in common database format. When using Debian just apt-get install libdb3-util. Afterwards you need to create a file which contains the login and on the next line the password:

sample accounts.tmp (for building accounts.db)
user1
password_for_user1
user2
password_for_user2


After creating the accounts.tmp, which is just a list of usernames and passwords, you need to build the database with db3_load -T -t hash -f accounts.tmp /etc/vsftpd/accounts.db. Afterwards you can erase your accounts.tmp since it is no longer required - until you upgrade your username/password database. You should now set pretty restrictive permissions to the database: chmod 600 /etc/vsftpd/accounts.db


Virtual user configuration 
Depending on your base configuration, you have a different per-user configuration:

/etc/vsftpd/users/user1 (without chmod capabilites)

anon_mkdir_write_enable=YES
anon_other_write_enable=YES
anon_upload_enable=YES
dirlist_enable=YES
download_enable=YES
local_root=/home/user1
write_enable=YES



If you require chmod capabilities and have specified that in your base configuration, you will go for the following:

/etc/vsftpd/users/user1 (with chmod capabilites)

dirlist_enable=YES
download_enable=YES
local_root=/home/user1
write_enable=YES




Appendix a: vsftpd configuration options
The configuration file takes a couple of options, which are partly explained shortly below. For more information please refer to the vsftpd.conf man page, where this information has been stripped off.

option description
anon_umask The value that the umask for file creation is set to for anonymous users.
anon_mkdir_write_enable If set to YES, anonymous users will be permitted to create new directories under certain conditions. For this to work, the option write_enable must be activated, and the anonymous ftp user must have write permission on the parent directory.
anon_other_write_enable If set to YES, anonymous users will be permitted to perform write operations other than upload and create directory, such as deletion and renaming. This is generally not recommended but included for completeness.
anon_upload_enable If set to YES, anonymous users will be permitted to upload files under certain conditions. For this to work, the option write_enable must be activated, and the anonymous ftp user must have write permission on desired upload locations.
anon_world_readable_only When enabled, anonymous users will only be allowed to download files which are world readable. This is recognising that the ftp user may own files, especially in the presence of uploads.
anonymous_enable Controls whether anonymous logins are permitted or not.
async_abor_enable When enabled, a special FTP command known as "async ABOR" will be enabled. Only ill advised FTP clients will use this feature. Addtionally, this feature is awkward to handle, so it is disabled by default. Unfortunately, some FTP clients will hang when cancelling a transfer unless this feature is available, so you may wish to enable it.
chroot_local_user If set to YES, local users will be placed in a chroot() jail in their home directory after login.
connect_from_port_20 This controls whether PORT style data connections use port 20 (ftp-data) on the server machine. For security reasons, some clients may insist that this is the case. Conversely, disabling this option enables vsftpd to run with slightly less privilege.
dirlist_enable If set to NO, all directory list commands will give permission denied.
download_enable If set to NO, all download requests will give permission denied.
guest_enable If enabled, all non-anonymous logins are classed as "guest" logins. A guest login is remapped to the user specified in the guest_username setting.
guest_username This setting is the real username which guest users are mapped to.
hide_ids If enabled, all user and group information in directory listings will be displayed as "ftp".
listen If enabled, vsftpd will run in standalone mode. This means that vsftpd must not be run from an inetd of some kind. Instead, the vsftpd executable is run once directly. vsftpd itself will then take care of listening for and handling incoming connections.
listen_address If vsftpd is in standalone mode, the default listen address (of all local interfaces) may be overridden by this setting. Provide a numeric IP address.
local_enable Controls whether local logins are permitted or not. If enabled, normal user accounts in /etc/passwd may be used to log in.
local_root This option represents a directory which vsftpd will try to change into after a local (i.e. non-anonymous) login. Failure is silently ignored.
local_umask The value that the umask for file creation is set to for local users.
max_clients If vsftpd is in standalone mode, this is the maximum number of clients which may be connected. Any additional clients connecting will get an error message.
max_per_ip If vsftpd is in standalone mode, this is the maximum number of clients which may be connected from the same source internet address. A client will get an error message if they go over this limit.
nopriv_user This is the name of the user that is used by vsftpd when it want to be totally unprivileged. Note that this should be a dedicated user, rather than nobody. The user nobody tends to be used for rather a lot of important things on most machines.
pam_service_name This string is the name of the PAM service vsftpd will use.
pasv_max_port The maximum port to allocate for PASV style data connections. Can be used to specify a narrow port range to assist firewalling.
pasv_min_port The minimum port to allocate for PASV style data connections. Can be used to specify a narrow port range to assist firewalling.
session_support This controls whether vsftpd attempts to maintain sessions for logins. If vsftpd is maintaining sessions, it will try and update utmp and wtmp. It will also open a pam_session if using PAM to authenticate, and only close this upon logout. You may wish to disable this if you do not need session logging, and you wish to give vsftpd more opportunity to run with less processes and / or less privilege.
use_localtime If enabled, vsftpd will display directory listings with the the time in your local time zone. The default is to display GMT. The times returned by the MDTM FTP command are also affected by this option.
user_config_dir This powerful option allows the override of any config option specified in the manual page, on a per-user basis. Usage is simple, and is best illustrated with an example. If you set user_config_dir=/etc/vsftpd_user_conf and then log on as the user "chris", then vsftpd will apply the settings in the file /etc/vsftpd_user_conf/chris for the duration of the session.
userlist_enable If enabled, vsftpd will load a list of usernames, from the filename given by userlist_file. If a user tries to log in using a name in this file, they will be denied before they are asked for a password. This may be useful in preventing cleartext passwords being transmitted.
userlist_file This option is the name of the file loaded when the userlist_enable option is active.
virtual_use_local_privs If enabled, virtual users will use the same privileges as local users. By default, virtual users will use the same privileges as anonymous users, which tends to be more restrictive (especially in terms of write access).
write_enable This controls whether any FTP commands which change the filesystem are allowed or not. These commands are: STOR, DELE, RNFR, RNTO, MKD, RMD, APPE and SITE.
xferlog_enable If enabled, a log file will be maintained detailling uploads and downloads.


Appendix b: xinetd configuration options
The xinetd configuration file takes a couple of different options, which are explained shortly below. For more information please refer to the xinetd.conf man page, where this information has been stripped off.

option description
banner_fail Takes the name of a file to be splatted at the remote host when a connection to that service is denied. This banner is printed immediately upon denial of access.

This is useful for informing your users that they are doing something bad and they shouldn't be doing it anymore.

disable This is boolean "yes" or "no".
This will result in the service being disabled and not starting.
instances Determines the number of servers that can be simultaneously active for a service (the default is no limit). The value of this attribute can be either a number or UNLIMITED which means that there is no limit.

log_on_failure Determines what information is logged when a server cannot be started (either because of a lack of resources or because of access control restrictions). The service id is always included in the log entry along with the reason for failure.

log_on_success Determines what information is logged when a server is started and when that server exits (the service id is always included in the log entry).

no_access Determines the remote hosts to which the particular service is unavailable. Its value can be specified in the same way as the value of the only_from attribute. These two attributes determine the location access control enforced by xinetd. If none of the two is specified for a service, the service is available to anyone. If both are specified for a service, the one that is the better match for the address of the remote host determines if the service is available to that host (for example, if the only_from list contains 128.138.209.0 and the no_access list contains 128.138.209.10 then the host with the address 128.138.209.10 can not access the service).

only_from Determines the remote hosts to which the particular service is available. Its value is a list of IP addresses which can be specified in any combination of the following ways:

a numeric address in the form of %d.%d.%d.%d. If the rightmost components are 0, they are treated as wildcards (for example, 128.138.12.0 matches all hosts on the 128.138.12 subnet). 0.0.0.0 matches all Internet addresses.
a factorized address in the form of %d.%d.%d.{%d,%d,...}. There is no need for all 4 components (i.e. %d.%d.{%d,%d,...%d} is also ok). However, the factorized part must be at the end of the address.
a network name (from /etc/networks).
a host name. When a connection is made to xinetd, a reverse lookup is performed, and the canonical name returned is compared to the specified host name. You may also use domain names in the form of .domain.com. If the reverse lookup of the client's IP is within .domain.com, a match occurs.
an ip address/netmask range in the form of 1.2.3.4/32.

per_source Takes an integer or "UNLIMITED" as an argument. This specifies the maximum instances of this service per source IP address.

server Determines the program to execute for this service
server_args Determines the arguments passed to the server.
socket_type Possible values for this attribute include:

dgram  datagram-based service
raw  service that requires direct access to IP
seqpacket  service that requires reliable sequential datagram transmission
stream  stream-based service

user Determines the uid for the server process. The user name must exist in /etc/passwd. This attribute is ineffective if the effective user ID of xinetd is not super-user.

wait This attribute determines if the service is single-threaded or multi-threaded. If its value is yes the service is single-threaded; this means that xinetd will start the server and then it will stop handling requests for the service until the server dies. If the attribute value is no, the service is multi-threaded and xinetd will keep handling new service requests.



Appendix c: faq
If you have a question regarding vsftpd which has not been answered in any section of this tutorial, feel free to email your question to website@linux-corner.net.

Frequently asked questions which have already been answered:

Firewalling information
Where can I find binary packages for other distributions than Debian?
Why do you prefer vsftpd over other ftp servers?
Why should one disallow system users?
Firewalling information
The configuration options pasv_max_port and pasv_min_port assist you in firewalling:
INPUT chain:
tcp
new/established
source port: 1024 - 65535
destination port: 21
tcp
new/established/related
destination port: pasv_min_port - pasv_max_port


OUTPUT chain:
tcp
related/established
source port: 20
destination port: 1024 - 65535
tcp
established
source port: 21
destination port: 1024 - 65535
tcp
established
source port: pasv_min_port - pasv_maxport
destination port: 1024 - 65535
With the above information (protocol, connection status, ports) you should be able to write the iptables ruleset. Your kernel needs to support connection tracking though; additionally you will require to use the ip_conntrack_ftp module of netfilter.

Where can I find binary packages for other distributions than Debian?
If you are not using Debian you are probably looking for RPM packages. I suggest you take a look at rpmseek.com. Here you can probably also find the db_load program used for creating virtual users with the common database format.
db3_load binary packages
vsftpd binary packages

Why do you prefer vsftpd?
I could quote that mostly from the vsftpd website. I am using vsftpd for it's excellent points in the following areas:
security
stability
performance
I am not really quoting it, I have verified all of the above points and I would not be using vsftpd if it would not perform that excellent. I know that there are other ftp servers out that are said to be secure, however until now I have not verified others.
Why should one disallow system users?
The typical system user has a lot of more privileges than required for the standard FTP user - like shell access. Granting each ftp user the privileges of a system user will definately affect system security, also since FTP transmitts passwords in cleartext. You can limit your real system users to not being able to login, however in that case there is no reason why you should not go for virtual users.

Immagine the root user logs in at the ftp server, the password is transmitted in cleartext and it is PRETTY easy to sniff out the password with standard tools. Do you really want to share passwords for users with probably unneccessary privileges with the whole world?


reference: http://www.debiansec.com/linux/services/ftp.html

Monday, October 1, 2012

Bash Parameter Expansion

If you use bash you already know what Parameter Expansion is, although you may have used it without knowing its name. Anytime you use a dollar sign followed by a variable name you're doing what bash calls Parameter expansion, eg echo $a or a=$b. But parameter expansion has numerous other forms which allow you to expand a parameter and modify the value or substitute other values in the expansion process.

Parameter expansion comes in many forms in bash, the simplest is just a dollar sign followed by a name, eg $a. This form merely substitutes the value of the variable in place of the parameter expansion expression. The variable name can also optionally be surround by braces, eg ${a}. If the variable name is immediately followed by characters that could be part of a variable name then the braces are needed to delimit the variable name, for example if you remove the braces from echo ${a}bc bash will try to expand the variable "abc" rather than "a".

One useful form of parameter expansion is to use a default value for a variable if it is not set. This is done with the syntax: ${VAR:-DFLT}. You might use this to allow your code to be modified via variables from the environment. Consider the following from a script, call it test.sh:

  TEST_MODE=${TEST_MODE:-0}
  ...
  if [[ $TEST_MODE -eq 0 ]]; then
      echo "Running in live mode"
  else
      echo "Running in test mode"
  fi

Normally the script runs in "live" mode but if you run it via:

  $ env TEST_MODE=1 sh test.sh

it runs in test mode.
You might also use the default value expansion with command line arguments or values from a config file, for example:

  # set cmd_param_x to 1 if seen on the command line
  ...
  if [[ ${cmd_param_x:-0} -eq 0 ]]; then
      echo "-x not specified"
  else
      echo "-x specified"
  fi

Another useful form of parameter expansion is to expand a variable and do string substitution on the value using the form ${VAR/search/replace}. For example:

  VAR=aabbcc
  echo ${VAR/b/-dd-}

outputs "aa-dd-bcc". Note that only the first instance of the search string is replaced, if you want to replace all instances use a double slash:

  VAR=aabbcc
  echo ${VAR//b/-dd-}

which now outputs "aa-dd--dd-cc".
There are also expansions for removing prefixes and suffixes. The form ${VAR#pattern} removes any prefix from the expanded value that matches the pattern. The removed prefix is the shortest matching prefix, if you use double pound-signs/hash-marks the longest matching prefix is removed. Similarily, the form ${VAR%pattern} removes a matching suffix (single percent for the shortest suffix, double for the longest). For example:

  file=data.txt
  echo ${file%.*}
  echo ${file#*.}

outputs the file base and extension respectively ("data" and "txt").
Note: if you have trouble remembering which is which of these two syntaxes, the "#" is to the left of the "%" key on your keyboard, just as prefixes come before suffixes. Also note that these are glob patterns not regular expressions.

Another expansion that exists is to extract substrings from the expanded value using the form ${VAR:offset:length}. This works in the expected form: offsets start at zero, if you don't specify a length it goes to the end of the string. For example:

  str=abcdefgh
  echo ${str:0:1}
  echo ${str:1}

outputs "a" and "bcdefgh".

This form also accepts negative offsets which count backwards from the end of the string. So this:

  str=abcdefgh
  echo ${str:-3:2}

produces "abcdefgh"... oops, what happened there? What happened was that bash misinterpretted what we wanted because the expansion looks like a default value expansion: ${VAR:-DFLT}. First time I tried this I stared at it for quite a while before a light came on as to how to do it (without using a variable [see below]):

  str=abcdefgh
  echo ${str:$((-3)):2}

which outputs the desired value "fg". The "$((...))" causes bash to treat the value as an arithmetic expansion (ie a number). Another slightly longer way of doing this is:

  str=abcdefgh
  i=-3
  echo ${str:$i:2}

The final form of parameter expansion I want to mention is one which simply expands to the length of the variable's value, its form is ${#VAR}. So for example:

  str=abcdef
  echo ${#str}

outputs "6".

Using these forms of parameter expansion in your shell scripts can simplify and shorten your scripts. These are not the only forms of parameter expansion that bash supports but they're the ones that I've found most useful over time. For more information see the "Parameter Expansion" section of the bash man page.

p.s. Note that all of the above forms of parameter expansion also work with bash's Special parameters: "$$", "$0", "$1", etc.

Credit to: Mitch Frazier

How to automatically backup mysql database using mysqldump?


It's a really good idea to use a least-privilege approach to most system administration tasks, and especially automated ones. This post describes using a "read only" MySQL user to handle backing up MySQL databases.

We use mysqldump to backup our databases on a regular basis, using scripts like this one:

#!/bin/sh

DIR=/backup/mysql/
DATESTAMP=$(date +%Y%m%d)
DB_USER=backup
DB_PASS='readonly'

# remove backups older than $DAYS_KEEP
DAYS_KEEP=30
find ${DIR}* -mtime +$DAYS_KEEP -exec rm -f {} \; 2> /dev/null

# create backups securely
umask 006

# list MySQL databases and dump each
DB_LIST=`mysql -u $DB_USER -p"$DB_PASS" -e'show databases;'`
DB_LIST=${DB_LIST##Database}
for DB in $DB_LIST;
do
  FILENAME=${DIR}${DB}-${DATESTAMP}.sql.gz
  mysqldump -u $DB_USER -p"$DB_PASS" --opt --flush-logs $DB | gzip > $FILENAME
done

You'll note that this script uses the user 'backup' to do the dumping. This is because our production servers grant potentially dangerous permissions (such as DROP TABLE) on a per-database basis. In order to run an automated backup, however, we need a single user that has just enough permissions to read from all the databases, but not enough to pose a risk to them.

The MySQL permissions required for the script above are SHOW DATABASES, SELECT, LOCK TABLES, and RELOAD. Grant them by entering the mysql command line and issuing these commands (choosing a better password than 'readonly' of course)

GRANT SHOW DATABASES, SHOW VIEW, SELECT, LOCK TABLES, RELOAD ON *.* to backup@localhost
 IDENTIFIED BY 'readonly';
FLUSH PRIVILEGES;

You can now back up all your databases by way of a single MySQL account that has just enough access to do the job, and not enough to cause significant harm. Which is what least-privilege access is all about.

Credit to: Stevem

Friday, September 28, 2012

How to force Sendmail to use smarthost without DNS

1. make sure your smarthost is in /etc/hosts.
2. Create /etc/mail/service.switch file and put following two lines inside:

hosts files
aliases files.

3.Replace this line in /etc/mail/submit.mc file.

define(`SMART_HOST',`my smarthost from /etc/hosts')dnl

4. Go to /etc/mail and type "m4 sendmail.mc > /etc/sendmail.cf" to build new sendmail.cf.
5. type /etc/init.d/sendmail restart

Monday, September 17, 2012

How to combat DoS attacks without any firewall in Windows?


By Prashant Bharadwaj
As you all might know, DoS is typically a kind of attack where the attacker repeatedly send SYN packets to you. When you have a Firewall or IPS you can be sure of protection. Without a Firewall, you can still enable protection and I will be speaking more about this in this post.
You should have heard about the TCP/IP service in Windows. By making a change in TCP/IP service we are going to enable DoS protection.
  1. Run regedit.exe
  2. Navigate to the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters registry subkey.
  3. From the Edit menu, select New, DWORD Value.
  4. Enter the name TcpMaxHalfOpen, then press Enter.
  5. Double-click the new value, set it to 100, then click OK.
  6. Enter the name TcpMaxHalfOpenRetried, then press Enter.
  7. Double-click the new value, set it to 80, then click OK.
  8. Enter the name SynAttackProtect, then press Enter.
  9. Double-click the new value, set it to 1, then click OK.
  10. Reboot the machine.
When SynAttackProtect value is 0, it offers no protection. Value 1 indicate to delay the response Notification untill three way handshake is complete by the received by the SYN packet. By default, this is not invoke untill it exceeds the TcpMaxHalfOpen and TcpMaxHalfOpenRetried values. The values TcpMaxHalfOpen and TcpMaxHalfOpenRetried could be changed, and I strongly recommend to test with different settings in your environment, then choose the best ones.

Hardening the TCP/IP stack to SYN attacks


by Mariusz Burdach

Most people know how problematic protection against SYN denial of service attacks can be. Several methods, more or less effective, are usually used. In almost every case proper filtering of packets is a viable solution. In addition to creating packet filters, the modification of the TCP/IP stack of a given operating system can be performed by an administrator. This method, the tuning of the TCP/IP stack in various operating systems, will be described in depth in this article.
While SYN attacks may not be entirely preventable, tuning the TCP/IP stack will help reduce the impact of SYN attacks while still allowing legitimate client traffic through. It should be noted that some SYN attacks do not always attempt to upset servers, but instead try to consume all of the bandwidth of your Internet connection. This kind of flood is outside the scope of scope of this article, as is the filtering of packets which has been discussed elsewhere.

What can an administrator do when his servers are under a classic, non-bandwidth flooding SYN attack? One of most important steps is to enable the operating system's built-in protection mechanisms like SYN cookies or SynAttackProtect. Additionally, in some cases it is worth tuning parameters of the TCP/IP stack. Changing the default values of stack variables can be another layer of protection and help better secure your hosts. In this paper I will concentrate on:

Increasing the queue of half-open connections (in the SYN RECEIVED state).
Decreasing the time period of keeping a pending connection in the SYN RECEIVED state in the queue. This method is accomplished by decreasing the time of the first packet retransmission and by either decreasing the number of packet retransmissions or by turning off packet retransmissions entirely. The process of packet retransmissions is performed by a server when it doesn't receive an ACK packet from a client. A Packet with the ACK flag finalizes the process of the three-way handshake.
Note that an attacker can simply send more packets with the SYN flag set and then the above tasks will not solve the problem. However, we can still increase the likelihood of creating a full connection with legitimate clients by performing the above operations.

We should remember that our modification of variables will change the behavior of the TCP/IP stack. In some cases the values can be too strict. So, after the modification we have to make sure that our server can properly communicate with other hosts. For example, the disabling of packet retransmissions in some environments with low bandwidth can cause a legitimate request to fail. In this article you will find a description of the TCP/IP variables for the fallowing operating systems: Microsoft Windows 2000, RedHat Linux 7.3, Sun Solaris 8 and HP-UX 11.00. These variables are similar or the same in current releases.

Definitions: SYN flooding and SYN spoofing

A SYN flood is a type of Denial of Service attack. We can say that a victim host is under a SYN flooding attack when an attacker tries to create a huge amount of connections in the SYN RECEIVED state until the backlog queue has overflowed. The SYN RECEIVED state is created when the victim host receives a connection request (a packet with SYN flag set) and allocates for it some memory resources. A SYN flood attack creates so many half-open connections that the system becomes overwhelmed and cannot handle incoming requests any more.

To increase an effectiveness of a SYN flood attack, an attacker spoofs source IP addresses of SYN packets. In this case the victim host cannot finish the initialization process in a short time because the source IP address can be unreachable. This malicious operation is called a SYN spoofing attack.

We need to know that the process of creating a full connection takes some time. Initially, after receiving a connection request (a packet with SYN flag set), a victim host puts this half-open connection to the backlog queue and sends out the first response (a packet with SYN and ACK flags set). When the victim does not receive a response from a remote host, it tries to retransmit this SYN+ACK packet until it times out, and then finally removes this half-open connection from the backlog queue. In some operating systems this process for a single SYN request can take about 3 minutes! In this document you will learn how to change this behavior. The other important information you need to know is that the operating system can handle only a defined amount of half-open connections in the backlog queue. This amount is controlled by the size of the backlog queue. For instance, the default backlog size is 256 for RedHat 7.3 and 100 for Windows 2000 Professional. When this size is reached, the system will no longer accept incoming connection requests.

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 | grep 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 TcpMaxHalfOpen, TcpMaxHalfOpenRetried 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 at http://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 Entry Format Value
EnableDynamicBacklog DWORD 1
MinimumDynamicBacklog DWORD 20
MaximumDynamicBacklog DWORD 20000
DynamicBacklogGrowthDelta DWORD 10

Operating system: Linux

A 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).



Value Time of retransmission Total time to keep half-open connections in the backlog queue
1 in 3rd second 9 seconds
2 in 3rd and 9th second 21 seconds
3 in 3rd , 9th and 21st second 45 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

A 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 seconds
5000 in 2nd second5 seconds
10000in 2nd and 5th second10 seconds
60000 in 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.

Reference:

http://www.symantec.com/connect/articles/hardening-tcpip-stack-syn-attacks

Tuesday, July 24, 2012

PHP 4 can not connect to mysql server with error "Client does not support authentication protocol"


MySQL 4.1+ uses an authentication protocol based on a password hashing algorithm that is incompatible with that used by older (pre-4.1) clients. MySQL extension for PHP4 was compiled with old (pre-4.1) client library.

When you connect to server. It will shows error

"Client does not support authentication protocol requested by server; consider upgrading MySQL client"

To solve this problem, you should use one of the following approaches:
1. reset password to old style password

SET PASSWORD FOR 'some_user'@'some_host' = OLD_PASSWORD('newpwd');

For PHP mysql_connect command, you must specify parameters following

mysql_connect($server,$user,$pass,false,0);

2.Tell the server to use the older password hashing algorithm:
add this line to mysql configuration (my.ini/my.cnf)

[mysqld]
.
.
old-passwords = 1
.
.
[client]
.
.
old-passwords = 1
.
.

then restart service and reset password using command

SET PASSWORD FOR 'some_user'@'some_host' = PASSWORD('newpwd');

MySQL native driver for PHP can not connect to mysql. It shows error "mysqlnd cannot connect to MySQL 4.1+ using old authentication"

Symptom
MySQL native driver for PHP can not connect to mysql. It shows error "mysqlnd cannot connect to MySQL 4.1+ using old authentication"

Cause
New version of MySQL native driver for PHP uses an authentication protocol based on improved password hashing algorithm that is incompatible with an account that still has a pre-4.1-style password. 


Solution 
Reset the password to 4.1+ style for each user that needs to use the client program. 


SET SESSION OLD_PASSWORDS = FALSE; 
USE mysql;
UPDATE user SET password = PASSWORD('newpass') WHERE user='someuser'; 
FLUSH PRIVILEGES;

Saturday, June 16, 2012

Hosting Multiple FTP Sites with FTP User Isolation (IIS 6.0)

How to chroot ftp users in IIS 6?
How to jail ftp users in IIS6?


This is answer.


IIS 6.0 introduce 3 new modes for ftp site:

a) Do not isolate users - This mode does not enable FTP user isolation and it work similarly to earlier versions of IIS.

b) Isolate users - This mode authenticates users against local or domain accounts before they can access the home directory that matches their user name. All user home directories are in a directory structure under a single FTP root directory where each user is placed and restricted to their home directory. Users are not permitted to navigate out of their home directory.

c) Isolate users using Active Directory - This mode authenticates user credentials against a corresponding Active Directory container, rather than searching the entire Active Directory, which requires large amounts of processing time. Specific FTP server instances can be dedicated to each customer to ensure data integrity and isolation. 

You can select the isolation mode during FTP site setup using the FTP Site Creation Wizard. You can use Iisftp.vbs to configure FTP User Isolation, using the/isolationparameter. When you use the/isolation parameter, specify either AD, for Active Directory isolation, or Local, for local isolation. If you do not include the /isolation parameter, the site will not isolate users.

Note: This article focus on Isolate users in normal mode (b)

To create a new FTP site that isolates users
1. In IIS Manager, expand the local computer, right-click the FTP Sites folder, point to New, and click FTP Site
2. Provide the required information in the FTP Site Description and IP Address and Port Settings dialog boxes, and click Next
3. In the FTP User Isolation dialog box, click Isolate users, and click Next
4. In the Path box, type or browse to the directory that contains, or will contain, the site content, and then click Next.
5. Select the check boxes for the FTP site access permissions you want to assign to your users, and then click Next
6. Click Finish


To create FTP root-point and user folders
If users of the local computer log in with their individual account user names, create the subdirectoriesLocalUser under the FTP site root directory you specified when you creating the FTP site.
For Example -
FTP root directory -> D:\MyFTP\
LocalUser locate at D:\MyFTP\LocalUser

For individual user, you need to create folder in this format - LocalUser\username
User: Susan locate at D:\MyFTP\LocalUser\Susan

If users of different domains log on with their explicit domain\username credentials, create a subdirectory for each domain (by using the name of the domain) under the FTP site root directory you specified when you creating the FTP site.
For Example -
Domain Name: Account
FTP root directory -> D:\MyFTP\
LocalUser locate at D:\MyFTP\Account

For individual domain user, you need to create folder in this format - Domain\username
Domain User: Nancy locate at D:\MyFTP\Account\Nancy


Anonymous access in isolated ftp site
If anonymous access is allowed, create the subdirectories LocalUser and LocalUser\Public under the FTP site home directory. 


Note: All user home directories are in a directory structure under a single FTP root directory where each user is placed and restricted to their home directory. Users are not permitted to navigate out of their home directory. If users need access to dedicated shared folders, you can also establish a virtual root.