Loading

Friday, July 31, 2009

BT4 PreFinal Manual Installation to Hard Drive

Create the following volumes:

  • /dev/sda1 +64M Partition Boot Sector
  • /dev/sda2 Varies Swap
  • /dev/sda3 Varies /
  • /dev/sda4 Varies Windows (this is optional)

Format Drives

  • root@bt:~# mke2fs /dev/sda1
  • root@bt:~# mkswap /dev/sda2
  • root@bt:~# swapon /dev/sda2
  • root@bt:~# mkreiserfs /dev/sda3

Manually Copy OS Files

  • root@bt:~# mkdir /mnt/bt4
  • root@bt:~# mount /dev/sda3 /mnt/bt4/
  • root@bt:~# mkdir /mnt/bt4/boot
  • root@bt:~# mount /dev/sda1 /mnt/bt4/boot
  • root@bt:~# cp --preserve -R /{bin,dev,home,pentest,root,usr,boot,etc,lib,opt,sbin,var} /mnt/bt4/
  • root@bt:~# mkdir /mnt/bt4/{mnt,tmp,proc,sys}
  • root@bt:~# mount -t proc proc /mnt/bt4/proc
  • root@bt:~# mount -o bind /dev /mnt/bt4/dev/

Kernel BootSplash

  • root@bt:~# cd /media/cdrom0/boot
  • root@bt:~# cp --preserve -R {bootsplash,vmlinuz,initrd.gz} /mnt/bt4/boot/

Switch to Newly Created Installation

  • root@bt:~# chroot /mnt/bt4/ /bin/bash

Edit GRUB

  • root@bt:~# nano /boot/grub/menu.lst

----------------------------------------------------------------------------------
timeout 5 #The number of seconds GRUB should wait before booting an OS
default 0 #The entry which should be booted by default
fallback 1 #The entry which should be booted in the event of the first one failing

splashimage=(hd0,0)/grub/bt4.xpm.gz

# This is an example of using a separate partition for /boot (as in this example)
title BT4 PreFinal
root (hd0,0) # Boot Partition
kernel /vmlinuz root=/dev/sda3 rw vga=0x317 # 0x317 defines the right resolution for the monitor
initrd /initrd.gz
bootsplash

title Microsoft Windows XP Home #An entry for a Windows installation
root (hd0,3)
makeactive
chainloader +1
----------------------------------------------------------------------------------

Installing GRUB (When /boot resides in its own partition as in this example)

  • root@bt:~# grub
  • grub> find /grub/stage1
    (hd0,0)
  • grub> root (hd0,0)
  • grub> setup (hd0)
  • grub> quit

Note: The “root” line must point to the location of your /boot/ partition if you have one. If you do not have one, point it at your / partition.

Even a stopped clock is right twice a day

Cyber Security - Password Creation

Passwords are the most common means of authentication, but if you do not choose good passwords or keep them confidential, they are almost as ineffective as not having any password at all. Many systems and services have been successfully broken into due to the use of insecure and inadequate passwords. Some viruses and worms have exploited systems by guessing weak passwords. One good tip for creating a secure password is to use a combination of upper and lower case letters with numerals and symbols interposed that are not related to your birthday, social security number, etc. For example use “Il2pbb!” for I love to play basketball! This mnemonics device adds several layers of security ultimately decreasing your risk of becoming a victim.

Tune in next week for ways to protect your password.

Linux User Commands

Every user who has access to a Linux system needs a login and a password. Each user must belong to a primary group and for security or access purposes can belong to several secondary groups.

In order to create new logins, modify or delete users, you must already be logged in as root. The root login is the highest level and only certain individuals should have access to the root account.

useradd - Adding a new user
Options:
-d home directory
-s starting program (shell)
-p password
-g (primary group assigned to the users)
-G (Other groups the user belongs to)
-m (Create the user's home directory

Example: To add a new user with

  • a primary group of users
  • a second group mgmt
  • starting shell /bin/bash
  • password of xxxx
  • home directory of bubba
  • create home directory
  • a login name of bubba

useradd -gusers -Gmgmt -s/bin/shell -pxxxx -d/home/bubba -m bubba

usermod - Modifying existing user
Options:
-d home directory
-s starting program (shell)
-p password
-g (primary group assigned to the users)
-G (Other groups the user belongs to)

Example: To add the group 'others' to the user bubba

usermod -Gothers bubba

userdel - Deleting a user
Options:
-r (remove home directory)

Example: To remove the user 'bubba' and his home directory

userdel -r bubba

passwd - User's Password
Options:
user's name (Only required if you are root and want to change another user's password)

Example: To change the password for the account you are currently logged in as...
passwdEnter existing passwordEnter new passwordEnter new password again (to validate)

Example: To change the password for the user 'bubba' (only you are logged in as root)...
passwd bubbaEnter existing password (can be either bubba's password or root's password)Enter new passwordEnter new password again (to validate)

Where user and group information stored
User names and primary groups are stored in /etc/passwd. This file can be directly edited using the 'vi' editor, although this is not recommended. Format of the file is...
User (name normally all lower case)
Password (encrypted - only contains the letter 'x')
User ID (a unique number of each user)
Primary Group ID
Comment (Normally the person's full name)
Home directory (normally /home/
Default shell (normally /bin/bash)
Each field is separated by a colon.
Passwords for each user are stored in /etc/shadow. This file should only be changed using the passwd command.
Group information is stored in /etc/group. This file can be directly edited using the 'vi' editor. Format of the file is...
Group name
Group password (hardly ever used)
Group ID
User names (separated by commas)
Each field is separated by a colon.

Default files
When a new user is created, the default files and directories that are created are stored in /etc/skel.

This directory can be modified to fit your needs. Modifications only effect new users and does not change anything for existing users.

su - Switch User
To switch to another user, use the su command. This is most commonly used to switch to the root account.

Example: To switch to root account...suEnter root's passwd
Example: To switch to the user 'bubba'...su bubbaEnter bubba's or root's passwd

To return to original user, enter exit

Connecting to AWS EC2 (Linux) Instance With PuTTY via SSH

In order to connect to an Amazon Web Services EC2 Linux instance using PuTTY over SSH you must generate a PPK file from your private key, then import the PPK to PuTTY.  PuTTY does not natively support the private key format generated by Amazon EC2, therefore PuttyGen must be used to convert keys to its internal format.

First, associate the private key (<keyname>.PEM) with the instance to which you want to connect using PuTTYgen.  Click on the Load button and browse to the location of your private key (you will probably have to change the file type to All Files (*.*)).  If all goes well you will see the message "Successfully imported foreign key. . ."










Click OK, then click Save Private Key.



Click Yes when PuTTYgen prompts you about saving the key without a passphrase.









Save the key as <keyname>.ppk.

Next launch Putty to open an SSH session and tell Putty to use that PPK file -- NOT the PEM file! Expand connection, SSH, and select Auth. Click the browse button next to the Private key file for authentication: field, and select the .PPK file you just created with Puttygen.



Under category on the left go back to Session and Save the session.  Then click Open to connect.



Possible error messages with incorrect credentials.
* Putty failed: "Disconnected: No supported authentication methods available"
* Server refused our key

Keywords:


aws ssh instance
connecting to aws instance with putty
ec2 putty
how do you use putty with aws instance
access aws using putty
aws key file putty puttygen
aws putty
aws putty ppk pem
aws puttygen
connect to aws instance with putty

Display Today's (Current) Date Dynamically in HTML Pages

The Easy Way

<script language="javascript">
<!--
document.write(Date());
-->
</script>


The easy way provides date, time and timezone information. If you want to display the date only, the following way will do that.

The Hard Way

<script language="javascript">
<!--
Today = new Date();

TodayDay = Today.getDate();
TodayMon = Today.getMonth();
TodayYear = Today.getYear();
if (TodayYear < 2000) TodayYear += 1900;

if (TodayMon == 0) { TodayMonth = "January"; }

else if (TodayMon == 1) { TodayMonth = "February"; }
else if (TodayMon == 2) { TodayMonth = "March"; }
else if (TodayMon == 3) { TodayMonth = "April"; }
else if (TodayMon == 4) { TodayMonth = "May"; }
else if (TodayMon == 5) { TodayMonth = "June"; }
else if (TodayMon == 6) { TodayMonth = "July"; }

else if (TodayMon == 7) { TodayMonth = "August"; }
else if (TodayMon == 8) { TodayMonth = "September"; }
else if (TodayMon == 9) { TodayMonth = "October"; }
else if (TodayMon == 10) { TodayMonth = "November"; }
else if (TodayMon == 11) { TodayMonth = "December"; }
else { TodayMonth = TodayMon; }

document.write(TodayMonth + " " + TodayDay + ", " + TodayYear);

-->
</script>

How to recover missing, lost, or deleted files from Windows XP, Vista, Server 2003 and 2008 and Windows 7 as well as Apple Macs

Before reviewing the below recommendations and suggestions, verify that the files have actually been deleted; in some cases the files may have simply been moved. You can search the hard disk drive for the files you believe to be missing by running find or search on the computer.

Recover file from backup
If the file has been backed up to floppy disk or other medium it is recommended that the file be restored from that backup if the file cannot be found.

Restore from Recycling Bin or Trash
If you are running Apple MacOS, Microsoft Windows 95, NT, 98, 2000, ME, XP, Vista, or later operating system and the file has been recently deleted it is possible that the file may still be in the Trash or Recycle Bin. If present within this area it can be recovered.

Download freeware program and/or purchase a program
Below is a list of freeware file recovery programs that can be used freely to recover lost data.
PC Inspector File Recover
Restoration
Recuva
Undelete Plus
FreeUndelete
Photorec

In addition to the above freeware programs there are also several companies who have created programs designed to recover your lost data. For example, PowerQuest makes the utility Drive Image that in some cases can be used to recover data from a hard drive.

Utilize a service from a company that specializes in recovering lost data
Utilize the service of a local data recovery company or an out of state data recovery company. One word of caution is that these services can sometimes be very expensive. It is only recommended they be used if the data is extremely important. Below is a listing of a few major data recovery companies.
Action Front Data Recovery
CBL Data Recovery Technologies Inc.
Doctor Byte
DriveSavers Data Recovery
Lazarus Data Recovery
Ontrack
Virtual Data Recovery
Stellar Data Recovery
DataCent Professional Data Recovery

There are also several companies that specialize in the service of recovering files or documents that are password protected. Below is a listing of some of the companies that provide this service.

Passwordcrackers
Passwordservices.com
Password Recovery software

How to recover emails, folders or public folders in Outlook

How to recover emails, folders or public folders in Outlook

1. Select parent folder of deleted item by clicking on to it and highlighting it.
2. Select Tools at top
3. Select Recover Deleted Item Tool
4. Right click item to restore and click restore
5. Confirm restoration

Exchange 2007 OWA Virtual Directory Creation

HOW TO CREATE OWA Virtual Directory in Exchange 2007 (using MSH)
========================================================================================
New-OWAVirtualDirectory -OwaVersion:Exchange2007 -Name "owa" -WebSite "Default Web Site"

New-OWAVirtualDirectory -OwaVersion:Exchange2007 -Name "owa" -WebSite "Exchange.1701media.com"


OUTPUT:

Name Server OwaVersion
---- ------ ----------
owa (Default Web Site) 1701DC01 Exchange2007

Linux local content backup and rotation script

### Script by jim ballowe - content.sh can be put into
### /etc/cron.dailly on a RH linux box once complete
### and will backup to TARGET location on local filesystem

### Define variables for naming the final backup file
DATE=`date +%Y%m%d-%H%M` # Datestamp e.g 20080109-2200
DOW=`date +%A` # Day of the week e.g. Monday
DNOW=`date +%u` # Day number of the week 1 to 7 where 1 represents Monday
DOM=`date +%d` # Date of the Month e.g. 27
M=`date +%B` # Month e.g January
W=`date +%V` # Week Number e.g 37
VER=2.5 # Version Number

SOURCE=/var/www/html ### source directory being backed up
TARGET=/var/backup ### target where backups will live
AGE=15 ### number days of backup to keep

### TEST ECHO OF STRINGS
# echo Date = "$DATE"
# echo Source = "$SOURCE"
# echo Target = "$TARGET"
# echo Age = "$AGE"

### Search SOURCE for all files last modified AGE or more days ago
### executes a recursive forced (-rf) remove (rm) on those files
### The "{}" (curly braces) is placeholder for exec to use where it will put filenames
### The "\;" tells exec that's the end of the statement.
### Replace "rm -rf" with "ls -la" to get a list of all the files that would be removed
### If you want to remove files with specific names or extensions use the "-name" argument.

### USE THIS TO REMOVE FILES
find "$TARGET" -mtime +"$AGE" -type f -exec rm -rf {} \;

### USE TO TEST THE FIND LOGIC
# find "$TARGET" -mtime +"$AGE" -type f -exec ls -alh {} \;


# tar up the content in the backup directory
/bin/tar -cvf "$TARGET"/"$DATE"_cvsroot.tar "$SOURCE"

# compress the tar file
/bin/gzip -f "$TARGET"/"$DATE"_cvsroot.tar

### Once it works, create symbolic link to /root/bin/backup.sh in /etc/cron.daily
# ln -s /etc/cron.daily/backup.sh /root/bin/backup.sh

# move the tar file to another location (if necessary)
# mv /var/backup/content/"$DATE"_content.tar.gz /mnt/backup/content/"$DATE"_content.tar.gz

Lefthand SAN Remote Access

To access the iLo port on a Lefthand NSM 2120 using the HP DL320S hardware use the following credentials.

username - sanmon
password - sanmon

https://nodeIP:2381

Thursday, July 30, 2009

MySQL Crib Sheet Cheat Sheet

To login (from unix shell) use -h only if needed.
[mysql dir]/bin/mysql -h hostname -u root -p

Create a database on the sql server.
create database [databasename];

List all databases on the sql server.
show databases;

Switch to a database.
use [db name];

To see all the tables in the db.
show tables;

To see database's field formats.
describe [table name];

To delete a db.
drop database [database name];

To delete a table.
drop table [table name];

Show all data in a table.
SELECT * FROM [table name];

Returns the columns and column information pertaining to the designated table.
show columns from [table name];

Show certain selected rows with the value "whatever".
SELECT * FROM [table name] WHERE [field name] = "whatever";

Show all records containing the name "Bob" AND the phone number '3444444'.
SELECT * FROM [table name] WHERE name = "Bob" AND phone_number = '3444444';

Show all records not containing the name "Bob" AND the phone number '3444444' order by the phone_number field.
SELECT * FROM [table name] WHERE name != "Bob" AND phone_number = '3444444' order by phone_number;

Show all records starting with the letters 'bob' AND the phone number '3444444'.
SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number = '3444444';

Use a regular expression to find records. Use "REGEXP BINARY" to force case-sensitivity. This finds any record beginning with a.
SELECT * FROM [table name] WHERE rec RLIKE "^a$";

Show unique records.
SELECT DISTINCT [column name] FROM [table name];

Show selected records sorted in an ascending (asc) or descending (desc).
SELECT [col1],[col2] FROM [table name] ORDER BY [col2] DESC;

Return number of rows.
SELECT COUNT(*) FROM [table name];

Sum column.
SELECT SUM(*) FROM [table name];

Join tables on common columns.
select lookup.illustrationid, lookup.personid,person.birthday from lookup left join person on lookup.personid=person.personid=statement to join birthday in person table with primary illustration id;

Switch to the mysql db. Create a new user.
INSERT INTO [table name] (Host,User,Password) VALUES('%','user',PASSWORD('password'));

Change a users password.(from unix shell).
[mysql dir]/bin/mysqladmin -u root -h hostname.blah.org -p password 'new-password';

Change a users password.(from MySQL prompt).
SET PASSWORD FOR 'user'@'hostname' = PASSWORD('passwordhere');

Allow the user "bob" to connect to the server from localhost using the password "passwd"
grant usage on *.* to bob@localhost identified by 'passwd';

Give user privilages for a db.
grant all privileges on databasename.* to username@localhost;

To update info already in a table.
UPDATE [table name] SET Select_priv = 'Y',Insert_priv = 'Y',Update_priv = 'Y' where [field name] = 'user';

Delete a row(s) from a table.
DELETE from [table name] where [field name] = 'whatever';

Update database permissions/privilages.
FLUSH PRIVILEGES;

Delete a column.
alter table [table name] drop column [column name];

Add a new column to db.
alter table [table name] add column [new column name] varchar (20);

Change column name.
alter table [table name] change [old column name] [new column name] varchar (50);

Make a unique column so you get no dupes.
alter table [table name] add unique ([column name]);

Make a column bigger.
alter table [table name] modify [column name] VARCHAR(3);

Delete unique from table.
alter table [table name] drop index [colmn name];

Load a CSV file into a table.
LOAD DATA INFILE '/tmp/filename.csv' replace INTO TABLE [table name] FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (field1,field2,field3);

Dump all databases for backup. Backup file is sql commands to recreate all db's.
[mysql dir]/bin/mysqldump -u root -ppassword --opt >/tmp/alldatabases.sql

Dump one database for backup.
[mysql dir]/bin/mysqldump -u username -ppassword --databases databasename >/tmp/databasename.sql

Dump a table from a database.
[mysql dir]/bin/mysqldump -c -u username -ppassword databasename tablename > /tmp/databasename.tablename.sql

Restore database (or database table) from backup.
[mysql dir]/bin/mysql -u username -ppassword databasename < /tmp/databasename.sql

Create Table Example 1.
CREATE TABLE [table name] (firstname VARCHAR(20), middleinitial VARCHAR(3), lastname VARCHAR(35),suffix VARCHAR(3),officeid VARCHAR(10),userid VARCHAR(15),username VARCHAR(8),email VARCHAR(35),phone VARCHAR(25), groups VARCHAR (15),datestamp DATE,timestamp time,pgpemail VARCHAR(255));

Create Table Example 2.
create table [table name] (personid int(50) not null auto_increment primary key,firstname varchar(35),middlename varchar(50),lastname varchar(50) default 'bato');

Here’s a list of the commands to control mysql:
service mysqld restart
service mysqld status
service mysqld stop
service mysqld start

Wednesday, July 29, 2009

HowTo: Backtrack 4 (Beta) Hard Drive Installation

UPDATE: See BackTrack 4 Pre-Release Hard Disk Install for updated instructions for the newer BackTrack 4 Beta.

Backtrack 4 does not contain an installer, so we wrote this step by step guide based on muts cookbook on how to install Backtrack 4 on our hard disk drive.

Step 1 - Creating the partitions
First we will need to create three partitions to be able to install backtrack on our hard disk drive. We will need boot, swap and root partitions to be created. (We can still create 2 partitions and install the boot inside the root partition)
fdisk /dev/sda


Creating the partitions

Enter 'n' for new partition.
Enter 'p' for primary.
Partition number '1'.
Press Enter to accept default First cylinder.
Enter Size: '+256M'

Enter 'n' for new partition.
Enter 'p' for primary.
Partition number '2'.
Press Enter to accept default First cylinder.
Enter Size: '+1024M'

Enter 'n' for new partition.
Enter 'p' for primary.
Partition number '3'.
Press Enter to accept default First cylinder.
Enter Size: '+32G' NOTE: I used 32GB, you can use a size you prefer.



NOTES:
- Select 'p' to print the partition table and verify newly created partitions.

Type 'w' to write changes and exit fdisk.

Activate Boot Partition & Specify Swap



Step 2 - Format the file systems
I formated my file system with mkreiserfs for root partition, ext2 for boot and swap for the swap partition.
mkfs.ext2 /dev/sda1



prepare swap using:
mkswap /dev/sda2
swapon /dev/sda2


mkfs.reiserfs /dev/sda3


Step 3 - Mount and Copy Directories

Now its time to copy over the backtrack files to the hard drive and configure it to run the backtrack on boot.

Mount and Copy the Directory Structure using:
mkdir /mnt/bt4
mount /dev/sda3 /mnt/bt4/
mkdir /mnt/bt4/boot
mount /dev/sda1 /mnt/bt4/boot/
cp --preserve -R /{bin,dev,home,pentest,root,usr,boot,etc,lib,opt,sbin,var} /mnt/bt4/
mkdir /mnt/bt4/{mnt,tmp,proc,sys}
chmod 1777 /mnt/bt4/tmp/
mount -t proc proc /mnt/bt4/proc/
mount -o bind /dev /mnt/bt4/dev/
chroot /mnt/bt4/ /bin/bash



NOTE: The copy operation will take some time so be patient until it finish

Step 4 - Configure Bootloader
nano /etc/lilo.conf


We will need to configure /etc/lilo.conf and define the boot and root partition so we will be able to boot into backtrack. In case we do not correctly define the root partition we will get an error “Kernel panic: no init found”.

Configure fstab



Edit /etc/fstab and append the following lines:

/dev/sda3 / reiserfs defaults 0 0 # AutoUpdate
/dev/sda2 none swap sw 0 0

Execute lilo -v

NOTE: lilo may not be installed, if not make sure you are connected to the Internet (use ifconfig to view IP address, etc., and dhclient to renew IP address if necessary). Once connected run the following to install lilo.
apt-get install lilo
You will receive the message, "LILO configuration
It seems to be your first LILO installation. It is absolutely necessary to run liloconfig(8) when you complete this process and execute /sbin/lilo after this.
LILO won't work if you don't do this.

So, select OK then run liloconfig, then /sbin/lilo. If you get the message, "fatal: cannot open: /etc/lilo.conf" you are basically screwed and need to search for a solution.



Execute lilo -v and reboot

Reference: http://www.offensive-security.com/documentation/bt4install.pdf

BackTrack links
Keywords:

install bt4 final to the hard disk hdd
backtrack 4 no clients
make persistent hard drive install
install backtrack 4 from usb to hard drive
bt4 manual
backtrack 4 hdd image

Linux Command: iwconfig

NAME

iwconfig - configure a wireless network interface

SYNOPSIS

iwconfig [interface]
iwconfig interface [essid X] [nwid N] [mode M] [freq F]
[channel C][sens S ][ap A ][nick NN ]
[rate R] [rts RT] [frag FT] [txpower T]
[enc E] [key K] [power P] [retry R]
[commit]
iwconfig --help
iwconfig --version

DESCRIPTION

Iwconfig is similar to ifconfig(8), but is dedicated to the wireless interfaces. It is used to set the parameters of the network interface which are specific to the wireless operation (for Example: the frequency). Iwconfig may also be used to display those parameters, and the wireless statistics (extracted from /proc/net/wireless).

All these parameters and statistics are device dependent. Each driver will provide only some of them depending on hardware support, and the range of values may change. Please refer to the man page of each device for details.


PARAMETERS

essid
Set the ESSID (or Network Name - in some products it may also be called Domain ID). The ESSID is used to identify cells which are part of the same virtual network. As opposed to the AP Address or NWID which define a single cell, the ESSID defines a group of cells connected via repeaters or infrastructure, where the user may roam transparently. With some cards, you may disable the ESSID checking (ESSID promiscuous) with off or any (and on to reenable it). If the ESSID of your network is one of the special keywords (off, on or any), you should use -- to escape it.
Examples:
iwconfig eth0 essid any
iwconfig eth0 essid "My Network"
iwconfig eth0 essid -- "ANY"

nwid/domain
Set the Network ID (in some products it may also be called Domain ID). As all adjacent wireless networks share the same medium, this parameter is used to differenciate them (create logical colocated networks) and identify nodes belonging to the same cell. This parameter is only used for pre-802.11 hardware, the 802.11 protocol uses the ESSID and AP Address for this function. With some cards, you may disable the Network ID checking (NWID promiscuous) with off (and on to reenable it).
Examples:
iwconfig eth0 nwid AB34
iwconfig eth0 nwid off

freq/channel
Set the operating frequency or channel in the device. A value below 1000 indicates a channel number, a value greater than 1000 is a frequency in Hz. You may append the suffix k, M or G to the value (for example, "2.46G" for 2.46 GHz frequency), or add enough ’0’. Channels are usually numbered starting at 1, and you may use iwlist(8) to get the total number of channels, list the available frequencies, and display the current frequency as a channel. Depending on regulations, some frequencies/channels may not be available. When using Managed mode, most often the Access Point dictates the channel and the driver may refuse the setting of the fre-
quency. In Ad-Hoc mode, the frequency setting may only be used at initial cell creation, and may be ignored when joining an existing cell. You may also use off or auto to let the card pick up the best channel (when supported).
Examples:
iwconfig eth0 freq 2422000000
iwconfig eth0 freq 2.422G
iwconfig eth0 channel 3
iwconfig eth0 channel auto

sens
Set the sensitivity threshold. This is the lowest signal level for which the hardware will consider receive packets usable. Positive values are assumed to be the raw value used by the hardware or a percentage, negative values are assumed to be dBm. Depending on the hardware implementation, this parameter may control various functions. This parameter may control the receive threshold, the lowest signal level for which the hardware attempts packet reception, signals weaker than this are ignored. This may also controls the defer threshold, the lowest signal level for which the hardware considers the channel busy. Proper setting of those thresholds prevent the card to waste time receiving background noise. Modern designs seems to control those thresholds automatically. On modern cards, this parameter may control handover/roaming threshold, the lowest signal level for which the hardware remains associated with the current Access Point. When the signal level goes below this threshold the card starts looking for a new/better Access Point.
Example:
iwconfig eth0 sens -80

mode
Set the operating mode of the device, which depends on the network topology. The mode can be Ad-Hoc (network composed of only one cell and without Access Point), Managed (node connects to a network composed of many Access Points, with roaming), Master (the node is the synchronisation master or acts as an Access Point), Repeater (the node forwards packets between other wireless nodes), Secondary (the node acts as a backup master/repeater), Monitor (the node is not associated with any cell and passively monitor all packets on the frequency) or Auto.
Example:
iwconfig eth0 mode Managed
iwconfig eth0 mode Ad-Hoc

ap
Force the card to register to the Access Point given by the address, if it is possible. When the quality of the connection goes too low, the driver may revert back to automatic mode (the card selects the best Access Point in range). You may also use off to re-enable automatic mode without changing the current Access Point, or you may use any or auto to force the card to reassociate with the currently best Access Point.
Example:
iwconfig eth0 ap 00:60:1D:01:23:45
iwconfig eth0 ap any
iwconfig eth0 ap off

nick[name]
Set the nickname, or the station name. Some 802.11 products do define it, but this is not used as far as the protocols (MAC, IP, TCP) are concerned and completely useless as far as configuration goes. Only some diagnostic tools may use it.
Example:
iwconfig eth0 nickname "My Linux Node"

rate/bit[rate]
For cards supporting multiple bit rates, set the bit-rate in b/s. The bit-rate is the speed at which bits are transmitted over the medium, the user speed of the link is lower due to medium sharing and various overhead.

You may append the suffix k, M or G to the value (decimal multiplier : 10^3, 10^6 and 10^9 b/s), or add enough ’0’. Values below 1000 are card specific, usually an index in the bit-rate list. Use auto to select automatic bit-rate mode (fallback to lower rate on noisy channels), which is the default for most cards, and fixed to revert back to fixed setting. If you specify a bit-rate value and append auto, the driver will use all bitrates lower and equal than this value.
Examples :
iwconfig eth0 rate 11M
iwconfig eth0 rate auto
iwconfig eth0 rate 5.5M auto

rts[_threshold]
RTS/CTS adds a handshake before each packet transmission to make sure that the channel is clear. This adds overhead, but increases performance in case of hidden nodes or a large number of active nodes. This parameter sets the size of the smallest packet for which the node sends RTS ; a value equal to the maximum packet size disables the mechanism. You may also set this parameter to auto, fixed or off.
Examples :
iwconfig eth0 rts 250
iwconfig eth0 rts off

frag[mentation_threshold]
Fragmentation allows to split an IP packet in a burst of smaller fragments transmitted on the medium. In most cases this adds overhead, but in a very noisy environment this reduces the error penalty and allow packets to get through interference bursts. This parameter sets the maximum fragment size ; a value equal to the maximum packet size disables the mechanism. You may also set this parameter to auto, fixed or off.
Examples :
iwconfig eth0 frag 512
iwconfig eth0 frag off

key/enc[ryption]
Used to manipulate encryption or scrambling keys and security mode.

To set the current encryption key, just enter the key in hex digits as XXXX-XXXX-XXXX-XXXX or XXXXXXXX. To set a key other than the current key, prepend or append [index] to the key itself (this won’t change which is the active key). You can also enter the key as an ASCII string by using the s: prefix.

Passphrase is currently not supported. To change which key is the currently active key, just enter [index] (without entering any key value).

off and on disable and reenable encryption.

The security mode may be open or restricted, and its meaning depends on the card used. With most cards, in open mode no authentication is used and the card may also accept non-encrypted sessions, whereas in restricted mode only encrypted sessions are accepted and the card will use authentication if available.

If you need to set multiple keys, or set a key and change the active key, you need to use multiple key directives. Arguments can be put in any order, the last one will take precedence.
Examples :
iwconfig eth0 key 0123-4567-89
iwconfig eth0 key [3] 0123-4567-89
iwconfig eth0 key s:password [2]
iwconfig eth0 key [2]
iwconfig eth0 key open
iwconfig eth0 key off
iwconfig eth0 key restricted [3] 0123456789
iwconfig eth0 key 01-23 key 45-67 [4] key [4]

power
Used to manipulate power management scheme parameters and mode. To set the period between wake ups, enter period ???value???. To set the timeout before going back to sleep, enter timeout ???value???. You can also add the min and max modifiers. By default, those values are in seconds, append the suffix m or u to specify values in milliseconds or microseconds. Sometimes, those values are without units (number of beacon periods, dwell or similar).

off and on disable and reenable power management. Finally, you may set the power management mode to all (receive all packets), unicast (receive unicast packets only, discard multicast and broadcast) and multicast (receive multicast and broadcast only, discard unicast packets).
Examples :
iwconfig eth0 power period 2
iwconfig eth0 power 500m unicast
iwconfig eth0 power timeout 300u all
iwconfig eth0 power off
iwconfig eth0 power min period 2 power max period 4

txpower
For cards supporting multiple transmit powers, sets the transmit power in dBm. If W is the power in Watt, the power in dBm is P = 30 + 10.log(W). If the value is postfixed by mW, it will be automatically converted to dBm.

In addition, on and off enable and disable the radio, and auto and fixed enable and disable power control (if those features are available).
Examples :
iwconfig eth0 txpower 15
iwconfig eth0 txpower 30mW
iwconfig eth0 txpower auto
iwconfig eth0 txpower off

retry
Most cards have MAC retransmissions, and some allow to set the
behaviour of the retry mechanism.
To set the maximum number of retries, enter limit ???value???. This
is an absolute value (without unit). To set the maximum length
of time the MAC should retry, enter lifetime ???value???. By
defaults, this value in in seconds, append the suffix m or u to
specify values in milliseconds or microseconds.

You can also add the min and max modifiers. If the card supports automatic mode, they define the bounds of the limit or lifetime. Some other cards define different values depending on packet size, for example in 802.11 min limit is the short retry limit (non RTS/CTS packets).
Examples :
iwconfig eth0 retry 16
iwconfig eth0 retry lifetime 300m
iwconfig eth0 retry min limit 8

commit
Some cards may not apply changes done through Wireless Extensions immediately (they may wait to aggregate the changes or apply it only when the card is brought up via ifconfig). This command (when available) forces the card to apply all pending changes. This is normally not needed, because the card will eventually apply the changes, but can be useful for debugging.


DISPLAY

For each device which supports wireless extensions, iwconfig will display the name of the MAC protocol used (name of device for proprietary protocols), the ESSID (Network Name), the NWID, the frequency (or channel), the sensitivity, the mode of operation, the Access Point address, the bit-rate, the RTS threshold, the fragmentation threshold, the encryption key and the power management settings (depending on availability).

The parameters displayed have the same meaning and values as the parameters you can set, please refer to the previous part for a detailed explanation of them. Some parameters are only displayed in short/abbreviated form (such as encryption). You may use iwlist(8) to get all the details. Some parameters have two modes (such as bitrate). If the value is prefixed by ‘=’, it means that the parameter is fixed and forced to that value, if it is prefixed by ‘:’, the parameter is in automatic mode and the current value is shown (and may change).

Access Point/Cell
An address equal to 00:00:00:00:00:00 means that the card failed to associate with an Access Point (most likely a configuration issue). The Access Point parameter will be shown as Cell in ad-hoc mode (for obvious reasons), but otherwise works the same.

If /proc/net/wireless exists, iwconfig will also display its content.
Note that those values will depend on the driver and the hardware specifics, so you need to refer to your driver documentation for proper interpretation of those values.

Link quality
Overall quality of the link. May be based on the level of contention or interference, the bit or frame error rate, how good the received signal is, some timing synchronisation, or other hardware metric. This is an aggregate value, and depends totally on the driver and hardware.

Signal level
Received signal strength (RSSI - how strong the received signal is). May be arbitrary units or dBm, iwconfig uses driver meta information to interpret the raw value given by /proc/net/wireless and display the proper unit or maximum value (using 8 bit arithmetic). In Ad-Hoc mode, this may be undefined and you should use iwspy.

Noise level
Background noise level (when no packet is transmitted). Similar comments as for Signal level.

Rx invalid nwid
Number of packets received with a different NWID or ESSID. Used to detect configuration problems or adjacent network existence (on the same frequency).

Rx invalid crypt
Number of packets that the hardware was unable to decrypt. This can be used to detect invalid encryption settings.

Rx invalid frag
Number of packets for which the hardware was not able to prop erly re-assemble the link layer fragments (most likely one was missing).

Tx excessive retries
Number of packets that the hardware failed to deliver. Most MAC protocols will retry the packet a number of times before giving up.

Invalid misc
Other packets lost in relation with specific wireless operations.

Missed beacon
Number of periodic beacons from the Cell or the Access Point we have missed. Beacons are sent at regular intervals to maintain the cell coordination, failure to receive them usually indicates that the card is out of range.


FILES

/proc/net/wireless


SEE ALSO

ifconfig, iwspy, iwlist, iwevent, iwpriv, wireless.


Reference: http://linuxcommand.org/man_pages/iwconfig8.html

Renew IP in Linux Using dhclient

dhclient -r eth0
dhclient eth0

login script vbscript printer mappings

Create a file called file.vbs, then copy and past the content below
the pound signs w/ appropriate information to map network printers
Reference it in the user account after placing it under %NETLOGON%
##############################################

on error resume next

Set WshNetwork = Wscript.CreateObject("Wscript.Network")

wshNetwork.AddWindowsPrinterConnection "\\server\printershare"

WSCript.Quit

Securing Linux & PHP

MOD_REWRITE OVERVIEW
http://www.sitepoint.com/article/guide-url-rewriting
http://www.jeffdarlington.com/tag/mod_rewrite/

LINUX SECURE CONFIG
http://aymanh.com/tips-to-secure-linux-workstation

PHP SECURE CONFIG
http://aymanh.com/checklist-for-securing-php-configuration

MOD_REWRITE SCRIPTS FOR APACHE
SIMPLEST SET OF RULES
==================================================================



#Turn on mod_rewrite
RewriteEngine On
RewriteOptions inherit
RewriteLog "/var/log/httpd/rewrite_log"

# Prevent harmful binary execution through injection
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)chmod(.*) [OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)chown(.*) [OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)wget(.*) [OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)cmd(.*) [OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)cd%20(.*) [OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)scp(.*) [OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)curl(.*) [OR]

# Disable TRACE & TRACK methods
RewriteCond %{REQUEST_METHOD} TRACE [OR]
RewriteCond %{REQUEST_METHOD} TRACK [OR]

# Redirect objectional persons to the bit bucket
RewriteRule ^.* - [F,L]








#Turn on mod_rewrite
RewriteEngine On
RewriteOptions inherit
RewriteLog w3g_rewrite_log





#Disable command line hacks via XSS scripting w/ vulnerable PHP options & includes
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)chmod(.*) [OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)chown(.*) [OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)wget(.*) [OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)cmd(.*) [OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)cd%20(.*) [OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)scp(.*) [OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)curl(.*) [OR]

#Disable TRACE & TRACK methods
RewriteCond %{REQUEST_METHOD} TRACE [OR]
RewriteCond %{REQUEST_METHOD} TRACK [OR]

#Other hack prevention, mostly windows-based
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)/winnt/system32/(.*) [NC,OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)/winnt/system/(.*) [NC,OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)/windows/system32/(.*) [NC,OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)/windows/system/(.*) [NC,OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)/cmd\.exe[$|\?(.*)] [NC,OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)/scripts/root.exe[$|\?(.*)] [NC,OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)/msadc/root\.exe[$|\?(.*)] [NC,OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)\\\.\.(.*) [NC,OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)/admin\.dll[$|\?(.*)] [NC,OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)/msadcs\.dll[$|\?(.*)] [NC,OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)/ext\.dll[$|\?(.*)] [NC,OR]
RewriteCond %{REQUEST_URI} (.*)/\.(.*) [NC,OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)/php\.exe[$|\?(.*)] [NC,OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} (.*)\|(.*) [OR]
RewriteCond %{REQUEST_URI} (.{255,}) [OR]
RewriteCond %{QUERY_STRING} (.{127,}) [OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} [\x00-\x1f]+ [OR]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} [\x7f|\xff]+

#Rewrite offending persons to forbidden page
RewriteRule (.*) [F]






# Stop bad bots/spiders
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} ^BlackWidow [OR]
RewriteCond %{HTTP_USER_AGENT} ^Bot\ mailto:craftbot@yahoo.com [OR]
RewriteCond %{HTTP_USER_AGENT} ^ChinaClaw [OR]
RewriteCond %{HTTP_USER_AGENT} ^Custo [OR]
RewriteCond %{HTTP_USER_AGENT} ^DISCo [OR]
RewriteCond %{HTTP_USER_AGENT} ^Download\ Demon [OR]
RewriteCond %{HTTP_USER_AGENT} ^eCatch [OR]
RewriteCond %{HTTP_USER_AGENT} ^EirGrabber [OR]
RewriteCond %{HTTP_USER_AGENT} ^EmailSiphon [OR]
RewriteCond %{HTTP_USER_AGENT} ^EmailWolf [OR]
RewriteCond %{HTTP_USER_AGENT} ^Express\ WebPictures [OR]
RewriteCond %{HTTP_USER_AGENT} ^ExtractorPro [OR]
RewriteCond %{HTTP_USER_AGENT} ^EyeNetIE [OR]
RewriteCond %{HTTP_USER_AGENT} ^FlashGet [OR]
RewriteCond %{HTTP_USER_AGENT} ^GetRight [OR]
RewriteCond %{HTTP_USER_AGENT} ^GetWeb! [OR]
RewriteCond %{HTTP_USER_AGENT} ^Go!Zilla [OR]
RewriteCond %{HTTP_USER_AGENT} ^Go-Ahead-Got-It [OR]
RewriteCond %{HTTP_USER_AGENT} ^GrabNet [OR]
RewriteCond %{HTTP_USER_AGENT} ^Grafula [OR]
RewriteCond %{HTTP_USER_AGENT} ^HMView [OR]
RewriteCond %{HTTP_USER_AGENT} HTTrack [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Image\ Stripper [OR]
RewriteCond %{HTTP_USER_AGENT} ^Image\ Sucker [OR]
RewriteCond %{HTTP_USER_AGENT} Indy\ Library [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^InterGET [OR]
RewriteCond %{HTTP_USER_AGENT} ^Internet\ Ninja [OR]
RewriteCond %{HTTP_USER_AGENT} ^JetCar [OR]
RewriteCond %{HTTP_USER_AGENT} ^JOC\ Web\ Spider [OR]
RewriteCond %{HTTP_USER_AGENT} ^larbin [OR]
RewriteCond %{HTTP_USER_AGENT} ^LeechFTP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Mass\ Downloader [OR]
RewriteCond %{HTTP_USER_AGENT} ^MIDown\ tool [OR]
RewriteCond %{HTTP_USER_AGENT} ^Mister\ PiX [OR]
RewriteCond %{HTTP_USER_AGENT} ^Navroad [OR]
RewriteCond %{HTTP_USER_AGENT} ^NearSite [OR]
RewriteCond %{HTTP_USER_AGENT} ^NetAnts [OR]
RewriteCond %{HTTP_USER_AGENT} ^NetSpider [OR]
RewriteCond %{HTTP_USER_AGENT} ^Net\ Vampire [OR]
RewriteCond %{HTTP_USER_AGENT} ^NetZIP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Octopus [OR]
RewriteCond %{HTTP_USER_AGENT} ^Offline\ Explorer [OR]
RewriteCond %{HTTP_USER_AGENT} ^Offline\ Navigator [OR]
RewriteCond %{HTTP_USER_AGENT} ^PageGrabber [OR]
RewriteCond %{HTTP_USER_AGENT} ^Papa\ Foto [OR]
RewriteCond %{HTTP_USER_AGENT} ^pavuk [OR]
RewriteCond %{HTTP_USER_AGENT} ^pcBrowser [OR]
RewriteCond %{HTTP_USER_AGENT} ^RealDownload [OR]
RewriteCond %{HTTP_USER_AGENT} ^ReGet [OR]
RewriteCond %{HTTP_USER_AGENT} ^SiteSnagger [OR]
RewriteCond %{HTTP_USER_AGENT} ^SmartDownload [OR]
RewriteCond %{HTTP_USER_AGENT} ^SuperBot [OR]
RewriteCond %{HTTP_USER_AGENT} ^SuperHTTP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Surfbot [OR]
RewriteCond %{HTTP_USER_AGENT} ^tAkeOut [OR]
RewriteCond %{HTTP_USER_AGENT} ^Teleport\ Pro [OR]
RewriteCond %{HTTP_USER_AGENT} ^VoidEYE [OR]
RewriteCond %{HTTP_USER_AGENT} ^Web\ Image\ Collector [OR]
RewriteCond %{HTTP_USER_AGENT} ^Web\ Sucker [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebAuto [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebCopier [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebFetch [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebGo\ IS [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebLeacher [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebReaper [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebSauger [OR]
RewriteCond %{HTTP_USER_AGENT} ^Website\ eXtractor [OR]
RewriteCond %{HTTP_USER_AGENT} ^Website\ Quester [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebStripper [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebWhacker [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebZIP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Wget [OR]
RewriteCond %{HTTP_USER_AGENT} ^Widow [OR]
RewriteCond %{HTTP_USER_AGENT} ^WWWOFFLE [OR]
RewriteCond %{HTTP_USER_AGENT} ^Xaldon\ WebSpider [OR]
RewriteCond %{HTTP_USER_AGENT} ^Zeus
RewriteRule ^.* - [F,L]

Tuesday, July 28, 2009

Changing hostname in Linux

Change hostname linux

If your change is only temporary, or you want to make it without rebooting, you just need to use the hostname command, which can be found at /bin/hostname. Running it without arguments just outputs the current hostname. To change it, su to root and run hostname newhostname.

You need to look at the value for hostname in /etc/sysconfig/network

The contents will look something like this:
NETWORKING=yes
HOSTNAME=oldname
GATEWAY=10.10.1.1

Change the HOSTNAME= parameter value to the proper hostname
NETWORKING=yes
HOSTNAME=fancynewname
GATEWAY=10.10.1.1

...and save the file

Make sure that /etc/hosts has the new hostname properly referenced in it

Then restart the network service (this will not take the box down)
service network restart

If that doesn't do it, you can modify /proc/sys/kernel/hostname to modify it on the fly.

If that doesn't do it, reboot the machine after making those changes and it should come back up with the new hostname.

Linux SMTP Test Script

Must telnet to port 25 of the mail server first
---------------------------------------------------

ehlo test

mail from:

rcpt to:

data

subject: test via telnet

test via telnet to jim b - should create a log entry

.

Creating Client SSL VPN on Cisco ASAs

Introduction

This document how to allow remote access VPN connections to the ASA from the Cisco AnyConnect 2.0 client.
Prerequisites
Requirements

Ensure that you meet these requirements before you attempt this configuration:

*

Basic ASA configuration that runs software version 8.0
*

ASDM 6.0(2)

Components Used

The information in this document is based on these software and hardware versions:

* Cisco ASA 8.0(2), ASDM 6.0 (2)
* Cisco AnyConnect 2.0
Background Information

The Cisco AnyConnect 2.0 client is an SSL-based VPN client. The AnyConnect client can be utilized and installed on a variety of operating systems, such as Windows 2000, XP, Vista, Linux (Multiple Distros) and MAC OS X. The AnyConnect client can be installed manually on the remote PC by the system administrator. It can also be loaded onto the security appliance and made ready for download to remote users. After the application is downloaded, it can automatically uninstall itself after the connection terminates, or it can remain on the remote PC for future SSL VPN connections. This example makes the AnyConnect client ready to download upon successful browser-based SSL authentication.

For more information on the AnyConnect 2.0 client, refer to AnyConnect 2.0 Release Notes.

Note: MS Terminal Services is not supported in conjunction with the AnyConnect client. You cannot RDP to a computer and then initiate an AnyConnect session. You cannot RDP to a client that is connected via AnyConnect.

Note: The first installation of AnyConnect requires the user to have admin rights (whether you use the standalone AnyConnect msi package or push the pkg file from the ASA). If the user does not have admin rights, a dialog box appears that states this requirement. Subsequent upgrades will not require the user that installed AnyConnect previously to have admin rights.


Configure
Step 1. Configure a Self-Issued Certificate

By default, the security appliance has a self-signed certificate that is regenerated every time the device is rebooted. You can purchase your own certificate from vendors, such as Verisign or EnTrust, or you can configure the ASA to issue an identity certificate to itself. This certificate remains the same even when the device is rebooted. Complete this step in order to generate a self-issued certificate that persists when the device is rebooted.

ASDM Procedure

1.

Click Configuration, and then click Remote Access VPN.
2.

Expand Certificate Management, and then choose Identity Certificates.
3.

Click Add, and then click the Add a new identity certificate radio button.
4.

Click New.
5.

In the Add Key Pair dialog box, click the Enter new key pair name radio button.
6.

Enter a name to identify the keypair.

This example uses sslvpnkeypair.
7.

Click Generate Now.
8.

In the Add Identity Certificate dialog box, ensure the newly created key pair is selected.
9.

For Certificate Subject DN, enter the fully qualified domain name (FQDN) that will be used to connect to the VPN terminating interface.

CN=sslvpn.cisco.com
10.

Click Advanced, and enter the FQDN used for the Certificate Subject DN field.

For example, FQDN: sslvpn.cisco.com
11.

Click OK.
12.

Check the Generate Self Signed Certificate check box, and click Add Certificate.
13.

Click OK.
14.

Click Configuration, and then click Remote Access VPN.
15.

Expand Advanced, and choose SSL Settings.
16.

In the Certificates area, choose the interface that will be used to terminate the SSL VPN (outside), and click Edit.
17.

In the Certificate drop-down list, choose the self-signed certificate that you generated earlier.
18.

Click OK, and then click Apply.


Step 2. Upload and Identify the SSL VPN Client Image

This document uses the AnyConnect SSL 2.0 client. You can obtain this client at the Cisco Software Download Website. A separate Anyconnect image is required for each operating system that remote users plan to use. For more information, refer to Cisco AnyConnect 2.0 Release Notes.

Once you obtain the AnyConnect client, complete these steps:

ASDM Procedure

1.

Click Configuration, and then click Remote Access VPN.
2.

Expand Network (Client) Access, and then expand Advanced.
3.

Expand SSL VPN, and choose Client Settings.
4.

In the SSL VPN Client Images area, click Add, and then click Upload.
5.

Browse to the location where you downloaded the AnyConnect client.
6.

Select the file, and click Upload File.

Once the client uploads, you receive a message that states the file was uploaded to flash successully.
7.

Click OK.

A dialog box appears to confirm that you want to use the newly uploaded image as the current SSL VPN client image.
8.

Click OK.
9.

Click OK, and then click Apply.
10.

Repeat the steps in this section for each operating system-specific Anyconnect package that you want to use.


Step 3. Enable Anyconnect Access

In order to allow the AnyConnect client to connect to the ASA, you must enable access on the interface that terminates SSL VPN connections. This example uses the outside interface in order to terminate Anyconnect connections.

ASDM Procedure

1.

Click Configuration, and then click Remote Access VPN.
2.

Expand Network (Client) Access, and then choose SSL VPN Connection Profiles.
3.

Check the Enable Cisco AnyConnect VPN Client check box.
4.

Check the Allow Access check box for the outside interface, and click Apply.


Step 4. Create a new Group Policy

A group policy specifies the configuration parameters that should be applied to clients when they connect. This example creates a group policy named SSLClientPolicy.

ASDM Procedure

1.

Click Configuration, and then click Remote Access VPN.
2.

Expand Network (Client) Access, and choose Group Policies.
3.

Click Add.
4.

Choose General, and enter SSLClientPolicy in the Name field.
5.

Uncheck the Address Pools Inherit check box.
6.

Click Select, and then click Add.

The Add IP Pool dialog box appears.
7.

Configure the address pool from an IP range that is not currently in use on your network.

This example uses these values:
*

Name: SSLClientPool
*

Starting IP Address: 192.168.25.1
*

Ending IP Address: 192.168.25.50
*

Subnet Mask: 255.255.255.0
8.

Click OK.
9.

Choose the newly created pool, and click Assign.
10.

Click OK, and then click More Options.
11.

Uncheck the Tunneling Protocols Inherit check box.
12.

Check SSL VPN Client.
13.

In the left pane, choose Servers.
14.

Uncheck the DNS Servers Inherit check box, and enter the IP address of the internal DNS server that the AnyConnect clients will use.

This example uses 192.168.50.5.
15.

Click More Options.
16.

Uncheck the Default Domain Inherit check box.
17.

Enter the domain used by your internal network. For example, tsweb.local .
18.

Click OK, and then click Apply.


Configure Access List Bypass for VPN Connections

When you enable this option, you allow the SSL/IPsec clients to bypass the interface access list.

ASDM Procedure

1.

Click Configuration, and then click Remote Access VPN.
2.

Expand Network (Client) Access, and then expand Advanced.
3.

Expand SSL VPN, and choose Bypass Interface Access List.
4.

Ensure the Enable inbound SSL VPN and IPSEC Sessions to bypass interface access lists check box is checked, and click Apply.


Step 6. Create a Connection Profile and Tunnel Group for the AnyConnect Client Connections

When VPN clients connect to the ASA, they connect to a connection profile or tunnel group. The tunnel group is used to define connection parameters for specific types of VPN connections, such as IPsec L2L, IPsec remote access, clientless SSL, and client SSL.

ASDM Procedure

1.

Click Configuration, and then click Remote Access VPN.
2.

Expand Network (Client) Access, and then expand SSL VPN.
3.

Choose Connection Profiles, and click Add.
4.

Choose Basic, and enter these values:
*

Name: SSLClientProfile
*

Authentication: LOCAL
*

Default Group Policy: SSLClientPolicy
5.

Ensure the SSL VPN Client Protocol check box is checked.
6.

In the left pane, expand Advanced, and choose SSL VPN.
7.

Under Connection Aliases, click Add, and enter a name to which users can associate their VPN connections. For example, SSLVPNClient.
8.

Click OK, and then click OK again.
9.

At the bottom of the ASDM window, check the Allow user to select connection, identified by alias in the table above at login page check box, and click Apply.


Step 7. Configure NAT Exemption for AnyConnect Clients

NAT exemption should be configured for any IP addresses or ranges you want to allow the SSL VPN clients to access. In this example, the SSL VPN clients need access to the internal IP 192.168.50.5 only.

Note: If NAT-control is not enabled, this step is not required. Use the show run nat-control command to verify. In order to verify through ASDM, click Configuration, click Firewall, and choose Nat Rules. If the Enable traffic through the firewall without address translation check box is checked, you can skip this step.

ASDM Procedure

1.

Click Configuration, and then click Firewall.
2.

Choose Nat Rules, and click Add.
3.

Choose Add NAT Exempt Rule, and enter these values:
*

Action: Exempt
*

Interface: inside
*

Source: 192.168.50.5
*

Destination: 192.168.25.0/24
*

NAT Exempt Direction: NAT Exempt outbound traffic from interface 'inside' to lower security interfaces (Default)
4.

Click OK, and then click Apply.


Step 8. Add Users to the Local Database

If you use local authentication (the default), you must define user names and passwords in the local database for user authentication.

ASDM Procedure

1.

Click Configuration, and then click Remote Access VPN.
2.

Expand AAA Setup, and choose Local Users.
3.

Click Add, and enter these values:
*

Username: matthewp
*

Password: p@ssw0rd
*

Confirm Password: p@ssw0rd
4.

Select the No ASDM, SSH, Telnet or Console Access radio button.
5.

Click OK, and then click Apply.
6.

Repeat this step for additional users, and then click Save.


Verify SSL VPN Client Connections

Use the show vpn-sessiondb svc command in order to verify connected SSL VPN clients.

ciscoasa(config-group-policy)#show vpn-sessiondb svc

Session Type: SVC

Username : matthewp Index : 6
Assigned IP : 192.168.25.1 Public IP : 172.18.12.111
Protocol : Clientless SSL-Tunnel DTLS-Tunnel
Encryption : RC4 AES128 Hashing : SHA1
Bytes Tx : 35466 Bytes Rx : 27543
Group Policy : SSLClientPolicy Tunnel Group : SSLClientProfile
Login Time : 20:06:59 UTC Tue Oct 16 2007
Duration : 0h:00m:12s
NAC Result : Unknown
VLAN Mapping : N/A VLAN : none

ciscoasa(config-group-policy)#

The vpn-sessiondb logoff name username command logs off users by user name. An Administrator Reset message is sent to the user when disconnected.

ciscoasa(config)#vpn-sessiondb logoff name matthewp
Do you want to logoff the VPN session(s)? [confirm]
INFO: Number of sessions with name "matthewp" logged off : 1

ciscoasa(config)#

Monday, July 27, 2009

Installing Backtrack 3 to a harddrive

I started with a clean drive, so you might have to manipulate your partition tables. I’m going to assume that you’re comfortable working with partition tables. If not, work on your google-fu.

Here are the steps I took to install Backtrack 3 on to my laptop harddrive

1. Boot system from Backtrack 3 CD.

2. Once booted, open a terminal and type cfdisk

3. Create these 3 partitons:

A. sda1=/boot
B. sda2=swap
C. sda3= /

NOTE: Format A and C using mkfs.ext3 /dev/sda1 and mkfs.ext3 /dev/sda3.

4. Boot your live CD and open a bash shell and begin. If your swap is not yet made then do this..(otherwise omit this step)

bt~# mkswap /dev/sda2
bt~# swapon /dev/sda2

5. Starting installation

bt~# mkdir /mnt/backtrack
bt~# mount /dev/sda3 /mnt/backtrack/
bt~# mkdir /mnt/backtrack/boot/
bt~# mount /dev/sda1 /mnt/backtrack/boot/

(note: If you only have one partiton to install backtrack to simply omit this step)

bt~# cp --preserve -R /{bin,dev,pentest,usr,etc,lib,opt,sbin,var,root} /mnt/backtrack/
bt~# mkdir /mnt/backtrack/{mnt,proc,sys,tmp,boot,root}
bt~# mount --bind /dev/ /mnt/backtrack/dev/
bt~# mount -t proc proc /mnt/backtrack/proc/
bt~# cp /boot/vmlinuz /mnt/backtrack/boot/

6. Now for lilo.

bt~# chroot /mnt/backtrack/ /bin/bash
bt~# nano /etc/lilo.conf

7. Now I like to delete all the BS in the lilo config file so here is what mine would look like. (remember to set your own VGA accordingly )

lba32
boot /dev/sda
prompt
timeout=60
change-rules
reset
vga=791
image = /boot/vmlinuz
root = /dev/sda3
label = backtrack3_final

GRUB users (Thanks to drwalter)

title Backtrack 3 KDE
rootnoverify (hd0,2)
kernel /boot/vmlinuz vga=791 root=/dev/sda3 ro autoexec=xconf;kdm
boot

title Backtrack 3
rootnoverify (hd0,2)
kernel /boot/vmlinuz vga=791 root=/dev/sda3 ro
boot

REMEMBER: hd0,2 would be for partition 3 NOT 2. Change accordingly!

Excellent. Save that and then execute lilo (I like to use the verbose flag)

bt~# lilo -v

after that exit your chroot enviorment

bt~# exit

and reboot and cross your fingers

bt~# reboot


BackTrack links

Max The Battery Life Of Your New BlackBerry

battery life is known to be excellent on many BlackBerry models. However, other models often have shorter battery life.

Try this if you are a new BlackBerry owner.

1. You need to break in the BlackBerry battery. Charge-discharge it fully about 3 times. This will max the battery life of a fresh, new Lithium ion.
Note: once you do that, don't get in the habit of fully discharging the battery everytime -- to prevent wearing it out -- lithium batteries can be damaged with excessive deep discharges like a car battery can be.... When breaking in the battery, make sure you keep it plugged in long after the battery says it is fully charged (i.e. overnight), you really want to trickle-charge your BlackBerry to top-off your battery.

2. Lithium batteries LOVE to be topped-off. In regular use (After initial first-use conditioning), plug it in whenever you have the opportunity. This will also help keep the battery life maxed out for those days you really need long battery life.

3. If you are constantly starved for battery power, avoid continuously realtime software such as BBToday software; it uses a lot of battery power.

4. Keep your Bluetooth turned off when not in use.

5. If you use instant messaging software, leave it running in the background or quit it when not in use. Also, stay logged off the networks you do not use much.

6. When using your BlackBerry, make sure you keep the backlight turned low or off whenever possible (rather than bright mode).

7. Some BlackBerries have an extended battery available, such as the Nextel 7510. There may be an extended battery product for your specific BlackBerry product.

8. There's the novelty factor of using a BlackBerry for the first time; we tend to play with them much more heavily at first. So your usage may normallize after you get used to it.

9. If you haven't bought a BlackBerry yet, you should be aware that the GSM/GPRS BlackBerries have the longest battery life. Battery life is longer on GPRS BlackBerries than the CDMA and iDEN BlackBerries.

10. Phone calls made on your BlackBerry is the biggest consumer of battery life. If you make lots of phone calls for hours, then your battery life can be extremely short. Making phone calls in areas of weak reception will also use up more battery power.

11. Consider a car power kit, or an office charger/cable. That way, you have more opportunities to top-off your BlackBerry battery.

As noted earlier, it's always a good idea to top-off the battery in a BlackBerry anyway, even if it's not almost dead. It is not necessary to follow the age-old advice of using up the battery before charging, and can wear out modern lithium-ion batteries if done on a constant basis.

12. Your battery may be defective or worn out. Compare your battery life to other people using the same model of BlackBerry.

If you have been using your BlackBerry for a long time, it may be time to replace your battery. If you purchased your BlackBerry as used, you may want to replace the battery with a new one. For best battery life, it is generally best to use genuine brand-name batteries rather than inexpensive aftermarket batteries.

13. Occasionally, it may be a BlackBerryOS issue if you are having unusually short battery life all the time. Early versions of BlackBerryOS on the 7100 tended to use a lot more battery life than newer versions of BlackBerryOS. Upgrade to a newer version of BlackBerryOS.

MSSQL: View actively running commands by SPID

--- View actively running commands by SPID.

select session_id, Text
from sys.dm_exec_requests r
cross apply sys.dm_exec_sql_text(sql_handle) t

Troubleshooting
Backup failed: System.Data.SqlClient.SqlError: Backup and file manipulation... must be serialized

Run Scheduled Task Batch File to Run Minimized on Task Bar

Problem: Batch file running Perl script to parse and copy SQL log files every five minutes as a Scheduled Task in Windows was creating a DOS window on the console. This made working on the server difficult and dangerous.

Solution: Create another batch file for the Scheduler to run with the commands 'start /min '
The old batch file must have the command 'exit' at the end of it for the DOS window to close.

Mac connect to Windows File Share

By default, Windows 2003 Server domain controllers have "Microsoft network server: Digitally sign communications (always)" set to "Enabled" by default. This is likely causing the Macs to fail to authenticate with the "error = -5000" when trying to connect via CIFS or SMB (samba)

To change this on a given domain controller, go to "Start" ->"Administrative Tools" -> "Domain Controller Security Policy" (not Domain Policy) and look for "Security Settings" -> "Local Policies" -> "Security Options" -> "Microsoft network server: Digitally sign communications (always)". It should show "Enabled" by default. Double-click on it and set to "Disabled".

Then close the app and click on start | Run - enter the command 'gpudate' to refresh group policy and hit enter.

You should now be able to use the "Go" > "Connect to Server" command in Finder to map to a share as shown below:

cifs://SERVER/SHARE

MySQL Backup Shell Script

***TO CREATE BACKUP SCRIPT ON LOCAL SERVER
mkdir /root/bin
vi /root/bin/mysqlbak.sh (then copy script into this file)
change parameters in script to match database
chmod 755 /root/bin/mysqlback.sh

***TO VERIFY SCRIPT WORKS
1. run this command
/root/bin/mysqlbak.sh
2. when script is done, check subdirs of /var/backup/db/daily for tarred & gzipped backups

***TO SCHEDULE THIS TO RUN DAILY, CREATE SYMBOLIC LINK
ln -s /root/bin/mysqlbak.sh /etc/cron.daily/mysqlbak.sh

***TO RESTORE
mysql -uUSER -pPASSWORD DBNAME_RESTORE < DBNAME_BACKUPFILE.sql

#!/bin/bash
#
# MySQL Backup Script
# VER. 2.5 - http://sourceforge.net/projects/automysqlbackup/
# Copyright (c) 2002-2003 wipe_out@lycos.co.uk
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#=====================================================================
#=====================================================================
# Set the following variables to your system needs
# (Detailed instructions below variables)
#=====================================================================

# crontab entry that will work for this script
# 57 5 * * 2,3,4,5,6 /root/bin/mysqlbackup.sh


# Username to access the MySQL server e.g. dbuser
USERNAME=

# Username to access the MySQL server e.g. password
PASSWORD=


# Host name (or IP address) of MySQL server e.g localhost
DBHOST=localhost

# List of DBNAMES for Daily/Weekly Backup e.g. "DB1 DB2 DB3" - you can put "all" as the value to backup all

DBNAMES=" mysql phpMyAdmin"
# Backup directory location e.g /var/www/backup/db
BACKUPDIR="/var/backup/db"

# Mail setup
# What would you like to be mailed to you?
# - log : send only log file
# - files : send log file and sql files as attachments (see docs)
# - stdout : will simply output the log to the screen if run manually.
# - quiet : Only send logs if an error occurs to the MAILADDR.
MAILCONTENT="log"

# Set the maximum allowed email size in k. (4000 = approx 5MB email [see docs])
MAXATTSIZE="4000"

# Email Address to send mail to? (user@domain.com)
MAILADDR="backups@soundenterprises.com"


# ============================================================
# === ADVANCED OPTIONS ( Read the doc's below for details )===
#=============================================================

# List of DBBNAMES for Monthly Backups.
MDBNAMES="mysql $DBNAMES"

# List of DBNAMES to EXCLUDE if DBNAMES are set to all (must be in " quotes)
DBEXCLUDE=""

# Include CREATE DATABASE in backup?
CREATE_DATABASE=yes

# Separate backup directory and file for each DB? (yes or no)
SEPDIR=yes

# Which day do you want weekly backups? (1 to 7 where 1 is Monday)
DOWEEKLY=7

# Choose Compression type. (gzip or bzip2)
COMP=gzip

# Compress communications between backup server and MySQL server?
COMMCOMP=no

# Additionally keep a copy of the most recent backup in a seperate directory.
LATEST=no

# The maximum size of the buffer for client/server communication. e.g. 16MB (maximum is 1GB)
MAX_ALLOWED_PACKET=

# For connections to localhost. Sometimes the Unix socket file must be specified.
SOCKET=

# Command to run before backups (uncomment to use)
#PREBACKUP="/etc/mysql-backup-pre"

# Command run after backups (uncomment to use)
#POSTBACKUP="/etc/mysql-backup-post"

#=====================================================================
# Options documantation
#=====================================================================
# Set USERNAME and PASSWORD of a user that has at least SELECT permission
# to ALL databases.
#
# Set the DBHOST option to the server you wish to backup, leave the
# default to backup "this server".(to backup multiple servers make
# copies of this file and set the options for that server)
#
# Put in the list of DBNAMES(Databases)to be backed up. If you would like
# to backup ALL DBs on the server set DBNAMES="all".(if set to "all" then
# any new DBs will automatically be backed up without needing to modify
# this backup script when a new DB is created).
#
# If the DB you want to backup has a space in the name replace the space
# with a % e.g. "data base" will become "data%base"
# NOTE: Spaces in DB names may not work correctly when SEPDIR=no.
#
# You can change the backup storage location from /backups to anything
# you like by using the BACKUPDIR setting..
#
# The MAILCONTENT and MAILADDR options and pretty self explanitory, use
# these to have the backup log mailed to you at any email address or multiple
# email addresses in a space seperated list.
# (If you set mail content to "log" you will require access to the "mail" program
# on your server. If you set this to "files" you will have to have mutt installed
# on your server. If you set it to "stdout" it will log to the screen if run from
# the console or to the cron job owner if run through cron. If you set it to "quiet"
# logs will only be mailed if there are errors reported. )
#
# MAXATTSIZE sets the largest allowed email attachments total (all backup files) you
# want the script to send. This is the size before it is encoded to be sent as an email
# so if your mail server will allow a maximum mail size of 5MB I would suggest setting
# MAXATTSIZE to be 25% smaller than that so a setting of 4000 would probably be fine.
#
# Finally copy automysqlbackup.sh to anywhere on your server and make sure
# to set executable permission. You can also copy the script to
# /etc/cron.daily to have it execute automatically every night or simply
# place a symlink in /etc/cron.daily to the file if you wish to keep it
# somwhere else.
# NOTE:On Debian copy the file with no extention for it to be run
# by cron e.g just name the file "automysqlbackup"
#
# Thats it..
#
#
# === Advanced options doc's ===
#
# The list of MDBNAMES is the DB's to be backed up only monthly. You should
# always include "mysql" in this list to backup your user/password
# information along with any other DBs that you only feel need to
# be backed up monthly. (if using a hosted server then you should
# probably remove "mysql" as your provider will be backing this up)
# NOTE: If DBNAMES="all" then MDBNAMES has no effect as all DBs will be backed
# up anyway.
#
# If you set DBNAMES="all" you can configure the option DBEXCLUDE. Other
# wise this option will not be used.
# This option can be used if you want to backup all dbs, but you want
# exclude some of them. (eg. a db is to big).
#
# Set CREATE_DATABASE to "yes" (the default) if you want your SQL-Dump to create
# a database with the same name as the original database when restoring.
# Saying "no" here will allow your to specify the database name you want to
# restore your dump into, making a copy of the database by using the dump
# created with automysqlbackup.
# NOTE: Not used if SEPDIR=no
#
# The SEPDIR option allows you to choose to have all DBs backed up to
# a single file (fast restore of entire server in case of crash) or to
# seperate directories for each DB (each DB can be restored seperately
# in case of single DB corruption or loss).
#
# To set the day of the week that you would like the weekly backup to happen
# set the DOWEEKLY setting, this can be a value from 1 to 7 where 1 is Monday,
# The default is 6 which means that weekly backups are done on a Saturday.
#
# COMP is used to choose the copmression used, options are gzip or bzip2.
# bzip2 will produce slightly smaller files but is more processor intensive so
# may take longer to complete.
#
# COMMCOMP is used to enable or diable mysql client to server compression, so
# it is useful to save bandwidth when backing up a remote MySQL server over
# the network.
#
# LATEST is to store an additional copy of the latest backup to a standard
# location so it can be downloaded bt thrid party scripts.
#
# If the DB's being backed up make use of large BLOB fields then you may need
# to increase the MAX_ALLOWED_PACKET setting, for example 16MB..
#
# When connecting to localhost as the DB server (DBHOST=localhost) sometimes
# the system can have issues locating the socket file.. This can now be set
# using the SOCKET parameter.. An example may be SOCKET=/private/tmp/mysql.sock
#
# Use PREBACKUP and POSTBACKUP to specify Per and Post backup commands
# or scripts to perform tasks either before or after the backup process.
#
#
#=====================================================================
# Backup Rotation..
#=====================================================================
#
# Daily Backups are rotated weekly..
# Weekly Backups are run by default on Saturday Morning when
# cron.daily scripts are run...Can be changed with DOWEEKLY setting..
# Weekly Backups are rotated on a 5 week cycle..
# Monthly Backups are run on the 1st of the month..
# Monthly Backups are NOT rotated automatically...
# It may be a good idea to copy Monthly backups offline or to another
# server..
#
#=====================================================================
# Please Note!!
#=====================================================================
#
# I take no resposibility for any data loss or corruption when using
# this script..
# This script will not help in the event of a hard drive crash. If a
# copy of the backup has not be stored offline or on another PC..
# You should copy your backups offline regularly for best protection.
#
# Happy backing up...
#
#=====================================================================
# Restoring
#=====================================================================
# Firstly you will need to uncompress the backup file.
# eg.
# gunzip file.gz (or bunzip2 file.bz2)
#
# Next you will need to use the mysql client to restore the DB from the
# sql file.
# eg.
# mysql --user=username --pass=password --host=dbserver database < /path/file.sql
# or
# mysql --user=username --pass=password --host=dbserver -e "source /path/file.sql" database
#
# NOTE: Make sure you use "<" and not ">" in the above command because
# you are piping the file.sql to mysql and not the other way around.
#
# Lets hope you never have to use this.. :)
#

#
#=====================================================================
#=====================================================================
#=====================================================================
#
# Should not need to be modified from here down!!
#
#=====================================================================
#=====================================================================
#=====================================================================
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/mysql/bin
DATE=`date +%Y-%m-%d_%Hh%Mm` # Datestamp e.g 2002-09-21
DOW=`date +%A` # Day of the week e.g. Monday
DNOW=`date +%u` # Day number of the week 1 to 7 where 1 represents Monday
DOM=`date +%d` # Date of the Month e.g. 27
M=`date +%B` # Month e.g January
W=`date +%V` # Week Number e.g 37
VER=2.5 # Version Number
LOGFILE=$BACKUPDIR/$DBHOST-`date +%N`.log # Logfile Name
LOGERR=$BACKUPDIR/ERRORS_$DBHOST-`date +%N`.log # Logfile Name
BACKUPFILES=""
OPT="--quote-names --opt" # OPT string for use with mysqldump ( see man mysqldump )

# Add --compress mysqldump option to $OPT
if [ "$COMMCOMP" = "yes" ];
then
OPT="$OPT --compress"
fi

# Add --compress mysqldump option to $OPT
if [ "$MAX_ALLOWED_PACKET" ];
then
OPT="$OPT --max_allowed_packet=$MAX_ALLOWED_PACKET"
fi

# Create required directories
if [ ! -e "$BACKUPDIR" ] # Check Backup Directory exists.
then
mkdir -p "$BACKUPDIR"
fi

if [ ! -e "$BACKUPDIR/daily" ] # Check Daily Directory exists.
then
mkdir -p "$BACKUPDIR/daily"
fi

if [ ! -e "$BACKUPDIR/weekly" ] # Check Weekly Directory exists.
then
mkdir -p "$BACKUPDIR/weekly"
fi

if [ ! -e "$BACKUPDIR/monthly" ] # Check Monthly Directory exists.
then
mkdir -p "$BACKUPDIR/monthly"
fi

if [ "$LATEST" = "yes" ]
then
if [ ! -e "$BACKUPDIR/latest" ] # Check Latest Directory exists.
then
mkdir -p "$BACKUPDIR/latest"
fi
eval rm -fv "$BACKUPDIR/latest/*"
fi

# IO redirection for logging.
touch $LOGFILE
exec 6>&1 # Link file descriptor #6 with stdout.
# Saves stdout.
exec > $LOGFILE # stdout replaced with file $LOGFILE.
touch $LOGERR
exec 7>&2 # Link file descriptor #7 with stderr.
# Saves stderr.
exec 2> $LOGERR # stderr replaced with file $LOGERR.


# Functions

# Database dump function
dbdump () {
mysqldump --user=$USERNAME --password=$PASSWORD --host=$DBHOST $OPT $1 > $2
return 0
}

# Compression function plus latest copy
SUFFIX=""
compression () {
if [ "$COMP" = "gzip" ]; then
gzip -f "$1"
echo
echo Backup Information for "$1"
gzip -l "$1.gz"
SUFFIX=".gz"
elif [ "$COMP" = "bzip2" ]; then
echo Compression information for "$1.bz2"
bzip2 -f -v $1 2>&1
SUFFIX=".bz2"
else
echo "No compression option set, check advanced settings"
fi
if [ "$LATEST" = "yes" ]; then
cp $1$SUFFIX "$BACKUPDIR/latest/"
fi
return 0
}


# Run command before we begin
if [ "$PREBACKUP" ]
then
echo ======================================================================
echo "Prebackup command output."
echo
eval $PREBACKUP
echo
echo ======================================================================
echo
fi


if [ "$SEPDIR" = "yes" ]; then # Check if CREATE DATABSE should be included in Dump
if [ "$CREATE_DATABASE" = "no" ]; then
OPT="$OPT --no-create-db"
else
OPT="$OPT --databases"
fi
else
OPT="$OPT --databases"
fi

# Hostname for LOG information
if [ "$DBHOST" = "localhost" ]; then
HOST=`hostname`
if [ "$SOCKET" ]; then
OPT="$OPT --socket=$SOCKET"
fi
else
HOST=$DBHOST
fi

# If backing up all DBs on the server
if [ "$DBNAMES" = "all" ]; then
DBNAMES="`mysql --user=$USERNAME --password=$PASSWORD --host=$DBHOST --batch --skip-column-names -e "show databases"| sed 's/ /%/g'`"

# If DBs are excluded
for exclude in $DBEXCLUDE
do
DBNAMES=`echo $DBNAMES | sed "s/\b$exclude\b//g"`
done

MDBNAMES=$DBNAMES
fi

echo ======================================================================
echo AutoMySQLBackup VER $VER
echo http://sourceforge.net/projects/automysqlbackup/
echo
echo Backup of Database Server - $HOST
echo ======================================================================

# Test is seperate DB backups are required
if [ "$SEPDIR" = "yes" ]; then
echo Backup Start Time `date`
echo ======================================================================
# Monthly Full Backup of all Databases
if [ $DOM = "01" ]; then
for MDB in $MDBNAMES
do

# Prepare $DB for using
MDB="`echo $MDB | sed 's/%/ /g'`"

if [ ! -e "$BACKUPDIR/monthly/$MDB" ] # Check Monthly DB Directory exists.
then
mkdir -p "$BACKUPDIR/monthly/$MDB"
fi
echo Monthly Backup of $MDB...
dbdump "$MDB" "$BACKUPDIR/monthly/$MDB/${MDB}_$DATE.$M.$MDB.sql"
compression "$BACKUPDIR/monthly/$MDB/${MDB}_$DATE.$M.$MDB.sql"
BACKUPFILES="$BACKUPFILES $BACKUPDIR/monthly/$MDB/${MDB}_$DATE.$M.$MDB.sql$SUFFIX"
echo ----------------------------------------------------------------------
done
fi

for DB in $DBNAMES
do
# Prepare $DB for using
DB="`echo $DB | sed 's/%/ /g'`"

# Create Seperate directory for each DB
if [ ! -e "$BACKUPDIR/daily/$DB" ] # Check Daily DB Directory exists.
then
mkdir -p "$BACKUPDIR/daily/$DB"
fi

if [ ! -e "$BACKUPDIR/weekly/$DB" ] # Check Weekly DB Directory exists.
then
mkdir -p "$BACKUPDIR/weekly/$DB"
fi

# Weekly Backup
if [ $DNOW = $DOWEEKLY ]; then
echo Weekly Backup of Database \( $DB \)
echo Rotating 5 weeks Backups...
if [ "$W" -le 05 ];then
REMW=`expr 48 + $W`
elif [ "$W" -lt 15 ];then
REMW=0`expr $W - 5`
else
REMW=`expr $W - 5`
fi
eval rm -fv "$BACKUPDIR/weekly/$DB_week.$REMW.*"
echo
dbdump "$DB" "$BACKUPDIR/weekly/$DB/${DB}_week.$W.$DATE.sql"
compression "$BACKUPDIR/weekly/$DB/${DB}_week.$W.$DATE.sql"
BACKUPFILES="$BACKUPFILES $BACKUPDIR/weekly/$DB/${DB}_week.$W.$DATE.sql$SUFFIX"
echo ----------------------------------------------------------------------

# Daily Backup
else
echo Daily Backup of Database \( $DB \)
echo Rotating last weeks Backup...
eval rm -fv "$BACKUPDIR/daily/$DB/*.$DOW.sql.*"
echo
dbdump "$DB" "$BACKUPDIR/daily/$DB/${DB}_$DATE.$DOW.sql"
compression "$BACKUPDIR/daily/$DB/${DB}_$DATE.$DOW.sql"
BACKUPFILES="$BACKUPFILES $BACKUPDIR/daily/$DB/${DB}_$DATE.$DOW.sql$SUFFIX"
echo ----------------------------------------------------------------------
fi
done
echo Backup End `date`
echo ======================================================================


else # One backup file for all DBs
echo Backup Start `date`
echo ======================================================================
# Monthly Full Backup of all Databases
if [ $DOM = "01" ]; then
echo Monthly full Backup of \( $MDBNAMES \)...
dbdump "$MDBNAMES" "$BACKUPDIR/monthly/$DATE.$M.all-databases.sql"
compression "$BACKUPDIR/monthly/$DATE.$M.all-databases.sql"
BACKUPFILES="$BACKUPFILES $BACKUPDIR/monthly/$DATE.$M.all-databases.sql$SUFFIX"
echo ----------------------------------------------------------------------
fi

# Weekly Backup
if [ $DNOW = $DOWEEKLY ]; then
echo Weekly Backup of Databases \( $DBNAMES \)
echo
echo Rotating 5 weeks Backups...
if [ "$W" -le 05 ];then
REMW=`expr 48 + $W`
elif [ "$W" -lt 15 ];then
REMW=0`expr $W - 5`
else
REMW=`expr $W - 5`
fi
eval rm -fv "$BACKUPDIR/weekly/week.$REMW.*"
echo
dbdump "$DBNAMES" "$BACKUPDIR/weekly/week.$W.$DATE.sql"
compression "$BACKUPDIR/weekly/week.$W.$DATE.sql"
BACKUPFILES="$BACKUPFILES $BACKUPDIR/weekly/week.$W.$DATE.sql$SUFFIX"
echo ----------------------------------------------------------------------

# Daily Backup
else
echo Daily Backup of Databases \( $DBNAMES \)
echo
echo Rotating last weeks Backup...
eval rm -fv "$BACKUPDIR/daily/*.$DOW.sql.*"
echo
dbdump "$DBNAMES" "$BACKUPDIR/daily/$DATE.$DOW.sql"
compression "$BACKUPDIR/daily/$DATE.$DOW.sql"
BACKUPFILES="$BACKUPFILES $BACKUPDIR/daily/$DATE.$DOW.sql$SUFFIX"
echo ----------------------------------------------------------------------
fi
echo Backup End Time `date`
echo ======================================================================
fi
echo Total disk space used for backup storage..
echo Size - Location
echo `du -hs "$BACKUPDIR"`
echo
echo ======================================================================
echo If you find AutoMySQLBackup valuable please make a donation at
echo http://sourceforge.net/project/project_donations.php?group_id=101066
echo ======================================================================

# Run command when we're done
if [ "$POSTBACKUP" ]
then
echo ======================================================================
echo "Postbackup command output."
echo
eval $POSTBACKUP
echo
echo ======================================================================
fi

#Clean up IO redirection
exec 1>&6 6>&- # Restore stdout and close file descriptor #6.
exec 1>&7 7>&- # Restore stdout and close file descriptor #7.

if [ "$MAILCONTENT" = "files" ]
then
if [ -s "$LOGERR" ]
then
# Include error log if is larger than zero.
BACKUPFILES="$BACKUPFILES $LOGERR"
ERRORNOTE="WARNING: Error Reported - "
fi
#Get backup size
ATTSIZE=`du -c $BACKUPFILES | grep "[[:digit:][:space:]]total$" |sed s/\s*total//`
if [ $MAXATTSIZE -ge $ATTSIZE ]
then
BACKUPFILES=`echo "$BACKUPFILES" | sed -e "s# # -a #g"` #enable multiple attachments
mutt -s "$ERRORNOTE MySQL Backup Log and SQL Files for $HOST - $DATE" $BACKUPFILES $MAILADDR < $LOGFILE #send via mutt
else
cat "$LOGFILE" | mail -s "WARNING! - MySQL Backup exceeds set maximum attachment size on $HOST - $DATE" $MAILADDR
fi
elif [ "$MAILCONTENT" = "log" ]
then
cat "$LOGFILE" | mail -s "MySQL Backup Log for $HOST - $DATE" $MAILADDR
if [ -s "$LOGERR" ]
then
cat "$LOGERR" | mail -s "ERRORS REPORTED: MySQL Backup error Log for $HOST - $DATE" $MAILADDR
fi
elif [ "$MAILCONTENT" = "quiet" ]
then
if [ -s "$LOGERR" ]
then
cat "$LOGERR" | mail -s "ERRORS REPORTED: MySQL Backup error Log for $HOST - $DATE" $MAILADDR
cat "$LOGFILE" | mail -s "MySQL Backup Log for $HOST - $DATE" $MAILADDR
fi
else
if [ -s "$LOGERR" ]
then
cat "$LOGFILE"
echo
echo "###### WARNING ######"
echo "Errors reported during AutoMySQLBackup execution.. Backup failed"
echo "Error log below.."
cat "$LOGERR"
else
cat "$LOGFILE"
fi
fi

if [ -s "$LOGERR" ]
then
STATUS=1
else
STATUS=0
fi

# Clean up Logfile
eval rm -f "$LOGFILE"
eval rm -f "$LOGERR"

exit $STATUS