Реалиазация скриптовго шлюза для коммутаторов DES-3526, DES-3550, DES-3828, DES-3852, DGS-3200-10 и им подобных

Материал из BiTel WiKi

Перейти к: навигация, поиск

Настройка шлюза на основе коммутаторов Dlink. В сети используются коммутаторы серии DES-3526, DES-3550, DES-3828, DES-3852, DGS-3200-10. Чтоб отказаться от привязки клиента по мак адресу, было решено подключать одного клиента на отдельный порт коммутатора. А возможность смены клиентом IP адреса запретить с помощью ACL на порту клиента. Коммутаторы соединяются между собой только аплинк портами. В 4.5 версии BGBilling появилась возможность при помощи скриптов самому настраивать параметры ACL под свои потребности. На коммутаторе нужно создать профили в которые биллинг будет записывать правила клиету. Для DGS-3200-10

create access_profile profile_id 4 ip udp dst_port_mask 0xFFFF 
 
config access_profile profile_id 4 add access_id auto_assign ip udp dst_port 67  port 1-8 permit rx_rate no_limit 
 
create access_profile profile_id 8 ip source_ip_mask 255.255.255.255 destination_ip_mask 255.255.255.128 
 
create access_profile profile_id 12 ip source_ip_mask 255.255.255.128 destination_ip_mask 255.255.255.255 
 
create access_profile profile_id 16 ip source_ip_mask 0.0.0.0 destination_ip_mask 255.255.255.255 
 
create access_profile profile_id 20 ip source_ip_mask 255.255.255.255 destination_ip_mask 0.0.0.0 
 
create access_profile profile_id 24 ethernet ethernet_type 
 
config access_profile profile_id 24 add access_id auto_assign ethernet ethernet_type 0x806  port 1-8 permit rx_rate no_limit 
 
create access_profile profile_id 28 ethernet source_mac 00-00-00-00-00-00 
 
config access_profile profile_id 28 add access_id auto_assign ethernet source_mac 00-00-00-00-00-00  port 1-8 deny

Правила в профилях 4, 24, 28 одинаковы для всех портов и не изменяются биллингом. Эти правила записываются сразу и сохраняются в конфиге.

Коммутатор фильтрует приходящие на порт пакеты. Выполняется первое правило сверху подходящее пакету. Профиль 4 пропускает DHCP запросы. Профиль 24 разрешает arp запросы. Профиль 28 запрещает любые пакеты с любым макадресом. В таком виде на клиентских портах устройство способно получить IP адрес, но остальные пакеты будут блокированы.

Для DES-3526 первоначальная настройка профилей выглядит так.

create access_profile ip destination_ip_mask 0.0.0.0 udp dst_port_mask 0xFFFF profile_id 4 
config access_profile profile_id 4 add access_id 1 ip destination_ip 0.0.0.0 udp dst_port 67 port 1 permit 
config access_profile profile_id 4 add access_id 2 ip destination_ip 0.0.0.0 udp dst_port 67 port 2 permit 
config access_profile profile_id 4 add access_id 3 ip destination_ip 0.0.0.0 udp dst_port 67 port 3 permit 
config access_profile profile_id 4 add access_id 4 ip destination_ip 0.0.0.0 udp dst_port 67 port 4 permit 
config access_profile profile_id 4 add access_id 5 ip destination_ip 0.0.0.0 udp dst_port 67 port 5 permit 
config access_profile profile_id 4 add access_id 6 ip destination_ip 0.0.0.0 udp dst_port 67 port 6 permit 
config access_profile profile_id 4 add access_id 7 ip destination_ip 0.0.0.0 udp dst_port 67 port 7 permit 
config access_profile profile_id 4 add access_id 8 ip destination_ip 0.0.0.0 udp dst_port 67 port 8 permit 
config access_profile profile_id 4 add access_id 9 ip destination_ip 0.0.0.0 udp dst_port 67 port 9 permit 
config access_profile profile_id 4 add access_id 10 ip destination_ip 0.0.0.0 udp dst_port 67 port 10 permit 
config access_profile profile_id 4 add access_id 11 ip destination_ip 0.0.0.0 udp dst_port 67 port 11 permit 
config access_profile profile_id 4 add access_id 12 ip destination_ip 0.0.0.0 udp dst_port 67 port 12 permit 
config access_profile profile_id 4 add access_id 13 ip destination_ip 0.0.0.0 udp dst_port 67 port 13 permit 
config access_profile profile_id 4 add access_id 14 ip destination_ip 0.0.0.0 udp dst_port 67 port 14 permit 
config access_profile profile_id 4 add access_id 15 ip destination_ip 0.0.0.0 udp dst_port 67 port 15 permit 
config access_profile profile_id 4 add access_id 16 ip destination_ip 0.0.0.0 udp dst_port 67 port 16 permit 
config access_profile profile_id 4 add access_id 17 ip destination_ip 0.0.0.0 udp dst_port 67 port 17 permit 
config access_profile profile_id 4 add access_id 18 ip destination_ip 0.0.0.0 udp dst_port 67 port 18 permit 
config access_profile profile_id 4 add access_id 19 ip destination_ip 0.0.0.0 udp dst_port 67 port 19 permit 
config access_profile profile_id 4 add access_id 20 ip destination_ip 0.0.0.0 udp dst_port 67 port 20 permit 
config access_profile profile_id 4 add access_id 21 ip destination_ip 0.0.0.0 udp dst_port 67 port 21 permit 
config access_profile profile_id 4 add access_id 22 ip destination_ip 0.0.0.0 udp dst_port 67 port 22 permit 
config access_profile profile_id 4 add access_id 23 ip destination_ip 0.0.0.0 udp dst_port 67 port 23 permit 
config access_profile profile_id 4 add access_id 24 ip destination_ip 0.0.0.0 udp dst_port 67 port 24 permit 
 
create access_profile ip source_ip_mask 255.255.255.255 destination_ip_mask 255.255.255.128 profile_id 8 
 
create access_profile ip source_ip_mask 255.255.255.128 destination_ip_mask 255.255.255.255 profile_id 12 
 
create access_profile ip destination_ip_mask 255.255.255.255 profile_id 16 
 
create access_profile ip source_ip_mask 255.255.255.255 profile_id 20 
 
create access_profile ethernet ethernet_type profile_id 24 
config access_profile profile_id 24 add access_id 1 ethernet ethernet_type 0x806 port 1 permit 
config access_profile profile_id 24 add access_id 2 ethernet ethernet_type 0x806 port 2 permit 
config access_profile profile_id 24 add access_id 3 ethernet ethernet_type 0x806 port 3 permit 
config access_profile profile_id 24 add access_id 4 ethernet ethernet_type 0x806 port 4 permit 
config access_profile profile_id 24 add access_id 5 ethernet ethernet_type 0x806 port 5 permit 
config access_profile profile_id 24 add access_id 6 ethernet ethernet_type 0x806 port 6 permit 
config access_profile profile_id 24 add access_id 7 ethernet ethernet_type 0x806 port 7 permit 
config access_profile profile_id 24 add access_id 8 ethernet ethernet_type 0x806 port 8 permit 
config access_profile profile_id 24 add access_id 9 ethernet ethernet_type 0x806 port 9 permit 
config access_profile profile_id 24 add access_id 10 ethernet ethernet_type 0x806 port 10 permit 
config access_profile profile_id 24 add access_id 11 ethernet ethernet_type 0x806 port 11 permit 
config access_profile profile_id 24 add access_id 12 ethernet ethernet_type 0x806 port 12 permit 
config access_profile profile_id 24 add access_id 13 ethernet ethernet_type 0x806 port 13 permit 
config access_profile profile_id 24 add access_id 14 ethernet ethernet_type 0x806 port 14 permit 
config access_profile profile_id 24 add access_id 15 ethernet ethernet_type 0x806 port 15 permit 
config access_profile profile_id 24 add access_id 16 ethernet ethernet_type 0x806 port 16 permit 
config access_profile profile_id 24 add access_id 17 ethernet ethernet_type 0x806 port 17 permit 
config access_profile profile_id 24 add access_id 18 ethernet ethernet_type 0x806 port 18 permit 
config access_profile profile_id 24 add access_id 19 ethernet ethernet_type 0x806 port 19 permit 
config access_profile profile_id 24 add access_id 20 ethernet ethernet_type 0x806 port 20 permit 
config access_profile profile_id 24 add access_id 21 ethernet ethernet_type 0x806 port 21 permit 
config access_profile profile_id 24 add access_id 22 ethernet ethernet_type 0x806 port 22 permit 
config access_profile profile_id 24 add access_id 23 ethernet ethernet_type 0x806 port 23 permit 
config access_profile profile_id 24 add access_id 24 ethernet ethernet_type 0x806 port 24 permit 
 
create access_profile ethernet source_mac 00-00-00-00-00-00 profile_id 28 
config access_profile profile_id 28 add access_id 1 ethernet source_mac 00-00-00-00-00-00 port 1 deny 
config access_profile profile_id 28 add access_id 2 ethernet source_mac 00-00-00-00-00-00 port 2 deny 
config access_profile profile_id 28 add access_id 3 ethernet source_mac 00-00-00-00-00-00 port 3 deny 
config access_profile profile_id 28 add access_id 4 ethernet source_mac 00-00-00-00-00-00 port 4 deny 
config access_profile profile_id 28 add access_id 5 ethernet source_mac 00-00-00-00-00-00 port 5 deny 
config access_profile profile_id 28 add access_id 6 ethernet source_mac 00-00-00-00-00-00 port 6 deny 
config access_profile profile_id 28 add access_id 7 ethernet source_mac 00-00-00-00-00-00 port 7 deny 
config access_profile profile_id 28 add access_id 8 ethernet source_mac 00-00-00-00-00-00 port 8 deny 
config access_profile profile_id 28 add access_id 9 ethernet source_mac 00-00-00-00-00-00 port 9 deny 
config access_profile profile_id 28 add access_id 10 ethernet source_mac 00-00-00-00-00-00 port 10 deny 
config access_profile profile_id 28 add access_id 11 ethernet source_mac 00-00-00-00-00-00 port 11 deny 
config access_profile profile_id 28 add access_id 12 ethernet source_mac 00-00-00-00-00-00 port 12 deny 
config access_profile profile_id 28 add access_id 13 ethernet source_mac 00-00-00-00-00-00 port 13 deny 
config access_profile profile_id 28 add access_id 14 ethernet source_mac 00-00-00-00-00-00 port 14 deny 
config access_profile profile_id 28 add access_id 15 ethernet source_mac 00-00-00-00-00-00 port 15 deny 
config access_profile profile_id 28 add access_id 16 ethernet source_mac 00-00-00-00-00-00 port 16 deny 
config access_profile profile_id 28 add access_id 17 ethernet source_mac 00-00-00-00-00-00 port 17 deny 
config access_profile profile_id 28 add access_id 18 ethernet source_mac 00-00-00-00-00-00 port 18 deny 
config access_profile profile_id 28 add access_id 19 ethernet source_mac 00-00-00-00-00-00 port 19 deny 
config access_profile profile_id 28 add access_id 20 ethernet source_mac 00-00-00-00-00-00 port 20 deny 
config access_profile profile_id 28 add access_id 21 ethernet source_mac 00-00-00-00-00-00 port 21 deny 
config access_profile profile_id 28 add access_id 22 ethernet source_mac 00-00-00-00-00-00 port 22 deny 
config access_profile profile_id 28 add access_id 23 ethernet source_mac 00-00-00-00-00-00 port 23 deny 
config access_profile profile_id 28 add access_id 24 ethernet source_mac 00-00-00-00-00-00 port 24 deny

На аплинкпортах мы не можем применять профиль 28 из-за транзитного трафика. Поэтому достаточно в профиль 20 добавить правило разрешающее движение пакетов с IP клиента, что и делает биллинг переводя шлюз для клиента в состояние открыт.

Закрывая шлюз, клиенту оставляется окно для доступа к статистике. Это выполняют в профилях 8 и 12 маска 255.255.255.128 и open.address=192.168.158.128 в настройках шлюза. В этой зоне 192.168.158.128/25 размещается страница статистики и DNS сервер. Я также разместил в этой зоне VPN шлюз, и состояние шлюза “жёсткая блокировка” позволяет отключить клиенту локальную сеть, оставляя доступ к статистике и интернету. Правда есть вероятность брутфорса ВПН со стороны клиента с отрицательным балансом, но так как сменить IP клиент не может, выщёлкиваются эти горе хакеры, с помощью биллинга очень легко. Подсеть открытых адресов вы можете задать по своему усмотрению. Профиль 16 закрывает движение на аплинк портах пакетов на IP адрес клиента.

Чтоб клиент мог получать IP динамически, настройте на свиче DHCP-relay option 82.

enable dhcp_relay
config dhcp_relay hops 16 time 0 
config dhcp_relay option_82 state enable
config dhcp_relay option_82 check disable
config dhcp_relay option_82 policy replace
config dhcp_relay option_82 remote_id default
config dhcp_relay add ipif System 10.133.10.4
config dhcp_relay add ipif System 10.133.10.131

10.133.10.4, 10.133.10.131 – адреса DHCP серверов Статьи по настройке DHCP серверов. Встроенного в бгбиллинг смотрите в руководстве биллинга. С сайта Dlink http://www.dlink.ru/technical/faq_hub_switch_72.php

Настройка типа шлюза в бгбиллинге. Клиент БГБиллинга -> Модули -> IPN модуль -> Типы шлюзов Добавляем новый шлюз. Название: DxS-3xxx Комментарий: Универсальный шлюз Длинк Конфигурация:

user_rule.editor.class=bitel.billing.module.services.ipn.editor.DlinkContractRuleEditor
gate_manager.class=bitel.billing.server.ipn.DlinkGateWorker
use.script=1

Скрипт:

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import bitel.billing.common.IPUtils;
import bitel.billing.common.module.ipn.IPNContractStatus;
import bitel.billing.server.ipn.UserStatus;
import bitel.billing.server.ipn.bean.ManadUtils;
import bitel.billing.server.ipn.bean.VlanManager;
import bitel.billing.server.ipn.dlink.UserPortStatus;
import bitel.billing.server.util.DefaultServerSetup;
import bitel.billing.server.util.Utils;
import bitel.billing.server.util.telnet.TelnetSession;
 
protected void doSync()
{
	try
	{
		String host = gate.getHost();
		int port = gate.getPort();
 
 
		DefaultServerSetup gateSetup = new DefaultServerSetup( gate.getConfig(), "\r\n" );        
 
 
		String pswd = gate.getKeyword();
		String login = gateSetup.getStringValue( "login");
 
 
 
		StringBuffer result = new StringBuffer();
 
 
		if( log.isDebugEnabled() )
		{
		    log.debug( gate.getId() + " gate: " + host + ":" + port  + " login: " + login + " pswd: " + 		pswd );
		}
 
 
		TelnetSession session = new TelnetSession( host, port);
		session.setLoginPromptSequence( ":" );						
 
		log.debug( "before connect" );
		session.connect();		
		log.debug( "after connect" );
 
		result.append( session.doCommand( login ) );
		log.debug( "after command" );
 
 
		session.setLoginPromptSequence( "#" );
		result.append( session.doCommand( pswd ) );
		log.debug( "before pswd" );
 
 
		log.debug( "execute commands" );
		doCommands( session, result, gateSetup);
 
 
 
		//TODO commands here 
 
		session.setLoginPromptSequence( "****" );
		result.append( session.doCommand( "logout" ) );
 
 
		log.info( result.toString() );
 
 
 
		log.debug( "ok" );
	} catch (Exception e)
	{
 
		throw new RuntimeException ( e );
	} 
}
 
 
 
private void doCommands( TelnetSession session, StringBuffer result, DefaultServerSetup gateSetup) 
throws IOException
{
 
 
	String openAddress =  gateSetup.getStringValue( "open.address",  "255.255.255.255" ) ;
 
	log.debug( "openAddress = " +  openAddress );
 
 
	uplinks = Utils.stringToIntegerList( gateSetup.getStringValue( "uplink" ) );
 
 
	List ports = getUserList( statusList );
 
 
 
	String [] openRules = new String [] {
 
			//Профиль 20 Разрешаем клиенту видеть мир 
			// разрешающие правила добавляются с номером порта клиента						
			"config access_profile profile_id 20 add access_id ${port} ip source_ip ${ip} destination_ip 0.0.0.0 port ${port} permit"};
 
 
 
	String [] closeRules = new String [] {
 
		// Профиль 8 разрешаем клиенту видеть Стат+ДНС сервер
			// разрешающие правила добавляются с номером порта клиента			
			"config access_profile profile_id 8 add access_id ${port} ip source_ip ${ip} destination_ip ${openAdress} port ${port} permit",
 
			//Профиль 12 Разрешаем ИП запросы на аплинках на адрес клиента со статистики
			"config access_profile profile_id 12 add access_id ${mod}${port} ip source_ip ${openAdress} destination_ip ${ip} port ${upport} permit", 
 
 
			//16 Запрещаем ИП запросы на аплинках на адрес клиента
			"config access_profile profile_id 16 add access_id ${mod}${port} ip source_ip 0.0.0.0 destination_ip ${ip} port ${upport} deny"};
 
 
	for( UserPortStatus port : ports )
	{
 
		log.debug("port.ipAddr=" + port.ipAddr);
		//удаляюшие правила 
 
		if ( port.status.status == IPNContractStatus.STATUS_REMOVED )
		{
 
			int [] profiles = new int [] { 8, 20 }; 
 
			for (int profile : profiles)
			{
 
				String rule = "config access_profile profile_id " + profile + " delete access_id " + port.port;
				log.debug("rule=" + rule); 
				result.append(  session.doCommand( rule ) );
			}
 
			int [] profiles = new int [] { 12, 16 };
			for (int profile : profiles)
			{
 
				for (int j = 0; j < uplinks.size(); j++)
				{
 
					Integer upport = uplinks.get(j);			
					pref = j > 0 ? String.valueOf( j * 10 ) : "";
					String rule = "config access_profile profile_id " + profile + " delete access_id " + pref + port.port;
					log.debug("rule=" + rule); 
					result.append(  session.doCommand( rule ) );
				}
			}
 
 
		} 
		else 
		if ( port.status.status == IPNContractStatus.STATUS_OPEN )			
		{
			int [] profiles = new int [] { 8 }; 
 
			for (int profile : profiles)
			{
 
				String rule = "config access_profile profile_id " + profile + " delete access_id " + port.port;
				log.debug("rule=" + rule); 
				result.append(  session.doCommand( rule ) );
			}
 
			int [] profiles = new int [] { 12, 16 };
			for (int profile : profiles)
			{
 
				for (int j = 0; j < uplinks.size(); j++)
				{
 
					Integer upport = uplinks.get(j);			
					pref = j > 0 ? String.valueOf( j * 10 ) : "";
					String rule = "config access_profile profile_id " + profile + " delete access_id " + pref + port.port;
					log.debug("rule=" + rule); 
					result.append(  session.doCommand( rule ) );
				}
			}
 
 
			//20
			rule = openRules[0];
			rule = setValues( rule, port.port, port.ipAddr, openAddress, "" );
			log.info("rule=" + rule);
			result.append(  session.doCommand( rule ) );
 
		}
		else //close
		{
			int [] profiles = new int [] { 20 }; 
 
			for (int profile : profiles)
			{
 
				String rule = "config access_profile profile_id " + profile + " delete access_id " + port.port;
				log.debug("rule=" + rule); 
				result.append(  session.doCommand( rule ) );
			}
 
 
			//8
			rule = closeRules[0];
			rule = setValues( rule, port.port, port.ipAddr, openAddress, "" );
 
			log.info("rule=" + rule);
			result.append(  session.doCommand( rule ) );
 
			//12, 16
			for (int j = 0; j < uplinks.size(); j++)
			{
				Integer upport = uplinks.get(j);			
 
				for (int i = 1; i < 3; i++)
				{	
					rule = closeRules[i];
					rule = setValues( rule, port.port, port.ipAddr, openAddress, String.valueOf( upport ) );
					rule = rule.replaceAll( "\\$\\{mod\\}" , String.valueOf( j * 10 )  );
					log.info("rule=" + rule);
					result.append(  session.doCommand( rule ) );
				}
 
			}
 
		}		
 
 
 
 
	}
 
 
}
 
 
private String setValues( String rule,  int port, String ip, String openAddress,  String upport )
{
	rule = rule.replaceAll( "\\$\\{port\\}", String.valueOf( port ) );
	rule = rule.replaceAll( "\\$\\{ip\\}" , ip  );
	rule = rule.replaceAll( "\\$\\{openAdress\\}", openAddress );	
	rule = rule.replaceAll( "\\$\\{upport\\}",  upport  );
	return rule;
}
 
 
 
 
protected void doParentSync()
{
}
 
public List getUserList( List statusList )
{
    List userList = new ArrayList();
    for( UserStatus status : statusList )
    {
        String rule = status.rule.getRuleText();
        StringTokenizer st = new StringTokenizer( rule, ";" );
 
        while( st.hasMoreTokens() )
        {
            String token = st.nextToken().trim();
            data = token.split( ":" );
            if( data.length == 2 )
            {
                UserPortStatus portStatus = new UserPortStatus();
                portStatus.port = Utils.parseIntString( data[0] );
                portStatus.ipAddr = data[1];
                portStatus.status = status;
                userList.add( portStatus );
            }
            else if ( data.length == 3 )
            {
                UserPortStatus portStatus = new UserPortStatus();
                portStatus.port = Utils.parseIntString( data[0] );
                portStatus.macAddr = data[1].toUpperCase().replaceAll( "\\-", " " );
                portStatus.ipAddr = data[2];
                portStatus.status = status;
                userList.add( portStatus );
            }
        }                
    }
    return userList;
}

Этот скрипт скорее всего является универсальным для большинства управляемых свичей Dlink. Скрипт переделан из первоначально написанного Денисом Пименовым. В скрипте оставлена некая избыточность кода. При переключении шлюза в состояние “открыт”, скрипт удаляет правила из 8, 12 и 16 профилей и добавляет правило в 20 профиль. При переключении шлюза в состояние “закрыт”, “блокировка”, “жёсткая блокировка”, скрипт удаляет правило из 20 профиля и добавляет правила в 8, 12, и 16 профиль. При переключении шлюза в состояние “удалён”, скрипт удаляет правила из 8, 12, 16 и 20 профиля.

Этим скриптом можно пользоваться для DES-3200-10, но в этой моделе можно добавлять ограничение скорости на правило. Ещё отличается эта модель тем, что позволяет перезаписывать уже записанное правило. Поэтому для модели 3200-10, я использую такой скрипт, ограничивающий скорость клиента на порту в 100Мbs.

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import bitel.billing.common.IPUtils;
import bitel.billing.common.module.ipn.IPNContractStatus;
import bitel.billing.server.ipn.UserStatus;
import bitel.billing.server.ipn.bean.ManadUtils;
import bitel.billing.server.ipn.bean.VlanManager;
import bitel.billing.server.ipn.dlink.UserPortStatus;
import bitel.billing.server.util.DefaultServerSetup;
import bitel.billing.server.util.Utils;
import bitel.billing.server.util.telnet.TelnetSession;
import bitel.billing.server.ipn.bean.Gate;
import bitel.billing.server.ipn.bean.GateType;
import bitel.billing.server.ipn.GateWorker;
import bitel.billing.server.ipn.GateWorker.ParentGateWorker;
 
protected void doSync()
{
	try
	{
		String host = gate.getHost();
		int port = gate.getPort();
 
 
		DefaultServerSetup gateSetup = new DefaultServerSetup( gate.getConfig(), "\r\n" );        
 
 
		String pswd = gate.getKeyword();
		String login = gateSetup.getStringValue( "login");
 
 
 
		StringBuffer result = new StringBuffer();
 
 
		if( log.isDebugEnabled() )
		{
		    log.debug( gate.getId() + " gate: " + host + ":" + port  + " login: " + login + " pswd: " + 		pswd );
		}
 
 
		TelnetSession session = new TelnetSession( host, port);
		session.setLoginPromptSequence( ":" );						
 
		log.debug( "before connect" );
		session.connect();		
		log.debug( "after connect" );
 
		result.append( session.doCommand( login ) );
		log.debug( "after command" );
 
 
		session.setLoginPromptSequence( "#" );
		result.append( session.doCommand( pswd ) );
		log.debug( "before pswd" );
 
 
		log.debug( "execute commands" );
		doCommands( session, result, gateSetup);
 
 
 
		//TODO commands here 
 
		session.setLoginPromptSequence( "****" );
		result.append( session.doCommand( "logout" ) );
 
 
		log.info( result.toString() );
 
 
 
		log.debug( "ok" );
	} catch (Exception e)
	{
 
		throw new RuntimeException ( e );
	} 
}
 
 
 
private void doCommands( TelnetSession session, StringBuffer result, DefaultServerSetup gateSetup) 
throws IOException
{
 
 
	String openAddress =  gateSetup.getStringValue( "open.address",  "255.255.255.255" ) ;
 
	log.debug( "openAddress = " +  openAddress );
 
 
	uplinks = Utils.stringToIntegerList( gateSetup.getStringValue( "uplink" ) );
 
 
	List ports = getUserList( statusList );
 
 
 
	String [] openRules = new String [] {
 
			// Профиль 8 разрешаем клиенту видеть Стат+ДНС сервер
			// разрешающие правила добавляются с номером порта клиента			
			"config access_profile profile_id 8 add access_id ${port} ip source_ip ${ip} destination_ip ${openAdress} port ${port} permit rx_rate 1600",
 
			//Профиль 12 Разрешаем ИП запросы на аплинках на адрес клиента со статистики
			"config access_profile profile_id 12 add access_id ${mod}${port} ip source_ip ${openAdress} destination_ip 	${ip} port ${upport} permit rx_rate 1600", 
 
 
			//16 Запрещаем ИП запросы на аплинках на адрес клиента
			"config access_profile profile_id 16 add access_id ${mod}${port} ip source_ip 0.0.0.0 destination_ip ${ip} port ${upport} permit rx_rate 1600",			
 
			//Профиль 20 Разрешаем клиенту видеть мир 
			// разрешающие правила добавляются с номером порта клиента						
			"config access_profile profile_id 20 add access_id ${port} ip source_ip ${ip} destination_ip 0.0.0.0 port ${port} permit rx_rate 1600"};
 
 
 
	String [] closeRules = new String [] {
 
		// Профиль 8 разрешаем клиенту видеть Стат+ДНС сервер
			// разрешающие правила добавляются с номером порта клиента			
			"config access_profile profile_id 8 add access_id ${port} ip source_ip ${ip} destination_ip ${openAdress} port ${port} permit rx_rate 80",
 
			//Профиль 12 Разрешаем ИП запросы на аплинках на адрес клиента со статистики
			"config access_profile profile_id 12 add access_id ${mod}${port} ip source_ip ${openAdress} destination_ip ${ip} port ${upport} permit rx_rate 80", 
 
 
			//16 Запрещаем ИП запросы на аплинках на адрес клиента
			"config access_profile profile_id 16 add access_id ${mod}${port} ip source_ip 0.0.0.0 destination_ip ${ip} port ${upport} deny",			
 
			//Профиль 20 Разрешаем клиенту видеть мир 
			// разрешающие правила добавляются с номером порта клиента						
			"config access_profile profile_id 20 add access_id ${port} ip source_ip ${ip} destination_ip 0.0.0.0 port ${port} deny"};
 
 
	for( UserPortStatus port : ports )
	{
 
		log.debug("port.ipAddr=" + port.ipAddr);
		//удаляюшие правила 
 
		if ( port.status.status == IPNContractStatus.STATUS_REMOVED )
		{
 
			int [] profiles = new int [] { 8, 20 }; 
 
			for (int profile : profiles)
			{
 
				String rule = "config access_profile profile_id " + profile + " delete access_id " + port.port;
				log.debug("rule=" + rule); 
				result.append(  session.doCommand( rule ) );
			}
 
			int [] profiles = new int [] { 12, 16 };
			for (int profile : profiles)
			{
 
				for (int j = 0; j < uplinks.size(); j++)
				{
 
					Integer upport = uplinks.get(j);			
					pref = j > 0 ? String.valueOf( j * 10 ) : "";
					String rule = "config access_profile profile_id " + profile + " delete access_id " + pref + port.port;
					log.debug("rule=" + rule); 
					result.append(  session.doCommand( rule ) );
				}
			}
 
 
		} 
		else 
		if ( port.status.status == IPNContractStatus.STATUS_OPEN )			
		{
			int [] profiles = new int [] { 8 }; 
 
			for (int profile : profiles)
			{
 
				String rule = "config access_profile profile_id " + profile + " delete access_id " + port.port;
				log.debug("rule=" + rule); 
				result.append(  session.doCommand( rule ) );
			}
 
			int [] profiles = new int [] { 12, 16 };
			for (int profile : profiles)
			{
 
				for (int j = 0; j < uplinks.size(); j++)
				{
 
					Integer upport = uplinks.get(j);			
					pref = j > 0 ? String.valueOf( j * 10 ) : "";
					String rule = "config access_profile profile_id " + profile + " delete access_id " + pref + port.port;
					log.debug("rule=" + rule); 
					result.append(  session.doCommand( rule ) );
				}
			}																																																																																																																																			
			//12, 16
			for (int j = 0; j < uplinks.size(); j++)
			{
				Integer upport = uplinks.get(j);			
 
				for (int i = 2; i < 3; i++)
				{
					rule = openRules[i];
					rule = setValues( rule, port.port, port.ipAddr, openAddress, String.valueOf( upport ) );
					rule = rule.replaceAll( "\\$\\{mod\\}" , String.valueOf( j * 10 )  );
					log.info("rule=" + rule);
					result.append(  session.doCommand( rule ) );
				}
			}
			//20
			rule = openRules[3];
			rule = setValues( rule, port.port, port.ipAddr, openAddress, "" );
			log.info("rule=" + rule);
			result.append(  session.doCommand( rule ) );
 
		}
		else //close
		{		
			int [] profiles = new int [] { 20 }; 
 
			for (int profile : profiles)
			{
 
				String rule = "config access_profile profile_id " + profile + " delete access_id " + port.port;
				log.debug("rule=" + rule); 
				result.append(  session.doCommand( rule ) );
			}
 
																																																																																	//8
 
			rule = closeRules[0];
			rule = setValues( rule, port.port, port.ipAddr, openAddress, "" );
 
			log.info("rule=" + rule);
			result.append(  session.doCommand( rule ) );
 
			//12, 16
			for (int j = 0; j < uplinks.size(); j++)
			{
				Integer upport = uplinks.get(j);			
 
				for (int i = 1; i < 3; i++)
				{	
					rule = closeRules[i];
					rule = setValues( rule, port.port, port.ipAddr, openAddress, String.valueOf( upport ) );
					rule = rule.replaceAll( "\\$\\{mod\\}" , String.valueOf( j * 10 )  );
					log.info("rule=" + rule);
					result.append(  session.doCommand( rule ) );
				}
 
			}
		}		
 
 
 
 
	}
 
 
}
 
 
private String setValues( String rule,  int port, String ip, String openAddress,  String upport )
{
	rule = rule.replaceAll( "\\$\\{port\\}", String.valueOf( port ) );
	rule = rule.replaceAll( "\\$\\{ip\\}" , ip  );
	rule = rule.replaceAll( "\\$\\{openAdress\\}", openAddress );	
	rule = rule.replaceAll( "\\$\\{upport\\}",  upport  );
	return rule;
}
 
 
 
 
protected void doParentSync()
{
}
 
public List getUserList( List statusList )
{
    List userList = new ArrayList();
    for( UserStatus status : statusList )
    {
        String rule = status.rule.getRuleText();
        StringTokenizer st = new StringTokenizer( rule, ";" );
 
        while( st.hasMoreTokens() )
        {
            String token = st.nextToken().trim();
            data = token.split( ":" );
            if( data.length == 2 )
            {
                UserPortStatus portStatus = new UserPortStatus();
                portStatus.port = Utils.parseIntString( data[0] );
                portStatus.ipAddr = data[1];
                portStatus.status = status;
                userList.add( portStatus );
            }
            else if ( data.length == 3 )
            {
                UserPortStatus portStatus = new UserPortStatus();
                portStatus.port = Utils.parseIntString( data[0] );
                portStatus.macAddr = data[1].toUpperCase().replaceAll( "\\-", " " );
                portStatus.ipAddr = data[2];
                portStatus.status = status;
                userList.add( portStatus );
            }
        }                
    }
    return userList;
}

При переключении шлюза в состояние “открыт”, скрипт удаляет правила из 8, 12 профилей и добавляет правило в 16 и 20 профиль ограничивающие скорость на порту клиента в 100Mbs = 1600*64Kbs. (rx_rate 1 == 64Kbs ) При переключении шлюза в состояние “закрыт”, “блокировка”, “жёсткая блокировка”, скрипт удаляет правило из 20 профиля и добавляет правила в 8, 12, и 16 профиль. Для доступа к статистике 5Mbs (rx_rate 80) считаю вполне достаточно. При переключении шлюза в состояние “удалён”, скрипт удаляет правила из 8, 12, 16 и 20 профиля.

Создание шлюза в бгбиллинге.

Клиент БГБиллинга -> Модули -> IPN модуль -> Шлюзы Добавляем новый шлюз.

Хост шлюза: 10.128.0.38 ( IP административного интерфейса коммутатора.) Порт шлюза: 23 (телнет должен быть разрешён на коммутаторе.) Ключевое слово: хххххххх (пароль административного аккаунта коммутатора.) Конфигурация: login=admin (логин административного аккаунта коммутатора.) open.address=192.168.158.128 uplink=25,26 (аплинк порты коммутатора, в данном случае DES-3526.)


Не забываем поставить в планировщик задание проверка шлюзов IPN.

За сим откланиваюсь. Евгений Новиков. Ce$$. Г. Владивосток. 02.06.08

Личные инструменты