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