SSH — беспарольная аутентификация с помощью ssh-agent

Генерируем приватный и публичный ключи для сервера с паролем:

root@priovtb-sftp:~# ssh-keygen -t dsa
Generating public/private dsa key pair.
Enter file in which to save the key (/root/.ssh/id_dsa):
/root/.ssh/id_dsa already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_dsa.
Your public key has been saved in /root/.ssh/id_dsa.pub.
The key fingerprint is:
fe:61:e8:3e:0e:56:b5:13:c1:c7:f0:fe:fd:78:21:fa root@priovtb-sftp
The key's randomart image is:
+--[ DSA 1024]----+
|         .oo     |
|          .oo    |
|          o..    |
|         . +     |
|        S o .    |
|       o . . o o |
|      o o o . o o|
|     . o.o o   .o|
|       o+.. .E...|
+-----------------+

Запустим ssh-agent:

root@priovtb-sftp:~# exec ssh-agent /bin/bash

Проверим, какие ключи хранит в себе ssh-agent:

root@priovtb-sftp:~# ssh-add  -l
The agent has no identities.

Ключей пока нет.

Добавляем приватный ключ:

root@priovtb-sftp:~# ssh-add ~/.ssh/id_dsa
Enter passphrase for /root/.ssh/id_dsa:
Identity added: /root/.ssh/id_dsa (/root/.ssh/id_dsa)

Пробуем соединиться с хостом. Хост запрашивает пароль, потому что ключа пока нет.

root@priovtb-sftp:~# ssh 10.50.10.75
root@10.50.10.75's password:
^C

Заливаем на хост наш ключ. В процессе заливки ключа, хост запросит пользовательский пароль хоста:

root@priovtb-sftp:~# scp /root/.ssh/id_dsa.pub 10.50.10.75:~/.ssh/authorized_keys
root@10.50.10.75's password:
id_dsa.pub                       100%  607     0.6KB/s   00:00

Ключ на хосте. Пробуем соединиться по SSH:

root@priovtb-sftp:~# ssh 10.50.10.75
Linux lina 2.6.32-5-686 #1 SMP Mon Mar 26 05:20:33 UTC 2012 i686

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Thu Mar 29 15:25:00 2012 from 10.50.10.39
root@malina:~# exit
logout
Connection to 10.50.10.75 closed.
root@priovtb-sftp:~#

Отлично. Аутентификация прошла без запроса пароля, но при этом сам ключ запаролен. 🙂

Cisco, QoS и NBAR

Restrict Traffic Flow including P2P (Peer to Peer) using NBAR: An Overview

Introduction

NBAR (Network-Based Application Recognition) is a very indepth topic hence this FAQ will try to illustrate one of its many functionalities and how to action packets that match the protocol criteria required.

NBAR has its niche within the QoS (Quality of Service) crowd where specific applications are given precedence or not as the case maybe depending on the network requirements at the time of the implementation. NBAR allows recognition of a wide variety of applications where QoS may be implemented on them, i.e. from the bandwidth intensive Citrix to the port changing Kazaa P2P (Peer-to-Peer) application.

NBAR allows the classification of protocols from layer 4 to 7 hence allowing the router in some respects to disregard its layer 3 position and to look at the high layer protocols. NBAR can recognise:

• Statically assigned TCP and UDP port numbers

• Non-UDP and non-TCP IP protocols

• Dynamically assigned TCP and UDP port numbers. Classification of such applications requires stateful inspection; that is, the ability to discover the data connections to be classified by parsing the connections where the port assignments are made.

• Sub-port classification or classification based on deep packet inspection; that is, classification by looking deeper into the packet.

NBAR can classify static port protocols. Although access control lists (ACLs) can also be used for this purpose, NBAR is easier to configure and can provide classification statistics that are not available when using ACLs.

NBAR includes a Protocol Discovery feature that provides an easy way to discover application protocols that are transversing an interface. The Protocol Discovery feature discovers any protocol traffic supported by NBAR. Protocol Discovery maintains the following per-protocol statistics for enabled interfaces: total number of input and output packets and bytes, and input and output bit rates. The Protocol Discovery feature captures key statistics associated with each protocol in a network that can be used to define traffic classes and QoS policies for each traffic class.

The router (depending on model and IOS version) has built-in NBAR functionality which may be seen when configuring NBAR:

london-colo-east(config-cmap)#match protocol ?

Or when scrutinising a port-map:

london-colo-east-01-e-01#sh ip nbar port-map

which will demonstrate the ports and IP protocol of the various protoocols present.

An external Packet Description Language Module (PDLM) can be loaded at any time to extend the NBAR list of recognized protocols. PDLMs can also be used to enhance an existing protocol recognition capability. PDLMs allow NBAR to recognize new protocols without requiring a new Cisco IOS image or a router reload, hence PDLMs allow the router to gain the functionality of recognising applications at the application layer for the protoocols which when the router was shipped, was either not available or have changed in its function so much that an update is required.

To view a list of currently available PDLMs or to download a PDLM:

NBAR Packet Description Language Module Download

There are a number of examples, such as Citrix, gnuttella, skinny, etc. This type of traffic would have been hard to classify using standard QoS tecniques, either to minimise the impact of such programs on bandwidth, to drop them or to allocate the most amount of bandwidth to. PDLMs give the router this added ability to recognise the traffic specified by it as well as some other types of traffic pre-defined in the IOS.


Procedure (* optional if application NBAR required on is already present:

CEF should be enabled.

1.)* Copy the pdlm into the router’s flash:

london-colo-east-01-e-01#copy tftp flash
Address or name of remote host []? 192.168.1.254
Source filename []? bittorrent.pdlm
Destination filename [bittorrent.pdlm]? 
Accessing tftp://192.168.1.254/bittorrent.pdlm...
Erase flash: before copying? [confirm]n
Loading bittorrent.pdlm from 192.168.1.254 (via FastEthernet0.1): !
[OK - 4125 bytes]

Verifying checksum... OK (0xA1BF)
4125 bytes copied in 0.192 secs (21484 bytes/sec)
london-colo-east-01-e-01#sh flash:

System flash directory:
File Length Name/status
1 9773168 c1700-k9o3sy7-mz.123-10.bin 
2 4125 bittorrent.pdlm 
[9777424 bytes used, 6737644 available, 16515068 total]
16384K bytes of processor board System flash (Read/Write)

2.) Enable CEF

london-colo-east-01-e-01#conf t
Enter configuration commands, one per line.  End with CNTL/Z.
london-colo-east-01-e(config)#ip cef

3.)* Reference the pdlm in the config:

london-colo-east-01-e-01#conf t
Enter configuration commands, one per line.  End with CNTL/Z.
london-colo-east-01-e(config)#ip nbar pdlm bittorrent.pdlm 
london-colo-east-01-e(config)#

The result:

ip cef
ip nbar pdlm bittorrent.pdlm
!

4.) Create a class-map and policy map and apply it to the interface concerned:

class-map match-all bittorrent
  match protocol bittorrent
!
policy-map bittorrent-policy
  class bittorrent
   drop
!
interface FastEthernet0
 description Facing LAN
 ip address 192.168.1.1 255.255.255.0
 ip nat inside
 service-policy input bittorrent-policy
 speed 100
 full-duplex
!

Basically, within the policy-map bittorrent-policy, the action for any packets matching that protocol arriving on the fa0 interface was to DROP them. Packet manipulation is possible using QoS such as setting the precedence bits or setting maximum/limited bandwidth for further processing down the line but in this instance, the packets are set to be dropped as soon as they arrive on the fa0 interface.

QoS (Quality of Service) and NBAR

QoS should be the suggested reading for any more indepth look at policy-maps. As illustration, following is sample configuration using NBAR and QoS CBWFQ (Class-Based Weighted Fair Queue) for most common P2P protocols.

Unlike the previous sample configuration where P2P traffic is dropped or blocked, this sample configuration objective is to permit with restriction. The restriction is that all P2P traffic will be limited to only 8 kbps bandwidth. Any attempt from P2P traffic to use more than 8 kbps bandwidth will be dropped or blocked.

class-map match-any p2p
 match protocol bittorrent
 match protocol edonkey
 match protocol fasttrack
 match protocol gnutella
 match protocol kazaa2
 match protocol skype
!
policy-map QoS-inbound-policy
 class p2p
   police cir 8000
     conform-action drop
     exceed-action drop
!
interface FastEthernet0
 description Facing LAN
 ip address 192.168.1.1 255.255.255.0
 ip nat inside
 service-policy input QoS-inbound-policy
 speed 100
 full-duplex
!

==============================================================

 

Is your network bandwidth being consumed by Peer-to-Peer (P2P) traffic? (Hint: If you don’t know, it’s time to fire up NBAR and do a little investigating.) One way to stop P2P traffic is to use an access-list to block traffic on the well-know P2P ports. Unfortunately, many P2P technologies no longer rely on fixed ports. This means you can’t depend on access-lists being able to block the traffic. Cisco’s NBAR users packet inspection to determine what traffic class a data stream belongs to. With NBAR, it’s no longer necessary to know what ports an application is using.

Stopping P2P traffic with Cisco NBAR is a simple three step process. In the following example, we’ll use NBAR to block BitTorrent on our router’s Gigabit interface.

  1. Create a class-map to match the protocols to be blocked.
    SLAP(config)#class-map match-any P2P
    SLAP(config-cmap)#match protocol bittorrent
  2. Create a policy-map to specify what should be done with the traffic.
    SLAP(config)#policy-map P2P
    SLAP(config-pmap)#class P2P
    SLAP(config-pmap-c)#drop
  3. Apply the policy to the user-facing (incoming) interface.
    SLAP(config)#interface GigabitEthernet 0/2
    SLAP(config-if)#service-policy input P2P

You can ensure the policy is working with the show policy-map command.

SLAP#show policy-map interface g0/2 input
 GigabitEthernet0/2

  Service-policy input: P2P

    Class-map: P2P (match-any)
      994 packets, 327502 bytes
      30 second offered rate 43000 bps, drop rate 43000 bps
      Match: protocol bittorrent
        994 packets, 327502 bytes
        30 second rate 43000 bps
      drop

    Class-map: class-default (match-any)
      195253 packets, 51828774 bytes
      30 second offered rate 7282000 bps, drop rate 0 bps
      Match: any

In this example you can see that 43Kbps of BitTorrent traffic was blocked. 7.2Mbps of non-BitTorrent traffic was untouched (this is the class-default at the bottom of the output).

Unfortunately, the drop command used in the policy-map above was not introduced until IOS 12.2(13)T. If you are using a version of IOS older than 12.2(13)T, you will need to follow a not-as-simple five step process. This process relies on setting the DSCP field in the incoming packets, and then dropping those packets on the outbound interface. In the following example, we’ll block BitTorrent again, this time using the DSCP field.

  1. Create a class-map to match the protocols to be blocked.
    OLDSLAP(config)#class-map match-any P2P
    OLDSLAP(config-cmap)#match protocol bittorrent
  2. Create a policy-map to specify what should be done with the traffic.
    OLDSLAP(config)#policy-map P2P
    OLDSLAP(config-pmap)#class P2P
    OLDSLAP(config-pmap-c)#set ip dscp 1
  3. Create an access-list to block packets with the DSCP field set to 1.
    OLDSLAP(config)#access-list 100 deny ip any any dscp 1
    OLDSLAP(config)#access-list 100 permit ip any any
  4. Apply the policy to the user-facing (incoming) interface.
    OLDSLAP(config)#interface GigabitEthernet0/2
    OLDSLAP(config-if)#service-policy input P2P
  5. Apply the blocking access-list to the outbound interface.
    OLDSLAP(config)#interface POS1/1
    OLDSLAP(config-if)#ip access-group 100 out

Congratulations, you’ve successfully blocked P2P traffic on your network. Now, bolt the door and be ready for the angry mob with torches and pitchforks.

 

==========================================================

Начиная с IOS версии 12.4 (4) в Cisco стало возможным блокировать Skype. Для этого нужно создать простое правило. Также можно блокировать другие p2p приложения.

class−map match−any p2p
 match protocol skype
policy−map block−p2p
class p2p
drop

int FastEthernet0
description PIX−facing interface
service−policy input block−p2p

Если вы хотите посмотреть какие протоколы съедают ваш канал, то можно добавить в конфиг настройку:

ip nbar protocol-discovery

И потом смотреть с разбивкой по протоколам, какой тип трафика преобладает:

show ip nbar protocol-discovery stats bit-rate top-n 10

Так же можно посмотреть какие порты используют протоколы:

ip nbar port-map protocol-name [tcp | udp] port-number

Cisco PIX/ASA – Capturing Traffic

This document shows how to capture traffic directly at the Cisco PIX/ASA Firewall. Thats a very powerful tool for troubleshooting.

 

The Topology used in this test:

Capturing Traffic on the PIX — Topology

All traffic for the bastionhost (172.16.1.2) has to be captured for further analysis, the IP of the insidehost (10.0.1.12) is source-NATed to 172.16.1.20 when connecting to the DMZ.

This setup is based on the following PixOS-Release:

pix1# show version

Cisco PIX Firewall Version 6.3(3)
...
Hardware:   PIX-515, 64 MB RAM, CPU Pentium 200 MHz
Licensed Features:
Failover:                    Enabled
VPN-DES:                     Enabled
VPN-3DES-AES:                Enabled
Maximum Physical Interfaces: 6
Maximum Interfaces:          10
Cut-through Proxy:           Enabled
Guards:                      Enabled
URL-filtering:               Enabled
Inside Hosts:                Unlimited
Throughput:                  Unlimited
IKE peers:                   Unlimited

The capture-command:

pix1(config)# capture
Not enough arguments.
Usage: capture  [access-list ] [buffer ]
               [ethernet-type ] [interface ]
               [packet-length ]
               [circular-buffer]
       clear capture
       no capture  [access-list []] [circular-buffer]
               [interface ]
       show capture [ [access-list ] [count ]
                     [detail] [dump]]

Configuring the capture-function:

  1. Write an access-list that describes the interesting traffic (optional)
  2. Bind a capture-statement to an interface
  3. Wait for traffic
  4. Display or download the capture

Example:

pix1(config)# access-list capture-bastion permit ip any host bastionhost
pix1(config)# access-list capture-bastion permit ip host bastionhost any
pix1(config)# capture cap1 access-list capture-bastion interface dmz
pix1(config)#
pix1(config)# show capture
capture cap1 access-list capture-bastion interface dmz
pix1(config)#
pix1(config)# show capture cap1
0 packet captured
0 packet shown
pix1(config)#

(now we ping the bastionhost and access the web-server)

The resulting capture on the PIX:

pix1(config)# show capture cap1 detail
9 packets captured
19:28:27.554536 000d.56a9.3bbe 000c.297c.dffa 0x0800 74: 172.16.1.20 > bastionhost:
	icmp: echo request (ttl 128, id 46758)
19:28:27.555131 000c.297c.dffa 0002.b326.0704 0x0800 74: bastionhost > 172.16.1.20:
	icmp: echo reply (ttl 255, id 210)
19:28:38.482488 000d.56a9.3bbe 000c.297c.dffa 0x0800 62: 172.16.1.20.3874 > bastionhost.80:
	S [tcp sum ok] 306572975:306572975(0) win 65520  (DF)
	(ttl 128, id 46777)
19:28:38.483159 000c.297c.dffa 0002.b326.0704 0x0800 62: bastionhost.80 > 172.16.1.20.3874:
	S [tcp sum ok] 2581607285:2581607285(0) ack 306572976 win 15120
	 (DF) (ttl 64, id 211)
19:28:38.483419 000d.56a9.3bbe 000c.297c.dffa 0x0800 54: 172.16.1.20.3874 > bastionhost.80:
	. [tcp sum ok] 306572976:306572976(0) ack 2581607286 win 65520 (DF) (ttl 128, id 46778)
19:28:38.484731 000d.56a9.3bbe 000c.297c.dffa 0x0800 402: 172.16.1.20.3874 > bastionhost.80:
	P 306572976:306573324(348) ack 	2581607286 win 65520 (DF) (ttl 128, id 46779)
19:28:38.485158 000c.297c.dffa 0002.b326.0704 0x0800 60: bastionhost.80 > 172.16.1.20.3874:
	. [tcp sum ok] 2581607286:2581607286(0) ack 306573324 win 15120 (DF) (ttl 64, id 212)
19:28:38.488179 000c.297c.dffa 0002.b326.0704 0x0800 584: bastionhost.80 > 172.16.1.20.3874:
	P 2581607286:2581607816(530) ack 306573324 win 16380 (DF) (ttl 64, id 213)
19:28:38.614714 000d.56a9.3bbe 000c.297c.dffa 0x0800 54: 172.16.1.20.3874 > bastionhost.80:
	. [tcp sum ok] 306573324:306573324(0) ack 2581607816 win 64990 (DF) (ttl 128, id 46783)
9 packets shown
pix1(config)# show capture cap1 dump
13 packets captured
19:28:27.554536 172.16.1.20 > bastionhost: icmp: echo request
0x0000   4500 003c b6a6 0000 8001 29e4 ac10 0114        E..<......).....
0x0010   ac10 0102 0800 315c 0300 1900 6162 6364        ......1....abcd
0x0020   6566 6768 696a 6b6c 6d6e 6f70 7172 7374        efghijklmnopqrst
0x0030   7576 7761 6263                                 uvwabc
19:28:27.555131 bastionhost > 172.16.1.20: icmp: echo reply
0x0000   4500 003c 00d2 0000 ff01 60b8 ac10 0102        E..<......`.....
0x0010   ac10 0114 0000 395c 0300 1900 6162 6364        ......9....abcd
0x0020   6566 6768 696a 6b6c 6d6e 6f70 7172 7374        efghijklmnopqrst
0x0030   7576 7761 6263                                 uvwabc
19:28:38.482488 172.16.1.20.3874 > bastionhost.80: S 306572975:306572975(0)
    win 65520
0x0000   4500 0030 b6b9 4000 8006 e9d7 ac10 0114        E..0..@.........
0x0010   ac10 0102 0f22 0050 1245 eeaf 0000 0000        .....".P.E......
0x0020   7002 fff0 1959 0000 0204 04ec 0101 0402        p....Y..........
19:28:38.483159 bastionhost.80 > 172.16.1.20.3874: S 2581607285:2581607285(0)
    ack 306572976 win 15120
0x0000   4500 0030 00d3 4000 4006 dfbe ac10 0102        E..0..@.@.......
0x0010   ac10 0114 0050 0f22 99e0 3375 1245 eeb0        .....P."..3u.E..
0x0020   7012 3b10 10d3 0000 0204 04ec 0101 0402        p.;.............

Now we want to see more payload:

pix1(config)# clear capture cap1
pix1(config)# show capture cap1
0 packet captured
0 packet shown
pix1(config)#
pix1(config)# capture cap1 packet-length 1500
pix1(config)#
pix1(config)# show capture
capture cap1 access-list capture-bastion packet-length 1500 interface dmz
pix1(config)#

(we access the web-server again)

pix1(config)# show capture cap1 dump
...
19:40:04.374980 172.16.1.20.3876 > bastionhost.80: P 2217891186:2217891534(348)
    ack 3327525020 win 65520
0x0000   4500 0184 b868 4000 8006 e6d4 ac10 0114        E....h@.........
0x0010   ac10 0102 0f24 0050 8432 5572 c656 009c        .....$.P.2Ur.V..
0x0020   5018 fff0 4f1b 0000 4745 5420 2f66 6176        P...O...GET /fav
0x0030   6963 6f6e 2e69 636f 2048 5454 502f 312e        icon.ico HTTP/1.
0x0040   310d 0a48 6f73 743a 2031 3732 2e31 362e        1..Host: 172.16.
0x0050   312e 320d 0a55 7365 722d 4167 656e 743a        1.2..User-Agent:
0x0060   204d 6f7a 696c 6c61 2f35 2e30 2028 5769         Mozilla/5.0 (Wi
0x0070   6e64 6f77 733b 2055 3b20 5769 6e64 6f77        ndows; U; Window
0x0080   7320 4e54 2035 2e31 3b20 656e 2d55 533b        s NT 5.1; en-US;
0x0090   2072 763a 312e 372e 3529 2047 6563 6b6f         rv:1.7.5) Gecko
0x00a0   2f32 3030 3431 3130 3720 4669 7265 666f        /20041107 Firefo
0x00b0   782f 312e 300d 0a41 6363 6570 743a 2069        x/1.0..Accept: i
0x00c0   6d61 6765 2f70 6e67 2c2a 2f2a 3b71 3d30        mage/png,*/*;q=0
0x00d0   2e35 0d0a 4163 6365 7074 2d4c 616e 6775        .5..Accept-Langu
0x00e0   6167 653a 2064 652d 6465 2c64 653b 713d        age: de-de,de;q=
0x00f0   302e 382c 656e 2d75 733b 713d 302e 352c        0.8,en-us;q=0.5,
0x0100   656e 3b71 3d30 2e33 0d0a 4163 6365 7074        en;q=0.3..Accept
0x0110   2d45 6e63 6f64 696e 673a 2067 7a69 702c        -Encoding: gzip,
0x0120   6465 666c 6174 650d 0a41 6363 6570 742d        deflate..Accept-
0x0130   4368 6172 7365 743a 2049 534f 2d38 3835        Charset: ISO-885
0x0140   392d 312c 7574 662d 383b 713d 302e 372c        9-1,utf-8;q=0.7,
0x0150   2a3b 713d 302e 370d 0a4b 6565 702d 416c        *;q=0.7..Keep-Al
0x0160   6976 653a 2033 3030 0d0a 436f 6e6e 6563        ive: 300..Connec
0x0170   7469 6f6e 3a20 6b65 6570 2d61 6c69 7665        tion: keep-alive
0x0180   0d0a 0d0a                                      ....

We can transfer the capture to our workstation:

pix1(config)# copy capture:cap1 tftp://10.0.1.12/bastion.txt
copying Capture to tftp://10.0.1.12/bastion.txt:
pix1(config)#
C:TFTP-Root>dir
 Volume in drive C has no label.
 Volume Serial Number is 5001-0224

 Directory of C:TFTP-Root

16.11.2004  18:50          .
16.11.2004  18:50          ..
16.11.2004  18:49             2.754 bastion.txt
               1 File(s)          2.754 bytes
               2 Dir(s)   1.801.687.040 bytes free

C:TFTP-Root>

The capture on the workstation (viewed with notepad):

We can also export the capture in pcap-format (tcpdump):

pix1(config)# copy capture:cap1 tftp://10.0.1.12/bastion.cap pcap
copying Capture to tftp://10.0.1.12/bastion.cap:
pix1(config)#
C:TFTP-Root>dir
 Volume in drive C has no label.
 Volume Serial Number is 5001-0224

 Directory of C:TFTP-Root

16.11.2004  18:55             .
16.11.2004  18:55             ..
16.11.2004  18:55             5.747 bastion.cap
16.11.2004  18:49             2.754 bastion.txt
               2 File(s)          8.501 bytes
               2 Dir(s)   1.801.527.296 bytes free

C:TFTP-Root>

The capture on the workstation (viewd with Ethereal):

The capture can also be downloaded with a browser

If we want to view or download the capture with a browser we have to activate the https-server (thats automatically done if you have activated the PDM/ASDM). This Example shows the PIXv6 syntax:

pix1(config)# http server enable
pix1(config)#
pix1(config)# http 10.0.1.12 255.255.255.255 inside
pix1(config)#
pix1(config)# domain-name security-planet.de
pix1(config)#
pix1(config)# ca generate rsa key 1024
For  >= 1024, key generation could
  take up to several minutes. Please wait.
Keypair generation process begin.
.Success.

pix1(config)#

We can view the capture in the browser:

Or we can download the capture as pcap:

Finally we delete the capture on the PIX:

pix1(config)# no capture cap1
pix1(config)#
pix1(config)# show capture cap1
ERROR: capture  does not exist
pix1(config)# show capture
pix1(config)#

Источник: http://security-planet.de/2005/07/26/cisco-pix-capturing-traffic/

Настройка port forwarding в Cisco

Задачей будет настроить трансляцию с внешних адресов 200.100.50.56, 200.100.50.57 на адреса 192.168.1.1 — ftp сервис, 192.168.1.2 — веб сервис, 172.18.9.202 — все порты с адреса 200.100.50.57.

Схема подключения наших серверов:

Для проброса портов в Cisco PIX / ASA добавим в конфигурацию NAT-трансляцию:

FTP

static (inside,outside) tcp 200.100.50.56 ftp-data 192.168.1.1 ftp-data netmask 255.255.255.255
static (inside,outside) tcp 200.100.50.56 ftp 192.168.1.1 ftp netmask 255.255.255.255

WEB

static (inside,outside) tcp 200.100.50.56 www 192.168.1.2 www netmask 255.255.255.255 

Пробросим все порты на адрес в DMZ-зоне

static (dmz,outside) 200.100.50.57 172.18.9.202 netmask 255.255.255.255
static (dmz,inside) 200.100.50.57 172.18.9.202 netmask 255.255.255.255 

Тоже самое в IOS будет выглядеть примерно так:

ip nat inside source static tcp 192.168.1.1 21 200.100.50.56 21
ip nat inside source static tcp 192.168.1.2 80 200.100.50.56 80
ip nat inside source static tcp 172.18.9.202 200.100.50.57 extendable

Источник: http://sysadminblog.ru/cisco/2010/05/25/nastroyka-probrosa-portov-port-forwarding-v-cisco-2.html

Ускорение sh run в Cisco IOS

Наткнулся в буржуйском блоге на интересную команду в cisco ios. Если в конфиг добавить

parser config cache interface

то команды

copy system:running-configuration
show running-configuration
write terminal

работают в 2-3 раза быстрее. Особенно актуально на разросшихся конфигурациях, которые бывает формируются больше 5-10 секунд.

Команда появилась начиная с IOS версии 12.2(25).

Подробней о команде можно почитать тут.

Защита Apache от DDOS-атак

Пару недель назад позвонил один знакомый и пожаловался, что плохо работает сайт и канал поменяли на FTTX с xDSL и тариф выбрали со скоростью повыше, но помогло мало — пользователи жалуются на HTTP/1.1 403 Forbidden. Сервер настраивал им не я, благо что установлена Ubuntu 10.04 LTS — люблю продукты семейства long time support — очень уж они хорошо. Получив доступ начал ковырять систему — первое что бросилось в глаза — практически пустой фаейр — десятка 2 правил на вход-выход ЛВС и сайта в мир. Набрав в консоли команду

netstat -n --tcp | grep SYN_RECV

— несколько секунд наблюдал строчки вида:

tcp     0   0 xxx.xxx.xxx.xxx:80    206.192.175.100:1084    SYN_RECV tcp     0   0 xxx.xxx.xxx.xxx:80    206.192.175.100:1228    SYN_RECV tcp     0   0 xxx.xxx.xxx.xxx:80    206.192.175.100:2652    SYN_RECV tcp     0   0 xxx.xxx.xxx.xxx:80    206.192.175.100:3446    SYN_RECV

Сразу стало понятно — что сайт завален большим количеством syn-пакетов, потому так плохо и работает.


Удаленно ковырять файер не гут, потому ограничился минимумом — загнал в конфиг несколько дополнительных команд, заодно ограничил количество syn-пакетов до 500 в секунду, при превышении порога в 1500 — новые пакеты блокируются:

— выполняем с консоли и добавляем в /etc/rc.local на случай перезагрузки:

echo "20000" > /proc/sys/net/ipv4/tcp_max_syn_backlog echo "1" > /proc/sys/net/ipv4/tcp_synack_retries echo "30" > /proc/sys/net/ipv4/tcp_fin_timeout echo "5" > /proc/sys/net/ipv4/tcp_keepalive_probes echo "15" > /proc/sys/net/ipv4/tcp_keepalive_intvl echo "20000" > /proc/sys/net/core/netdev_max_backlog echo "20000" > /proc/sys/net/core/somaxconn

— добавляем в наш firewall-скрипт:

iptables -N syn_flood $IPT -A INPUT -p tcp --syn -j syn_flood $IPT -A syn_flood -m limit --limit 500/s --limit-burst 1500 -j RETURN $IPT -A syn_flood -j DROP

Портянка netstat стала существенно короче, но в логи все равно периодически выскакивала HTTP/1.1 403 Forbidden. Пришлось поковырять настройки apache2 — оказалось что подгружен mod_evasive — модуль для защиты от DOS/DDOS-атак, в принципе модуль неплохой, но для больших сайтов не годиться, потому решил что лучше его выключить и положиться на файер и настройки ядра, которые я сделал выше. Несколько дней понаблюдал за логами — HTTP/1.1 403 Forbidden выскочила раза 2-3, на том мы и остановились.

Вкратце о том что же за команды такие добавлены в настройки системы:

— tcp_syncookies — SYN cookies не использует очередь SYN, вместо этого ядро отвечает на каждый SYN пакет, как обычно SYN|ACK, но при этом в пакет будет включено специально сгенерированное число на основе IP адресов и портов источника и получателя, а также времени посылки пакета. Соответственно атакующий никогда не получит эти пакеты, а поэтому и не ответит на них. При реальном запросе, будет отправлен третий пакет, который содержащий число, а сервер проверит был ли это ответ на SYN cookie и, если да, то разрешит соединение даже в том случае, если в очереди SYN нет соответствующей записи. (З.Ы.: доступен только когда ядро собрано с CONFIG_SYNCOOKIES — тогда по умолчанию должен быть равен — 1)

— tcp_max_syn_backlog — размер очереди half-open connection (полуоткрытых соединений), по-умолчанию колеблется в диапазоне 1024-2048, лучше задавать от 15000 и выше.

— tcp_synack_retries — определяет сколько разрешено попыток повторной передачи пакетов SYNACK для пассивных соединений TCP. Не должно превышать 255. По-умолчанию значение 5 соответствует приблизительно 180 секундам на выполнение попыток организации соединения. Урезаем примерно до 9 секунд — присваиваем — 1.

— tcp_fin_timeout — определяет время сохранения сокета в состоянии FIN-WAIT-2 после его закрытия локальной стороной. Запрашивающая сторона может не закрыть это соединение никогда, поэтому следует закрыть его по своей инициативе по истечении тайм-аута. По умолчанию тайм-аут составляет 60 секунд, в некоторых старых ядрах linux — было 180 секунд. Если у WEB-сервера очень высокая нагрузкая смело поджимайте до 20-30.

— tcp_keepalive_probes — определяет keepalive-запросов, после которого соединение считается разорванным, По-умолчанию передается 9 запросов. Так как каналы у всех достаточно быстрые — жмем до 5, в принципе проблем не замечено и при 4, но когда из Нижних дыр юзеры лезут по диал-ап — могут быть проблемы.

— tcp_keepalive_intvl — определяет интервал передачи проб. Вычисляется как [tcp_keepalive_probes]*[tcp_keepalive_intvl] — результат дает нам время, по истечении которого соединение будет разорвано при отсутствии откликов. По умолчанию установлен интервал 75 секунд, таким образом разрыв соединения произойдет примерно через 675 секунд (больше 10 минут!!!!).

— netdev_max_backlog — определяет максимальное количество пакетов в очередь на обработку если интерфейс получает пакеты быстрее, чем ядро может их обработать. Для современного железа можно задавать высокие показатели, по-умолчанию 1000.

— somaxconn — определяет максимальное число открытых сокетов, ждущих соединения.

Источник: http://sysadminblog.ru/linux/2012/03/20/zaschita-ot-apache-ot-ddos-atak.html#comment921