Подключение вирусного сканера к HP Openmail alexiv@ashmanov.com Все расписать совсем подробно не совсем получается, посылаю, что удалось успеть. Завтра попробую еще чего-нибудь прокопать. Состояние софта на текущий момент Openmail - почтовая система с централизованным mail-storage, удовлетворяющая спецификациям X.400. Активно развивался в конце 80-х. В начале 90-х вышли версии OM 5.10 и 5.20, после чего развитие его было заморожено на 10 лет. В 2000-2001 запущены версии 6.0 и 7.0 - основное дополнение в них - реализация более тесной интеграцией с обычной интернетовской почтой на базе SMTP/sendmail (внятная система мапинга интернет-маил-адресов в openmailовские и обратно), добавление антивирусной системы "VirtualVault" от фирмы Trend Micro и порт Openmail в Linux. На этом HP остановил проект, распустил команду разработчиков, сидевшую в Англии, а сам Openmail продал Самсунг'у. В данный момент связаться с разработчиками не представляется возможным (? еще раз проверить), ибо старые распущены, а с новыми нет установленных контактов. Продажа Openmail и раздача evaluation версий прекращена, поддержка зарегистрированных клиентов (уже имеющих проданную версию) будет прекращена в 2006 году. Документация расположена по адресу http://www.openmail.com/cyc/om/00/tocl3_73.html ║ http://www.openmail.com/cyc/om/00/tocl3_73.html Контакты openmail'овцев В Москве: Николай Починок (???@hp.com) (может давать советы, где кого искать) В Англии: ??? (команда разработчиков распущена) В Samsung: (поиск не проводился) Вывод: надежда получить информацию из первоисточника довольно призрачная, расчитывать (пока) придется на собственные силы. Поскольку добавлять антивирус предстоит в _старые_ версии Openmail, ожидать помощи и консультации по этому вопросу от Samsung - бесполезно. Openmail в Самсунге Теперь положительные новости: Самсунг приступил к продажам обновленной версией Openmail под новым названием. Отныне это почтовая система "Samsung Contact 7.1" http://www.samsungcontact.com/en/ ║ http://www.samsungcontact.com/en/ ОПИСАНИЕ ОБЩЕГО УСТРОЙСТВА OM Все хранение почты - в централизованом Мessage Storе (формат хранения - закрытый, с использованием индексного метода доступа dbVista, может изменяться в будующем и ничего приятного не представляет. В OM 5.0, которой кто-то из возможных заказчиков может пользоваться (спросить), письмо хранится в виде нескольких файлов: список адресов, текст, аттачменты - поотдельности, в OM 5.10 - 7.0 введен новый формат - составные части письма живут как части одного файла. Или как ссылки, указывающие на подмножества в других файла (для аттачментов и текстов, разосланных по нескольким адресам). "Вброс" и "забор" почты в MS идет через: (в них проще всего вмонтировать вирусный сканер) РОДНЫЕ КЛИЕНТСКИЕ ИНТЕРФЕЙСЫ: UAL, P7 (мало используемы) ВНЕШНИЕ КЛИЕНТСКИЕ ИНТЕРФЕЙСЫ: (навешены поверх UAL) POP3, IMAP4, IMAPI ГЕЙТВЕИ (вброс/выброс из/в альтернативных почтовых систем): (примерно 10 разных) используется в основном SMTP/sendmail и иногда X.400. ТРАНСПОРТЫ: (туннелирование-перевозка из одного MessageStore в другой OM-сообщений с помощью альтернативных почтовых служб) используется в основном SMTP/sendmail и иногда X.400 Службы, через которые проходит почта при обработке ЛОКАЛЬНАЯ ДОСТАВКА: доставляет письмо в In-бокс пользователя (интерфейса для вставки сканера не обнаружено) SERVICE ROUTER: служба маршрутизации почты. Наиболее перспективен для "правильного" подключения сканера. Но есть проблемы. ARCHIEVE SERVER: выгрузка копий всех проходящих сообщений в отдельный каталог в формате "serialized encoded" Клиенты UAL - родной клиентский интерфейс самого OM, по нему подключаются: пакетный рассыльщик OMSEND (используется только сисадминами в unix); HP-клиент OMGUI (для Windows и Unix) - пользоваться им невозможно из-за неудобности и убогости интерфейса. MAPI - дравер-переходник для MS Outlook === UAL (вероятность использование незначительная, но ненулевая, как встраиваться в UAL совершенно непонятно) POP3 - OM запускает свой собственный pop3d, он работает с MS через UAL. ПЕРЕХВАТ возможен: посадить впереди опенмайловского на 110 порт свою программу и прозрачно фильтровать POP3-протокол. (Не очень элегантно. Есть ли у готовое решение для POP3?) IMAP4 - OM запускает свой собственный in.imap41d, он работает с MS через UAL. ПЕРЕХВАТ возможен: посадить впереди опенмайловского на imap-порт свою программу и прозрачно фильтровать IMAP4-протокол. (Не очень элегантно. Есть ли готовое решение для IMAP4?) Что имеют заказчики Версии OpenMail: Интересны только версии OM 5.10, 6.0, 7.0, причем 7.0 - основная. С некоторым напряжением, но от 5.10 можно отказаться. В основном используется в качестве клиента "OutLook Express" и "OutLook". Забор почты - по pop3/imap4, отсылка - по smtp. Как видим, при типовом использовании забираться почта из Message Store может несколькими путями, а вот попадать - тремя (а в благоприятном случае) всего двумя: 1. Втягивание из интернет-почты (Internet mail gateway) 2. И транспортом sendmail из удаленных ОМ-систем (Sendmail Interface) 3. Редко, но бывает HP Клиент для Outlook - через MAPI (UAL) 4. X.400 как ОМ-транспорт не используется. БЛАГОПРИЯТНОЕ НАПРАВЛЕНИЕ РАБОТЫ: "ЗАЩИТА ПЕРИМЕТРА" Поскольку большинство попадающей в ОМ почты приходит к нам из sendmail, именно в него на приеме удобнее всего устанавливать сканер. ("По периметру") Отдельно придется обрабатывать два разных случая: 1. Входящая интернет-почта (идущая из интернета а так же отправляемая с клиентских машин пользователей) Гейт интернет-почты работает через добавляемый майлер "openmail". Майлер openmail вызывает обрабатывающую программу unix.in /opt/openmail/bin/unix.in конфиг-файлы: /var/opt/openmail/sys/unixin.* она конвертирует письмо из сендмейловского формата и размещает его в Mes╜ sage Store. Письмо передается в unix.in на STDIN (проверить, что не SMTP!) (См. ключи мейлера опенмаил в sendmail.cf) (*) NB. Проверить насчет SMTP, мог перепутать с unix.out или xport.in 2. Входящая почта из других ОМ-систем - приходит в "serialized encoded" формате - открытом, запакованом MIME'ом виде. Перенаправляется на мейлер omxport, обрабатывающая программа xport.in - сообщение передается ей в пайп. Описание serialized encoded см. в "OpenMail Subsystem Developer's Guide" 2.3. Developing Outgoing Gateways..................... 14 2.3.4. Encoded Joined Message Format................. 17 ualdocs/ssdg.htm ║ file:/home/openmail/ual/ualdocs/ssdg.htm /home/openmail/ual/ualdocs/ssdg.htm У сообщения возможна довольно сложная "деревянная" структура - оно может содержать аттачменты в т.ч. другие письма, содержащие аттачменты и т.д. Описание - внизу, в "ПРИЛОЖЕНИИ" О взведении флагов для пользователя об обнаружении вируса Метить письмо с вирусным аттачментом придется искажением в нем Subject'a - в него будем добавлять метки/атрибуты. Обработку этих меток мы сможем провести на стадии маршрутизации писем, в службе Service Router, см. "Message Deliv╜ ery Rulesets", особенно "Script for SUBJECT Attribute" Описание формата и пример скрипта: http://www.openmail.com/cyc/om/00/100-1330.dir/TRG/OTG81005.HTM#1045061 ║ http://www.openmail.com/cyc/om/00/100-1330.dir/TRG/OTG81005.HTM#1045061 "Правила доставки" задаваемые в для Service Router дадут нам возможность анализировать Subject'ы всех маршрутизируемых писем http://www.openmail.com/cyc/om/00/100-1097.dir/COR/OTG/OTG_HTML/OTGM0590.HTM#OTGM0590 При этом анализирующий скрипт (проверить!) сможет восстанавливать оригинальный Subject письма, который мы покалечим на стадии приема его из сендмеил'а. и в зависимости от их содержания предписывать результирующие акции с письмом: ALLOW DEFER (задержать доставку до времени, указанном в правиле) DISCARD (уничтожить молча) REJECT (уничтожить с оповещением отправителя) RETURN При этом текстом, посылаемым в NON-delivery-report можно управлять. Подробнее описание формата правил см. "TRG/ Service Router" (ПРИЛОЖЕНИЕ) АЛЬТЕРНАТИВНЫЕ ПУТИ В принципе, выше описан наиболее технологичный и ясный метод решения, но, к сожалению, он не может охватить письма, попадающие в MS через MAPI/UAL, поэтому придется рассмотреть альтернативные пути, и исследовать их реализуемость. Сканировать _также_ и исходящую с сервера почту "Уходить" из системы почта может через: 1. Gateway в Internet-mail. Уходящее сообщение берется программой unix.out, и из нее подается на вход sendmail'у (через пайп, но по протоколу SMTP). Программа, которой "скармливается" сообщение, задается в конфигурационном файле гейтвея - "стиринг"-файле, и поэтому при желании сканер можно подставить уже здесь, перед сендмаил'ом, хотя наверное, вставлять его лучше в самом сендмаил. (NB! вспомнить название конфиг файла, в котором задаются ключи команды sendmail) /var/opt/openmail/sys/xport.mappers/XPORT (?) 2. Sendmail Транспорт - для перевозки в другие OM-системы. Аналогично пп.1, сообщение берется программой xport.out, конвертируется им в "serialized en╜ coded" формат, и скармливается сендмеил'у (NB! вспомнить название конфиг файла, в котором задаются ключи команды sendmail) 3. Openmail'овские POP3 и IMAP4. В этих случаях сканер придется ставить "прозрачно" над протоколом pop3 и imap4 соответственно. 4. UAL (как добавить сканер непонятно) Сканировать почту в момент ее маршрутизации в Service Router ВАРИАНТ А. - "хакнуть" бинарники Router'a и добавить вызов сканера в него. Именно так поступила TrendMicro со своим антивирусным пакетом - HP для них выделил интерфейсную библиотеку для встраивания в service router и описание ее API. Доводы "против": Openmail'a больше нет. В OM 5.10 этой интерфейсной библиотеки нет, она появилась в 6.0, т.е. для 5.10 все равно придется делать привязку сканера в sendmail, и точно так же она будет работать для 6.0 и 7.0. Не даром первая версия сканера от Trend╜ Micro была прицеплена точно так же, через sendmail на входе. Доводы "за": Самсунг начал продвижение "Samsung Contact 7.1", с ним можно договориться об интерфейсах для этой версии продукта. Беда в том, что у заказчика только 7.0. ВАРИАНТ Б. Попытаться воспользоваться проводимой в SR "File Type Coercion" http://www.openmail.com/cyc/om/00/100-1164.dir/COR/OTG/OTG_HTML/OTGM0070.HTM#OTGM0070 ║ http://www.openmail.com/cyc/om/00/100-1164.dir/COR/OTG/OTG_HTML/OTGM0070.HTM#OTGM0070 В ОМ есть своя (не маймовская) система обозначения типов файлов (каждый тип имеет свой целочисленный номер), и есть пополняемая таблица конверторов, которыми допустимо перекодировать файлы одного типа в другой. А так же есть некий аналог /etc/magic - таблицы с сигнатурами, по которой можно уточнить тип аттачнутого файла. "Coertion" - уточнение типа файла по этой таблице. При смене типа файла к нему может быть применено преобразующее перекодирование - одного типа в другой. Под видом такого форсированного перекодировани и можно попытаться подставить вирусный сканер. Доводы "против": Coertion применяется при отправке письма в _чужие_ системы, через гейты. Т.е. в сендмаил, в поп3, имап, ual. Но при локальной машрутизации почты тип файла остается неизменным и Цоертион не происходит, а значит в самом интересном для нас месте к нему прицепиться не получится. ВАРИАНТ В. Служба архивирования. Все проходящие через SR письма можно дублировать в архивную директорию в serialize-encoded формате. Т.е. перед обработкой в SR письма, его копия сбрасывается в служебный каталог в доступном нам формате. http://www.openmail.com/cyc/om/00/100-1164.dir/COR/OTG/OTG_HTML/OTGM0294.HTM#OTGM0294 ║ http://www.openmail.com/cyc/om/00/100-1164.dir/COR/OTG/OTG_HTML/OTGM0294.HTM#OTGM0294 Включение архивного сервера: SR_DUMP_MSGS=BEFORE Проблема в том, что нам в руки попадут КОПИИ, и если работать с ними, то предстоит сами оригиналы уничтожать, а это опасно. Для уничтожения оригиналов писем в SR надо подключить правило примерно такого содержания: SUBJECT="CHECKED:*" ACTION=ALLOW SUBJECT="VIRUS:*" ACTION=REJECT SUBJECT="*" ACTION=DISCARD если в сабжекте нет волшебного слова, то его - DISCARD. Этим мы уничтожаем все оригиналы, оставляя в живых только копии. В фоновом режиме сканируем лежащие в архиве мессаджи, добавляем им волшебное слово "CHECKED:" в сабжект, даем команду "вбросить" мессаджи из архива обратно на доставку, в очередь роутера. omresubdmp Поскольку волшебное слово в сабже просканированных месаджей теперь есть, роутер их промаршрутизирует куда надо. Но сабжекты останутся в измененном состоянии. ССЫЛКИ: TRG 7.0 стр 59. 4. Archive Server Еще способы "обойти" SR для сообщений, вбрасываемых из Archieve-очереди: Установка им ACTION=DEFER, a затем отправка через Defered mail manager (он маршрутизирует почту сам, без испольования SR), а так же опции самого Archieve-servera (тоже возможна маршрутизация им самим, минуя SR). Обход SR нужен, чтобы на копиях из архива повторно не сработали уничтожающие правила, убивающие оригуиналы. ВАРИАНТ Г. Пакетное сканирование MessageStore через API клиентского интерфейса. API для написания UAL-клиента (и исходники пакетного текстового клиента) описаны в OpenMail Client Developer's Guide. На его базе можно написать пакетный UAL-клиент, который будет прочесывать MS и сканировать все лежащие в нем аттачменты.  * ПРИЛОЖЕНИЕ: ССЫЛКИ НА ТЕХНИЧЕСКУю ИНФОРМАЦИЮ Описание внутреннего формата ОМ-message. Отсутствует Вопросы, вопросы *** Coertion подробнее.  * ПРИЛОЖЕНИЯ ТЕХНИЧЕСКИЕ *  ПОДКЛЮЧЕНИЕ ПРАВИЛ ДЛЯ SR и Subject script 1. Создаем файл с правилами /var/opt/openmail/rules/omvirus с содержанием: NAME=viruschecker SUBJECT="@omsubj.map" ACTION=ALLOW 2. omsubj.map - subj-чекер должен лежать в каталоге /var/opt/openmail/rules/ #!/usr/bin/perl # OpenMail Router Subject Mapping Protocols /var/opt/openmail/rules/subject.map # COMMAND REPLY REPLY COMMENTS # 220 Mapper must output this when starts up # HELO 250 Mapper accepts OpenMail session # SUBJECT: 251 Subject does not match requirement # SUBJECT: 252 Subject matches requirement # QUIT 221 Mapper terminates session # 500 Unexpected command/syntax ########################################################################## $|=1; # autoflush sysout buffer NB! should be set! print "220 Subject Mapper Ready\n" ; while(<>){chop; if (/^HELO/i ){print "250 Ok\n";} elsif (/^SUBJECT:VIRUS:(.*)/i ){print "252 $1\n"; } elsif (/^SUBJECT:(.*)/i ){print "251 Subj don't Match:$1\n";} elsif (/^QUIT/i ){print "221 Subject Mapper Close\n"; exit 0;} else {print "500 Unrecognised Command or Syntax Error\n";} } exit 0; ########################################################################### omaddrt -m mail1,node1 -d omvirus # регистрируем файл с правилами omaddrt -m mail2,node2 -d omvirus # повторить для всех адресов в таблице роутинга omoff -d 0 -s sr ; omon -s sr # перезапускаем ServiceRouter Особенности работы subj-чекера: Команда omaddrt запускает скрипт для тестирования его корректности. В штатном режиме скрипт запускается только раз, дальше сидит на пайпе до окончания работы SR Если несколько писем _подряд_ имеют одинаковый Subject, то он подается в скрипт на проверку только первый раз. Для SR значение имеет _только_ код возврата. Преобразование Subject внутри скрипта не оказывает влияния на Sub╜ ject в письме. Он остается неизменным, поэтому использовать скрипт для восстановления "зафлагованых" subject'ов не удастся. Если в правиле задается ACTION=ALLOW, то "matched"-сообщения проходят, а "not-matched" - тоже (что, впрочем, не страшно, их можно задавить правилом вида SUBJECT="*" ACTION=REJECT ВЫДЕРЖКИ ИЗ TECHNICAL REFERENCE GUIDE. 45. Service Router Message Delivery Rulesets The Service Router determines if any messages require special handling (for example, to be rejected or have their delivery deferred) by checking the settings of attributes in any ruleset specified for a given route. Each rule within a ruleset defines the conditions under which the Service Router should reject or defer the delivery of a message. Rules also specify how the Service Router should handle these messages and the time at which it should perform the specified action. The contents of the message are compared against each rule within the ruleset to check for a match: ╥ If all the attributes for a rule are matched, the Service Router performs the action defined for the rule. If the defined action is to defer the message, it submits the message to the Deferred Mail Manager queue DMM (see the section "Deferred Mail Manager"). ╥ If not all of the attributes in the ruleset are matched, by default the Service Router continues with its procedure to route the message (see the section "How the Service Router Handles Messages"). To tell the Service Router to check a ruleset for a particular route, you associate the ruleset with the route using either the command omaddrt (for new routes) or ommodrt (for existing routes). For example, to associate the ruleset off-peak with an existing route of remote,sales, enter the following command: ommodrt -m "remote,sales" -d off-peak You can see which ruleset (if any) is associated with a given route by using the omshowrt command. For details, see the section "Routing Table Commands". Note: When you specify a ruleset to an OpenMail command, OpenMail checks the contents of the ruleset and reports any syntax errors. If you change any rules in a ruleset, you are recommended to run the ommodrt command to verify the syntax of the new rule is correct. Ruleset File Format A ruleset is a text file you create. There are no restrictions on the filename you give your ruleset; however, rulesets must be stored under the following directory: /var/opt/openmail/rules For example, a ruleset with a filename of "off-peak" would be stored as: /var/opt/openmail/rules/off-peak A ruleset consists of a series of text lines. Lines that are blank or start with a hash character (#) are regarded as comment lines. If an argument contains white space, enclose the argument in double quotation marks ("). If an argument contains a double quotation mark (") or a backslash character (/), precede the character with a backslash character. Each rule in a ruleset must be defined on a single line. A rule contains a number of attributes specified as TAG=value pairs, which define the criteria to be matched in a message. There are three categories of ruleset attributes: message_filter Is one or more of the attributes defining the parts of the message against which the Service Router checks for matches when processing the message. If no message filter attributes are defined for a rule, then all attributes are considered a match. day_time Is one or both of the attributes defining the period during which the Deferred Mail Manager should perform the specified action on the deferred message. These attributes apply only when the DEFER action is defined in the rule. action_info Is one or more of the attributes defining the action to be performed or the information to be supplied when the values of the message_filter and day_time attributes are matched. These attributes are described in the following sections. Examples are provided in the section "Examples of Message Delivery Rules". Note: Any files specified as input to ruleset attributes must be stored in the directory /var/opt/openmail/rules. Message Filter Attributes These attributes define the parts of a message that, when matched, cause the specified action to be performed. These attributes are optional; if none are specified, the Service Router assumes a match for all attributes. The message_filter attributes are: ╥ BCC-COUNT The number of BCC addressees that can be contained in a message. This is matched when the number of BCC addresses in the message is greater than or equal to the value specified for this tag. For example, BCC-COUNT=10 causes all messages that have 10 or more BCC addresses to be deferred or rejected, depending on the defined action. ╥ DL-COUNT The number of addressees that can be contained in the primary Distribution List of a message. This is matched when the number of addresses in the Distribution List is greater than or equal to the value specified for this tag. For example, DL-COUNT=100 causes all messages that have 100 or more addresses in the primary Distribution List to be deferred or rejected, depending on the defined action. Note that a Distribution List can contain one or more Public Distribution Lists. Each such PDL is initially counted as just one address by the Service Router. However, when it is expanded by the Local Delivery service and passed back to the Service Router, each individual address in the PDL will add to the number of addresses in the primary Distribution List, and so may cause the message to be deferred or rejected. ╥ OMLIMIT-EXCEEDED A percentage indicating how full a message store component is in relation to its configured limit. A number of message store size limits can be configured for users: overall message store, In Tray, Pending Tray, and so on. See the man page for omlimit for more information. This filter is matched when the sender has a message store component which is at the specified percentage of its configured limit. For example, a value of 100 would match all messages from senders who had exceeded a limit by any amount; a value of 110 would match all messages from users who had exceeded a limit by 10 percent or more. A value less than 100 can be used to match messages from senders who are near to, but not yet at, one of their limits. For example, a value of 90 would match messages from senders who were at 90 percent or more of a limit. See the OpenMail Overview for more information on configuring message store limits, and creating rules to implement sanctions. ORIGINATOR One of: "pattern" An OpenMail Address pattern to match against the originator of the message. "!filename[:charset]" A separate file containing one or more OpenMail Address patterns to match against the originator of the message. The optional charset attribute specifies that the text of the file uses a character set other than IA5. The appropriate character set conversion is performed. Address patterns must observe the format and rules for Access Control List address patterns (see "ACL Address Patterns" in Chapter 1). PRIORITY One of: HIGH An urgent message MEDIUM A normal message LOW A non-urgent message RECIPIENT-SERVICE-LEVEL The service level of the recipient of a message. Service levels are assigned to users solely to enable receipt and delivery rules to be constructed. A value of 0 would check for those recipients for which a service level has not been sent. See the OpenMail Overview for more information on service levels. SENDER-SERVICE-LEVEL The service level of the sender of a message. Service levels are assigned to users solely to enable receipt and delivery rules to be constructed. A value of 0 would check for those senders for which a service level has not been sent. See the OpenMail Overview for more information on service levels. SIZE The size in kilobytes of a message (this is matched when the message size is greater than or equal to the value specified for this tag). SUBJECT One of: "pattern" The string of text to match against the subject of the message. Wildcard characters (*) can be used. The entire subject line of the message is compared with the pattern for a match. This comparison is case sensitive. "!filename[:charset]" A separate file containing the string of text to match against the subject of the message. The optional charset attribute specifies that the text of the file uses a character set other than IA5. The appropriate character set conversion is performed. The entire subject line of the message is compared with the specified string of text for a match. This comparison is case sensitive. "@script[:charset]" A separate script or program containing predefined protocols syntax to communicate with the Service Router and the Deferred Mail Manager to match the contents of the subject of a message. script must be a readable and executable file. The optional charset attribute specifies that the script (or program) uses a character set other than IA5 for the display of the subject. The appropriate character set conversion is performed, and the script (or program) checks for the contents of the subject in the display character set. The script returns a status of matched, or not matched, based on the predefined protocols syntax. A sample script is provided in the section "Example Script for SUBJECT Attribute". ╥ VIRUS-FOUND Specifies whether a message contains a virus. A value of 0 indicates that a virus was not found in the message; a value of 1 indicates that a virus was found. Include this attribute in a rule to enable virus scanning, but not virus cleaning. See the OpenMail Overview for more information on virus protection. This attribute can only be used in the ruleset ALL-ROUTES.VIR, and applies to all routes. It cannot be applied selectively to specified routes. ╥ VIRUS-UNCLEANED Specifies whether a message that contains a virus could not be cleaned. A value of 0 indicates that the message was checked and was successfully cleaned of any viruses that were found. A value of 1 indicates that the message contained a virus that could not be cleaned. Include this attribute in a rule to enable virus cleaning. See the OpenMail Overview for more information on virus protection. This attribute can only be used in the ruleset ALL-ROUTES.VIR, and applies to all routes. It cannot be applied selectively to specified routes. Day/Time Ruleset Attributes These attributes define the period during which the Deferred Mail Manager should defer messages when all other rule attributes are matched and ACTION=DEFER is specified. See the section "Deferred Mail Manager" for details. The day_time attributes are: ╥ DAY The day of the week on which to defer messages. This attribute is specified with an integer where 0=Sunday, 1=Monday, 2=Tuesday, etc. You can specify a range of days (for example, 1-5 for Monday through Friday) If no value is specified, all week is assumed. ╥ TIME The time of day the DEFER action should be performed. This attribute is the local time specified in HH:MM or HH format, using the 24-hour clock (00:00 or 00 is midnight). This attribute must be specified. You can specify a duration of time during which deferred messages can be delivered using the following syntax: time_interval The start and stop times during which actions should be performed specified in HH:MM-HH:MM format or in HH-HH format You also can specify a time at which to begin storing a batch of deferred messages and an interval of time during which to deliver the deferred messages using the following syntax: batch_spec The time to start batching messages and the interval during which to deliver the batch of deferred messages specified in HH:MM@HH:MM format or in HH@HH format. Action/Information Ruleset Attributes These attributes define the action to be taken or the information to be provided when the message_filter and date_time attributes are matched. The action_info attributes are: ╥ ACTION One of: ALLOW Route the message immediately. DEFER Defer delivery of the message during the period specified by the day and time attributes. DISCARD Discard the message without returning a Non-Delivery Notification to the originator. REJECT Don't route the message and return a Non-Delivery Notification to the originator. RETURN Don't route the message and return a Non-Delivery Notification and the original message to the originator. An ACTION attribute must be specified for a rule. For actions which do not automatically return a Non-Delivery Notification, you can specify a message to be returned to the user with the NOTIFY tag. ╥ NAME The name of a rule within the ruleset. This name is used in any notification message generated and written to the OpenMail Event Log and is useful in determining which rule is being applied when a message is routed. This tag is optional. ╥ NDN-INFO Enables you to replace the standard text string in the supplementary information field with the specified text when Non-Delivery Notification is required. This tag is optional. NDN-INFO is one of: "text" The text to be included in a Non-Delivery Notification. "!filename[:charset]" A separate file containing the text to be included in a Non-Delivery Notification. The optional charset attribute specifies that the text of the file uses a character set other than IA5. The text is converted to IA5. ╥ NOTIFY Enables you to include supplementary text in the standard notification message returned to the originator when the defined action has been performed on the message. This tag is optional. When NOTIFY is specified, the supplementary text is imported as a text part and attached in front of the standard notification message text. NOTIFY is one of: No value The standard notification message text containing details of the ruleset applied and the recipients affected is used if NOTIFY is specified with no value. "text" The supplementary text to be included in a message to the originator. The maximum size of text is 255 bytes. "!filename[:charset]" A separate file containing the supplementary text to be included in a message to the originator. The optional charset attribute specifies that the text of the file uses a character set other than IA5. The appropriate character set conversion is performed. There is no restriction on the size of text contained in filename. NOTIFY is typically used with the ACTION=DEFER or ACTION=DISCARD attributes, since Non-Delivery Notification is not returned to the originator of the message. Examples of Message Delivery Rules This section contains example rules illustrating how rules are specified within a ruleset and describing the action taken when the rules are matched by a message. ╥ Deferring messages based on originator PRIORITY=LOW ORIGINATOR="*/lab" ACTION=DEFER TIME=11:00-18:00 Delivery of all low priority messages sent from the lab mailnode is deferred between 11 a.m. and 6 p.m. (that is, these messages are delivered after 6 p.m. and before 11 a.m.). ╥ Delivering messages based on subject PRIORITY=MEDIUM SIZE=1000 SUBJECT="PUBLIC:*" ACTION=REJECT Messages with a subject starting with the text "PUBLIC:", of normal priority and of a size 1Mbyte or greater are not routed, and a Non-Delivery Notification is returned to the message originator. Any other messages are routed without delay according to the normal Service Router routing process. ╥ Delivering messages based on priority PRIORITY=HIGH ACTION=ALLOW PRIORITY=MEDIUM ACTION=DEFER TIME=09:00-17:00 DAY=1-5 PRIORITY=LOW ACTION=DEFER TIME=06:00-21:00 DAY=1-5 Any high priority messages are delivered Sunday through Saturday without delay according to the normal Service Router routing process. Any medium priority messages are submitted to the Deferred Mail Manager for deferral between 9 a.m. and 5 p.m., Monday through Friday. Any low priority messages are submitted to the Deferred Mail Manager for deferral between 6 a.m. and 9 p.m., Monday through Friday. ╥ Rejecting or deferring message delivery based on size NAME=Reject_1Mb SIZE=1000 ACTION=REJECT NAME=Defer_100Kb SIZE=100 ACTION=DEFER TIME=22:00-06:00 Any messages of a size 1Mbyte or greater are rejected, and a Non-Delivery Report is sent to the message originator. The delivery of any messages 100 Kbytes in size (but less than 1Mbyte) is deferred between 10 p.m. and 6 a.m. ╥ Providing supplementary text for a Non-Delivery Notification. SIZE=1000 ACTION=REJECT NDN-INFO="Message too large" Messages over 1Mbyte in size are rejected, and a Non-Delivery Notification containing the text "Message too large" is returned to the message originator. ╥ Notifying deferred message delivery PRIORITY=LOW ACTION=DEFER DAY=5 TIME=09:00-18:00 NOTIFY="!delaynote" The delivery of any low priority messages is deferred between 9 a.m. and 6 p.m. on Friday. The following text (contained in the file /var/opt/openmail/rules/delaynote) is appended as a text part before the standard notification text, which is routed to the message originator without delay according to the normal Service Router routing proces: Item 1 (distribution list) . . . Item 2 (delaynote) To speed the delivery of normal and urgent messages during normal office hours (9am-6pm) on Fridays, any low priority messages are not delivered during these hours. Item 3 (standard notification text) Delivery of your message has been delayed for some recipients: ------- Deferred Mail Manager Report from 'machine_x' ------- Message Reference: S3086127 Message Id. String: H000003d00015469 Routing rule name: Low priority messages sent at 6p.m. Routing rule action: DEFER Deferred until: Fri Apr 12th 18:00:01 1997 Message Priority: NON-URGENT Recipients affected: Amy Flinders / SPE, Sales John Person / unix (johnp@acmesoft.com) Frank Underwood / SPE, Training ╥ Deferring delivery of a batch of messages PRIORITY=LOW ACTION=DEFER TIME=8:00@1:00 Any low priority message received from 8 a.m. are held in a batch and delivered at 1-hour intervals, that is, at 9 a.m., 10 a.m., 11 a.m., and so on. Example Script for SUBJECT Attribute Below is an example of a script that can be used with the SUBJECT tag. This script (/opt/openmail/examples/general/subject) is supplied with OpenMail. You can copy this script into /var/opt/openmail/rules and Deferred Mail Manager The Service Router automatically starts the Deferred Mail Manager process (defer.manager), which handles any messages whose delivery is to be deferred. The Deferred Mail Manager monitors the DMM queue, and picks up any new messages submitted to it by the Service Router when all the attributes of a rule are matched and ACTION=DEFER is specified. All deferred messages and the deferral period defined in the specified ruleset are stored in the deferred message list (/var/opt/openmail/msglists/DEFER.SR). When the deferral period specified in the rule is reached, the Deferred Mail Manager delivers the deferred messages. The Deferred Mail Manager does not resubmit messages to the Service Router, but routes the messages itself. You can view a list of deferred messages by using the command omstat -d. You can attempt to force the delivery of a deferred message by using the command omresub. For details of these commands, see the online manual entries. 2.3.4. ENCODED JOINED MESSAGE FORMAT

 

The encoded joined message consists of an ARPA header followed by an empty line followed by the string "openmail‑encoded‑message" followed by:

 

 ~pri~                     The next line after this token is the priority of the message.  This allows Transport (not Gateway) programs to determine the priority of the message without touching the body of the message.   0 = normal, 1 = low, 2 = high.

 

 ~to~                       The next line gives you the name of the queue (or service), preceded by a ">" to escape any queue names that begin with "~".  The information after the ">" is the name of the queue on whose behalf this Gateway is working.  When you are working through the Transaction File, you must only deliver to recipients who are active and who are routed to this queue (service).  The "passive" flag (in the header of all Transaction File records) is used to indicate if a recipient is active or passive.  The name of the queue (service) for each recipient is held in the recipient record from byte 22 onwards.  The recipient record is record number 40000.  Refer to the chapter Using Transaction Files for more details.

 

                                The service name can be followed by a ":" and some more information.  The ":" should not appear if you are a Gateway.  If it does appear, ignore the ":" and any information after it.

 

                                If "~to~" is not present in the file, then deliver to all "active" recipients in the Transaction File.

 

 ~tf~                        This marks the start of the encoded Transaction File for this message.  The end of the Transaction File is denoted by a line starting with a space.  If more than one "~tf~" is found, then this stdin stream contains more than one message.  This is valid and you must cater for it.

 

 ~bf~                       This marks the start of the next attached content file.  This file is always ASCII encoded too.  An OpenMail message can have as many content parts as it likes.

 

You may ignore all lines of your stdin until you see the text string "openmail‑encoded‑message".  You must consider what you will do if you don't ever see this string on your stdin.  Because other tokens may be added in the future, just skip over those you don't recognise.

 

NOTE: The content files in the joined message format appear in the same order as their corresponding TFR_CONTENT_FILE entries in the encoded Transaction File.

 

With the Gateway API library supplied (exxp.a) you will find the functions DecodeMsgPart and EncodeMsgPart.  Their usage is described below ...

 

 

DecodeMsgPart

 

------------------------------------------------------------------------

int DecodeMsgPart (pErrorStatus, pEncodedMsg, pDecodedMsg)

OM_ERROR_STATUS  *pErrorStatus;     /* ptr to OpenMail error structure */

FILE             *pEncodedMsg;      /* file containing encoded text */

FILE             *pDecodedMsg;      /* file to receive decoded item */

------------------------------------------------------------------------

 

Used to decode an encoded item.

 

pErrorStatus is a pointer to a standard OpenMail error structure.

pEncodedMsg is a pointer to the FILE structure of an open file which contains an encoded item at the current position in the file.

pDecodedMsg is a pointer to the FILE structure of an open file which is to receive the decoded item.

 

0 is returned if the call has been successful, -1 if the call has been unsuccessful, in which case the error structure will contain full details of the error.

 

Error Groups returned: FSYS

 

 

EncodeMsgPart

 

------------------------------------------------------------------------

int EncodeMsgPart (pErrorStatus, pUncodedMsg, pEncodedMsg)

OM_ERROR_STATUS  *pErrorStatus;     /* ptr to OpenMail error structure */

FILE             *pUncodedMsg;      /* file containing item to be

                                              encoded */

FILE             *pEncodedMsg;     /* file to receive encoded text */

------------------------------------------------------------------------

 

Used to encode a message content item.

 

pErrorStatus is a pointer to a standard OpenMail error structure.

pUncodedMsg is a pointer to the FILE structure of an open file which contains the item to be encoded.

pEncodedMsg is a pointer to the FILE structure of an open file which is to receive the encoded text.

 

0 is returned if the call is successful, -1 is returned if the call has been unsuccessful, in which case the error structure will contain full details of the error.

 

Error Groups returned: FSYS

 

 

Below is an example from the "openmail‑encoded‑message" string :

 

        ARPA HEADER

                                       <‑‑‑ Blank line

        openmail‑encoded‑message

        ~to~

        >#SMINTFC:openmail@hpopdla

        ~pri~

        0

        ~tf~

        M +QA3@    $    D   $3          H  $         ! 0      P    $

        M  !&   G$          H        !0,               !!8G)A:&%M'4UA

        M=7)I8V4='1UP:6YE=V]O9!UL86(=;VT     )0  *UP         *$5X86UP

        M;&4@365S<V%G90  24$U     !8  #+(         "@EC[K#       T   S

        M+          H  !(,# P,#4P,S P,#<X8S W $@P,# P‑3 S,# P‑SAC,#<

        M    .0  =R0         *   !(X   2.     @          1$E35%))0E54

        M24].      !)034     /P  =R0         *   !(\   2/           

        M    17AA;7!L92!‑97‑S86=E    24$U  !)034     1P  G$         

        M*  @     2‑334E.5$9# &]P96YM86EL0&AP;W!D;&$ 0G5N=&5R'4)I;&QY

        M'1T=;G5T<QTP,0     9  "L1          H)8^ZQ     4     ,   J^ 

        G        *"6/NM      :'!O<&1L8AU'96YE<VES+&%D9'(Q+#$

    

        ~bf~

        M +QA3@    $    D   $3          H  $    " ^@                

        M   D  !.*@         H       !     0                 O  !65  

        E     ! H          !"=6YT97(=0FEL;'D='1UN=71S'3 Q   O

    

        ~bf~

        M5&AI<R!I<R!A('‑I;7!L92!E>&%M<&QE(&]F(&$@;65S<V%G92!I;G1E;F1E

        M9"!T;R!I;F1I8V%T92!W:&%T(&%N(&5N8V]D960@"G1R86YS<&]R="!M97‑S

        M86=E('=O=6QD(&QO;VL@;&EK92X*"E1H:7,@<VAO=6QD(&‑O;G1A:6X@96YO

        M=6=H('1E>'0@=&\@;6%K92!I="=S(&5N8V]D960@9F]R(&=O(&]V97(@<V5V

        I97)A;"!L:6YE<R *:6X@=&AE(")S97)I86QI<V5D(B!M97‑S86=E+@H@

 

 

2.3.5. Parsing The Transaction File

 

You have now split up and decoded the message into a Transaction File and a series of Content Files.   The first Content File will be the Distribution List as entered by the sender.  It will be in Transaction File format too.  How to parse both the main TF and the entered Distribution List is detailed in the chapter Using Transaction Files.

 

 

2.3.6. Converting Content Files

 

The conversion strategy used within OpenMail is to convert message contents on the way out of OpenMail to formats supported by the "foreign" system.  As a Gateway developer you have the choice of leaving the conversion to OpenMail and just set up the necessary steering files on installation of your Gateway, or handle the conversions yourself.

 

Using OpenMail's conversion

 

It is  easier to leave conversion to OpenMail unless you have an existing conversion mechanism you wish to use.  The details of files used in conversion within OpenMail are given in Section 3 of the OpenMail Technical Guide, but there is only one of these files that should concern you, the conversion‑steering‑file. The format for each line of this file is :

 

        From_Type   Choice_1   Choice_2   .....    Choice_8

 

where "From Type" and "Choice_n" are file types.

 

Filetypes are numbers allocated by HP.  A list of the mappings from filetype to an English string is given in the file /users/openmail/nls/english/filetype.  In general, the mapping for language $LANG is given in /users/openmail/nls/$LANG/filetype.

 

When a From Type content part is encountered, choice 1 is tried.  If that fails, choice 2 is tried, and so on.

 

There is a special value of From Type of "*".  This means, "all file types".  There are two special choice types, "T" and "R".  T means "trash" the part, and R means "retain the part as it is".  If a part is trashed, a textual message is substituted explaining what the part was.  Below is the steering file for the UNIX gateway:

 

        *   1167    R

 

The filetype "1167" is the number for text.

 

Handling conversions yourself

 

If you have your own conversion mechanism then simply leave out the conversion‑steering‑file line in your gateway steering file.  Alternatively you may wish to use whatever conversions are set up for OpenMail before receiving the message in your Gateway, in which case put "R" at the end of each line of your conversion‑steering‑file to retain the contents of files which could not be converted.  ПРИМЕРЫ ФИЛЬТРАЦИИ АТТАЧМЕНТОВ ПО РАСШИРЕНИЮ ФАЙЛА



 638/3/1/3/2: Another way to block .VBS files

    Re:  638/3/1/3: What about stopping all mails with VBS scripts? (Poul Kornmod)
    Keywords: iloveyou virus worm
    Date: Tue, 09 May 2000 13:52:35 GMT
    From: richi@hp.com (Richi Jennings)

Our Expert Center (2nd line support) came up with this... /richi.

--

A question that has been asked by some customers is how to strip out attach╜
ments with a particular extension (.vbs for example) from messages  entering
a system through the internet gateway (i.e., depending on the system config╜
uration, from outside the company).

I  believe that [...] we have identified a possible solution; acknowledments
are due to Leslie Ward, Peter Heiniger and Dave Kelly  for  contributing  to
this.

This  is a 'low-cost' solution that may help some customers who don't have a
full virus scanning solution.

This will work for B.06.00 systems, not for B.05.10.

Setup -----

In mime.types, insert the following line:
 2188   */*                            vbs

ahead of the line:
 0       application/octet-stream

so the file entries start:
=============
 2130    application/*                 rtf
 2188    */*                           vbs
 0       application/octet-stream
 1167    text/plain                    txt
 1168    text/RFC822-Headers           txt
 .....
=============

Then, in general.cfg, add the following:
 SR_FILTER_TYPES_OF_ATT=2188

(If you already have an entry for SR_FILTER_TYPES_OF_ATT, add ,2188 to the list).

Restart service router.

What this does: --------------

Attachments entering the Internet gateway with an extension of .vbs, regard╜
less of the mimetype, will be typed as 2188 (this is  an  already  allocated
code for a virus infected file).  At the service router, attachments of type
2188 will be stripped from the message. So, all attachments entering through
the  internet  gateway  with an extension of .vbs will be removed before the
message is delivered.

Comments --------

A  new filecode could be used; I'm not aware of anything special about 2188,
but I'm still checking with the lab. However, filecodes are allocated by the
lab, and 2188 is already defined and (nearly) appropriate.

This  solution  could  be used for other extensions, not just .vbs; just add
another line to mime.types.

No entry for 2188 is needed in mime.types for outgoing messages (i.e. an en╜
try without a wildcard) since the attachments will be stripped by  the  ser╜
vice router before they get to the gateway.

This  will  not  remove  .vbs  files that originate within OpenMail, as they
won't get the filecode set to 2188.

You  could  match on a more explicit mime type, e.g. application/*, but that
would miss a .vbs that came in as, for example, text/plain.

mime.types Matching -------------------

The mime.types file is used for mapping between OpenMail filecodes and mime╜
types for attachments. It is used for both incoming and  outgoing  matching,
and some fields or entries only apply in one direction.

There are 3 fields on each line, an OpenMail filecode, a mimetype and a list
of extensions. For incoming attachments, the matching goes through the  file
looking at each line. If the MIME type (field 2) matches that of the attach╜
ment in the message exactly, then the file code (field 1) is  used.  If  the
MIME type matches, due to wild carding (in field 2), then the extension list
(field 3) is looked at. If any match, then the filecode is used. If  neither
the  mimetype  nor  the extension matches, then the next line in the file is
examined. If there was a match, the scan stops as the filecode is found.

For  outgoing  attachments,  the  first line with the filecode that matches,
which does not have a wild-carded mimetype (field 2) is used.

Best Regards, Andrew Merritt MAPA WTEC



   638/3/1/3/2/1: what about SR_FILTER_TYPES_OF_ATT=TRUE?

    Re:  638/3/1/3/2: Another way to block .VBS files (Richi Jennings)
    Keywords: iloveyou virus worm
    Date: Wed, 10 May 2000 21:45:50 GMT
    From: dlippolt@ascensionortho.com (drew lippolt)

richi,

your  quoted instructions indicate that there might be other numbers listed,
and that we should just add ",2188 to the list"

so,  if  (just  for  example)  i already was filtering #2130, i might end up
with:

SR_FILTER_TYPES_OF_ATT=2130,2188

but...



SR_FILTER_TYPES_OF_ATT=TRUE
   Causes the Service Router to remove WINMAIL.DAT
   attachments, used by some clients.



so the result is: SR_FILTER_TYPES_OF_ATT=TRUE,2188



 638/3/1/3/2/2: Doesn't spot name.txt.vbs

    Re:  638/3/1/3/2: Another way to block .VBS files (Richi Jennings)
    Keywords: iloveyou virus worm
    Date: Mon, 22 May 2000 08:21:45 GMT
    From: Andy_Merritt@hp.com (Andrew Merritt)

Some points on this work-around:

If  the  attachment has a name of the form 'name.txt.vbs', as in some of the
variants of the virus, this will not be picked up by the the internet  gate╜
way  as  it takes everything after the first '.' as the extension. (Unfortu╜
nately, a maximum of  3  characters  is  supported  for  the  extension,  so
'txt.vbs' won't work).

To  repeat, this will only work on B.06.00, it will not work on earlier ver╜
sions of OpenMail. Even if you changed the mime.types file the code is  sim╜
ply not there to deal with it.

Yes,  when  it says 'add ,2188 to the list', the implication is that a value
is being added to a list of types. If you have  '=TRUE'  you  will  need  to
change this to '=1734,2188'.

Andrew

To  force the downgrade you edit the file: /var/opt/openmail/sys/unixout.str
to include at the end of it the following lines:

2130  1167  R  which  means turn MS Rich Text into plain text and retain the
body parts.

You  could also do something like * 1167 R Which would be a little more dan╜
gerous, but means change everything into plain text.