ISP`s IT Аутсорсинг
Быстрый переход: Главная блога Главная сайта Форум
Если Вы чего то недопоняли или не нашли - задайте
вопрос на нашем форуме и мы попробуем Вам помочь.
Subnets.ru Регистрация IP и Автономных систем mega-net.ru

Добро пожаловать в блог! Надеемся, что Вы еще вернетесь.

Все кто ставил браузер google chrome под FreeBSD и обновил его до последней версии столкнулся с проблемой: «run google chrome as root»

Браузер перестал запускаться под пользователем root.

Поддерживаю народ который возмущается на тему того что Гугл решил что в праве решить за нас как нам и что запускать. Так же как и они не понимаю зачем было так делать, я сам решу что и как мне запустить.

Ну да ладно, есть способ это пофиксить, расскажу о нем.

Идем в порт с хромом:

# cd /usr/ports/www/chromium

Делаем clean (на всякий случай):

# make clean

Затем делаем:

# make extract

После выполнения должна появиться папка work. У меня версия chrome 11.0.696.57,  идем в папку work и далее:

# cd work/chromium-courgette-redacted-11.0.696.57/chrome/browser

В этой папке ищем файл browser_main_gtk.cc, найдя откройте его на редактирование вашим любимым редактором, перейдите к строке 77 или найдите поиском строчку:

if (geteuid() == 0) {

Замените цифру ноль (это ID пользователя root):

# id
uid=0(root) gid=0(wheel) groups=0(wheel),5(operator)

на любой другой ID, который не пользуется в вашей системе, ну скажем 12345, получится строка:

if (geteuid() == 12345) {

После этого возвращаемся в корень порта:

# cd /usr/ports/www/chromium

Выполняем сборку и инсталл:

# make && make install

После этих действий google chome запустился от пользователя root.

(либо можно закоментировать весь этот IF полностью)

З.Ы. При копировании статьи ссылка на источник ОБЯЗАТЕЛЬНА ! Пожалуйста, уважайте чужой труд.

Автор: Николаев Дмитрий (virus (at) subnets.ru)

Ничего не понялТак себе...Не плохоДовольно интересноОтлично ! То что нужно ! (голосов: 3, среднее: 5,00 из 5)
Загрузка...
Отправить на почту Отправить на почту
    Не найдено

В продолжение статей (AS5350 в качестве VoIP-шлюза и Cisco AS5350 и RADIUS) о настройке Cisco AS5350 рассказываем решение по ограничению длительности вызовов, проходящих через Cisco AS5350.

После нахождения очередного зависшего вызова (такое случается уже не часто, но тем не менее бывает) было решено попробовать ввести ограничение максимальной длительности вызова. Использование этого функционала возможно, начиная с  Cisco IOS Release 12.4(4)T.

Активируем данную фичу, дав команды в режиме глобальной конфигурации:

application
package callfeature

Ограничиваем макисмальную длительность вызова 60 минутами:
param long-dur-duration 60

По достижении максимальной длительности вызова завершаем его:

param long-dur-action disconnnect

Помимо завершения доступны еще действия: ignore и syslog.

Включаем режим определения длительности вызова:
param long-dur-call-mon enable

Код причины завершения вызова — «прерывание» (передается в Radius, м.б. полезно для последующей выборки завершенных звонков):
long-dur-disc-cause 8

В логах фиксируется завершенный вызов:

show logging
Mar 23 2011 17:49:43.372 MSK: %SIP-6-LONG_DUR_CALL_DETECTED: Long Duration Call is detected on call with CallId 1011872, GUID 76CC44C1-549311E03/23/2011 17:49:43, Calling number 8499678xxxx, Called Number 89104xxxxxx, at 03/23/2011 17:49:43.372, Duration: 60 min, RTP Media:Active; Control:Inactive.

Mar 23 2011 17:49:43.372 MSK: %VTSP-6-LONG_DUR_CALL_DETECTED: Long Duration Call is detected for call with CallId 1011873, GUID 76CC44C1-549311E0-9E4EECE1-281A6C12, CIC 3/1.31, Calling number 8499678xxxx, CalledNumber 89104xxxxxx, at 03/23/2011 17:49:43.372, Duration: 60 min, RTP media status = N/A

Благодарю Сергея Бабичева (aka zaikini) за наводку на документацию производителя оборудования по этому вопросу.

P.S. На IOS 12.4(15)T11 (на других версиях не проверялось в силу их отсутствия) обнаружилось следующее:

при заданных глобальных настройках ограничения длительности вызовов и указанных в диалпире кастомных настройках, например:


dial-peer voice 46 voip
paramspace callfeature long-dur-duration 1
paramspace callfeature long-dur-action disconnect
paramspace callfeature long-dur-call-mon enable

имеем следующее:

  1. заданной в диалпире длительностью ограничиваются вызовы, не попадающие под данный диалпир (но не все вызовы, закономерности выявить не смог).
  2. у вызова, попадающего под данный диалпир, длительность ограничивается только если это вызов в ТфОП, исходящий ИЗ SIP, если же идет вызов из ТфОП В SIP, то ограничение на него не действует.

P.P.S. Т.к. в закладках периодически «протухают» линки на коды завершения вызовов согласно рекомендации ITU-T Q.850, то я решил их «увековечить» в нашем блоге (будьте внимательны — коды даны в десятичном представлении, а в radius’e и дебаге cisco они фигурируют в шестнадцатиричном представлении) :

ISDN Cause Codes (Источник)

Cause No. 0
This is usually given by the router when none of the other codes apply. This cause usually occurs in the same type of situations as cause 1, cause 88, and cause 100.

Cause No. 1 — Unallocated (unassigned) number.
This cause indicates that the destination requested by the calling user cannot be reached because, although the number is in a valid format, it is not currently assigned (allocated).
What it usually means:
The SPIDS may be incorrectly entered in the router or the Telco switch, giving a SPID failure in the router logs.
The ISDN phone number being dialed by the router is invalid and the telco switch cannot locate the number to complete the call, as it is invalid.
On long distance calls, the call cannot be properly routed to its destination.

Cause No. 2 — No route to specified transit network (national use).
This cause indicates that the equipment sending this cause has received a request to route the call through a particular transit network which it does not recognize. The equipment sending this cause does not recognize the transit network either because the transit network does not exist or because that particular transit network not serve the equipment which is sending this cause.

Cause No. 3 — No route to destination.
This cause indicates that the called party cannot be reached because the network through which the call has been routed does not serve the destination desired. This cause is supported on a network dependent basis.

Cause No. 4 — send special information tone.
This cause indicates that the called party cannot be reached for reasons that are of a long term nature and that the special information tone should be returned to the calling party.

Cause No. 5 — misdialed trunk prefix (national use).
This cause indicates the erroneous inclusion of a trunk prefix in the called party number. This number is to sniped from the dialed number being sent to the network by the customer premises equipment.

Cause No. 6 — channel unacceptable.
This cause indicates that the channel most recently identified is not acceptable to the sending entity for use in this call.

Cause No. 7 — call awarded. being delivered in an established channel.
This cause indicates that the user has been awarded the incoming call and that the incoming call is being connected to a channel already established to that user for similar calls (e.g. packet-mode x.25 virtual calls).

Cause No. 8 — preemption.
This cause indicates the call is being preempted.

Cause No. 9 — preemption — circuit reserved for reuse.
This cause indicates that the call is being preempted and the circuit is reserved for reuse by the preempting exchange.

Cause No. 16 — normal call clearing.
This cause indicates that the call is being cleared because one of the users involved in the call has requested that the call be cleared.
What it means:
This could be almost anything; it is the vaguest of the cause codes. The call comes down normally, but the reasons for it could be:
— Bad username or password
— Router’s settings do not match what is expected by the remote end.
— Telephone line problems.
— Hung session on remote end.

Cause No. 17 — user busy.
This cause is used to indicate that the called party is unable to accept another call because the user busy condition has been encountered. This cause value may be generated by the called user or by the network. In the case of user determined user busy it is noted that the user equipment is compatible with the call.
What is means:
Calling end is busy.

Cause No. 18 — no user responding.
This cause is used when a called party does not respond to a call establishment message with either an alerting or connect indication within the prescribed period of time allocated.
What it means:
The equipment on the other end does not answer the call. Usually this is a misconfiguration on the equipment being called.

Cause No. 19 — no answer from user (user alerted).
This cause is used when the called party has been alerted but does not respond with a connect indication within a prescribed period of time. Note — This cause is not necessarily generated by Q.931 procedures but may be generated by internal network timers.

Cause No. 20 — subscriber absent.
This cause value is used when a mobile station has logged off. Radio contact is not obtained with a mobile station or if a personal telecommunication user is temporarily not addressable at any user-network interface.

Cause No. 21 — call rejected.
This cause indicates that the equipment sending this cause does not wish to accept this call. although it could have accepted the call because the equipment sending this cause is neither busy nor incompatible. This cause may also be generated by the network, indicating that the call was cleared due to a supplementary service constraint. The diagnostic field may contain additional information about the supplementary service and reason for rejection.
What it means:
This is usually a telco issue. The call never reaches the final destination, which can be caused by a bad switch translation, or a misconfiguration on the equipment being called.

Cause No. 22 — number changed.
This cause is returned to a calling party when the called party number indicated by the calling party is no longer assigned. The new called party number may optionally be included in the diagnostic field. If a network does not support this cause, cause no. 1, unallocated (unassigned) number shall be used.

Cause No. 26 — non-selected user clearing.
This cause indicates that the user has not been awarded the incoming call.

Cause No. 27 — destination out of order.
This cause indicates that the destination indicated by the user cannot be reached because the interface to the destination is not functioning correctly. The term «not functioning correctly» indicates that a signal message was unable to be delivered to the remote party; e.g., a physical layer or data link layer failure at the remote party or user equipment off-line.

Cause No. 28 — invalid number format (address incomplete).
This cause indicates that the called party cannot be reached because the called party number is not in a valid format or is not complete.

Cause No. 29 — facilities rejected.
This cause is returned when a supplementary service requested by the user cannot be provide by the network.

Cause No. 30 — response to STATUS INQUIRY.
This cause is included in the STATUS message when the reason for generating the STATUS message was the prior receipt of a STATUS INQUIRY.

Cause No. 31 — normal. unspecified.
This cause is used to report a normal event only when no other cause in the normal class applies.

Cause No. 34 — no circuit/channel available.
This cause indicates that there is no appropriate circuit/channel presently available to handle the call.
What it means:
There is no place on the Public Telephone network to place the call; the call never gets to its destiation. This is usually a temporary problem.

Cause No. 35 — Call Queued.

Cause No. 38 — network out of order.
This cause indicates that the network is not functioning correctly and that the condition is likely to last a relatively long period of time e.g., immediately re-attempting the call is not likely to be successful.

Cause No. 39 — permanent frame mode connection out-of-service.
This cause is included in a STATUS message to indicate that a permanently established frame mode connection is out-of-service (e.g. due to equipment or section failure)

Cause No. 40 — permanent frame mode connection operational.
This cause is included in a STATUS message to indicate that a permanently established frame mode connection is operational and capable of carrying user information.

Cause No. 41 — temporary failure.
This cause indicates that the network is not functioning correctly and that the condition is no likely to last a long period of time; e.g., the user may wish to try another call attempt almost immediately.
What it means:
This means that there is a temporary failure at the physical layer on the ISDN network. If you remove the ISDN cable from the Netopia, you would see this. It’s usually temporary.

Cause No. 42 — switching equipment congestion.
This cause indicates that the switching equipment generating this cause is experiencing a period of high traffic.
What it means:
Just too much going on at this point on the ISDN network to get the call through to its destination.

Cause No. 43 — access information discarded.
This cause indicates that the network could not deliver access information to the remote user as requested. i.e., user-to-user information, low layer compatibility, high layer compatibility or sub-address as indicated in the diagnostic. It is noted that the particular type of access information discarded is optionally included in the diagnostic.

Cause No. 44 — requested circuit/channel not available.
This cause is returned when the circuit or channel indicated by the requesting entity cannot be provided by the other side of the interface.

Cause No. 46 — precedence call blocked.
This cause indicates that there are no predictable circuits or that the called user is busy with a call of equal or higher preventable level.

Cause No. 47 — resource unavailable, unspecified.
This cause is used to report a resource unavailable event only when no other cause in the resource unavailable class applies.

Cause No. 49 — Quality of Service not available.
This cause is used to report that the requested Quality of Service, as defined in Recommendation X.213. cannot be provided (e.g., throughput of transit delay cannot be supported).

Cause No. 50 — requested facility not subscribed.
This cause indicates that the user has requested a supplementary service which is implemented by the equipment which generated this cause but the user is not authorized to use.
What it means:
The switch looks at the number being dialed and thinks it is for another service rather than ISDN. If the phone number is put in the correct format, the call should be placed properly. There are no standards for this, all Telcos have their own system for programming the number formats that the switches will recognize. Some systems want to see 7 digits, some 10, and others 11.

Cause No. 52 — outgoing calls barred.

Cause No. 53 — outgoing calls barred within CUG.
This cause indicates that although the calling party is a member of the CUG for the outgoing CUG call. Outgoing calls are not allowed for this member of the CUG.

Cause No. 54 — incoming calls barred

Cause No. 55 — incoming calls barred within CUG.
This cause indicates that although the calling party is a member of the CUG for the incoming CUG call. Incoming calls are not allowed for this member of the CUG.

Cause No. 57 — bearer capability not authorized.
This cause indicates that the user has requested a bearer capability which is implemented by the equipment which generated this cause but the user is not authorized to use.

Cause No. 58 — bearer capability not presently available.
This cause indicates that the user has requested a bearer capability which is implemented by the equipment which generated this cause but which is not available at this time.

Cause No. 62 — inconsistency in outgoing information element.
This cause indicates an inconsistency in the designated outgoing access information and subscriber class.

Cause No. 63 — service or option not available. unspecified.
This cause is used to report a service or option not available event only when no other cause in the service or option not available class applies.

Cause No. 65 — bearer capability not implemented.
This cause indicates that the equipment sending this cause does not support the bearer capability requested.
What it means:
In most cases, the number being called is not an ISDN number but an analog destination.
The equipment is dialing at a faster rate than the circuitry allows, for example, dialing at 64K when only 56K is supported.

Cause No. 66 — channel type not implemented.
This cause indicates that the equipment sending this cause does not support the channel type requested.

Cause No. 69 — requested facility not implemented.
This cause indicates that the equipment sending this cause does not support the requested supplementary services.

Cause No. 70 — only restricted digital information bearer capability is available.
This cause indicates that the calling party has requested an unrestricted bearer service but the equipment sending this cause only supports the restricted version of the requested bearer capability.

Cause No. 79 — service or option not implemented unspecified.
This cause is used to report a service or option not implemented event only when no other cause in the service or option not implemented class applies.

Cause No. 81 — invalid call reference value.
This cause indicates that the equipment sending this cause has received a message with a call reference which is not currently in use on the user-network interface.

Cause No. 82 — identified channel does not exist.
This cause indicates that the equipment sending this cause has received a request to use a channel not activated on the interface for a call. For example, if a user has subscribed to those channels on a primary rate interface numbered from l to 12 and the user equipment or the network attempts to use channels 3 through 23, this cause is generated.

Cause No. 83 — a suspended call exists, but this call identify does not.
This cause indicates that a call resume has been attempted with a call identity which differs from that in use for any presently suspended call(s).

Cause No. 84 — call identity in use.
This cause indicates that the network has received a call suspended request containing a call identity (including the null call identity) which is already in use for a suspended call within the domain of interfaces over which the call might be resumed.

Cause No. 85 — no call suspended.
This cause indicates that the network has received a call resume request containing a call identity information element which presently does not indicate any suspended call within the domain of interfaces over which calls may be resumed.

Cause No. 86 — call having the requested call identity has been cleared.
This cause indicates that the network has received a call resume request containing a call identity information element indicating a suspended call that has in the meantime been cleared while suspended (either by network time-out or by the remote user).

Cause No. 87 — user not a member of CUG.
This cause indicates that the called user for the incoming CUG call is not a member of the specified CUG or that the calling user is an ordinary subscriber calling a CUG subscriber.

Cause No. 88 — incompatible destination.
This cause indicates that the equipment sending this cause has received a request to establish a call which has low layer compatibility. high layer compatibility or other compatibility attributes (e.g., data rate) which cannot be accommodated.
What it means:
This usually means that the Number To Dial in the Connection Profile is in the wrong format. You may need to dial a 10 or 11 digit number, or dial a 9 in front of the number if it is a Centrex line.
This problem may also give a Cause 111.
Dialing at the wrong line speed can also give this Cause.

Cause No. 90 — non-existent CUG.
This cause indicates that the specified CUG does not exist.

Cause No. 91 — invalid transit network selection (national use).
This cause indicates that a transit network identification was received which is of an incorrect format as defined in Annex C/Q.931

Cause No. 95 — invalid message, unspecified.
This cause is used to report an invalid message event only when no other cause in the invalid message class applies.

Cause No. 96 — mandatory information element is missing.
This cause indicates that the equipment sending this cause has received a message which is missing an information element which must be present in the message before that message can be processed.
What it means:
This is rarely seen in North America but usually means that the number that is being dialed is in the wrong format, (similar to cause 88). Some part of the format being used is not understood by either the remote side equipment or the switching equipment between the source and destination of the call.

Cause No. 97 — message type non-existent or not implemented.
This cause indicates that the equipment sending this cause has received a message with a message type it does not recognize either because this is a message not defined of defined but not implemented by the equipment sending this cause.

Cause No. 98 — message not compatible with call state or message type non-existent.
This cause indicates that the equipment sending this cause has received a message such that the procedures do not indicate that this is a permissible message to receive while in the call state, or a STATUS message was received indicating an incompatible call state.

Cause No. 99 — Information element / parameter non-existent or not implemented.
This cause indicates that the equipment sending this cause has received a message which includes information element(s)/parameter(s) not recognized because the information element(s)/parameter name(s) are not defined or are defined but not implemented by the equipment sending the cause. This cause indicates that the information element(s)/parameter(s) were discarded. However, the information element is not required to be present in the message in order for the equipment sending the cause to process the message.

Cause No. 100 — Invalid information element contents.
This cause indicates that the equipment sending this cause has received and information element which it has implemented; however, one or more of the fields in the information element are coded in such a way which has not been implemented by the equipment sending this cause.
What it means:
Like cause 1 and cause 88, this usually indicates that the ISDN number being dialed is in a format that is not understood by the equipment processing the call. SPIDs will sometimes fail to initialize with a Cause 100, or a call will fail with this cause.

Cause No. 101 — message not compatible with call state.
This cause indicates that a message has been received which is incompatible with the call state.

Cause No. 102 — recovery on timer expiry.
This cause indicates that a procedure has been initiated by the expiration of a timer in association with error handling procedures.
What it means:
his is seen in situations where ACO (Alternate Call Offering) is being used. With this type of call pre-emption, the Telco switch operates a timer. For example, when an analog call is placed to a Netopia router that has two B Data Channels in place, the router relinquishes the second channel, but if it doesn’t happen in the time allotted by the switch programming, the call will not ring through and will be discarded by the switch.

Cause No. 103 — parameter non-existent or not implemented — passed on (national use).
This cause indicates that the equipment sending this cause has received a message which includes parameters not recognized because the parameters are not defined or are defined but not implemented by the equipment sending this cause. The cause indicates that the parameter(s) were ignored. In addition, if the equipment sending this cause is an intermediate point, then this cause indicates that the parameter(s) were passed unchanged.

Cause No. 110 — message with unrecognized parameter discarded.
This cause indicates that the equipment sending this cause has discarded a received message which includes a parameter that is not recognized.

Cause No. 111 — protocol error, unspecified.
This cause is used to report a protocol error event only when no other cause in the protocol error class applies.

Cause No. 127 — Intel-working, unspecified.
This cause indicates that an interworking call (usually a call to 5W56 service) has ended.
Notes about Cause Codes over 128
Cause code values of 128 and higher aren’t sent over the network. A terminal displaying a value 128 or higher and claiming it is a cause code arguably has a bug or is implementing some proprietary diagnostic code (not necessarily bad). Some commendation has cause codes listed with numbers higher than 128, but at this time they are proprietary in nature.
The PRI equipment vendors are the most likely to use these codes as they have been using proprietary messages in the facilities data link for some time now (there is an as yet undefined area in the FDL which is big enough to carry small datagrams or messages). It is typically used to pass proprietary control or maintenance messages between multiplexers.

При копировании статьи ссылка на источник ОБЯЗАТЕЛЬНА ! Пожалуйста, уважайте чужой труд.

Автор: Панфилов Алексей (lehis (at) subnets.ru)

Ничего не понялТак себе...Не плохоДовольно интересноОтлично ! То что нужно ! (голосов: 3, среднее: 5,00 из 5)
Загрузка...
Отправить на почту Отправить на почту
    Не найдено

Используем BIRD (Internet Routing Daemon) для создания «пограничного» маршрутизатора.

Итак, у нас появилась собственная автономная система и блок /23 PI адресов. Возник вопрос, что использовать для анонсирования своей AS и блока адресов, какое железо?
Клиенты использующие сеть для доступа к Интернет потребляют трафик порядка 300-400Мб/с. Ценник на «железный» роутер для таких задач будет от 400К рублей, поэтому было принято решение — используем opensource и имеющийся в наличии сервер HP Proliant DL140 G3 с двумя 2-х ядерными процессорами и 2Гб оперативной памяти. Используемая ОС — CentOS 5, а в качестве демона маршрутизации был выбран, после некторых тестов и сравнений, — BIRD. На используемом сервере установлена версия 1.2.4 (процесс установки описан здесь).

Описание схемы сети.

Смотрим рисунок. Сеть подключается через наш «пограничный» маршрутизатор к двум провайдерам, один из них AS65002 — основной, второй AS65001 — резервный, со вторым очень дружественные взаимоотношения и он по доброте душевной бесплатно транзитит наш трафик на точку обмена трафиком и обратно, таким образом, мы немного (а иногда и 50%) экономим на оплате трафика основному провайдеру. Наша AS — AS6500 и полученный префикс — zzz.zzz.zzz.0/23. Внутри нашей AS работает протокол OSPF (выбран исходя из того, что роутеры на базе opensource в сети будут появляться чаще, чем роутеры Cisco).  От обоих провайдеров мы получаем full-view. Дополнительно, второй провайдер (AS65001) «красит» маршруты с точки обмена трафиком с помощью community — 65001:1400. Для того, чтобы избежать ошибок с получением маршрута по умолчанию от провайдеров, мы сами его с пограничного маршрутизатора объявляем внутрь сети (тем самым, кстати гарантируем, что трафик на несуществующие префиксы не будет уходить дальше нашего роутера).  Стыковая  сеть с провайдером AS65002 — y.y.y.0/30, стыковая сеть с провайдером AS65001 — x.x.x.0/30. Внутри сети между роутерами используется сеть z.z.z.0/28.

Подготовка к созданию конфигурации BIRD, коротко о BIRD.

С документацией по использованию BIRD можно ознакомиться здесь. Самое основное в понимании работы с BIRD — это представление о таблицах маршрутизации и протоколах, которые работают с этими таблицами. BIRD поддерживает работу протоколов BGPv4, RIPv2, OSPFv2, OSPFv3 и виртуального протокола Pipe  для обмена маршрутами между различными таблицами маршрутизации. Для всех протоколов реализована работа с IPv6.  Между таблицей маршрутзации и протоколом устанавливаются два фильтра export и import, которые могут принимать, блокировать или изменять получаемую и передаваемую информацию из таблицы в протокол и обратно. Export — направление от таблицы к протоколу, import — в обратную сторону. Когда маршрут передается из протокола в таблицу, его стоимость пересчитывается и об этом оповещаются все протоколы, которые используют данную таблицу, после чего каждый протокол формирует update и рассылает сообщение согласно своему механизму оповещения об изменении маршрута.  По-умолчанию в BIRD существует таблица master, которая может использоваться всеми протоколами, если иное в конфигурации протокола не было указано. Кроме указанных выше протоколов, есть еще псевдопротокол kernel, отчечающий за синхронизацию между таблицами маршрутизации BIRD и ядра системы, протокол static — отвечающий за статическую маршрутизацию, протокол direct — создающий маршруты в BIRD на основе настроек сетевых интерфейсов полученных из ядра, и протокол device, отслеживающий состояниме интерфефсов в системе (up/down).

Составим список протоколов и их названий, которые мы будем использовать:
  • bgpAS65002 (в BIRD для работы с bgp соседом необходмо запустить отдельную «ветку» протокола) — для работы с основным провайдером;
  • bgpAS65001 — для работы с резервным провайдером;
  • ospfAS65000 — для обеспечения маршрутизации внутри сети;
  • static1 — понадобится для объявления маршрута по-умолчанию;
  • static2 — используем для объявления нашего «большого» префикса;
  • kernel — понадобится для передачи маршрутов из BIRD в систему;
  • direct и device — их назначение описано выше.

Т.к. конфигурация сети у нас довольно простая, будем использовать только одну таблицу маршрутизации — master.

Для составления конфигурационного файла, лучше все взаимосвязи сначала отразим на схеме:

На схеме видно, что нам для работы с информацией из таблицы master и из протоколов потребуются фильтры. Мы их опишем уже непосредственно в конфиге BIRD.

Файл конфигурации BIRD.

/*

* This is an example configuration file.

*/

#Задаем формат времени для логирования
timeformat base     iso long;
timeformat log      iso long;
timeformat protocol iso long;
timeformat route    iso long;

#Указываем путь к лог-файлу
log «/var/log/bird.log» all;
log stderr all;

##### Начнем описание наших протоколов, некоторые описания взяты из дефолтного конфига

# The direct protocol automatically generates device routes to

# all network interfaces. Can exist in as many instances as you wish

# if you want to populate multiple routing tables with device routes.
protocol direct {

interface «eth*», «*»; # Restrict network interfaces it works with

}

# This pseudo-protocol watches all interface up/down events.
protocol device {

scan time 10; # Scan interfaces every 10 seconds

}

# This pseudo-protocol performs synchronization between BIRD’s routing

# tables and the kernel. If your kernel supports multiple routing tables

# (as Linux 2.2.x does), you can run multiple instances of the kernel

# protocol and synchronize different kernel tables with different BIRD tables.
protocol kernel {
persist off; # Don’t remove routes on bird shutdown
scan time 20; # Scan kernel routing table every 20 seconds
import none; # Default is import all
export all; # Default is export none
}

#Статический маршрут, необходимый для добавления маршрута по-умолчанию в таблицу master
protocol static static1 {

route 0.0.0.0/0 via «lo»;

}

#Статический маршрут для добавления нашего префикса в таблицу
protocol static static2 {

preference 253;

route zzz.zzz.zzz.0/23 via «lo»;

}
###Конфигурация протокола OSPF:

#Как мы описывали выше, мы должны объявить нашим ospf соседям маршрут по-умолчанию и маршруты типа directly, а в таблицу master должны передать маршруты полученные от ospf соседей, кроме дефолта

#для этого используем соответствующие фильтры:
filter import_OSPF {

if ( source = RTS_OSPF && net != 0.0.0.0/0 ) then {

print «net accepted:», net;

accept;

}

reject;

}

filter export_OSPF {
#Передаем маршруты connected
if ( source = RTS_DEVICE ) then {

print «net accepted:», net;

ospf_metric2 = 20;

accept;

}
#Передаем маршрут по умолчанию, т.к. он у нас «завернут» на интефрейс loopback, то необходимо использовать конструкцию RTS_STATIC_DEVICE, а не RTS_STATIC
if ( source = RTS_STATIC_DEVICE && net = 0.0.0.0/0 ) then {

print «net accepted:», net;

ospf_metric2 = 5;

accept;

}

reject;

}

#Конфигурация протокола OSPF
protocol ospf ospfAS65000 {

router id 87.244.8.18;

export filter export_OSPF;

import filter import_OSPF;

area 0.0.0.0 {

interface «eth1.4» {

hello 10;

retransmit 5;

cost 10;

transmit delay 1;

dead count 4;

wait 40;

type broadcast;

priority 0;

};

};

}
###

###Настройка BGP

#Задаем функцию, с помощью которой мы будем блокировать сети RFC1918, дефолт, префиксы короче /24, префиксы /32, /0 и /7, если они вдруг «прилетят» от bgp соседей
function avoid_nonexist()
#Описываем префикс-лист, по которому будет происходить проверка маршрутов
prefix set nonexist;

{

nonexist = [ 169.254.0.0/16+, 172.16.0.0/12+, 192.168.0.0/16+, 10.0.0.0/8+, 224.0.0.0/4+, 240.0.0.0/4+, 0.0.0.0/32-, 0.0.0.0/0{25,32}, 0.0.0.0/0{0,7} ];

if net ~ nonexist then return false;

return true;

}
#Задаем функцию, с помощью которой будем фильтровать маршруты из нашей AS
function pref_from_myasset()

prefix set pref_from_65000;

{

pref_from_65000 = [ zzz.zzz.zzz.0/23  ];

if net ~ pref_from_65000 then return true;

return false;

}

###Основной провайдер

##Отфильтровываем маршруты и устанавливаем local preference
filter prov65002in {

if avoid_nonexist() then

{

bgp_local_pref = 340; #устанавливаем local preference
accept;

}

reject;

}

filter prov65002out {

if pref_from_myasset() then

{

bgp_community = -empty-; #не отправляем никаких коммьюнити
bgp_path.prepend(65000); #добавляем prepend
accept;

}

reject;

}


protocol bgp bgpAS65002 {

table master;

router id yyy.yyy.yyy.2;

description «AS65002»;

local as 65000;

neighbor yyy.yyy.yyy.1 as 65002;

hold time 240;

startup hold time 240;

connect retry time 120;

keepalive time 80;

start delay time 5;

error wait time 60, 300;

error forget time 300;

next hop self;

path metric 1;

default bgp_med 0;

source address yyy.yyy.yyy.2;

export filter prov65002in;

import filter prov65002out;

}
###

###Резервный провайдер

##Отфильтровываем маршруты, устанавливаем local preference для маршрутов помеченных community на стороне второго провайдера
filter prov65001in {

if (65001,1400) ~ bgp_community then

{

bgp_local_pref = 400; # local preference для маршрутов отмеченных community 65001:400

accept;

}

bgp_local_pref = 330; #local preference для остальных маршрутов
if avoid_nonexist() then accept;

}


filter prov65002out {

if pref_from_myasset() then

{

bgp_community = -empty-;

accept;

}

reject;

}

protocol bgp bgpAS65001 {

table master;

router id xxx.xxx.xxx.2;

description «AS65001»;

local as 65000;

neighbor xxx.xxx.xxx.1 as 65001;

hold time 240;

startup hold time 240;

connect retry time 120;

keepalive time 80;

start delay time 5;

error wait time 60, 300;

error forget time 300;

next hop self;

path metric 1;

default bgp_med 0;

source address xxx.xxx.xxx.2;

export filter prov65002out;

import filter prov65002in;

}
###

/*

* The End

*/

Для проверки работы фильтров, состояния протоколов, маршрутов и т.п. в BIRD есть свой CLI:

# /usr/local/sbin/birdc

BIRD 1.2.4 ready.

bird> >?

configure [soft] [«<file>»]                    Reload configuration

debug …                                      Control protocol debugging via BIRD logs

disable <protocol> | «<pattern>» | all         Disable protocol

down                                           Shut the daemon down

dump …                                       Dump debugging information

echo [all | off | <mask>] [<buffer-size>]      Configure echoing of log messages

enable <protocol> | «<pattern>» | all          Enable protocol

exit                                           Exit the client

help                                           Description of the help system

mrtdump …                                    Control protocol debugging via MRTdump files

quit                                           Quit the client

reload <protocol> | «<pattern>» | all          Reload protocol

restart <protocol> | «<pattern>» | all         Restart protocol

restrict                                       Restrict current CLI session to safe commands

show …                                       Show status information

На этом пока все, буду рад, если эта статья кому-то пожет в работе))

З.Ы. При копировании статьи ссылка на источник ОБЯЗАТЕЛЬНА ! Пожалуйста, уважайте чужой труд.

Автор: zaikini
Ничего не понялТак себе...Не плохоДовольно интересноОтлично ! То что нужно ! (голосов: 2, среднее: 5,00 из 5)
Загрузка...
Отправить на почту Отправить на почту
    Не найдено

Продолжая тему туннелей привожу ещё один способ поднять туннель между серверами под OS FreeBSD — это netgraph туннели.

Netgraph туннель как и OpenVPN туннель позволяет выбрать порт и протокол по которому будет устанавливаться туннель.

Их основное отличие в том, что netgraph туннель реализован на уровне ядра системы и использует все доступные ядра CPU, а OpenVPN реализован в userland`е и использует только одно ядро CPU.

Задача

Поднять netgraph туннель между двумя FreeBSD серверами и пророутить через туннель некоторые подсети.

Дано

  • Внешний IP-адрес сервера FreeBSD1: 1.1.1.1
  • Внешний IP-адрес сервера FreeBSD2: 2.2.2.2
  • Тунельный IP-адрес сервера FreeBSD1: 10.0.0.1
  • Тунельный IP-адрес сервера FreeBSD2: 10.0.0.2

Настройка

Туннель устанавливается между двумя внешнему IP-адресами по выбранному нами порту 2000 и протоколу UDP,  на туннеле назначаются IP-адреса из серой подсети 10.0.0.0/30.

Я приведу настройку только одной стороны, т.к. вторая сторона это просто зеркальное отражение первой.

Создадим интерфейс ng:
# ngctl mkpeer iface dummy inet

Укажем что будем использовать протокол UDP:
# ngctl mkpeer ng0: ksocket inet inet/dgram/udp

Укажем внешний IP сервера FreeBSD-1 (с которого мы и начали настройку) и зададим порт:
# ngctl msg ng0:inet bind inet/1.1.1.1:2000

Укажем внешний IP сервера FreeBSD-2 и порт, на которой мы и устанавливаем туннель:
ngctl msg ng0:inet connect inet/2.2.2.2:2000

Назначим IP-адреса на сам туннель (созданный интерфейс ng0):
ifconfig ng0 10.0.0.1 10.0.0.2 netmask 255.255.255.252

Теперь можно посмотреть что получилось:

# ifconfig ng0

ng0: flags=88d1<UP,POINTOPOINT,RUNNING,NOARP,SIMPLEX,MULTICAST> metric 0 mtu 1500
        inet 10.0.0.1 --> 10.0.0.2 netmask 0xfffffffc

Туннель с одной стороны готов, настройте зеркально вторую сторону (сервер FreeBSD-2) и вы должны «увидеть» (пинговать) туннельные IP-адреса с обоих сторон.
После чего можно уже роутить что угодно через установленный вами туннель.

Команда для уничтожения netgraph туннеля:

# ngctl shutdown ng0:

Внимание ! Символ двоеточия в конце это не очепятка, как многие думают, он должен там быть.

Для автозапуска туннеля заглянем в предоставленный нам пример /usr/share/examples/netgraph/udp.tunnel и создадим свой стартовый скрипт /usr/local/etc/rc.d/ng_tun_start.sh

#!/bin/sh

case "$1" in
stop)
        if ifconfig ng0 >/dev/null 2>&1; then
                ifconfig ng0 inet down delete >/dev/null 2>&1
                ngctl shutdown ng0:
                echo "tunnel ng0 was destroyed";
        fi
        ;;
start)
        LOC_EXTERIOR_IP=1.1.1.1
        REM_EXTERIOR_IP=2.2.2.2

        LOC_INTERIOR_IP=10.0.0.1
        REM_INTERIOR_IP=10.0.0.2

        UDP_TUNNEL_PORT=2000
        if ifconfig ng0 >/dev/null 2>&1; then
                echo "tunnel ng0 already up";
        else
                ngctl mkpeer iface dummy inet
                ngctl mkpeer ng0: ksocket inet inet/dgram/udp
                ngctl msg ng0:inet bind inet/${LOC_EXTERIOR_IP}:${UDP_TUNNEL_PORT}
                ngctl msg ng0:inet connect inet/${REM_EXTERIOR_IP}:${UDP_TUNNEL_PORT}
                ifconfig ng0 ${LOC_INTERIOR_IP} ${REM_INTERIOR_IP} netmask 255.255.255.252
        fi
        ;;
*)
        echo "Usage: `basename $0` {start|stop}" >&2
        ;;
esac

Теперь при старте сервера туннель будет автоматически создан и у вас есть возможность в ручную стартовать туннель:
# /usr/local/etc/rc.d/ng_tun_start.sh start

или разрушать его:
# /usr/local/etc/rc.d/ng_tun_start.sh stop

З.Ы. При копировании статьи ссылка на источник ОБЯЗАТЕЛЬНА ! Пожалуйста, уважайте чужой труд.

Автор: Панфилов Алексей (lehis (at) subnets.ru)

Ничего не понялТак себе...Не плохоДовольно интересноОтлично ! То что нужно ! (голосов: 1, среднее: 4,00 из 5)
Загрузка...
Отправить на почту Отправить на почту
    Не найдено

NetFlow — Netflow — протокол 5 (сеансового) уровня сетевой модели OSI, разработанный компанией Cisco и предназначенный для сбора информации об IP-трафике.

Стандартный пакет flow-tools, помимо приложений, которые показывают содержимое файлов статистики, содержит еще и две интересные службы flow-capture и flow-fanout.
Flow-capure служит для сохранения полученной статистики. Flow-fanout служит для дублирования статистики на разные машины. Обовсем подробнее.

Программно-аппаратное обеспечение
1. ПК P4 — CPU 2.4 GHz, RAM 512 Mb, HDD 1Tb.
2. ОС — FreeBSD 7.2, swap 4 Gb

Установка
1. Обновляем порты:

# portsnap fetch update

или если вы используете команду portsnap впервые:

# portsnap fetch extract

2.  Устанавливаем порт:

# cd /usr/ports/net-mgmt/flow-tools
# make install clean

Настройка

Правим файл /etc/rc.conf:

Так настраивается flow-capture:

# Запускаем flow-capture
flow_capture_enable=»YES»

# Указываем ip-адрес на котором слушается соединение (принимается поток)
flow_capture_localip=»IP_ADDRESS«
вместо IP_ADDRESS укажите IP-адрес сервера, пример: 10.0.0.1

# Указываем ip с которого принимать поток (по умолчанию 0.0.0.0 — принимать с любого ip)
flow_capture_remoteip=»0.0.0.0″

# Указываем порт на который будет приниматься поток
flow_capture_port=»9998″

# указываем путь, по которому будем складывать статистику
flow_capture_datadir=»/usr/local/_dump/ng»

# Параметры работы демона
flow_capture_flags=»-keyvalue»

Так настраивается flow-fanout:


#Включаем flow-fanout
flow_fanout_enable=»YES»

# Указываем ip-адрес на котором слушается соединение(принимается поток)
flow_fanout_ip=»IP_ADDRESS«

# Указываем ip с которого принимать поток (по умолчанию 0.0.0.0 — принимать с любого ip)
flow_fanout_remoteip=»0.0.0.0″

# Указываем порт на который будет приниматься поток
flow_fanout_port=»PORT_NUMBER«

# Указываем правила экспорта статистики
flow_fanout_export=»<source_ip1>/<det_ip1>/<dest_port1> <source_ip2>/<det_ip2>/<dest_port2>»

Перед настройкой следует определиться, каким образом будет осуществляться хранение статистики и её получение.
Вариантов существует по меньшей мере 2:

  • непосредственно принимать поток при помощи flow-capture и сохранять на этой же машине
  • принимать поток при помощи flow-capture и дублировать этот же поток на другую машину

Рассмотри оба варианта на примере использования mpd5 в связке с netflow.

Первый вариант

Допустим, mpd5 и flow-capture у нас работают на одной машине.

Эти параметры следует прописать в mpd.conf:
set iface enable netflow-in
set iface enable netflow-out

set netflow peer 127.0.0.1 9996 #Кому передаем
set netflow self 127.0.0.1 65500 #свой порт, от которого будет происходить передача

Это прописываем в /etc/rc.conf:
flow_capture_enable=»YES»
flow_capture_localip=»127.0.0.1″
flow_capture_remoteip=»0.0.0.0″
flow_capture_port=»9998″
flow_capture_datadir=»/usr/local/_dump/»
flow_capture_flags=»-S60 -z9 -n95 -N0″

Таким образом демон mpd5 будет скидывать, с порта 65500, на порт 9996, flow-capture, информацию о входящем и исходящем трафике,

а flow-capture, в свою очередь, будет складывать её по пути /usr/local/_dump .

Второй вариант
Допустим, mpd5 и flow-fanout у нас работают на одной машине, а flow-capture на другой и нам нужно сливать поток как на коллектор flow-capture, так и на еще одну стороннюю машину.

  • mpd5 и flow-fanout — IP 10.10.0.1
  • flow-capture — ip 10.10.0.2
  • сторонняя машина — ip 10.10.0.3

Сервер 1:
mpd.conf берем из предыдущего примера:
set iface enable netflow-in
set iface enable netflow-out

set netflow peer 127.0.0.1 9996 #Кому передаем
set netflow self 127.0.0.1 65500 #свой порт, от которого будет происходить передача

А вот в /etc/rc.conf настраиваем уже flow-fanout:
flow_fanout_enable=»YES»
flow_fanout_ip=»127.0.0.1″
flow_fanout_remoteip=»127.0.0.1″

# Укажу свой loopback, т.к. нет смысла слушать «с любого адреса»
flow_fanout_port=»9996″
flow_fanout_export=»10.10.0.1/10.10.0.2/9997 10.10.0.1/10.10.0.3/9998″

Сервер 2:
Именно на нем поднимаем flow-capture:
flow_capture_enable=»YES»
flow_capture_localip=»10.10.0.2″
flow_capture_remoteip=»10.10.0.1″

# Можно указать и 0.0.0.0
flow_capture_port=»9997″
flow_capture_datadir=»/usr/local/_dump/»
flow_capture_flags=»-S60 -z9 -n95 -N0″

Сервер 3:
Любое приложение которое принимает flow-поток, будь то биллинг, другой сервер статистики или что-то еще.

Объясню что происходит во втором случае:
Демон mpd5 будет скидывать, с порта 65500, на порт 9996, flow-fanout, информацию о входящем и исходящем трафике. Flow-fanout, в свою очередь, будет сливать это на второй сервер, на котором настроен flow-capture, на порт 9997, и так же он будет сливать эту статистику на третий сервер, порт 9998.

Связка flow-capture И flow-fanout довольно гибкая и позволяет работать с flow-потоком так, как это нужно в зависимости от сложившейся ситуации.

Ключи к flow-capture можно посмотреть в соответствующем man’е.

После всего проделанного запускаем используемые нами сервисы:

# /usr/local/etc/rc.d/flow_capture start

# /usr/local/etc/rc.d/flow_fanout start

Литература и ссылки:
Википедия

З.Ы. При копировании статьи ссылка на источник ОБЯЗАТЕЛЬНА !

Автор: Andrey

Ничего не понялТак себе...Не плохоДовольно интересноОтлично ! То что нужно ! (Еще не голосовали)
Загрузка...
Отправить на почту Отправить на почту
    Не найдено