Настройка доступа – Сети Для Самых Маленьких
При более глубокой настройке line vty существует одна опасность.
Есть такой параметр: access-class. Его настройка позволяет ограничить IP-адреса, с которых возможно подключение. И вот однажды я, как умная маша, решил заняться безопасностью в сети и на всём почти оборудование понаставил эти аксес-листы, чтобы комар не пролетел. В один прекрасный момент пришлось выехать в поле и в тот день я проклял свою аккуратность – никуда не мог достучаться – малейшей лазейки не оставил. В общем будьте с этой командой внимательны или оставляйте для себя лазейки.
При работе с access-list’ами и прочими опасными вещами, неправильная настройка которых может лишить вас доступа к устройству, можно использовать замечательную команду reload in min, где min время в минутах. Эта команда перезагрузит устройство по истечении указанного времени, если ее не прервать командой reload cancel. Т.е. схема работы такова: вы удаленно копаете что-то, что может в теории (закон Мерфи не забываем) прервать ваш сеанс связи с устройством. Сохраняем текущий (рабочий) конфиг в startup-config (он используется при загрузке), ставим reload in 15, вводим ключевую команду, относительно которой у нас сомнения ;-), и получаем обрыв связи, худшие опасения оправдались. Ждем 15 минут, устройство перегружается с рабочим конфигом, коннект — вуаля, связь есть. Либо (если связь не прервалась) проверяем, что все работает, и делаем reload cancel.
Cdp (lldp)
Сервис CDP включен на коммутаторе по-умолчанию. Для выключения:
(config)# no cdp run
На отдельном интерфейсе:
(config-if)# no cdp enable
Время между посылками CDP-пакетов:
(config)# cdp timer <sec>
Время, которое принятая от соседа информация считается действительной:
(config)# cdp holdtime <sec>
Если в сети находятся устройства иных производителей, то имеется возможность использовать протокол LLDP:
(config)# lldp run
На отдельном интерфейсе:
(config-if)# lldp transmit(config-if)# lldp receive
Change-of-authorization requests
Change of Authorization (CoA) requests, as described in RFC 5176, are used in a push model to allow for session identification, host reauthentication, and session termination. The model is comprised of one request (CoA-Request) and two possible response codes:
The request is initiated from a CoA client (typically a RADIUS or policy server) and directed to the switch that acts as a listener.
This section includes these topics:
Coa disconnect-request
This command is a standard Disconnect-Request. Because this command is session-oriented, it must be accompanied by one or more of the session identification attributes described in the “Session Identification” section. If the session cannot be located, the switch returns a Disconnect-NAK message with the “Session Context Not Found” error-code attribute.
If the switch fails-over to a standby switch before returning a Disconnect-ACK to the client, the process is repeated on the new active switch when the request is re-sent from the client. If the session is not found following re-sending, a Disconnect-ACK is sent with the “Session Context Not Found” error-code attribute.
Coa request: bounce-port
This command is carried in a standard CoA-Request message that contains the following new VSA:
Cisco:Avpair=”subscriber:command=bounce-host-port”
Because this command is session-oriented, it must be accompanied by one or more of the session identification attributes described in the “Session Identification” section. If the session cannot be located, the switch returns a CoA-NAK message with the “Session Context Not Found” error-code attribute.
If the switch fails before returning a CoA-ACK to the client, the process is repeated on the new active switch when the request is re-sent from the client. If the switch fails after returning a CoA-ACK message to the client but before the operation has completed, the operation is re-started on the new active switch.
Coa request: disable host port
This command is carried in a standard CoA-Request message that has this new VSA:
Cisco:Avpair=”subscriber:command=disable-host-port”
Because this command is session-oriented, it must be accompanied by one or more of the session identification attributes described in the “Session Identification” section. If the session cannot be located, the switch returns a CoA-NAK message with the “Session Context Not Found” error-code attribute. If the session is located, the switch disables the hosting port and returns a CoA-ACK message.
If the switch fails before returning a CoA-ACK to the client, the process is repeated on the new active switch when the request is re-sent from the client. If the switch fails after returning a CoA-ACK message to the client but before the operation has completed, the operation is restarted on the new active switch.
Configuring radius login authentication
To configure AAA authentication, you define a named list of authentication methods and then apply that list to various ports. The method list defines the types of authentication to be performed and the sequence in which they are performed; it must be applied to a specific port before any of the defined authentication methods are performed.
Configuring tacacs login authentication
To configure AAA authentication, you define a named list of authentication methods and then apply that list to various ports. The method list defines the types of authentication to be performed and the sequence in which they are performed; it must be applied to a specific port before any of the defined authentication methods are performed.
The only exception is the default method list (which, by coincidence, is named default). The default method list is automatically applied to all ports except those that have a named method list explicitly defined. A defined method list overrides the default method list.
Defining aaa server groups
You can configure the switch to use AAA server groups to group existing server hosts for authentication. You select a subset of the configured server hosts and use them for a particular service. The server group is used with a global server-host list, which lists the IP addresses of the selected server hosts.
Server groups also can include multiple host entries for the same server if each entry has a unique identifier (the combination of the IP address and UDP port number), allowing different ports to be individually defined as RADIUS hosts providing a specific AAA service.
You use the server group server configuration command to associate a particular server with a defined group server. You can either identify the server by its IP address or identify multiple host instances or entries by using the optional auth-port and acct-port keywords.
Beginning in privileged EXEC mode, follow these steps to define the AAA server group and associate a particular RADIUS server with it:
Step 1 | configure terminal | Enter global configuration mode. |
Step 2 | radius-server host { hostname | ip-address } [ auth-port port-number ] [ acct-port port-number ] [ timeout seconds ] [ retransmit retries ] [ key string ] | Specify the IP address or hostname of the remote RADIUS server host. Note The key is a text string that must match the encryption key used on the RADIUS server. Always configure the key as the last item in the radius-server host command. Leading spaces are ignored, but spaces within and at the end of the key are used. If you use spaces in your key, do not enclose the key in quotation marks unless the quotation marks are part of the key. To configure the switch to recognize more than one host entry associated with a single IP address, enter this command as many times as necessary, making sure that each UDP port number is different. The switch software searches for hosts in the order in which you specify them. Set the timeout, retransmit, and encryption key values to use with the specific RADIUS host. |
Step 3 | aaa new-model | Enable AAA. |
Step 4 | aaa group server radius group-name | Define the AAA server-group with a group name. This command puts the switch in a server group configuration mode. |
Step 5 | server ip-address | Associate a particular RADIUS server with the defined server group. Repeat this step for each RADIUS server in the AAA server group. Each server in the group must be previously defined in Step 2. |
Step 6 | end | Return to privileged EXEC mode. |
Step 7 | show running-config | Verify your entries. |
Step 8 | copy running-config startup-config | (Optional) Save your entries in the configuration file. |
Step 9 | Enable RADIUS login authentication. See the “Configuring RADIUS Login Authentication” section. |
To remove the specified RADIUS server, use the no radius-server host hostname | ip-address global configuration command. To remove a server group from the configuration list, use the no aaa group server radius group-name global configuration command.
In this example, the switch is configured to recognize two different RADIUS group servers ( group1 and group2). Group1 has two different host entries on the same RADIUS server configured for the same services. The second host entry acts as a fail-over backup to the first entry.
Identifying the radius server host
Switch-to-RADIUS-server communication involves several components:
You identify RADIUS security servers by their hostname or IP address, hostname and specific UDP port numbers, or their IP address and specific UDP port numbers. The combination of the IP address and the UDP port number creates a unique identifier, allowing different ports to be individually defined as RADIUS hosts providing a specific AAA service. This unique identifier enables RADIUS requests to be sent to multiple UDP ports on a server at the same IP address.
If two different host entries on the same RADIUS server are configured for the same service—for example, accounting—the second host entry configured acts as a fail-over backup to the first one. Using this example, if the first host entry fails to provide accounting services, the %RADIUS-4-RADIUS_DEAD message appears, and then the switch tries the second host entry configured on the same device for accounting services. (The RADIUS host entries are tried in the order that they are configured.)
A RADIUS server and the switch use a shared secret text string to encrypt passwords and exchange responses. To configure RADIUS to use the AAA security commands, you must specify the host running the RADIUS server daemon and a secret text (key) string that it shares with the switch.
The timeout, retransmission, and encryption key values can be configured globally for all RADIUS servers, on a per-server basis, or in some combination of global and per-server settings. To apply these settings globally to all RADIUS servers communicating with the switch, use the three unique global configuration commands: radius-server timeout, radius-server retransmit, and radius-server key. To apply these values on a specific RADIUS server, use the radius-server host global configuration command.
Identifying the tacacs server host and setting the authentication key
You can configure the switch to use a single server or AAA server groups to group existing server hosts for authentication. You can group servers to select a subset of the configured server hosts and use them for a particular service. The server group is used with a global server-host list and contains the list of IP addresses of the selected server hosts.
Beginning in privileged EXEC mode, follow these steps to identify the IP host or host maintaining TACACS server and optionally set the encryption key:
To remove the specified TACACS server name or address, use the no tacacs-server host hostname global configuration command. To remove a server group from the configuration list, use the no aaa group server tacacs group-name global configuration command.
Overview
A standard RADIUS interface is typically used in a pulled model where the request originates from a network attached device and the response come from the queried servers. Catalyst switches support the RADIUS Change of Authorization (CoA) extensions defined in RFC 5176 that are typically used in a pushed model and allow for the dynamic reconfiguring of sessions from external authentication, authorization, and accounting (AAA) or policy servers.
Beginning with Cisco IOS Release 12.2(52)SE, the switch supports these per-session CoA requests:
This feature is integrated with the Cisco Secure Access Control Server (ACS) 5.1. For information about ACS, refer to:
Privilege level
Ещё один важный момент, которому в статьях уделяют мало внимания: privelege level.
Как понятно из латинского звучания — это уровень прав пользователя. Всего существует 16 уровней: 0-15.
privilege level 0
— это команды disable, enable, exit, help и logout, которые работают во всех режимах;privilege level 1
— это команды пользовательского режима, то есть как только вы попадаете на циску и увидите приглашение Router> вы имеете уровень 1;privilege level 15
— это команды привилегированного режима, вроде, как root в Unix’ах.
Rfc 5176 compliance
The Disconnect Request message, which is also referred to as Packet of Disconnect (POD), is supported by the switch for session termination.
Table 9-2 shows the IETF attributes are supported for this feature.
Table 9-3 shows the possible values for the Error-Cause attribute.
Session identification
For disconnect and CoA requests targeted at a particular session, the switch locates the session based on one or more of the following attributes:
Unless all session identification attributes included in the CoA message match the session, the switch returns a Disconnect-NAK or CoA-NAK with the “Invalid Attribute Value” error-code attribute.
For disconnect and CoA requests targeted to a particular session, any one of the following session identifiers can be used:
If more than one session identification attribute is included in the message, all the attributes must match the session or the switch returns a Disconnect- negative acknowledgement (NAK) or CoA-NAK with the error code “Invalid Attribute Value.”
The packet format for a CoA Request code as defined in RFC 5176 consists of the fields: Code, Identifier, Length, Authenticator, and Attributes in Type:Length:Value (TLV) format.
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| Code | Identifier | Length |
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| |
| Authenticator |
| |
| |
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| Attributes...
- - - - - - - - - - - - -
The attributes field is used to carry Cisco VSAs.
Session reauthentication
The AAA server typically generates a session reauthentication request when a host with an unknown identity or posture joins the network and is associated with a restricted access authorization profile (such as a guest VLAN). A reauthentication request allows the host to be placed in the appropriate authorization group when its credentials are known.
To initiate session authentication, the AAA server sends a standard CoA-Request message which contains a Cisco vendor-specific attribute (VSA) in this form: Cisco:Avpair=“subscriber:command=reauthenticate” and one or more session identification attributes.
The current session state determines the switch response to the message. If the session is currently authenticated by IEEE 802.1x, the switch responds by sending an EAPoL2-RequestId message (see footnote 1 below) to the server.
If the session is currently authenticated by MAC authentication bypass (MAB), the switch sends an access-request to the server, passing the same identity attributes used for the initial successful authentication.
If session authentication is in progress when the switch receives the command, the switch terminates the process, and restarts the authentication sequence, starting with the method configured to be attempted first.
If the session is not yet authorized, or is authorized via guest VLAN, or critical VLAN, or similar policies, the reauthentication message restarts the access control methods, beginning with the method configured to be attempted first. The current authorization of the session is maintained until the reauthentication leads to a different authorization result.
Setting a telnet password for a terminal line
When you power-up your switch for the first time, an automatic setup program runs to assign IP information and to create a default configuration for continued use. The setup program also prompts you to configure your switch for Telnet access through a password.
Beginning in privileged EXEC mode, follow these steps to configure your switch for Telnet access:
To remove the password, use the no password global configuration command.
This example shows how to set the Telnet password to let45me67in89 :
Setting or changing a static enable password
The enable password controls access to the privileged EXEC mode. Beginning in privileged EXEC mode, follow these steps to set or change a static enable password:
To remove the password, use the no enable password global configuration command.
This example shows how to change the enable password to l1u2c3k4y5. The password is not encrypted and provides access to level 15 (traditional privileged EXEC mode access):
Setting the privilege level for a command
Beginning in privileged EXEC mode, follow these steps to set the privilege level for a command mode:
Step 1 | configure terminal | Enter global configuration mode. |
Step 2 | privilege mode level level command | Set the privilege level for a command. |
Step 3 | enable password level level password | Specify the enable password for the privilege level. |
Step 4 | end | Return to privileged EXEC mode. |
Step 5 | show running-config or show privilege | Verify your entries. The first command shows the password and access level configuration. The second command shows the privilege level configuration. |
Step 6 | copy running-config startup-config | (Optional) Save your entries in the configuration file. |
When you set a command to a privilege level, all commands whose syntax is a subset of that command are also set to that level. For example, if you set the show ip traffic command to level 15, the show commands and show ip commands are automatically set to privilege level 15 unless you set them individually to different levels.
To return to the default privilege for a given command, use the no privilege mode level level command global configuration command.
Snmpv3
Создать SNMP-tree view для чтения и записи:
(config)# snmp-server view READVIEW1 <MIB-view-family> { included | excluded }(config)# snmp-server view WRITEVIEW1 <MIB-view-family> { included | excluded }
где MIB-view-family может быть: [] mib2, system, internet, iso и т.д. []
Создать access-list:
(config)# ipv6 access-list SNMP-ACL1(config-ipv6-acl)# permit xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx(config-ipv6-acl)# exit
Создать SNMP-группу:
(config)# snmp-server group <grname> v3 auth read READVIEW1 write WRITEVIEW1 access ipv6 SNMP-ACL1
Создать пользователей SNMP-сервера:
Stacking guidelines for coa-request bounce-port
Because the bounce-port command is targeted at a session, not a port, if the session is not found, the command cannot be executed.
When the Auth Manager command handler on the stack master receives a valid bounce-port command, it checkpoints the following information before returning a CoA-ACK message:
The switch initiates a port-bounce (disables the port for 10 seconds, then re-enables it).
If the port-bounce is successful, the signal that triggered the port-bounce is removed from the standby stack master.
If the stack master fails before the port-bounce completes, a port-bounce is initiated after stack master change-over based on the original command (which is subsequently removed).
If the stack master fails before sending a CoA-ACK message, the new stack master treats the re-sent command as a new command.
Stacking guidelines for coa-request disable-port
Because the disable-port command is targeted at a session, not a port, if the session is not found, the command cannot be executed.
When the Auth Manager command handler on the stack master receives a valid disable-port command, it verifies this information before returning a CoA-ACK message:
The switch attempts to disable the port.
If the port-disable operation is successful, the signal that triggered the port-disable is removed from the standby stack master.
If the stack master fails before the port-disable operation completes, the port is disabled after stack master change-over based on the original command (which is subsequently removed).
If the stack master fails before sending a CoA-ACK message, the new stack master treats the re-sent command as a new command.
Vtpv3
Основные отличия от 1 и 2 версии:*** Поддержка Privat-VLAN;*** Поддержка полного диапазона VLAN ( 1 — 4096 );*** Возможность настройки на уровне отдельного порта;*** Защита пароля домена;*** Решена проблема с подключением нового коммутатора (когда происходила перезапись базы VLAN всего домена);*** Обмен данными более эффективен;*** Работа в режиме передачи данных между процессами MST.
Настройка VTPv3:
(config)# vtp domain <name>(config)# vtp version 3(config)# vtp mode { server | client }(config)# vtp password <passwd> { hidden | secret }
Если switch работает в режиме server, необходимо его тип — BACKUP(по-умолчанию) или PRIMAR:
Switch# vtp primary vlan This system is becoming primary server for feature vlan No conflicting VTP3 devices found. Do you want to continue? [confirm]
Обновления принимаются только от PRIMARY-сервера. В домене только один primary, остальные backup, client либо transparent. При подключении в сеть 2-ого primary, он автоматически становится backup.
Выключить VTP на интерфейсе можно командой:
(config-if)# no vtp
Базовые команды для конфигурирования cisco switch
Установка пароля для консоли
S1(config)#line console 0
S1(config-line)#password cisco
S1(config-line)#login
Установка пароля для telnet
S1(config)#line vty 0 4
S1(config-line)#password cisco
S1(config-line)#login
Удаление консольного пароля
switch(config)#line console 0
switch(config-line)#no login
switch(config-line)#no password
Удаление пароля Secret
switch(config)#no enable secret
Проверка параметра Register
switch>enable
switch#show version
Административное выключение интерфейса маршрутизатора
switch(config)#int f0/0
switchr(config-if)#shutdown
Посмотреть таблицу MAC адресов свитча
show mac-address-table
Статически прописать MAC адрес в таблицу адресов свитча
#mac-address-table static MAC address vlan {1-4096, ALL} interface interface-id command
Создать VLAN
S1(config)#vlan 20
S1(config-vlan)#name students
Создаем интерфейс для управления VLAN
S1(config)#interface vlan 20
S1(config-if)#ip address 10.2.2.1 255.255.255.0
S1(config-if)#no shutdown
Назначить порт для доступа к VLAN
S1(config)#interface fa0/18
S1(config-if)#switchport mode access
S1(config-if)#switchport access vlan 20
Назначить порт для транка Cisco Dynamic Trunking protocol
S1(config)#interface fa0/18
или S1(config-if)#switchport mode trunk
ли S1(config-if)#switchport mode dynamic auto
или S1(config-if)#switchport mode dynamic desirable
или S1(config-if)#switchport mode nonegotiate
Kакие vlan пропускать через trunk
S1(config-if)#switchport trunk allowed vlan 18 (можно указывать диапазоны или all)
Переключиться обратно из trunk в режим доступа
S1(config-if)#no switchport trunk allowed vlan
S1(config-if)#no switchport trunk native vlan
S1(config-if)#switchport mode access
Разрешить трафик местного (native) VLAN через порт транка
S1(config)#interface fa0/18
S1(config-if)#switchport mode trunk
S1(config-if)#switchport trunk native vlan 18
S1#show interfaces fa0/18 switchport
Посмотреть статистику VLAN
или show vlan brief
или show vlan id 20
или show vlan name students
или show vlan summary
Посмотреть статистику портов свитча
show interfaces vlan 20
show interfaces fa0/18 switchport
Назначить шлюз по умолчанию
S1(config)#ip default gateway 1.2.3.4
Защита коммутатора через cli
По умолчанию коммутатор Cisco Catalyst позволяет любому пользователю подключиться к консольному порту, получить доступ к пользовательскому режиму, а затем перейти в привилегированный режим без какой-либо защиты. Эти настройки заданы в сетевых устройствах Cisco по умолчанию и, если у вас есть физический доступ к устройству, то вы спокойно можете подключиться к устройству через консольный порт или USB, используя соответствующий кабель и соответственно производить различные настройки.
Однако не всегда имеется физический доступ к коммутатору и тогда необходимо иметь доступ к устройствам для удаленного управления, и первым шагом в этом процессе является обеспечение безопасности коммутатора так, чтобы только соответствующие пользователи могли получить доступ к интерфейсу командной строки коммутатора (CLI).
Защита пользовательского и привилегированного режима с помощью простых паролей.
Получить полный доступ к коммутатору Cisco можно только через консольный порт.
В этом случае, настройки по умолчанию, позволяют получить доступ сначала к режиму пользователя, а затем можно перейти в привилегированный режим без использования паролей.
А вот по протоколам удаленного доступа Telnet или SSH получить доступ даже к режиму пользователя невозможно.
Настройки по умолчанию идут у совершенно нового коммутатора, но в производственной среде необходимо обеспечить безопасный доступ через консоль, а также включить удаленный вход через Telnet и/или SSH, чтобы была возможность подключаться ко всем коммутаторам в локальной сети.
Можно организовать доступ к сетевому оборудованию с использованием одного общего пароля.
Этот метод позволяет подключиться к оборудованию, используя только пароль – без ввода имени пользователя – с одним паролем для входа через консольный порт и другим паролем для входа по протоколу Telnet. Пользователи, подключающиеся через консольный порт, должны ввести пароль консоли, который был предварительно настроен в режиме конфигурации.
Пользователи, подключающиеся через протокол Telnet, должны ввести пароль от Telnet, также называемый паролем vty, так называемый, потому что это режим конфигурации терминальных линий (vty). На рисунке 1 представлены варианты использования паролей с точки зрения пользователя, подключающегося к коммутатору.
Как видно из рисунка 1, на коммутаторах Cisco стоит защита привилегированного режима (enable) с помощью еще одного общего пароля, задаваемый командой enable password. Системный администратор, подключающийся к CLI коммутатора попадает в режим пользователя и далее, вводит команду enable.
Эта команда запрашивает у пользователя пароль входа в привилегированный режим; если пользователь вводит правильный пароль, IOS перемещает пользователя в привилегированный режим.
Пример 1. Пример входа в коммутатор из консоли, когда пароль консоли и пароль привилегированного режима были заранее установлены. Предварительно пользователь запустил эмулятор терминала, физически подключил ноутбук к консольному кабелю, а затем нажал клавишу Enter, чтобы войти в коммутатор.
Настройка параметров журналирования.
Включить ведение журнала:
(config)# logging on(config)# logging buffered(config)# logging trap <0-7>
0 — минимальное, 7- записывать все сообщения
Добавлять системное время в сообщения:
(config)# service timestamps log datetime msec localtime show-timezone
Сбор данных на syslog-сервер:
Для начала необходимо добавить строку в []/etc/syslogd.conf[] вида []Facility.Severity file[]
local7.info /var/log/cisco3750e-b1s3
Затем настроить роутер:
Настройка параметров терминала
Для базовой настройки параметров терминала:
Назначить имя устройства
(config)# hostname <string>
Если необходимо, изменить строку приглашения
(config)# prompt %n@%h%p
где:
%% — символ процента;%n — номер tty-порта;%h — имя хоста;%p — символ приглашения ( # или > );%s — пробел;%t — табуляция;
Создать баннеры:
(config)# banner motd # text #(config)# banner login # text #(config)# banner exec # text #(config)# banner incoming # text #
Отключить поиск в системе DNS:
(config)# no ip domain-lookup
Задать время сеанса (5 мин.):
(config)# line { console | vty | tty } <n>(config-line)# exec-timeout 5 0
Для вывода информации о местоположении устройства при входе пользователя в систему:
(config)# service linenumber(config)# line console 0(config-line)# location <text>
Чтобы сообщения консоли не мешали вводу команд:
(config)# line { console | vty | tty } <n>(config-line)# logging synchronous
Задать скорость консольного порта:
(config)# line console 0(config-line)# speed 115200
Определить длину истории команд:
(config)# line { console | vty | tty } <n>(config-line)# history size <0-256>
Включить запись истории изменения конфигурации:
(config)# archive(config-archive)# log config(config-archive-log-cfg)# logging on(config-archive-log-cfg)# hidekeys
Включить поддержку IPv6, перезагрузить роутер
(config)# sdm prefer dual-ipv4-and-ipv6 routing(config)# ^Z# wr# reload
Настройка парольного доступа к коммутатору cisco
В данной части рассматривается настройка безопасности входа для коммутатора Cisco Catalyst.
Защита CLI включает защиту доступа в привилегированный режим, поскольку из этого режима злоумышленник может перезагрузить коммутатор или изменить конфигурацию.
Защита пользовательского режима также важна, поскольку злоумышленники могут видеть настройки коммутатора, получить настройки сети и находить новые способы атаки на сеть.
Особенно важно, что бы все протоколы удаленного доступа и управления, чтобы IP-настройки коммутатора были настроены и работали.
Для того чтобы получить удаленный доступ по протоколам Telnet и Secure Shell (SSH) к коммутатору, необходимо на коммутаторе настроить IP-адресацию.
Чуть позже будет показано, как настроить IPv4-адресацию на коммутаторе.
В первой части статьи будут рассмотрены следующие вопросы защиты входа:
- Защита пользовательского режима и привилегированного режима с помощью простых паролей;
- Защита доступа в пользовательский режим с использованием локальной базы данных;
- Защита доступа в пользовательский режим с помощью внешних серверов аутентификации;
- Защита удаленного доступа с помощью Secure Shell (SSH);
Ну и на сладенькое: сброс пароля
Так, а что же делать, если на стол легла вам бушная циска с неизвестным паролем или вы очень невовремя забыли его? Вообще-то это многократно описано и легко гуглится, но повторить это необходимо.
Практически на любом сетевом устройстве есть возможность сбросить пароль, имея физический доступ. Если сделать это невозможно или это отдельная платная услуга, то скорее всего в ваших руках находится какая-то русская поделка (не в обиду, конечно, нашим производителям, но дважды я такие строки читал в документации:))
Итак, cisco:
- подключаетесь к устройству консольным кабелем,
- отправляете его в ребут (хоть по питанию, хоть командой
#reload
) - когда на экране побежит такая строчка ########…###, означающая загрузку образа (40-60 секунд после включения), необходимо отправить сигнал Break. Как это сделать в разных программах читать тут. Вы попадаете в режим ROMMON.
- в этом режиме введите команду:
confreg 0x2142
, она заставит устройство игнорировать startup-config при загрузке. - введите
reset
для перезагрузки - после загрузки running-config будет девственно чистым, а startup-config содержит по-прежнему последнюю сохранённую конфигурацию. Сейчас самое время поменять пароль или слить конфиг.
- самое важное: верните обратно регистры:
Router(config)#config-register 0x2102
Если вы этого не сделаете, то вся ваша конфигурация будет актуальна до первого ребута). И хорошо, если это устройство стоит рядом, и вы вспомните, что накосячили. Мне не повезло)
В следующей статье мы обратимся к вланам и локальной сети. Обязательно к прочтению:
Пароли
Подключение по telnet или ssh называется виртуальным терминалом (vt) и настраивается следующим образом:
Router(config)#line vty 0 4
Router(config-line)#password cisco
Router(config-line)#login
0 4 — это 5 пользовательских виртуальных терминалов=telnet сессий. Этого уже достаточно, чтобы попасть в пользовательский режим, но недостаточно для привилегированного:

Настроим пароль для enable-режима:
Router(config)#enable secret test

Чем отличается secret от password? Примерно тем же, чем ssh от telnet. При настройке secret пароль хранится в зашифрованном виде в конфигурационном файле, а password – в открытом. Поэтому рекомендуется использование secret.
Если вы всё-таки задаёте пароль командой password, то следует применить так же service password-encryption, тогда ваш пароль в конфигурационном файле будет зашифрован:
line vty 0 4
password 7 08255F4A0F0A0111
Пример 1
Router(config)#line vty 0 4
Router(config-line)privilege level 15
После входа на маршрутизатор при такой настройке вы сразу увидите Router# со всеми вытекающими правами.

Все уровни со 2 по 14 настраиваются вручную. То есть, например, вы можете дать добро пользователю с privelege level 2 на выполнение команды show running-config.
Примеры:
Установка пароля для консоли
R1(config)#line console 0
R1(config-line)#password cisco
R1(config-line)#login
Установка пароля для telnetR1(config)#line vty 0 4R1(config-line)#password ciscoR1(config-line)#login
Удаление консольного пароляrouter(config)#line console 0router(config-line)#no loginrouter(config-line)#no password
Удаление пароля Secretrouter(config)#no enable secret
Проверка параметра Registerrouter>enablerouter#show version
Задание адреса-маски и административное включение интерфейсаR1(config)#interface Serial0/0/0R1(config-if)#ip address 192.168.2.1 255.255.255.0
Административное выключение интерфейса маршрутизатораrouter(config)#int s0/0router(config-if)#shutdown
Включение интерфейса Serialrouter#configure terminalrouter(config)#interface s0/0router(config-if)#no shutdownУстановка тактовой частоты для интерфейса Serialrouter(config-if)#clock rate 64000
Проверка интерфейса Serialrouter(config)#show interfaces s0/0
Добавить статическую запись в таблицу маршрутизацииRouter(config)#ip route 10.10.10.0 255.255.255.0 {ip-address | exit-interface }
Посмотреть таблицу маршрутизацииR1#show ip route
Посмотреть интерфейсыR1#show interfaces
Посмотреть интерфейсы и их статистику в табличном видеR1#show ip interface brief
Посмотреть соседей устройства:Router#show cdp neighborsRouter#show cdp neighbors detail
Глобальное выключение CDP (cisco discovery protocol):Router(config)#no cdp runВыключение CDP (cisco discovery protocol) на интерфейсе:Router(config-if)#no cdp enable
Статус DTE/DCErouter#show controllers s0/0
Сохранение конфигурацииrouter#copy running-config startup-config
Загрузка файла (например IOS) с TFTP сервераR#copy tftp flash:
Резервное копирование Startup конфига на TFTProuter#copy startup-config tftp
Сохранение Running конфигаrouter#write memoryrouter#copy run st
Удаление конфигурации NVRAMrouter#write erase
Проверка конфигурации NVRAMrouter#show startup-config
Посмотреть таблицу MAC адресов свитчаshow mac-address-table
Статически прописать MAC адрес в таблицу адресов свитча#mac-address-table static MAC address vlan {1-4096, ALL} interface interface-id command
Создать VLANS1(config)#vlan 20S1(config-vlan)#name students
Создаем интерфейс для управления VLANS1(config)#interface vlan 20S1(config-if)#ip address 10.2.2.1 255.255.255.0S1(config-if)#no shutdown
Назначить порт для доступа к VLANS1(config)#interface fa0/18S1(config-if)#switchport mode accessS1(config-if)#switchport access vlan 20
Назначить порт для транка Cisco Dynamic Trunking protocolS1(config)#interface fa0/18или S1(config-if)#switchport mode trunkли S1(config-if)#switchport mode dynamic autoили S1(config-if)#switchport mode dynamic desirableили S1(config-if)#switchport mode nonegotiate
какие vlan пропускать через trunkS1(config-if)#switchport trunk allowed vlan 18 (можно указывать диапазоны или all)
Переключиться обратно из trunk в режим доступаS1(config-if)#no switchport trunk allowed vlanS1(config-if)#no switchport trunk native vlanS1(config-if)#switchport mode access
Разрешить трафик местного (native) VLAN через порт транкаS1(config)#interface fa0/18S1(config-if)#switchport mode trunkS1(config-if)#switchport trunk native vlan 18S1#show interfaces fa0/18 switchport
Посмотреть статистику VLANили show vlan briefили show vlan id 20или show vlan name studentsили show vlan summary
Посмотреть статистику портов свитчаshow interfaces vlan 20show interfaces fa0/18 switchport
Назначить шлюз по умолчаниюS1(config)#ip default gateway 1.2.3.4
Включить протокол динамической маршрутизацииR1(config)#router протокол (rip, eigrp и т.д.)R1(config-router)#network network_number [wildcard_mask]R1(config-if)#bandwidth 64
R1(config-router)#passive-interface s 0/0/0 Выключить динамическую маршрутизацию на интерфейсеилиR1(config-router)#passive-interface default Выключить динамическую маршрутизацию на всех интерфейсаха потом на некоторых включить:R1(config-router)#no passive-interface s 0/0/0
Создание меню быстрого вызова команд.
Задать заголовок:
(config)# menu <name> title # Текст #(config)# menu <name> clear-screen(config)# menu <name> line-mode
Ввести приглашение:
(config)# menu <name> prompt # Текст #
Для каждого пункта меню:
(config)# menu <name> text <pt-num> <Текст>(config)# menu <name> command <pt-num> <command>
Завершить пунктом выхода из меню:
(config)# menu <name> text <last-pt-num> Menu exit
Вызов меню из режима exec:
Switch# menu <name>
Способы подключения
В Packet Tracer’e управлять оборудованием можно следующими способами:
Интерфейс последних трёх идентичный – отличается лишь способ подключения. Разумеется, GUI – не наш метод.
В реальной же жизни доступны:
Последний вариант даже не упоминайте в приличном обществе. Даже если вы адепт мыши и браузера, очень не советую. На своём примере при работе с другим оборудованием я сталкивался с тем, что настроенное через веб не работает. Хоть ты тресни, но не работает.
Телнет – стандартная, всем известная утилита, как и ssh. Для доступа к cisco по этим протоколам нужно настроить пароли доступа, об этом позже. Возможность использования ssh зависит от лицензии IOS.
Управление по консоли
Ну вот принесли вы маршрутизатор, распечатали, питание на него дали. Он томно зашумел кулерами, подмигивает вам светодиодами своих портов. А чего дальше-то делать?
Воспользуемся один из древнейших и нестареющих способов управления практически любым умным устройством: консоль. Для этого вам нужен компьютер, само устройство и подходящий кабель.
Тут каждый вендор на что горазд. Какие только разъёмы они не используют: RJ-45, DB-9 папа, DB-9 мама, DB-9 с нестандартной распиновкой, DB-25. У циски используется разъём RJ-45 на стороне устройства и DB-9 мама (для подключения к COM-порту) на стороне ПК.
Консольный порт выглядит так:

Всегда выделен голубым цветом. С недавних пор стало возможным управление по USB.
А это консольный кабель cisco:

Раньше он поставлялся в каждой коробке, теперь зачастую стоит отдельных денег. В принципе подходит аналогичный кабель от HP.
Проблема в том, что современные ПК зачастую не имеют COM-порта. На выручку приходят часто используемые конвертеры USB-to-COM:

Либо редко используемые для этих целей конвертеры RS232-Ethernet.

После того, как вы воткнули кабель, определили номер COM-порта, для подключения можно использовать Hyperterminal или Putty в Виндоус и Minicom в Линукс.
Управление через консоль доступно сразу, а вот для телнета нужно установить пароль. Как это сделать? Обратимся к PT.
Начнём с создания маршрутизатора: выбираем его на панели внизу и переносим на рабочее пространство. Даём какое-нибудь название.

Что бы вы делали, если бы это был самый взаправдашний железный маршрутизатор? Взяли бы консольный кабель и подключились им в него и в компьютер. То же самое сделаем и тут:

Кликом по компьютеру вызываем окно настройки, в котором нас интересует вкладка Desktop. Далее выбираем Terminal, где нам даётся выбор параметров.

Впрочем, все параметры по умолчанию нас устраивают, и менять их особо смысла нет.
Если в энергонезависимой памяти устройства отсутствует конфигурационный файл (startup-config), а так оно и будет при первом включении нового железа, нас встретит Initial Configuration Dialog prompt:

Вкратце, это такой визард, позволяющий шаг за шагом настроить основные параметры устройства (hostname, пароли, интерфейсы). Но это неинтересно, поэтому отвечаем no и видим приглашение
Router>
Это стандартное совершенно для любой линейки cisco приглашение, которое характеризует пользовательский режим, в котором можно просматривать некоторую статистику и проводить самые простые операции вроде пинга. Ввод знака вопроса покажет список доступных команд:

Грубо говоря, это режим для сетевого оператора, инженера первой линии техподдержки, чтобы он ничего там не повредил, не напортачил и лишнего не узнал.
Гораздо большие возможности предоставляет режим с говорящим названием привилегированный. Попасть в него можно, введя команду >enable. Теперь приглашение выглядит так:
Router#
Здесь список операций гораздо обширнее, например, можно выполнить одну из наиболее часто используемых команд, демонстрирующую текущие настройки устройства ака “конфиг” #show running-config. В привилегированном режиме вы можете просмотреть всю информацию об устройстве.
Прежде, чем приступать к настройке, упомянем несколько полезностей при работе с cisco CLI, которые могут сильно упростить жизнь:
- все команды в консоли можно сокращать. Главное, чтобы сокращение однозначно указывало на команду. Например,
show running-config
сокращается доsh run
. Почему не доs r
? Потому, чтоs
(в пользовательском режиме) может означать как командуshow
, так и командуssh
, и мы получим сообщение об ошибке % Ambiguous command: «s r» (неоднозначная команда); - используйте клавишу Tab и знак вопроса. По нажатию Tab сокращенная команда дописывается до полной, а знак вопроса, следующий за командой, выводит список дальнейших возможностей и небольшую справку по ним (попробуйте сами в PT);
- используйте горячие клавиши в консоли:
- Ctrl A — передвинуть курсор на начало строки;
- Ctrl E — передвинуть курсор на конец строки;
- курсорные Up, Down — перемещение по истории команд;
- Ctrl W — стереть предыдущее слово;
- Ctrl U — стереть всю линию;
- Ctrl C — выход из режима конфигурирования;
- Ctrl Z — применить текущую команду и выйти из режима конфигурирования;
- Ctrl Shift 6 — остановка длительных процессов (так называемый escape sequence);
- используйте фильтрацию вывода команды. Бывает, что команда выводит много информации, в которой нужно долго копаться, чтобы найти определённое слово, например. Облегчаем работу с помощью фильтрации: после команды ставим
|
, пишем вид фильтрации и, собственно, искомое слово (или его часть). Виды фильтрации (ака модификаторы вывода):begin
— вывод всех строк, начиная с той, где нашлось слово;section
— вывод секций конфигурационного файла, в которых встречается слово;include
— вывод строк, где встречается слово;exclude
— вывод строк, где НЕ встречается слово.
Но вернемся к режимам. Третий главный режим, наряду с пользовательским и привилегированным: режим глобальной конфигурации. Как понятно из названия, он позволяет нам вносить изменения в настройки устройства. Активируется командой #configure terminal из привилегированного режима и демонстрирует такое приглашение:
Router(config)#
В режиме глобальной конфигурации не выполняются довольно нужные порой команды других режимов (тот же show running-config, ping, etc.). Но есть такая полезная штука, как do. Благодаря ей мы можем, не выходя из режима конфигурирования, выполнять эти самые команды, просто добавляя перед ними do. Примерно так:
Router(config)#do show running-config
Configuring the switch to use vendor-specific radius attributes
The Internet Engineering Task Force (IETF) draft standard specifies a method for communicating vendor-specific information between the switch and the RADIUS server by using the vendor-specific attribute (attribute 26). Vendor-specific attributes (VSAs) allow vendors to support their own extended attributes not suitable for general use.
The Cisco RADIUS implementation supports one vendor-specific option by using the format recommended in the specification. Cisco’s vendor-ID is 9, and the supported option has vendor-type 1, which is named cisco-avpair. The value is a string with this format:
Protocol is a value of the Cisco protocol attribute for a particular type of authorization. Attribute and value are an appropriate attribute-value (AV) pair defined in the Cisco TACACS specification, and sep is = for mandatory attributes and is * for optional attributes. The full set of features available for TACACS authorization can then be used for RADIUS.
For example, this AV pair activates Cisco’s multiple named ip address pools feature during IP authorization (during PPP IPCP address assignment):
Configuring the switch for vendor-proprietary radius server communication
Although an IETF draft standard for RADIUS specifies a method for communicating vendor-proprietary information between the switch and the RADIUS server, some vendors have extended the RADIUS attribute set in a unique way. Cisco IOS software supports a subset of vendor-proprietary RADIUS attributes.
As mentioned earlier, to configure RADIUS (whether vendor-proprietary or IETF draft-compliant), you must specify the host running the RADIUS server daemon and the secret text string it shares with the switch. You specify the RADIUS host and secret text string by using the radius-server global configuration commands.
Beginning in privileged EXEC mode, follow these steps to specify a vendor-proprietary RADIUS server host and a shared secret text string:
To delete the vendor-proprietary RADIUS host, use the no radius-server host {hostname | ip-address} non-standard global configuration command. To disable the key, use the no radius-server key global configuration command.
This example shows how to specify a vendor-proprietary RADIUS host and to use a secret key of rad124 between the switch and the server: