Tuesday, November 5, 2013
POSTGRESQL import export from csv
Wednesday, October 23, 2013
rebuild php module in centos6 (pdo_pgsql for example)
We have installed latest PostgreSQL 9.3, but pdo_pgsql from remi supports only 8.4
this is simple instruction, how to rebuild a php extension
go configure it and build. Use ./configure --help to see available options
this is simple instruction, how to rebuild a php extension
cd /usr/src/
mkdir php
cd php/
wget http://www.php.net/get/php-5.5.5.tar.gz/from/de1.php.net/mirror
tar -xzvf php-5.5.5.tar.gz
cd php-5.5.5/ext/pdo_pgsql
go configure it and build. Use ./configure --help to see available options
phpize
aclocal
./configure --help
./configure --with-pdo-pgsql=/usr/pgsql-9.3
make
ls modules
ls /usr/lib64/php/modules
rm -f /usr/lib64/php/modules/pdo_pgsql.so
cp modules/pdo_pgsql.so /usr/lib64/php/modules/
service httpd restart
Labels:
build php module,
pdo_pgsql,
phpize,
PostgreSQL 9.3
Программный RAID в Linux
source http://xgu.ru/wiki/%D0%9F%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D0%BC%D0%BD%D1%8B%D0%B9_RAID_%D0%B2_Linux
mdadm
Управление программным RAID-массивом в Linux выполняется с помощью программы mdadm.
У программы mdadm есть несколько режимов работы.
- Assemble (сборка)
- Собрать компоненты ранее созданного массива в массив. Компоненты можно указывать явно, но можно и не указывать — тогда выполняется их поиск по суперблокам.
- Build (построение)
- Собрать массив из компонентов, у которых нет суперблоков. Не выполняются никакие проверки, создание и сборка массива в принципе ничем не отличаются.
- Create (создание)
- Создать новый массив на основе указанных устройств. Использовать суперблоки размещённые на каждом устройстве.
- Monitor (наблюдение)
- Следить за изменением состояния устройств. Для RAID0 этот режим не имеет смысла.
- Grow (расширение или уменьшение)
- Расширение или уменьшение массива, включаются или удаляются новые диски.
- Incremental Assembly (инкрементальная сборка)
- Добавление диска в массив.
- Manage (управление)
- Разнообразные операции по управлению массивом, такие как замена диска и пометка как сбойного.
- Misc (разное)
- Действия, которые не относятся ни к одному из перечисленных выше режимов работы.
- Auto-detect (автоообнаружение)
- Активация автоматически обнаруживаемых массивов в ядре Linux.
Формат вызова
mdadm [mode] [array] [options]
Режимы:
- -A, --assemble — режим сборки
- -B, --build — режим построения
- -C, --create — режим создания
- -F, --follow, --monitor — режим наблюдения
- -G, --grow — режим расширения
- -I, --incremental — режим инкрементальной сборки
Настройка программного RAID-массива
Рассмотрим как выполнить настройку RAID-массива 5 уровня на трёх дисковых разделах. Мы будем использовать разделы:
/dev/hde1 /dev/hdf2 /dev/hdg1
В том случае если разделы иные, не забудьте использовать соответствующие имена файлов.
Создание разделов
Нужно определить на каких физических разделах будет создаваться RAID-массив. Если разделы уже есть, нужно найти свободные (fdisk -l). Если разделов ещё нет, но есть неразмеченное место, их можно создать с помощью программ fdisk или cfdisk.
Просмотреть какие есть разделы:
%# fdisk -l
Disk /dev/hda: 12.0 GB, 12072517632 bytes 255 heads, 63 sectors/track, 1467 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes
Device Boot Start End Blocks Id System /dev/hda1 * 1 13 104391 83 Linux /dev/hda2 14 144 1052257+ 83 Linux /dev/hda3 145 209 522112+ 82 Linux swap /dev/hda4 210 1467 10104885 5 Extended /dev/hda5 210 655 3582463+ 83 Linux ... ... /dev/hda15 1455 1467 104391 83 Linux
Просмотреть, какие разделы куда смонтированы, и сколько свободного места есть на них (размеры в килобайтах):
%# df -k Filesystem 1K-blocks Used Available Use% Mounted on /dev/hda2 1035692 163916 819164 17% / /dev/hda1 101086 8357 87510 9% /boot /dev/hda15 101086 4127 91740 5% /data1 ... ... ... /dev/hda7 5336664 464228 4601344 10% /var
Размонтирование
Если вы будете использовать созданные ранее разделы, обязательно размонтируйте их. RAID-массив нельзя создавать поверх разделов, на которых находятся смонтированные файловые системы.
%# umount /dev/hde1 %# umount /dev/hdf2 %# umount /dev/hdg1
Изменение типа разделов
Желательно (но не обязательно) изменить тип разделов, которые будут входить в RAID-массив и установить его равным FD (Linux RAID autodetect). Изменить тип раздела можно с помощью fdisk.
Рассмотрим как это делать на примере раздела /dev/hde1.
%# fdisk /dev/hde
The number of cylinders for this disk is set to 8355.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1) software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
(e.g., DOS FDISK, OS/2 FDISK)
Command (m for help):
Use FDISK Help
Now use the fdisk m command to get some help:
Command (m for help): m
...
...
p print the partition table
q quit without saving changes
s create a new empty Sun disklabel
t change a partition's system id
...
...
Command (m for help):
Set The ID Type To FD
Partition /dev/hde1 is the first partition on disk /dev/hde.
Modify its type using the t command, and specify the partition number
and type code.
You also should use the L command to get a full listing
of ID types in case you forget.
Command (m for help): t
Partition number (1-5): 1
Hex code (type L to list codes): L
...
...
...
16 Hidden FAT16 61 SpeedStor f2 DOS secondary
17 Hidden HPFS/NTF 63 GNU HURD or Sys fd Linux raid auto
18 AST SmartSleep 64 Novell Netware fe LANstep
1b Hidden Win95 FA 65 Novell Netware ff BBT
Hex code (type L to list codes): fd
Changed system type of partition 1 to fd (Linux raid autodetect)
Command (m for help):
Make Sure The Change Occurred
Use the p command to get the new proposed partition table:
Command (m for help): p
Disk /dev/hde: 4311 MB, 4311982080 bytes
16 heads, 63 sectors/track, 8355 cylinders
Units = cylinders of 1008 * 512 = 516096 bytes
Device Boot Start End Blocks Id System
/dev/hde1 1 4088 2060320+ fd Linux raid autodetect
/dev/hde2 4089 5713 819000 83 Linux
/dev/hde4 6608 8355 880992 5 Extended
/dev/hde5 6608 7500 450040+ 83 Linux
/dev/hde6 7501 8355 430888+ 83 Linux
Command (m for help):
Save The Changes
Use the w command to permanently save the changes to disk /dev/hde:
Command (m for help): w
The partition table has been altered!
Calling ioctl() to re-read partition table.
WARNING: Re-reading the partition table failed with error 16: Device or resource busy.
The kernel still uses the old table.
The new table will be used at the next reboot.
Syncing disks.
Аналогичным образом нужно изменить тип раздела для всех остальных разделов, входящих в RAID-массив.
Создание RAID-массива
Создание RAID-массива выполняется с помощью программы mdadm (ключ --create). Мы воспользуемся опцией --level, для того чтобы создать RAID-массив 5 уровня. С помощью ключа --raid-devices укажем устройства, поверх которых будет собираться RAID-массив.
%# mdadm --create --verbose /dev/md0 --level=5 --raid-devices=3 /dev/hde1 /dev/hdf2 /dev/hdg1
mdadm: layout defaults to left-symmetric
mdadm: chunk size defaults to 64K
mdadm: /dev/hde1 appears to contain an ext2fs file system
size=48160K mtime=Sat Jan 27 23:11:39 2007
mdadm: /dev/hdf2 appears to contain an ext2fs file system
size=48160K mtime=Sat Jan 27 23:11:39 2007
mdadm: /dev/hdg1 appears to contain an ext2fs file system
size=48160K mtime=Sat Jan 27 23:11:39 2007
mdadm: size set to 48064K
Continue creating array? y
mdadm: array /dev/md0 started.
Если вы хотите сразу создать массив, где диска не хватает (degraded) просто укажите слово missing вместо имени устройства. Для RAID5 это может быть только один диск; для RAID6 — не более двух; для RAID1 — сколько угодно, но должен быть как минимум один рабочий.
Проверка правильности сборки
Убедиться, что RAID-массив проинициализирован корректно можно просмотрев файл /proc/mdstat. В этом файле отражается текущее состояние RAID-массива.
%# cat /proc/mdstat
Personalities : [raid5]
read_ahead 1024 sectors
md0 : active raid5 hdg1[2] hde1[1] hdf2[0]
4120448 blocks level 5, 32k chunk, algorithm 3 [3/3] [UUU]
unused devices: <none>
Обратите внимание на то, как называется новый RAID-массив. В нашем случае он называется /dev/md0. Мы будем обращаться к массиву по этому имени.
Создание файловой системы поверх RAID-массива
Новый RAID-раздел нужно отформатировать, т.е. создать на нём файловую систему. Сделать это можно при помощи программы из семейства mkfs. Если мы будем создавать файловую систему ext3, воспользуемся программой mkfs.ext3. :
%# mkfs.ext3 /dev/md0
mke2fs 1.39 (29-May-2006)
Filesystem label=
OS type: Linux
Block size=1024 (log=0)
Fragment size=1024 (log=0)
36144 inodes, 144192 blocks
7209 blocks (5.00%) reserved for the super user
First data block=1
Maximum filesystem blocks=67371008
18 block groups
8192 blocks per group, 8192 fragments per group
2008 inodes per group
Superblock backups stored on blocks:
8193, 24577, 40961, 57345, 73729
Writing inode tables: done
Creating journal (4096 blocks): done
Writing superblocks and filesystem accounting information: done
This filesystem will be automatically checked every 33 mounts or
180 days, whichever comes first. Use tune2fs -c or -i to override.
Имеет смысл для лучшей производительности файловой системы указывать при создании количество дисков в рейде и количество блоков файловой системы которое может поместиться в один страйп ( chunk ), это особенно важно при создании массивов уровня RAID0,RAID5,RAID6,RAID10. Для RAID1 ( mirror ) это не имеет значения так как запись идет всегда на один device, a в других типах рейдов дата записывается последовательно на разные диски порциями соответствующими размеру stripe.Например если мы используем RAID5 из 3 дисков, с дефолтным размером страйпа в 64К и используем файловую систему ext3 с размером блока в 4К то можно вызывать команду mkfs.ext вот так:
%# mkfs.ext3 -b 4096 -E stride=16 stripe-width=32 /dev/md0
stripe-width обычно расчитывается как stride * N ( N это дата диски в массиве - например в RAID5 - два дата диска и один parity ) Для неменее популярной файловой системы XFS надо указывать не количество блоков файловой системы соответствующих размеру stripe в массиве, а непосредственно размер самого страйпа
%# mkfs.xfs -d su=64k,sw=3 /dev/md0
Создание конфигурационного файла mdadm.conf
Система сама не запоминает какие RAID-массивы ей нужно создать и какие компоненты в них входят. Эта информация находится в файлеmdadm.conf.
Строки, которые следует добавить в этот файл, можно получить при помощи команды
mdadm --detail --scan --verbose
Вот пример её использования:
%# mdadm --detail --scan --verbose
ARRAY /dev/md0 level=raid5 num-devices=4
UUID=77b695c4:32e5dd46:63dd7d16:17696e09
devices=/dev/hde1,/dev/hdf2,/dev/hdg1
Если файла mdadm.conf ещё нет, можно его создать:
%# echo "DEVICE partitions" > /etc/mdadm/mdadm.conf
%# mdadm --detail --scan --verbose | awk '/ARRAY/ {print}' >> /etc/mdadm/mdadm.conf
Создание точки монтирования для RAID-массива
Поскольку мы создали новую файловую систему, вероятно, нам понадобится и новая точка монтирования. Назовём её /raid.
%# mkdir /raid
Изменение /etc/fstab
Для того чтобы файловая система, созданная на новом RAID-массиве автоматически монтировалась при загрузке, добавим соответствующую запись в файл /etc/fstab хранящий список автоматически монтируемых при загрузке файловых систем.
/dev/md0 /raid ext3 defaults 1 2
Если мы объединяли в RAID-массив разделы, которые использовались раньше, нужно отключить их монтирование: удалить или закомментировать соответствующие строки в файле /etc/fstab. Закомментировать строку можно символом #.
#/dev/hde1 /data1 ext3 defaults 1 2
#/dev/hdf2 /data2 ext3 defaults 1 2
#/dev/hdg1 /data3 ext3 defaults 1 2
Монтирование файловой системы нового RAID-массива
Для того чтобы получить доступ к файловой системе, расположенной на новом RAID-массиве, её нужно смонтировать. Монтирование выполняется с помощью команды mount.
Если новая файловая система добавлена в файл /etc/fstab, можно смонтировать её командой mount -a (смонтируются все файловые системы, которые должны монтироваться при загрузке, но сейчас не смонтированы).
%# mount -a
Можно смонтировать только нужный нам раздел (при условии, что он указан в /etc/fstab).
%# mount /raid
Если раздел в /etc/fstab не указан, то при монтировании мы должны задавать как минимум два параметра — точку монтирования и монтируемое устройство:
%# mount /dev/md0 /raid
Проверка состояния RAID-массива
Информация о состоянии RAID-массива находится в файле /proc/mdstat.
%# raidstart /dev/md0
%# cat /proc/mdstat
Personalities : [raid5]
read_ahead 1024 sectors
md0 : active raid5 hdg1[2] hde1[1] hdf2[0]
4120448 blocks level 5, 32k chunk, algorithm 3 [3/3] [UUU]
unused devices: <none>
Если в файле информация постоянно изменяется, например, идёт пересборка массива, то постоянно изменяющийся файл удобно просматривать при помощи программы watch:
%$ watch cat /proc/mdstat
Как выполнить проверку целостности программного RAID-массива md0:
echo 'check' >/sys/block/md0/md/sync_action
Как посмотреть нашлись ли какие-то ошибки в процессе проверки программного RAID-массива по команде check или repair:
cat /sys/block/md0/md/mismatch_cnt
Проблема загрузки на многодисковых системах
В некоторых руководствах по mdadm после первоначальной сборки массивов рекомендуется добавлять в файл /etc/mdadm/mdadm.conf вывод команды "mdadm --detail --scan --verbose":
ARRAY /dev/md/1 level=raid1 num-devices=2 metadata=1.2 name=linuxWork:1 UUID=147c5847:dabfe069:79d27a05:96ea160b devices=/dev/sda1 ARRAY /dev/md/2 level=raid1 num-devices=2 metadata=1.2 name=linuxWork:2 UUID=68a95a22:de7f7cab:ee2f13a9:19db7dad devices=/dev/sda2
, в котором жёстко прописаны имена разделов (/dev/sda1, /dev/sda2 в приведённом примере).
Если после этого обновить образ начальной загрузки (в Debian вызвать 'update-initramfs -u' или 'dpkg-reconfigure mdadm'), имена разделов запишутся в файл mdadm.conf образа начальной загрузки и вы не сможете загрузиться с массива, если конфигурация жёстких дисков изменится (нужные разделы получат другие имена). Для этого не обязательно добавлять или убирать жёсткие диски: в многодисковых системах их имена могут меняться от загрузки к загрузке.
Решение: записывать в /etc/mdadm/mdadm.conf вывод команды "mdadm --detail --scan" (без --verbose).
При этом в файле mdadm.conf будут присутствовать UUID разделов, составляющих каждый RAID-массив. При загрузке системы mdadm находит нужные разделы независимо от их символических имён по UUID.
mdadm.conf, извлечённый из образа начальной загрузки Debian:
DEVICE partitions HOMEHOST <system> ARRAY /dev/md/1 metadata=1.2 UUID=147c5847:dabfe069:79d27a05:96ea160b name=linuxWork:1 ARRAY /dev/md/2 metadata=1.2 UUID=68a95a22:de7f7cab:ee2f13a9:19db7dad name=linuxWork:2
Результат исследования раздела командой 'mdadm --examine'"
/dev/sda1:
Magic : a92b4efc
Version : 1.2
Feature Map : 0x0
Array UUID : 147c5847:dabfe069:79d27a05:96ea160b
Name : linuxWork:1
Creation Time : Thu May 23 09:17:01 2013
Raid Level : raid1
Raid Devices : 2
Раздел c UUID 147c5847:dabfe069:79d27a05:96ea160b войдёт в состав массива, даже если станет /dev/sdb1 при очередной загрузке системы.
Вообще, существует 2 файла mdadm.conf, влияющих на автоматическую сборку массивов:
- один при загрузке системы, записывется в образ начальной загрузки при его обновлении;
- другой находится в каталоге /etc/mdadm/ и влияет на автосборку массивов внутри работающей системы.
Соответственно, вы можете иметь информацию:
1) в образе начальной загрузки (ОНЗ) и в /etc/mdadm/mdadm.conf;
2) только в ОНЗ (попадает туда при его создании обновлении);
3) только в /etc/mdadm/mdadm.conf;
4) нигде.
В том месте, где есть mdadm.conf, сборка происходит по правилам; где нет - непредсказуемо.
Примечание: если вы не обновили ОНЗ после создания RAID-массивов, их конфигурация всё равно в него попадёт - при обновлении образа другой программой / при обновлении системы (но вы не будете об этом знать со всеми вытекающими).
Дальнейшая работа с массивом
Пометка диска как сбойного
Диск в массиве можно условно сделать сбойным, ключ --fail (-f):
%# mdadm /dev/md0 --fail /dev/hde1 %# mdadm /dev/md0 -f /dev/hde1
Удаление сбойного диска
Сбойный диск можно удалить с помощью ключа --remove (-r):
%# mdadm /dev/md0 --remove /dev/hde1 %# mdadm /dev/md0 -r /dev/hde1
Добавление нового диска
Добавить новый диск в массив можно с помощью ключей --add (-a) и --re-add:
%# mdadm /dev/md0 --add /dev/hde1 %# mdadm /dev/md0 -a /dev/hde1
Сборка существующего массива
Собрать существующий массив можно с помощью mdadm --assemble. Как дополнительный аргумент указывается, нужно ли выполнять сканирование устройств, и если нет, то какие устройства нужно собирать.
%# mdadm --assemble /dev/md0 /dev/hde1 /dev/hdf2 /dev/hdg1 %# mdadm --assemble --scan
Расширение массива
Расширить массив можно с помощью ключа --grow (-G). Сначала добавляется диск, а потом массив расширяется:
%# mdadm /dev/md0 --add /dev/hdh2
Проверяем, что диск (раздел) добавился:
%# mdadm --detail /dev/md0 %# cat /proc/mdstat
Если раздел действительно добавился, мы можем расширить массив:
%# mdadm -G /dev/md0 --raid-devices=4
При необходимости, можно регулировать скорость процесса расширения массива, указав нужное значение в файлах
/proc/sys/dev/raid/speed_limit_min
/proc/sys/dev/raid/speed_limit_max
Убедитесь, что массив расширился:
%# cat /proc/mdstat
Нужно обновить конфигурационный файл с учётом сделанных изменений:
%# mdadm --detail --scan >> /etc/mdadm/mdadm.conf %# vi /etc/mdadm/mdadm.conf
Возобновление отложенной синхронизации
Отложенная синхронизация:
Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
md0 : active(auto-read-only) raid1 sda1[0] sdb1[1]
78148096 blocks [2/2] [UU]
resync=PENDING
Возобновить:
echo idle > /sys/block/md0/md/sync_action
P.S.: Если вы увидели «
active (auto-read-only)» в файле /proc/mdstat, то возможно вы просто ничего не записывали в этот массив. К примеру, после монтирования раздела и любых изменений в примонтированном каталоге, статус автоматически меняется:md0 : active raid1 sdc[0] sdd[1]
Переименование массива
Для начала отмонтируйте и остановите массив:
%# umount /dev/md0 %# mdadm --stop /dev/md0
Затем необходимо пересобрать как md5 каждый из разделов sd[abcdefghijk]1
%# mdadm --assemble /dev/md5 /dev/sd[abcdefghijk]1 --update=name
или так
%# mdadm --assemble /dev/md5 /dev/sd[abcdefghijk]1 --update=super-minor
Удаление массива
Для начала отмонтируйте и остановите массив:
%# umount /dev/md0 %# mdadm -S /dev/md0
Затем необходимо затереть superblock каждого из составляющих массива:
%# mdadm --zero-superblock /dev/hde1 %# mdadm --zero-superblock /dev/hdf2
Если действие выше не помогло, то затираем так:
%# dd if=/dev/zero of=/dev/hde1 bs=512 count=1 %# dd if=/dev/zero of=/dev/hdf2 bs=512 count=1
Saturday, October 19, 2013
monitoring cciss Smart RAID (HP HW raid)
Based on this article I come up with a script to monitor CCISS HP Smart RAID hardware C
#!/bin/bash
# Usage:
# hpacucli_mon <NUM OF ARRAYS> <NUM OF PHISYCAL DISKS> <MAIL TO>
HP_SLOT=`/usr/sbin/hpacucli ctrl all show status | grep -o -P 'Slot.{0,2}'| awk -F" " '{print $2}'`
if [ "$3" = "" ] || [ "$4" != "" ];then
echo ""
echo "ERROR: hpacucli_mon requires number of arrays, disks and valid email"
echo ""
echo "Usage: hpacucli_mon <NUM OF ARRAYS> <NUM OF PHISYCAL DISKS> <MAIL TO>"
echo ""
echo "To find amount of arrays and disks you do have run:"
echo "/usr/sbin/hpacucli ctrl slot=$HP_SLOT ld all show status"
echo "and"
echo "/usr/sbin/hpacucli ctrl slot=$HP_SLOT pd all show status"
exit
fi
EMAILMESSAGE="/tmp/hpacucli_message.txt"
LOCAL_IP=`/sbin/ifconfig eth0 | grep -Eo '(([0-9]{1,3}\.){3}[0-9]{1,3})' | grep -v ".255"`
MSG_SUBJECT="Smart HP array failure at $LOCAL_IP"
OK_ARRAY_CNT=`/usr/sbin/hpacucli ctrl slot=$HP_SLOT ld all show status | grep -o "OK" | wc -l`
OK_DISKS_CNT=`/usr/sbin/hpacucli ctrl slot=$HP_SLOT pd all show status | grep -o "OK" | wc -l`
if [ "$OK_ARRAY_CNT" -ne $1 ] || [ "$OK_DISKS_CNT" -ne $2 ]; then
echo "We have encountered a problem at $LOCAL_IP" > $EMAILMESSAGE
echo "Take look at this: ">> $EMAILMESSAGE
/usr/sbin/hpacucli ctrl slot=$HP_SLOT ld all show status >> $EMAILMESSAGE
/usr/sbin/hpacucli ctrl slot=$HP_SLOT pd all show status >> $EMAILMESSAGE
echo "===============================================" >> $EMAILMESSAGE
echo "INFORMATION PROVIDED BY SMARTCTL:" >> $EMAILMESSAGE
echo "" >> $EMAILMESSAGE
for (( i=0; i<$2; i++ ))
do
/usr/sbin/smartctl -a -d cciss,$i /dev/cciss/c0d0 | grep -E '(Serial|Health)' >> $EMAILMESSAGE
echo "" >> $EMAILMESSAGE
done
mail -s "$MSG_SUBJECT" "$3" < $EMAILMESSAGE
fi
create it as /usr/local/sbin/hpacucli_monthen add to your crontab (don't forget to set right arguments) :
00 */1 * * * /usr/local/sbin/hpacucli_mon 2 4 yourname@yourwebsite.com Once a "logicaldrive" or HDD gets failed, you will be mailed to yourname@yourwebsite.com :
We have encountered a problem at 192.168.12.13Take look at this:
logicaldrive 1 (136.7 GB, RAID 1): OK
physicaldrive 2I:1:1 (port 2I:box 1:bay 1, 146 GB): OK physicaldrive 2I:1:2 (port 2I:box 1:bay 2, 146 GB): OK
===============================================INFORMATION PROVIDED BY SMARTCTL:
Serial number: 3NM51VPY000098372XJXSMART Health Status: OK
Serial number: 3NM1LPG100009740XJX5SMART Health Status: OK
Wednesday, October 16, 2013
source: http://danielmiessler.com/study/tcpdump/
tcpdump is the premier network analysis tool for information securityprofessionals. Having a solid grasp of this über-powerful application is mandatory for anyone desiring a thorough understanding of TCP/IP. Many prefer to use higher level analysis tools such asEtherealWireshark, but I believe this to usually be a mistake.
Read Captured Traffic back into
tcpdump is the premier network analysis tool for information securityprofessionals. Having a solid grasp of this über-powerful application is mandatory for anyone desiring a thorough understanding of TCP/IP. Many prefer to use higher level analysis tools such as
In a discipline so dependent on a true understanding of concepts vs.rote learning, it's important to stay fluent in the underlying mechanics of the TCP/IP suite. A thorough grasp of these protocols allows one to troubleshoot at a level far beyond the average analyst, but mastery of the protocols is only possible through continued exposure to them.
When using a tool that displays network traffic a more natural (raw) way the burden of analysis is placed directly on the human rather than the application. This approach cultivates continued and elevated understanding of the TCP/IP suite, and for this reason I stronglyadvocate using
tcpdump instead of other tools whenever possible.15:31:34.079416 IP (tos 0x0, ttl 64, id 20244, offset 0, flags [DF], proto: TCP (6), length: 60) source.35970 > dest.80: S, cksum 0x0ac1 (correct), 2647022145:2647022145(0) win 5840 0x0000: 4500 003c 4f14 4000 4006 7417 0afb 0257 E.. 0x0010: 4815 222a 8c82 0050 9dc6 5a41 0000 0000 H."*...P..ZA.... 0x0020: a002 16d0 0ac1 0000 0204 05b4 0402 080a ................ 0x0030: 14b4 1555 0000 0000 0103 0302
Options
Below are a few options (with examples) that will help you greatly when working with the tool. They're easy to forget and/or confuse with other types of filters, i.e. ethereal, so hopefully this page can serve as a reference for you, as it does me.
First off, I like to add a few options to the
tcpdump command itself, depending on what I'm looking at. The first of these is -n, which requests that names are not resolved, resulting in the IPs themselves always being displayed. The second is -X, which displays both hex and ascii content within the packet. The final one is -S, which changes the display of sequence numbers to absolute rather than relative. The idea there is that you can't see weirdness in the sequence numbers if they're being hidden from you. Remember, the advantage of usingtcpdump vs. another tool is getting manual interaction with the packets.
It's also important to note that 68 96 bytes of data from a packet by default. If you would like to look at more, add the -s number option to the mix, where number is the number of bytes you want to capture. I recommend using 0 (zero) for a snaplength, which gets everything. Here's a short list of the options I use most:
tcpdump only takes the first -i any: Listen on all interfaces just to see if you're seeing any traffic.-n: Don't resolve hostnames.-nn: Don't resolve hostnames or port names.-X: Show the packet's contents in both hex and ASCII.- -A: Show ASCII only
-XX: Same as-X, but also shows the ethernet header.-v, -vv, -vvv: Increase the amount of packet information you get back.-c: Only get x number of packets and then stop.-s: Define the snaplength (size) of the capture in bytes. Use-s0to get everything, unless you are intentionally capturing less.-S: Print absolute sequence numbers.-e: Get the ethernet header as well.-q: Show less protocol information.-E: Decrypt IPSEC traffic by providing an encryption key.
[ The default snaplength as of
tcpdump 4.0 has changed from 68 bytes to 96 bytes. While this will give you more of a packet to see, it still won't get everything. Use-s 1514 to get full coverage ]Basic Usage
So, based on the kind of traffic I'm looking for, I use a different combination of options to
tcpdump, as can be seen below:- Basic communication // see the basics without many options# tcpdump -nS
- Basic communication (very verbose) // see a good amount of traffic, with verbosity and no name help# tcpdump -nnvvS
- A deeper look at the traffic // adds -X for payload but doesn't grab any more of the packet# tcpdump -nnvvXS
- Heavy packet viewing // the final "s" increases the snaplength, grabbing the whole packet# tcpdump -nnvvXSs 1514
Here's a capture of exactly two (
-c2) ICMP packets (a ping and pong) using some of the options described above. Notice how much we see about each packet.hermes root # tcpdump -nnvXSs 0 -c2 icmp tcpdump: listening on eth0, link-type EN10MB (Ethernet), 23:11:10.370321 IP (tos 0x20, ttl 48, id 34859, offset 0, flags [none], length: 84) 69.254.213.43 > 72.21.34.42: icmp 64: echo request seq 0 0x0000: 4520 0054 882b 0000 3001 7cf5 45fe d52b E..T.+..0.|.E..+ 0x0010: 4815 222a 0800 3530 272a 0000 25ff d744 H."*..50'*..%..D 0x0020: ae5e 0500 0809 0a0b 0c0d 0e0f 1011 1213 .^.............. 0x0030: 1415 1617 1819 1a1b 1c1d 1e1f 2021 2223 .............!"# 0x0040: 2425 2627 2829 2a2b 2c2d 2e2f 3031 3233 $%&'()*+,-./0123 0x0050: 3435 3637 4567 23:11:10.370344 IP (tos 0x20, ttl 64, id 35612, offset 0, flags [none], length: 84) 72.21.34.42 > 69.254.213.43: icmp 64: echo reply seq 0 0x0000: 4520 0054 8b1c 0000 4001 6a04 4815 222a E..T....@.j.H."* 0x0010: 45fe d52b 0000 3d30 272a 0000 25ff d744 E..+..=0'*..%..D 0x0020: ae5e 0500 0809 0a0b 0c0d 0e0f 1011 1213 .^.............. 0x0030: 1415 1617 1819 1a1b 1c1d 1e1f 2021 2223 .............!"# 0x0040: 2425 2627 2829 2a2b 2c2d 2e2f 3031 3233 $%&'()*+,-./0123 0x0050: 3435 3637 4567 2 packets captured 2 packets received by filter 0 packets dropped by kernel hermes root #
Common Syntax
Expressions allow you to trim out various types of traffic and find exactly what you're looking for. Mastering the expressions and learning to combine them creatively is what makes one truly powerful with
tcpdump. There are three main types of expression: type, dir, andproto.
Type options are
host, net, and port. Direction is indicated by dir, and there you can have src, dst, src or dst, and src and dst. Here are a few that you should definitely be comfortable with:host// look for traffic based on IP address (also works with hostname if you're not using -n)# tcpdump host 1.2.3.4src,dst// find traffic from only a source or destination (eliminates one side of a host conversation)# tcpdump src 2.3.4.5
# tcpdump dst 3.4.5.6net// capture an entire network using CIDR notation# tcpdump net 1.2.3.0/24proto// works for tcp, udp, and icmp. Note that you don't have to typeproto# tcpdump icmpport// see only traffic to or from a certain port# tcpdump port 3389src, dst port// filter based on the source or destination port# tcpdump src port 1025
# tcpdump dst port 389src/dst, port, protocol// combine all three# tcpdump src port 1025 and tcp
# tcpdump udp and src port 53
You also have the option to filter by a range of ports instead of declaring them individually, and to only see packets that are above or below a certain size.
- Port Ranges // see traffic to any port in a range
tcpdump portrange 21-23 - Packet Size Filter // only see packets below or above a certain size (in bytes)
tcpdump less 32tcpdump greater 128
[ You can use the symbols for less than, greater than, and less than or equal/ greater than or equal signs as well. ]
// filtering for size using symbolstcpdump > 32tcpdump <= 128Writing to a File
tcpdump allows you to send what you're capturing to a file for later use using the -w option, and then to read it back using the -r option. This is an excellent way to capture raw traffic and then run it through various tools later.
The traffic captured in this way is stored in
tcpdump format, which is pretty much universal in the network analysis space. This means it can be read in by all sorts of tools, including Wireshark, Snort, etc.Capture all Port 80 Traffic to a File
# tcpdump -s 1514 port 80 -w capture_file
Then, at some point in the future, you can then read the traffic back in like so:
Read Captured Traffic back into tcpdump
# tcpdump -r capture_file
Getting Creative
Expressions are nice, but the real magic of
tcpdump comes from the ability to combine them in creative ways in order to isolate exactly what you're looking for. There are three ways to do combinations, and if you've studied computers at all they'll be pretty familar to you:- AND
andor&& - OR
oror|| - EXCEPT
notor!
More Examples
# TCP traffic from 10.5.2.3 destined for port 3389
tcpdump -nnvvS and src 10.5.2.3 and dst port 3389
# Traffic originating from the 192.168 network headed for the 10 or 172.16 networks
tcpdump -nvX src net 192.168.0.0/16 and dst net 10.0.0.0/8 or172.16.0.0/16
# Non-ICMP traffic destined for 192.168.0.2 from the 172.16 network
tcpdump -nvvXSs 1514 dst 192.168.0.2 and src net and not icmp
# Traffic originating from Mars or Pluto that isn't to the SSH port
tcpdump -vv src mars and not dst port 22
As you can see, you can build queries to find just about anything you need. The key is to first figure out precisely what you're looking for and then to build the syntax to isolate that specific type of traffic.
Grouping
Also keep in mind that when you're building complex queries you might have to group your options using single quotes. Single quotes are used in order to tell
tcpdump to ignore certain special characters -- in this case the "( )" brackets. This same technique can be used to group using other expressions such as host, port, net, etc. Take a look at the command below:
# Traffic that's from 10.0.2.4 AND destined for ports 3389 or 22(incorrect)
tcpdump src 10.0.2.4 and (dst port 3389 or 22)
If you tried to run this otherwise very useful command, you'd get an error because of the parenthesis. You can either fix this by escaping the parenthesis (putting a \ before each one), or by putting the entire command within single quotes:
# Traffic that's from 10.0.2.4 AND destined for ports 3389 or 22 (correct)
tcpdump 'src 10.0.2.4 and (dst port 3389 or 22)'
Advanced
You can also filter based on specific portions of a packet, as well as combine multiple conditions into groups. The former is useful when looking for only SYNs or RSTs, for example, and the latter for even more advanced traffic isolation.
[ Hint: An anagram for the TCP flags: Unskilled Attackers Pester Real SecurityFolk ]
Show me all URGENT (URG) packets...
# tcpdump 'tcp[13] & 32!=0'
Show me all ACKNOWLEDGE (ACK) packets...
# tcpdump 'tcp[13] & 16!=0'
Show me all PUSH (PSH) packets...
# tcpdump 'tcp[13] & 8!=0'
Show me all RESET (RST) packets...
# tcpdump 'tcp[13] & 4!=0'
Show me all SYNCHRONIZE (SYN) packets...
# tcpdump 'tcp[13] & 2!=0'
Show me all FINISH (FIN) packets...
# tcpdump 'tcp[13] & 1!=0'
Show me all SYNCHRONIZE/ACKNOWLEDGE (SYNACK) packets...
# tcpdump 'tcp[13]=18'
[ Note: Only the PSH, RST, SYN, and FIN flags are displayed in
tcpdump's flag field output. URGs and ACKs are displayed, but they are shown elsewhere in the output rather than in the flags field ]
Keep in mind the reasons these filters work. The filters above find these various packets because
tcp[13] looks at offset 13 in the TCP header, the number represents the location within the byte, and the !=0 means that the flag in question is set to 1, i.e. it's on.
As with most powerful tools, however, there are multiple ways to do things. The example below shows another way to capture packets with specific TCP flags set.
Capture TCP Flags Using the
tcpflags Option...
# tcpdump 'tcp[tcpflags] & & tcp-syn != 0'
Specialized Traffic
Finally, there are a few quick recipes you'll want to remember for catching specific and specialized traffic, such as IPv6 and malformed/likely-malicious packets.
IPv6 traffic
# tcpdump ip6
Packets with both the RST and SYN flags set (why?)
# tcpdump 'tcp[13] = 6'
Traffic with the 'Evil Bit' Set
# tcpdump 'ip[6] & 128 != 0'
Conclusion
Well, this primer should get you going strong, but the man pageshould always be handy for the most advanced and one-off usage scenarios. I truly hope this has been useful to you, and feel free tocontact me if you have any questions. ::
Recommended
- A
vimPrimer
http://danielmiessler.com/study/vim/ - A
tcpdumpPrimer
http://danielmiessler.com/study/tcpdump/ - An
lsofPrimer
http://danielmiessler.com/study/lsof/ - An Encoding Primer
http://danielmiessler.com/study/encoding/ - An HTTP Primer
http://danielmiessler.com/study/http/ - A Git Primer
http://danielmiessler.com/study/git/ - A Collection of Less Commonly Used Unix Commands
http://danielmiessler.com/blog/collection-of-less-commonly-used-unix-commands - 9 Enhancements to Shell and Vim Productivity
http://danielmiessler.com/writing/vulnerability_assessment_penetration_test/ - Information Security Interview Questions
http://danielmiessler.com/study/infosec_interview_questions/ - Top Content
http://danielmiessler.com/popular/
Subscribe to:
Posts (Atom)