release version 1.10.0

This commit is contained in:
2024-12-14 04:07:49 +03:00
parent a5088587f7
commit c6b3d793c4
1916 changed files with 254306 additions and 0 deletions

View File

@ -0,0 +1,175 @@
ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ
Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой)
версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего
Правообладателю Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН
7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова,
д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу
https://www.emdev.ru/about (далее - Компания).
Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями»
(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения,
Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в
настоящем документе, в противном случае, он должен не использовать или не получать доступ
к Программному обеспечению.
1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ
a) ПО Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии
или редакции, исключительные права на которую принадлежат Правообладателю.
b) Правообладатель (Компания) ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные
права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ
для ЭВМ № 2021610848 от 19.01.2021 года.
c) Пользователь юридическое или физическое лицо, получившее через скачивание с сайта
https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО.
d) ИС интеллектуальная собственность закреплённое законом исключительное право, а также
личные неимущественные права авторов произведений на результат интеллектуальной деятельности.
e) Подписка это коммерческое предложение Правообладателя, состоящее из Лицензии на использование
ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка
включает предоставление Пользователю неисключительного права использования ПО, в том числе
получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение
патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается
Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается
для каждого Пользователя индивидуально в Сертификате.
f) Сертификат документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром),
подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное
обеспечение в ограниченном объёме и на определённый период времени.
g) Лицензия (простая (неисключительная) совокупность ограниченных прав использования ПО,
предоставленных Пользователю согласно условиям Подписки.
h) Библиотека совокупность подпрограмм и объектов, используемых для разработки программного
обеспечения.
i) Исходный код текст компьютерной программы на каком-либо языке программирования, состоящий
из одного или нескольких файлов, который может быть прочтён человеком.
j) Объектный код файл (часть машинного кода) с промежуточным представлением отдельного модуля
программы, полученный в результате обработки исходного кода, еще не связанный в полную программу.
Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый
продукт.
k) Некоммерческое использование индивидуальное личное использование Пользователем программного
обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации
возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая
выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения.
2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ
2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного
обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом
воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения
в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ.
2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит
неисключительный характер.
2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию,
лицензия на ограниченное использование Программного обеспечения.
2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования
имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан
обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения
вида лицензии с Базовой бесплатной версии на Подписки.
2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для
пробного использования программного обеспечения не ограничен.
2.6. Использование Пользователем настоящего программного обеспечения в целях разработки,
модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю,
без разрешения Правообладателя не допускается.
3. АВТОРСКОЕ ПРАВО.
3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение
и любые его копии принадлежат Правообладателю.
3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента,
к которому можно получить доступ с помощью Программного обеспечения, является собственностью
соответствующего владельца контента и защищается применимым законодательством об авторском
праве или другими законами и договорами об интеллектуальной собственности.
3.3. Условия использования Программного обеспечения.
Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь
придерживается следующих условий:
3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять
какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании
Программного обеспечения или на нем.
3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать,
расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать
Программное обеспечение.
3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования
ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне.
3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено
использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам.
4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС»
4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю
на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с
использованием Пользователем:
4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в
Программное обеспечение;
4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями
настоящего соглашения;
4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием,
или данными, не предоставленными Пользователю Правообладателем;
4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем.
5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ
ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ
И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ
ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ
И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ
ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО.
6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ.
НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ
ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ,
ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ;
ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ.
ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ
ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ;
КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ
ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ.
7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ:
Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия
(включая, но не ограничиваясь) по:
-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код)
Программного обеспечения;
-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный
код Программного обеспечения, за исключением тех изменений, которые вносятся средствами,
включёнными в Программное обеспечение и описанными непосредственно в документации к нему;
-созданию условий для использования Программного обеспечения лицами, не имеющими прав на
использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство
третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа
к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку;
-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию).
8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА.
8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из
лицензионных продуктов, используемых на законных основаниях, а
именно https://entaxy.ru/libs/licenses/root-aggregated.deps.
8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть
совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения.
8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться
Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения,
содержащих все изменения и дополнения программного обеспечения.
9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ.
9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым
программным обеспечением.
9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно
с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм
«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public.
9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий
пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя,
прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер
ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства
Российской Федерации.
10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ.
10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет
право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб,
недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий
пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере
2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения
исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy).
10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое
законодательство Российской Федерации.
10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным,
остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать
исполнять свои обязанности в соответствии с этими положениями.

View File

@ -0,0 +1,175 @@
ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ
Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой)
версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего
Правообладателю Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН
7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова,
д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу
https://www.emdev.ru/about (далее - Компания).
Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями»
(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения,
Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в
настоящем документе, в противном случае, он должен не использовать или не получать доступ
к Программному обеспечению.
1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ
a) ПО Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии
или редакции, исключительные права на которую принадлежат Правообладателю.
b) Правообладатель (Компания) ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные
права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ
для ЭВМ № 2021610848 от 19.01.2021 года.
c) Пользователь юридическое или физическое лицо, получившее через скачивание с сайта
https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО.
d) ИС интеллектуальная собственность закреплённое законом исключительное право, а также
личные неимущественные права авторов произведений на результат интеллектуальной деятельности.
e) Подписка это коммерческое предложение Правообладателя, состоящее из Лицензии на использование
ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка
включает предоставление Пользователю неисключительного права использования ПО, в том числе
получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение
патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается
Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается
для каждого Пользователя индивидуально в Сертификате.
f) Сертификат документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром),
подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное
обеспечение в ограниченном объёме и на определённый период времени.
g) Лицензия (простая (неисключительная) совокупность ограниченных прав использования ПО,
предоставленных Пользователю согласно условиям Подписки.
h) Библиотека совокупность подпрограмм и объектов, используемых для разработки программного
обеспечения.
i) Исходный код текст компьютерной программы на каком-либо языке программирования, состоящий
из одного или нескольких файлов, который может быть прочтён человеком.
j) Объектный код файл (часть машинного кода) с промежуточным представлением отдельного модуля
программы, полученный в результате обработки исходного кода, еще не связанный в полную программу.
Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый
продукт.
k) Некоммерческое использование индивидуальное личное использование Пользователем программного
обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации
возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая
выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения.
2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ
2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного
обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом
воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения
в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ.
2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит
неисключительный характер.
2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию,
лицензия на ограниченное использование Программного обеспечения.
2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования
имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан
обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения
вида лицензии с Базовой бесплатной версии на Подписки.
2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для
пробного использования программного обеспечения не ограничен.
2.6. Использование Пользователем настоящего программного обеспечения в целях разработки,
модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю,
без разрешения Правообладателя не допускается.
3. АВТОРСКОЕ ПРАВО.
3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение
и любые его копии принадлежат Правообладателю.
3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента,
к которому можно получить доступ с помощью Программного обеспечения, является собственностью
соответствующего владельца контента и защищается применимым законодательством об авторском
праве или другими законами и договорами об интеллектуальной собственности.
3.3. Условия использования Программного обеспечения.
Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь
придерживается следующих условий:
3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять
какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании
Программного обеспечения или на нем.
3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать,
расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать
Программное обеспечение.
3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования
ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне.
3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено
использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам.
4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС»
4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю
на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с
использованием Пользователем:
4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в
Программное обеспечение;
4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями
настоящего соглашения;
4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием,
или данными, не предоставленными Пользователю Правообладателем;
4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем.
5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ
ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ
И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ
ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ
И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ
ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО.
6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ.
НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ
ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ,
ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ;
ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ.
ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ
ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ;
КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ
ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ.
7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ:
Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия
(включая, но не ограничиваясь) по:
-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код)
Программного обеспечения;
-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный
код Программного обеспечения, за исключением тех изменений, которые вносятся средствами,
включёнными в Программное обеспечение и описанными непосредственно в документации к нему;
-созданию условий для использования Программного обеспечения лицами, не имеющими прав на
использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство
третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа
к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку;
-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию).
8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА.
8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из
лицензионных продуктов, используемых на законных основаниях, а
именно https://entaxy.ru/libs/licenses/root-aggregated.deps.
8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть
совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения.
8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться
Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения,
содержащих все изменения и дополнения программного обеспечения.
9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ.
9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым
программным обеспечением.
9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно
с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм
«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public.
9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий
пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя,
прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер
ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства
Российской Федерации.
10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ.
10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет
право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб,
недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий
пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере
2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения
исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy).
10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое
законодательство Российской Федерации.
10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным,
остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать
исполнять свои обязанности в соответствии с этими положениями.

View File

@ -0,0 +1,98 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>ru.entaxy.platform</groupId>
<artifactId>logging</artifactId>
<version>1.10.0</version>
</parent>
<groupId>ru.entaxy.platform.logging</groupId>
<artifactId>cef-logger-layout</artifactId>
<packaging>bundle</packaging>
<name>ENTAXY :: LOGGING :: CEF LOGGER</name>
<description>ENTAXY :: LOGGING :: CEF LOGGER</description>
<properties>
<bundle.osgi.export.pkg>ru.emdev.cef</bundle.osgi.export.pkg>
<bundle.osgi.import.pkg>!ru.emdev.cef</bundle.osgi.import.pkg>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.13.2</version>
<scope>compile</scope>
</dependency> <dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.13.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<executions>
<execution>
<id>log4j-plugin-processor</id>
<goals>
<goal>compile</goal>
</goals>
<phase>process-classes</phase>
<configuration>
<proc>only</proc>
<annotationProcessors>
<annotationProcessor>org.apache.logging.log4j.core.config.plugins.processor.PluginProcessor</annotationProcessor>
</annotationProcessors>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Fragment-Host>org.ops4j.pax.logging.pax-logging-log4j2</Fragment-Host>
<Include-Resource>META-INF=${project.build.outputDirectory}/META-INF</Include-Resource>
<DynamicImport-Package>*</DynamicImport-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,94 @@
/*-
* ~~~~~~licensing~~~~~~
* cef-logger-layout
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.emdev.cef;
import static java.util.regex.Pattern.compile;
import java.util.regex.Pattern;
public enum AuditEvent {
APP_OWNER_UPDATED("app_owner_updated", "Owner of application updated", compile(
"(?<msg>^Successfully updated the owner of application ((?!from).*) from ((?!to).*) to (?<suser>.*).$)")),
COMMON_ACTION_RESULT("action", "Common action result", compile(
"^Initiator : (?<suser>[^|]*) \\| Action : (?<eventName>[^|]*) \\| (?<msg>Target : ([^|]*) \\| Data : ([^|]*) \\| Result : (.*)$)")),
COMMON_ACTION_OUTCOME("action", "Common action outcome", compile(
"^Initiator=(?<suser>(?! Action).*) Action=(?<eventName>(?! Target).*) (?<msg>Target=((?! Data).*) Data=((?! Outcome).*) Outcome=((?!Error=).*)$)")),
COMMON_ACTION_ERROR("action", "Common action error", compile(
"^Initiator=(?<suser>(?! Action).*) Action=(?<eventName>(?! Target).*) (?<msg>Target=((?! Data).*) Data=((?! Outcome).*) Outcome=Failure Error=(.*)$)")),
COMMON_ACTION_CLAIMS("action", "Common action claims", compile(
"^Initiator : (?<suser>[^|]*) \\| Action : (?<eventName>[^|]*) \\| (?<msg>Target : ([^|]*) \\| Claims : (.*)$)")),
SIGN_WRAPPING_ATTACK("attack", "Possible Signature Wrapping Attack", compile(
"(?<msg>^Signature do not confirm to SAML signature profile. Possible XML Signature Wrapping (?<eventType>Attack)!$)")),
LOGGED_OUT("auth", "Logged out", compile(
"(?<msg>^'(?<suser>(?!@).*)@((?! ).*) \\[((?!]).*)]' logged out at (?<end>((?! delegated).*))$)")),
LOGGED_OUT_DELEGATED("auth", "Logged out", compile(
"(?<msg>^'(?<suser>(?!@).*)@((?! ).*) \\[((?!]).*)]' logged out at (?<end>((?! delegated).*)) delegated by (.*)$)")),
LOGIN_FAILED("auth", "Unauthorized login attempt", compile(
"(?<msg>^Login failed\\. Unauthorized login attempt '(?<suser>(?!\\[).*)\\[((?!]).*)]' at (?<end>.*)$)")),
LOGIN("auth", "Login success",
compile("(?<msg>^'(?<suser>[^@]*)@([^ ]*) \\[((?!]).*)]' logged in at (?<end>.*)$)")),
LOGIN_NULL_DOMAIN("auth", "Null domain login attempt",
compile("(?<msg>^User with null domain tried to login\\.$)")),
LOGIN_FROM_IP("auth", "Login success from ip", compile(
"(?<msg>^'(?<suser>(?!@).*)@((?! ).*) \\[((?!]).*)]' logged in at (?<end>(?! from).*) from IP address (?<shost>.*)$)")),
JMX_AUTHENTICATED("auth", "User authenticated to JMX", compile(
"(?<msg>^User (?<suser>(?! successfully).*) successfully authenticated to perform JMX operations\\.$)")),
JMX_AUTHORIZED("auth", "User authorized to JMX", compile(
"(?<msg>^User : (?<suser>(?! successfully).*) successfully authorized to perform JMX operations\\.$)")),
JMX_UNAUTHORIZED("auth", "Unauthorized access attempt to JMX", compile(
"(?<msg>^Unauthorized access attempt to JMX operation\\. $)")),
USER_NOT_AUTHORIZED("auth", "Unauthorized attempt to read the resource", compile(
"(?<msg>^User (?<suser>(?! is).*) is not authorized to read the resource (.*)$)")),
CSRF_ATTACK_WITH_HEADER("attack", "Possible CSRF attack", compile(
"(?<msg>^Possible CSRF attack. Refer header : (.*)$)")),
CSRF_ATTACK_WITHOUT_HEADER("attack", "Possible CSRF attack", compile(
"(?<msg>^Possible CSRF attack. Request to '([^']*)' does not have a Referer header$)")),
THREAT_ATTACK("attack", "Threat detected", compile(
"(?<msg>^(.*)Threat detected in (.*)$)"));
private final Pattern pattern;
private final String eventName;
private final String eventType;
AuditEvent(String eventType, String eventName, Pattern pattern) {
this.eventType = eventType;
this.eventName = eventName;
this.pattern = pattern;
}
public Pattern getPattern() {
return pattern;
}
public String getEventName() {
return eventName;
}
public String getEventType() {
return eventType;
}
}

View File

@ -0,0 +1,410 @@
/*-
* ~~~~~~licensing~~~~~~
* cef-logger-layout
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.emdev.cef;
import static java.util.Objects.nonNull;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.layout.AbstractStringLayout;
import org.apache.logging.log4j.core.lookup.StrSubstitutor;
import org.apache.logging.log4j.message.Message;
import org.apache.logging.log4j.util.Strings;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class AuditLayout extends AbstractStringLayout {
/**
* Формат сообщения и версия
*/
public static final String CEF_VERSION = "cefVersion";
/**
* Производитель ПО
*/
public static final String VENDOR = "vendor";
/**
* Имя компонента
*/
public static final String PRODUCT = "product";
/**
* Версия компонента
*/
public static final String VERSION = "version";
/**
* Версия компонента
*/
public static final String EVENT_TYPE = "typ";
/**
* Название события
*/
public static final String EVENT_NAME = "eventName";
/**
* Важность события
*/
public static final String SEVERITY = "severity";
public static final List<String> HEADER_FIELDS =
Arrays.asList(CEF_VERSION, VENDOR, PRODUCT, VERSION, EVENT_TYPE, EVENT_NAME, SEVERITY);
/**
* Дополнительные поля
*/
public static final String EXTENSION = "extension";
/**
* IP пользователя
*/
public static final String EXT_SRC = "src";
/**
* IP сервиса
*/
public static final String EXT_DST = "dst";
/**
* хост пользователя
*/
public static final String EXT_SHOST = "shost";
/**
* SID пользователя
*/
public static final String EXT_SUID = "suid";
/**
* имя пользователя
*/
public static final String EXT_SOURCE_USER_NAME = "suser";
/**
* описание события
*/
public static final String EXT_MSG = "msg";
/**
* время события
*/
public static final String EXT_END = "end";
public static final List<String> EXT_FIELDS =
Arrays.asList(EXT_SRC, EXT_DST, EXT_SHOST, EXT_SUID, EXT_SOURCE_USER_NAME, EXT_MSG, EXT_END);
public static final List<String> ALL_FIELDS =
Stream.concat(HEADER_FIELDS.stream(), EXT_FIELDS.stream()).collect(Collectors.toList());
public static final Map<String, String> DEFAULTS = new HashMap<String, String>() {
{
put(CEF_VERSION, "0");
put(VENDOR, "EMDEV");
put(PRODUCT, "ENTAXY");
put(VERSION, "1.10.0");
put(EVENT_TYPE, "common");
put(EVENT_NAME, "common event");
put(EXT_SRC, "");
put(EXT_DST, "");
put(EXT_SHOST, "");
put(EXT_SUID, "");
put(EXT_SOURCE_USER_NAME, "");
put(EXT_MSG, "");
put(EXT_END, "");
}
};
public static final Map<String, String> SEVERITY_BY_EVENT_NAME = new HashMap<String, String>() {
{
put("Add-User", "6");
put("Delete-User", "8");
put("Delete-User-Claim-Values", "8");
put("Delete-User-Claim-Value", "8");
put("Disable user account", "8");
put("Enable user account", "6");
put("bulk_user_import", "6");
put("Remove local user account association with federated account", "6");
put("Change-Password-by-User", "6");
put("Change-Password-by-Administrator", "6");
put("Login", "6");
put("Login success", "6");
put("LoginStepSuccess", "6");
put("Login success from ip", "6");
put("Unauthorized login attempt", "8");
put("Null domain login attempt", "8");
put("User authenticated to JMX", "6");
put("User authorized to JMX", "6");
put("Unauthorized access attempt to JMX", "8");
put("Unauthorized attempt to read the resource", "8");
put("DELETED", "8");
put("PRODUCT_DELETED", "8");
put("APIPRODUCT_DELETED", "8");
put("APPLICATION_DELETED", "8");
put("SUBSCRIPTION_DELETED", "8");
put("Owner of application updated", "6");
put("Possible Signature Wrapping Attack", "9");
put("Possible CSRF attack", "9");
put("Delete-Role", "8");
put("delete", "8");
put("Add-Role", "3");
put("Update-Role-Name", "3");
put("Update-Users-of-Role", "3");
put("Update-Roles-of-User", "3");
put("Threat detected", "9");
}
};
public static final String CEF_FORMAT =
"CEF:${" + CEF_VERSION + "}|${" + VENDOR + "}|${" + PRODUCT + "}|${" + VERSION + "}|${"
+ EVENT_TYPE + "}|${" + EVENT_NAME + "}|${" + SEVERITY + "}|${" + EXTENSION + "}";
private static final ObjectMapper objectMapper = new ObjectMapper();
private final String pattern;
public static final String ANY_NOT_WORD_SYMBOLS = "\\W";
public AuditLayout(String pattern) {
super(StandardCharsets.UTF_8);
this.pattern = pattern;
}
@SuppressWarnings("unused")
// @PluginFactory
public static AuditLayout createLayout(
// @PluginAttribute(value = "pattern", defaultString = CEF_FORMAT) String pattern) {
String pattern) {
return new AuditLayout(pattern);
}
@Override
public String toSerializable(LogEvent logEvent) {
return Optional.ofNullable(logEvent).map(LogEvent::getMessage).map(Message::getFormattedMessage)
.map(this::convert).orElse(null);
}
public Map<String, String> jsonMap(LogEvent logEvent) {
return Optional.ofNullable(logEvent).map(LogEvent::getMessage).map(Message::getFormattedMessage)
.map(this::asMap).orElse(Collections.emptyMap());
}
private Map<String, String> asMap(String message) {
final Map<String, String> allFields = new HashMap<>();
parseByRegexp(message, allFields);
if (allFields.isEmpty()) {
parseByJackson(message, allFields);
}
if (!allFields.isEmpty()) {
prepareAllFields(allFields);
prepareExtension(allFields);
prepareHeader(allFields);
enhance(allFields);
}
return allFields;
}
private String convert(String message) {
final Map<String, String> allFields = asMap(message);
parseByRegexp(message, allFields);
if (allFields.isEmpty()) {
parseByJackson(message, allFields);
}
if (!allFields.isEmpty()) {
message = StrSubstitutor.replace(pattern, allFields);
}
return message + Strings.LINE_SEPARATOR;
}
private void prepareAllFields(final Map<String, String> allFields) {
ALL_FIELDS.forEach(field -> {
String value = allFields.get(field);
if (nonNull(value) && !value.isEmpty()) {
if (HEADER_FIELDS.contains(field)) {
value = value.replace("|", "\\|");
}
if (EXT_FIELDS.contains(field)) {
value = value.replace("\\", "\\\\")
.replace("=", "\\=")
.replaceAll("\\n", " ");
}
if (field.equals(EXT_SRC)) {
value = DnsResolver.tryResolve(value);
}
allFields.put(field, value);
}
});
}
private void prepareExtension(final Map<String, String> allFields) {
StringBuilder extension = new StringBuilder();
EXT_FIELDS.stream().filter(f -> !f.equals(EXT_END)).forEach(key -> {
String value1 = allFields.get(key);
if (nonNull(value1) && !value1.isEmpty()) {
extension.append(key).append("=").append(value1).append(" ");
}
});
extension.append(EXT_END).append("=").append(ZonedDateTime.now().toInstant().toEpochMilli());
allFields.put(EXTENSION, extension.toString().trim());
}
private void prepareHeader(final Map<String, String> allFields) {
HEADER_FIELDS.forEach(s -> {
String value = Optional.ofNullable(allFields.get(s)).orElse(DEFAULTS.get(s));
allFields.put(s, value);
});
}
private void enhance(Map<String, String> allFields) {
final String eventName = allFields.get(EVENT_NAME);
String severity = SEVERITY_BY_EVENT_NAME.keySet().stream()
.filter(s -> eventEquals(eventName, s)).findFirst().map(s -> {
allFields.put(EVENT_NAME, s);
return s;
}).map(SEVERITY_BY_EVENT_NAME::get).orElse("3");
allFields.put(SEVERITY, severity);
if (eventEquals(eventName, "Login") && nonNull(allFields.get(EXT_MSG))) {
String msq = allFields.get(EXT_MSG).toLowerCase();
if (msq.contains("result : success")) {
allFields.put(SEVERITY, "6");
} else if (msq.contains("result : failed")) {
allFields.put(SEVERITY, "8");
}
}
}
private boolean eventEquals(String left, String right) {
if (left != null) {
left = left.replaceAll(ANY_NOT_WORD_SYMBOLS, "");
left = left.toUpperCase();
}
if (right != null) {
right = right.replaceAll(ANY_NOT_WORD_SYMBOLS, "");
right = right.toUpperCase();
}
return Objects.equals(left, right);
}
private void parseByJackson(String message, Map<String, String> reqFields) {
try {
JsonNode jsonNode = objectMapper.readTree(message);
if (jsonNode.isObject()) {
String typ = Optional.ofNullable(jsonNode.get("typ")).map(JsonNode::asText).orElse("");
String action =
Optional.ofNullable(jsonNode.get("action")).map(JsonNode::asText).orElse("");
if (!typ.isEmpty() && !action.isEmpty()) {
reqFields.put(EVENT_TYPE, "API");
if (!typ.equalsIgnoreCase("api")) {
action = typ + "_" + action;
}
}
if (!action.isEmpty()) {
reqFields.put(EVENT_NAME, action.toUpperCase());
}
Optional.ofNullable(jsonNode.get("performedBy")).map(JsonNode::asText)
.ifPresent(s -> reqFields.put(EXT_SOURCE_USER_NAME, s));
Optional.ofNullable(jsonNode.get("info")).map(JsonNode::toString)
.ifPresent(s -> reqFields.put(EXT_MSG, s));
}
} catch (IOException ignore) {
// ignore
}
}
public static void reverse(Object[] input) {
if (input == null || input.length == 0) {
return;
}
int i = 0;
int j = input.length - 1;
Object tmp;
while (j > i) {
tmp = input[j];
input[j] = input[i];
input[i] = tmp;
j--;
i++;
}
}
private void parseByRegexp(String message, Map<String, String> allFields) {
AuditEvent[] values = AuditEvent.values();
reverse(values);
for (AuditEvent auditEvent : values) {
Pattern pattern = auditEvent.getPattern();
Matcher matcher = pattern.matcher(message);
if (matcher.matches()) {
ALL_FIELDS.forEach(field -> {
String value = "";
try {
value = matcher.group(field);
} catch (IllegalArgumentException ignored) {
}
if (!value.isEmpty()) {
allFields.put(field, value);
allFields.put(EVENT_TYPE, auditEvent.getEventType());
if (Strings.isEmpty(allFields.get(EVENT_NAME))) {
allFields.put(EVENT_NAME, auditEvent.getEventName());
}
}
if (allFields.containsKey(EXT_SRC)) {
allFields.replace(EXT_SRC, DnsResolver.tryResolve(allFields.get(EXT_SRC)));
}
});
break;
}
}
}
public void addOverrides(Map<String, String> override) {
DEFAULTS.putAll(override);
}
}

View File

@ -0,0 +1,89 @@
/*-
* ~~~~~~licensing~~~~~~
* cef-logger-layout
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.emdev.cef;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.Core;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.config.AppenderControl;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.plugins.*;
import java.util.ArrayList;
import java.util.List;
@Plugin(name = "CEFAggregate", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE, printObject = true)
public class CEFAppender extends AbstractAppender {
private final Configuration config;
private final String children;
private final List<AppenderControl> controls = new ArrayList<>();
private CEFAppender(String name, Filter filter, String children, Configuration config, Boolean ignoreExceptions) {
super(name, filter, null, ignoreExceptions, null);
this.config = config;
this.children = children;
}
@Override
public void start() {
String[] refs = children.split(",");
for (String ref : refs) {
String cleaned = ref.trim();
Appender appender = config.getAppender(cleaned);
if (appender != null) {
controls.add(new AppenderControl(appender, null, null));
}
}
super.start();
}
@Override
public void append(LogEvent event) {
String formattedMessage = event.getMessage().getFormattedMessage();
boolean skipMessage = formattedMessage.startsWith("GET /") || formattedMessage.startsWith("POST /");
if (!skipMessage) {
for (AppenderControl control : controls) {
control.callAppender(event);
}
}
}
@PluginFactory
public static CEFAppender createAppender(
@PluginAttribute("name") final String name,
@PluginAttribute("children") final String children,
@PluginElement("Filter") final Filter filter,
@PluginConfiguration final Configuration config
) {
if (children == null) {
throw new IllegalArgumentException("`children` key cannot be null");
}
return new CEFAppender(name, filter, children, config, false);
}
}

View File

@ -0,0 +1,153 @@
/*-
* ~~~~~~licensing~~~~~~
* cef-logger-layout
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.emdev.cef;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Node;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.layout.AbstractStringLayout;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@Plugin(name = "CEFLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true)
public class CEFLayout extends AbstractStringLayout {
public static final String EMDEV_EVENTS = "isEmdevEvents";
private final String header;
private static final ObjectMapper mapper = new ObjectMapper();
private final String separator;
private final String format;
private final Map<String, String> defaults;
private AuditLayout auditLayout;
public CEFLayout(String version, String separator, String vendor, String product,
String productVersion, String format) {
super(Charset.defaultCharset());
this.separator = separator;
this.format = format;
header = new StringBuilder()
.append("CEF:").append(version).append(separator)
.append(vendor).append(separator)
.append(product).append(separator)
.append(productVersion).toString();
String pattern =
"CEF:${" + AuditLayout.CEF_VERSION + "}|${" + AuditLayout.VENDOR + "}|${" + AuditLayout.PRODUCT + "}|${"
+ AuditLayout.VERSION + "}|${"
+ AuditLayout.EVENT_TYPE + "}|${" + AuditLayout.EVENT_NAME + "}|${" + AuditLayout.SEVERITY
+ "}|${" + AuditLayout.EXTENSION + "}";
this.auditLayout = new AuditLayout(pattern);
Map<String, String> overrides = new HashMap<>();
overrides.put(AuditLayout.CEF_VERSION, version);
overrides.put(AuditLayout.VENDOR, vendor);
overrides.put(AuditLayout.PRODUCT, product);
overrides.put(AuditLayout.VERSION, productVersion);
this.defaults = new LinkedHashMap<>(overrides);
auditLayout.addOverrides(overrides);
}
// test-only
void setAuditLayout(AuditLayout layout) {
this.auditLayout = layout;
}
@Override
public String toSerializable(LogEvent event) {
String formattedMessage = event.getMessage().getFormattedMessage();
String result = null;
if (formattedMessage != null) {
try {
result = tryProcessEmdevEvent(formattedMessage);
} catch (IOException e) {
}
if (result == null) {
result = tryAlternate(event);
}
}
return result;
}
private String tryAlternate(LogEvent event) {
String result = null;
if (format.equalsIgnoreCase("json")) {
Map<String, String> parsedMessage = auditLayout.jsonMap(event);
try {
result = mapper.writeValueAsString(parsedMessage) + "\n";
} catch (JsonProcessingException e) {
// pass
}
} else {
result = auditLayout.toSerializable(event);
}
return result;
}
private String tryProcessEmdevEvent(String formattedMessage) throws IOException {
String result = null;
JsonNode jsonNode = mapper.readTree(formattedMessage);
JsonNode isEmdev = jsonNode.get(EMDEV_EVENTS);
boolean process = isEmdev != null && !isEmdev.isNull() && isEmdev.asBoolean(false);
if (process) {
CEFRecord record = CEFRecord.fromJson(jsonNode);
if (record.getSrc() != null) {
String resolvedAddress = DnsResolver.tryResolve(record.getSrc());
if (resolvedAddress != null) {
record.setSrc(resolvedAddress);
}
}
if (this.format.equalsIgnoreCase("cef")) {
result = record.asString(header, separator) + "\n";
} else if (format.equalsIgnoreCase("json")) {
Map<String, ?> jsonRecord = record.asJson(defaults);
result = mapper.writeValueAsString(jsonRecord) + "\n";
}
}
return result;
}
@PluginFactory
public static CEFLayout createCEFLayout(
@PluginAttribute(value = "version", defaultString = "0") String version,
@PluginAttribute(value = "separator", defaultString = "|") String separator,
@PluginAttribute(value = "vendor", defaultString = "EMDEV") String vendor,
@PluginAttribute(value = "product") String product,
@PluginAttribute(value = "productVersion") String productVersion,
@PluginAttribute(value = "format", defaultString = "cef") String format) {
return new CEFLayout(version, separator, vendor, product, productVersion, format);
}
}

View File

@ -0,0 +1,309 @@
/*-
* ~~~~~~licensing~~~~~~
* cef-logger-layout
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.emdev.cef;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.NullNode;
import java.time.ZonedDateTime;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.BiConsumer;
public class CEFRecord {
public static final String SPACE = " ";
public static final String EQUALS = "=";
private String type;
private String performedBy;
private String action;
private String src;
private String dst;
private String shost;
private String suid;
private String suser;
private String msg;
private String cs1;
private String cs1Label;
private String severity;
private final long end;
private String outcome;
private String duser;
private String spriv;
public CEFRecord() {
this.end = ZonedDateTime.now().toInstant().toEpochMilli();
}
public String getSrc() {
return src;
}
public CEFRecord setSrc(String src) {
this.src = src;
return this;
}
public String getDst() {
return dst;
}
public CEFRecord setDst(String dst) {
this.dst = dst;
return this;
}
public String getShost() {
return shost;
}
public CEFRecord setShost(String shost) {
this.shost = shost;
return this;
}
public String getSuid() {
return suid;
}
public CEFRecord setSuid(String suid) {
this.suid = suid;
return this;
}
public String getSuser() {
return suser;
}
public CEFRecord setSuser(String suser) {
this.suser = suser;
return this;
}
public String getMsg() {
return msg;
}
public CEFRecord setMsg(String msg) {
this.msg = msg;
return this;
}
public String getCs1() {
return cs1;
}
public CEFRecord setCs1(String cs1) {
this.cs1 = cs1;
return this;
}
public String getCs1Label() {
return cs1Label;
}
public CEFRecord setCs1Label(String cs1Label) {
this.cs1Label = cs1Label;
return this;
}
public long getEnd() {
return end;
}
public String getType() {
return type;
}
public CEFRecord setType(String type) {
this.type = type;
return this;
}
public String getPerformedBy() {
return performedBy;
}
public CEFRecord setPerformedBy(String performedBy) {
this.performedBy = performedBy;
return this;
}
public String getAction() {
return action;
}
public CEFRecord setAction(String action) {
this.action = action;
return this;
}
public String getSeverity() {
return severity;
}
public CEFRecord setSeverity(String severity) {
this.severity = severity;
return this;
}
public static CEFRecord fromJson(JsonNode jsonNode) {
String type = safeGet(jsonNode, "typ").asText("");
String action = safeGet(jsonNode, "action").asText("");
String performedBy = safeGet(jsonNode, "performedBy").asText("");
JsonNode info = safeGet(jsonNode, "info");
String src = safeGet(info, "src").asText("");
String shost = safeGet(info,"shost").asText("");
String dst = safeGet(info, "dst").asText("");
String suid = safeGet(info, "suid").asText("");
String msg = safeGet(info, "msg").asText("");
String suser = safeGet(info, "suser").asText("");
String outcome = safeGet(info, "outcome").asText("");
String severity = safeGet(info, "severity").asText("0");
String duser = safeGet(info, "duser").asText("");
String spriv = safeGet(info, "spriv").asText("");
return new CEFRecord()
.setType(type)
.setAction(action)
.setPerformedBy(performedBy)
.setShost(shost)
.setSrc(src)
.setDst(dst)
.setSuid(suid)
.setMsg(msg)
.setSuser(suser)
.setSeverity(severity)
.setOutcome(outcome)
.setDuser(duser)
.setSpriv(spriv);
}
private static JsonNode safeGet(JsonNode node, String path) {
JsonNode child = node.get(path);
if (child == null) {
return NullNode.getInstance();
} else {
return child;
}
}
public String asString(String header, String separator) {
final StringBuilder builder = new StringBuilder(header);
builder
.append(separator).append(type) //eventClassId
.append(separator).append(action) //name
.append(separator).append(severity).append(separator);
BiConsumer<String, Object> consumer = (key, value) -> builder.append(key).append(EQUALS).append(value).append(SPACE);
Processor p = new Processor(consumer);
p.process("src", src).
process("dst", dst).
process("shost", shost).
process("suid", suid).
process("suser", suser).
process("duser", duser).
process("spriv", spriv).
process("msg", msg.replaceAll("=", "\\\\=").replaceAll("\\n", " ")).
process("outcome", outcome).
process("end", end);
return builder.toString();
}
public Map<String, ?> asJson(Map<String, String> defaults) {
final Map<String, Object> data = new LinkedHashMap<>(defaults);
Processor p = new Processor(data::put);
p.process("typ", type).
process("action", action).
process("severity", severity).
process("src", src).
process("dst", dst).
process("shost", shost).
process("suid", suid).
process("suser", suser).
process("duser", duser).
process("spriv", spriv).
process("msg", msg.replaceAll("\\n", " ")).
process("outcome", outcome).
process("cs1", cs1).
process("cs1Label", cs1Label).
process("end", end);
return data;
}
private<T> void acceptNotEmpty(String key, T value, BiConsumer<String, T> consumer) {
if (value != null && notEmpty(String.valueOf(value))) {
consumer.accept(key, value);
}
}
public CEFRecord setOutcome(String outcome) {
this.outcome = outcome;
return this;
}
public String getOutcome() {
return outcome;
}
public CEFRecord setDuser(String duser) {
this.duser = duser;
return this;
}
public String getDuser() {
return duser;
}
public CEFRecord setSpriv(String spriv) {
this.spriv = spriv;
return this;
}
public String getSpriv() {
return spriv;
}
static class Processor {
final BiConsumer<String, Object> consumer;
Processor(BiConsumer<String, Object> consumer) {
this.consumer = consumer;
}
public Processor process(String key, Object value) {
acceptNotEmpty(key, value);
return this;
}
private<T> void acceptNotEmpty(String key, T value) {
if (value != null && notEmpty(String.valueOf(value))) {
consumer.accept(key, value);
}
}
}
private static boolean notEmpty(String s) {
return s != null && s.trim().length() > 0;
}
}

View File

@ -0,0 +1,45 @@
/*-
* ~~~~~~licensing~~~~~~
* cef-logger-layout
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.emdev.cef;
import java.io.IOException;
import java.net.InetAddress;
import java.util.concurrent.ConcurrentHashMap;
public class DnsResolver {
private final static ConcurrentHashMap<String, String> dnsCache = new ConcurrentHashMap<>(1024);
public static String tryResolve(String hostname) {
return dnsCache.computeIfAbsent(hostname, (s) -> {
try {
InetAddress addr = InetAddress.getByName(s);
return addr.getHostAddress();
} catch (IOException e) {
return s;
}
});
}
}

View File

@ -0,0 +1,94 @@
/*-
* ~~~~~~licensing~~~~~~
* cef-logger-layout
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.emdev.cef;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import static org.junit.jupiter.api.Assertions.*;
public class CEFRecordTest {
private final static ObjectMapper mapper = new ObjectMapper();
private final static String SEPARATOR = "|";
private final static String HEADER = "CEF:0|VENDOR|PRODUCT|1.0.0";
public static final int CEF_FIELD_COUNT = 8;
@Test
public void cefRecordCanBeBuiltFromEmptyJson() {
JsonNode jsonNode = readResource("examples/empty.json");
CEFRecord record = CEFRecord.fromJson(jsonNode);
assertNotNull(record);
assertNotEquals(0, record.getEnd());
}
@Test
public void cefRecordCanBeBuiltFromJsonWithouInfo() {
JsonNode jsonNode = readResource("examples/noinfo.json");
CEFRecord record = CEFRecord.fromJson(jsonNode);
assertNotNull(record);
assertNotEquals(0, record.getEnd());
assertEquals("type", record.getType());
assertEquals("action", record.getAction());
assertEquals("user", record.getPerformedBy());
assertEquals("0", record.getSeverity());
}
@Test
public void testFormatting() {
JsonNode jsonNode = readResource("examples/almostFull.json");
CEFRecord record = CEFRecord.fromJson(jsonNode);
assertNotNull(record);
assertEquals("10", record.getSeverity());
assertEquals("", record.getSuser());
assertEquals("", record.getSuid());
String message = record.asString(HEADER, SEPARATOR);
String[] mainFields = message.split("\\|");
assertEquals(CEF_FIELD_COUNT, mainFields.length);
assertEquals("type", mainFields[4]);
assertEquals("action", mainFields[5]);
assertEquals("10", mainFields[6]);
String[] secFields = mainFields[7].split("\\s");
assertEquals(5, secFields.length);
assertEquals("src=127.0.0.1", secFields[0]);
assertEquals("dst=127.0.0.1:443", secFields[1]);
assertEquals("shost=localhost.localdomain", secFields[2]);
assertEquals("msg=CODE\\=400", secFields[3]);
assertTrue(secFields[4].matches("^end=\\d+$"));
}
private static JsonNode readResource(String name) {
try (InputStream in = ClassLoader.getSystemResourceAsStream(name)){
return mapper.readTree(in);
} catch (IOException e) {
return null;
}
}
}

View File

@ -0,0 +1,93 @@
/*-
* ~~~~~~licensing~~~~~~
* cef-logger-layout
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.emdev.cef;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.message.Message;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
public class ProcessingTest {
public static final String AUDIT_LOG_MARKER = "auditLog";
private CEFLayout cefLayout;
private AuditLayout auditLayout;
@BeforeEach
protected void setUp() {
cefLayout = new CEFLayout("", "|", "", "", "", "cef");
auditLayout = Mockito.mock(AuditLayout.class);
Mockito.when(auditLayout.toSerializable(any())).thenReturn(AUDIT_LOG_MARKER);
cefLayout.setAuditLayout(auditLayout);
}
@Test
public void testIsEmdevEvents() {
LogEvent emdevOne = createLogEvent("{\"isEmdevEvents\": \"true\"}");
String message = cefLayout.toSerializable(emdevOne);
assertNotNull(message);
verify(auditLayout, never()).toSerializable(any());
}
@Test
public void testNotEmdevEvents() {
LogEvent emdevOne = createLogEvent("{\"isEmdevEvents\": \"false\"}");
String message = cefLayout.toSerializable(emdevOne);
assertNotNull(message);
verify(auditLayout, times(1)).toSerializable(any());
}
@Test
public void testSkipJsonWithoutEmdevMarker() {
LogEvent emdevOne = createLogEvent("{}");
String message = cefLayout.toSerializable(emdevOne);
assertNotNull(message);
verify(auditLayout, times(1)).toSerializable(any());
}
@Test
public void testSkipPlainText() {
LogEvent emdevOne = createLogEvent("Log message");
String message = cefLayout.toSerializable(emdevOne);
assertNotNull(message);
verify(auditLayout, times(1)).toSerializable(any());
}
private static LogEvent createLogEvent(String message) {
LogEvent event = Mockito.mock(LogEvent.class);
Message logMessage = Mockito.mock(Message.class);
Mockito.when(logMessage.getFormattedMessage()).thenReturn(message);
Mockito.when(event.getMessage()).thenReturn(logMessage);
return event;
}
}

View File

@ -0,0 +1,12 @@
{
"typ": "type",
"action": "action",
"performedBy": "user",
"info" : {
"severity": 10,
"shost": "localhost.localdomain",
"src": "127.0.0.1",
"dst": "127.0.0.1:443",
"msg": "CODE=400"
}
}

View File

@ -0,0 +1,5 @@
{
"typ": "type",
"action": "action",
"performedBy": "user"
}

View File

@ -0,0 +1,275 @@
[server]
hostname = "localhost"
#offset=0
base_path = "${carbon.protocol}://${carbon.host}:${carbon.management.port}"
#discard_empty_caches = false
server_role = "default"
[super_admin]
username = "admin"
password = "admin"
create_admin_account = true
[user_store]
type = "database_unique_id"
[database.apim_db]
type = "h2"
url = "jdbc:h2:./repository/database/WSO2AM_DB;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSE"
username = "wso2carbon"
password = "wso2carbon"
[database.shared_db]
type = "h2"
url = "jdbc:h2:./repository/database/WSO2SHARED_DB;DB_CLOSE_ON_EXIT=FALSE"
username = "wso2carbon"
password = "wso2carbon"
[keystore.tls]
file_name = "wso2carbon.jks"
type = "JKS"
password = "wso2carbon"
alias = "wso2carbon"
key_password = "wso2carbon"
#[keystore.listener_profile]
#bind_address = "0.0.0.0"
#[keystore.primary]
#file_name = "wso2carbon.jks"
#type = "JKS"
#password = "wso2carbon"
#alias = "wso2carbon"
#key_password = "wso2carbon"
#[keystore.internal]
#file_name = "wso2carbon.jks"
#type = "JKS"
#password = "wso2carbon"
#alias = "wso2carbon"
#key_password = "wso2carbon"
[[apim.gateway.environment]]
name = "Default"
type = "hybrid"
provider = "wso2"
display_in_api_console = true
description = "This is a hybrid gateway that handles both production and sandbox token traffic."
show_as_token_endpoint_url = true
service_url = "https://localhost:${mgt.transport.https.port}/services/"
username= "${admin.username}"
password= "${admin.password}"
ws_endpoint = "ws://localhost:9099"
wss_endpoint = "wss://localhost:8099"
http_endpoint = "http://localhost:${http.nio.port}"
https_endpoint = "https://localhost:${https.nio.port}"
websub_event_receiver_http_endpoint = "http://localhost:9021"
websub_event_receiver_https_endpoint = "https://localhost:8021"
[apim.sync_runtime_artifacts.gateway]
gateway_labels =["Default"]
#[apim.cache.gateway_token]
#enable = true
#expiry_time = "900s"
#[apim.cache.resource]
#enable = true
#expiry_time = "900s"
#[apim.cache.km_token]
#enable = false
#expiry_time = "15m"
#[apim.cache.recent_apis]
#enable = false
#[apim.cache.scopes]
#enable = true
#[apim.cache.publisher_roles]
#enable = true
#[apim.cache.jwt_claim]
#enable = true
#expiry_time = "15m"
#[apim.cache.tags]
#expiry_time = "2m"
[apim.analytics]
enable = false
auth_token = ""
#[apim.key_manager]
#service_url = "https://localhost:${mgt.transport.https.port}/services/"
#username = "$ref{super_admin.username}"
#password = "$ref{super_admin.password}"
#pool.init_idle_capacity = 50
#pool.max_idle = 100
#key_validation_handler_type = "default"
#key_validation_handler_type = "custom"
#key_validation_handler_impl = "org.wso2.carbon.apimgt.keymgt.handlers.DefaultKeyValidationHandler"
#[apim.idp]
#server_url = "https://localhost:${mgt.transport.https.port}"
#authorize_endpoint = "https://localhost:${mgt.transport.https.port}/oauth2/authorize"
#oidc_logout_endpoint = "https://localhost:${mgt.transport.https.port}/oidc/logout"
#oidc_check_session_endpoint = "https://localhost:${mgt.transport.https.port}/oidc/checksession"
#[apim.jwt]
#enable = true
#encoding = "base64" # base64,base64url
#generator_impl = "org.wso2.carbon.apimgt.keymgt.token.JWTGenerator"
#claim_dialect = "http://wso2.org/claims"
#convert_dialect = false
#header = "X-JWT-Assertion"
#signing_algorithm = "SHA256withRSA"
#enable_user_claims = true
#claims_extractor_impl = "org.wso2.carbon.apimgt.impl.token.ExtendedDefaultClaimsRetriever"
#[apim.oauth_config]
#enable_outbound_auth_header = false
#auth_header = "Authorization"
#revoke_endpoint = "https://localhost:${https.nio.port}/revoke"
#enable_token_encryption = false
#enable_token_hashing = false
#[apim.devportal]
#url = "https://localhost:${mgt.transport.https.port}/devportal"
#enable_application_sharing = false
#if application_sharing_type, application_sharing_impl both defined priority goes to application_sharing_impl
#application_sharing_type = "default" #changed type, saml, default #todo: check the new config for rest api
#application_sharing_impl = "org.wso2.carbon.apimgt.impl.SAMLGroupIDExtractorImpl"
#display_multiple_versions = false
#display_deprecated_apis = false
#enable_comments = true
#enable_ratings = true
#enable_forum = true
#enable_anonymous_mode=true
#enable_cross_tenant_subscriptions = true
#default_reserved_username = "apim_reserved_user"
[apim.cors]
allow_origins = "*"
allow_methods = ["GET","PUT","POST","DELETE","PATCH","OPTIONS"]
allow_headers = ["authorization","Access-Control-Allow-Origin","Content-Type","SOAPAction","apikey","Internal-Key"]
allow_credentials = false
#[apim.throttling]
#enable_data_publishing = true
#enable_policy_deploy = true
#enable_blacklist_condition = true
#enable_persistence = true
#throttle_decision_endpoints = ["tcp://localhost:5672","tcp://localhost:5672"]
#[apim.throttling.blacklist_condition]
#start_delay = "5m"
#period = "1h"
#[apim.throttling.jms]
#start_delay = "5m"
#[apim.throttling.event_sync]
#hostName = "0.0.0.0"
#port = 11224
#[apim.throttling.event_management]
#hostName = "0.0.0.0"
#port = 10005
#[[apim.throttling.url_group]]
#traffic_manager_urls = ["tcp://localhost:9611","tcp://localhost:9611"]
#traffic_manager_auth_urls = ["ssl://localhost:9711","ssl://localhost:9711"]
#type = "loadbalance"
#[[apim.throttling.url_group]]
#traffic_manager_urls = ["tcp://localhost:9611","tcp://localhost:9611"]
#traffic_manager_auth_urls = ["ssl://localhost:9711","ssl://localhost:9711"]
#type = "failover"
#[apim.workflow]
#enable = false
#service_url = "https://localhost:9445/bpmn"
#username = "$ref{super_admin.username}"
#password = "$ref{super_admin.password}"
#callback_endpoint = "https://localhost:${mgt.transport.https.port}/api/am/admin/v0.17/workflows/update-workflow-status"
#token_endpoint = "https://localhost:${https.nio.port}/token"
#client_registration_endpoint = "https://localhost:${mgt.transport.https.port}/client-registration/v0.17/register"
#client_registration_username = "$ref{super_admin.username}"
#client_registration_password = "$ref{super_admin.password}"
#data bridge config
#[transport.receiver]
#type = "binary"
#worker_threads = 10
#session_timeout = "30m"
#keystore.file_name = "$ref{keystore.tls.file_name}"
#keystore.password = "$ref{keystore.tls.password}"
#tcp_port = 9611
#ssl_port = 9711
#ssl_receiver_thread_pool_size = 100
#tcp_receiver_thread_pool_size = 100
#ssl_enabled_protocols = ["TLSv1","TLSv1.1","TLSv1.2"]
#ciphers = ["SSL_RSA_WITH_RC4_128_MD5","SSL_RSA_WITH_RC4_128_SHA"]
#[apim.notification]
#from_address = "APIM.com"
#username = "APIM"
#password = "APIM+123"
#hostname = "localhost"
#port = 3025
#enable_start_tls = false
#enable_authentication = true
#[apim.token.revocation]
#notifier_impl = "org.wso2.carbon.apimgt.keymgt.events.TokenRevocationNotifierImpl"
#enable_realtime_notifier = true
#realtime_notifier.ttl = 5000
#enable_persistent_notifier = true
#persistent_notifier.hostname = "https://localhost:2379/v2/keys/jti/"
#persistent_notifier.ttl = 5000
#persistent_notifier.username = "root"
#persistent_notifier.password = "root"
[[event_handler]]
name="userPostSelfRegistration"
subscriptions=["POST_ADD_USER"]
[service_provider]
sp_name_regex = "^[\\sa-zA-Z0-9._-]*$"
[database.local]
url = "jdbc:h2:./repository/database/WSO2CARBON_DB;DB_CLOSE_ON_EXIT=FALSE"
[[event_listener]]
id = "token_revocation"
type = "org.wso2.carbon.identity.core.handler.AbstractIdentityHandler"
name = "org.wso2.is.notification.ApimOauthEventInterceptor"
order = 1
[[event_listener]]
id = "token_refresh"
type = "org.wso2.carbon.identity.core.handler.AbstractIdentityHandler"
name = "org.wso2.carbon.identity.data.publisher.oauth.listener.RefreshTokenGrantAuditLogger"
order = 2
[[event_listener]]
id = "token_refresh_revoke"
type = "org.wso2.carbon.identity.core.handler.AbstractIdentityHandler"
name = "org.wso2.carbon.identity.data.publisher.oauth.listener.TokenRevocationAuditLogger"
order = 3
[event_listener.properties]
notification_endpoint = "https://localhost:${mgt.transport.https.port}/internal/data/v1/notify"
username = "${admin.username}"
password = "${admin.password}"
'header.X-WSO2-KEY-MANAGER' = "default"
[oauth.grant_type.token_exchange]
enable = true
allow_refresh_tokens = true
iat_validity_period = "1h"
[apim.key_manager]
enable_apikey_subscription_validation = true

View File

@ -0,0 +1,26 @@
# CEF logger
log4j2.logger.AUDIT_FILE.name = AUDIT_LOGFILE
log4j2.logger.AUDIT_FILE.level = INFO
log4j2.logger.AUDIT_FILE.appenderRef.AUDIT_LOGFILE.ref = AuditCompositeLogger
log4j2.logger.AUDIT_FILE.additivity = false
log4j2.appender.AUDIT_LOGFILE.type = CEFAggregate
log4j2.appender.AUDIT_LOGFILE.name = AuditCompositeLogger
log4j2.appender.AUDIT_LOGFILE.children = CefFile
log4j2.appender.AUDIT_LOGFILE.filter.threshold.type = ThresholdFilter
log4j2.appender.AUDIT_LOGFILE.filter.threshold.level = INFO
log4j2.appender.AUDIT_LOGFILE_1.type = RollingRandomAccessFile
log4j2.appender.AUDIT_LOGFILE_1.name = CefFile
log4j2.appender.AUDIT_LOGFILE_1.append = true
log4j2.appender.AUDIT_LOGFILE_1.fileName = ${karaf.log}/cef-audit.log
log4j2.appender.AUDIT_LOGFILE_1.filePattern = ${karaf.log}/cef-audit-%d{MM-dd-yyyy}.log
log4j2.appender.AUDIT_LOGFILE_1.layout.type = CEFLayout
log4j2.appender.AUDIT_LOGFILE_1.layout.vendor = EMDEV
log4j2.appender.AUDIT_LOGFILE_1.layout.product = ENTAXY
log4j2.appender.AUDIT_LOGFILE_1.layout.productVersion = 1.1.10-SNAPSHOT
log4j2.appender.AUDIT_LOGFILE_1.policies.type = Policies
log4j2.appender.AUDIT_LOGFILE_1.policies.size.type = SizeBasedTriggeringPolicy
log4j2.appender.AUDIT_LOGFILE_1.policies.size.size = 10MB
log4j2.appender.AUDIT_LOGFILE_1.filter.threshold.type = ThresholdFilter
log4j2.appender.AUDIT_LOGFILE_1.filter.threshold.level = INFO

View File

@ -0,0 +1,484 @@
# list of all appenders
#add entry "syslog" to use the syslog appender
appenders=CARBON_CONSOLE, CARBON_LOGFILE, AUDIT_LOGFILE, ATOMIKOS_LOGFILE, CARBON_TRACE_LOGFILE, ERROR_LOGFILE, OPEN_TRACING,SERVICE_APPENDER, TRACE_APPENDER, osgi, CORRELATION, BOTDATA_APPENDER, API_LOGFILE, AUDIT_LOGFILE_1, AUDIT_LOGFILE_2
#, syslog
# CARBON_CONSOLE is set to be a ConsoleAppender using a PatternLayout.
appender.CARBON_CONSOLE.type = Console
appender.CARBON_CONSOLE.name = CARBON_CONSOLE
appender.CARBON_CONSOLE.layout.type = PatternLayout
appender.CARBON_CONSOLE.layout.pattern = [%d{DEFAULT}] %5p - %c{1} %m%n
appender.CARBON_CONSOLE.filter.threshold.type = ThresholdFilter
appender.CARBON_CONSOLE.filter.threshold.level = DEBUG
# CARBON_LOGFILE is set to be a DailyRollingFileAppender using a PatternLayout.
appender.CARBON_LOGFILE.type = RollingFile
appender.CARBON_LOGFILE.name = CARBON_LOGFILE
appender.CARBON_LOGFILE.fileName = ${sys:carbon.home}/repository/logs/wso2carbon.log
appender.CARBON_LOGFILE.filePattern = ${sys:carbon.home}/repository/logs/wso2carbon-%d{MM-dd-yyyy}-%i.log
appender.CARBON_LOGFILE.layout.type = PatternLayout
appender.CARBON_LOGFILE.layout.pattern = TID: [%tenantId] [%appName] [%d] %5p {%c} - %m%ex%n
appender.CARBON_LOGFILE.policies.type = Policies
appender.CARBON_LOGFILE.policies.time.type = TimeBasedTriggeringPolicy
appender.CARBON_LOGFILE.policies.time.interval = 1
appender.CARBON_LOGFILE.policies.time.modulate = true
appender.CARBON_LOGFILE.policies.size.type = SizeBasedTriggeringPolicy
appender.CARBON_LOGFILE.policies.size.size = 10MB
appender.CARBON_LOGFILE.strategy.type = DefaultRolloverStrategy
appender.CARBON_LOGFILE.strategy.max = 20
appender.CARBON_LOGFILE.filter.threshold.type = ThresholdFilter
appender.CARBON_LOGFILE.filter.threshold.level = DEBUG
# Appender config to AUDIT_LOGFILE
appender.AUDIT_LOGFILE.type = CEFAggregate
appender.AUDIT_LOGFILE.name = AUDIT_LOGFILE
appender.AUDIT_LOGFILE.children = AUDIT_LOGFILE_1, AUDIT_LOGFILE_2
appender.AUDIT_LOGFILE.filter.threshold.type = ThresholdFilter
appender.AUDIT_LOGFILE.filter.threshold.level = INFO
# audit.log CEF output
appender.AUDIT_LOGFILE_1.type = RollingFile
appender.AUDIT_LOGFILE_1.name = AUDIT_LOGFILE_1
appender.AUDIT_LOGFILE_1.fileName = ${sys:carbon.home}/repository/logs/audit.log
appender.AUDIT_LOGFILE_1.filePattern = ${sys:carbon.home}/repository/logs/audit-%d{MM-dd-yyyy}.log
#appender.AUDIT_LOGFILE.layout.type = PatternLayout
#appender.AUDIT_LOGFILE.layout.pattern = TID: [%tenantId] [%d] %5p {%c} - %m%ex%n
appender.AUDIT_LOGFILE_1.layout.type = CEFLayout
appender.AUDIT_LOGFILE_1.layout.vendor = EMDEV
appender.AUDIT_LOGFILE_1.layout.product = WSO2APIM
appender.AUDIT_LOGFILE_1.layout.productVersion = 4.1.0
appender.AUDIT_LOGFILE_1.policies.type = Policies
appender.AUDIT_LOGFILE_1.policies.time.type = TimeBasedTriggeringPolicy
appender.AUDIT_LOGFILE_1.policies.time.interval = 1
appender.AUDIT_LOGFILE_1.policies.time.modulate = true
appender.AUDIT_LOGFILE_1.policies.size.type = SizeBasedTriggeringPolicy
appender.AUDIT_LOGFILE_1.policies.size.size = 10MB
appender.AUDIT_LOGFILE_1.strategy.type = DefaultRolloverStrategy
appender.AUDIT_LOGFILE_1.strategy.max = 20
appender.AUDIT_LOGFILE_1.filter.threshold.type = ThresholdFilter
appender.AUDIT_LOGFILE_1.filter.threshold.level = INFO
# console audit JSON output
appender.AUDIT_LOGFILE_2.type = Console
appender.AUDIT_LOGFILE_2.name = AUDIT_LOGFILE_2
appender.AUDIT_LOGFILE_2.layout.type = CEFLayout
appender.AUDIT_LOGFILE_2.layout.vendor = EMDEV
appender.AUDIT_LOGFILE_2.layout.product = WSO2APIM
appender.AUDIT_LOGFILE_2.layout.productVersion = 4.1.0
appender.AUDIT_LOGFILE_2.layout.format = json
appender.AUDIT_LOGFILE_2.filter.threshold.type = ThresholdFilter
appender.AUDIT_LOGFILE_2.filter.threshold.level = INFO
# Appender config API logging
appender.API_LOGFILE.type = RollingFile
appender.API_LOGFILE.name = API_LOGFILE
appender.API_LOGFILE.fileName = ${sys:carbon.home}/repository/logs/api.log
appender.API_LOGFILE.filePattern = ${sys:carbon.home}/repository/logs/api-%d{MM-dd-yyyy}-%i.log
appender.API_LOGFILE.layout.type = PatternLayout
appender.API_LOGFILE.layout.pattern = [%d] %5p {%c} %X{apiName} - %m%ex%n
appender.API_LOGFILE.policies.type = Policies
appender.API_LOGFILE.policies.time.type = TimeBasedTriggeringPolicy
appender.API_LOGFILE.policies.time.interval = 1
appender.API_LOGFILE.policies.time.modulate = true
appender.API_LOGFILE.policies.size.type = SizeBasedTriggeringPolicy
appender.API_LOGFILE.policies.size.size = 10MB
appender.API_LOGFILE.strategy.type = DefaultRolloverStrategy
appender.API_LOGFILE.strategy.max = 20
appender.API_LOGFILE.filter.threshold.type = ThresholdFilter
appender.API_LOGFILE.filter.threshold.level = DEBUG
# Appender config to send Atomikos transaction logs to new log file tm.out.
appender.ATOMIKOS_LOGFILE.type = RollingFile
appender.ATOMIKOS_LOGFILE.name = ATOMIKOS_LOGFILE
appender.ATOMIKOS_LOGFILE.fileName = ${sys:carbon.home}/repository/logs/tm.out
appender.ATOMIKOS_LOGFILE.filePattern = ${sys:carbon.home}/repository/logs/tm-%d{MM-dd-yyyy}.out
appender.ATOMIKOS_LOGFILE.layout.type = PatternLayout
appender.ATOMIKOS_LOGFILE.layout.pattern = [%d] [%tenantId] %5p {%c} - %m%ex%n
appender.ATOMIKOS_LOGFILE.policies.type = Policies
appender.ATOMIKOS_LOGFILE.policies.time.type = TimeBasedTriggeringPolicy
appender.ATOMIKOS_LOGFILE.policies.time.interval = 1
appender.ATOMIKOS_LOGFILE.policies.time.modulate = true
appender.ATOMIKOS_LOGFILE.strategy.type = DefaultRolloverStrategy
appender.ATOMIKOS_LOGFILE.strategy.max = 20
# Appender config to CARBON_TRACE_LOGFILE
appender.CARBON_TRACE_LOGFILE.type = RollingFile
appender.CARBON_TRACE_LOGFILE.name = CARBON_TRACE_LOGFILE
appender.CARBON_TRACE_LOGFILE.fileName = ${sys:carbon.home}/repository/logs/wso2carbon-trace-messages.log
appender.CARBON_TRACE_LOGFILE.filePattern = ${sys:carbon.home}/repository/logs/wso2carbon-trace-messages-%d{MM-dd-yyyy}.log
appender.CARBON_TRACE_LOGFILE.layout.type = PatternLayout
appender.CARBON_TRACE_LOGFILE.layout.pattern = [%d] [%tenantId] %5p {%c} - %m%ex%n
appender.CARBON_TRACE_LOGFILE.policies.type = Policies
appender.CARBON_TRACE_LOGFILE.policies.time.type = TimeBasedTriggeringPolicy
appender.CARBON_TRACE_LOGFILE.policies.time.interval = 1
appender.CARBON_TRACE_LOGFILE.policies.time.modulate = true
appender.CARBON_TRACE_LOGFILE.policies.size.type = SizeBasedTriggeringPolicy
appender.CARBON_TRACE_LOGFILE.policies.size.size = 10MB
appender.CARBON_TRACE_LOGFILE.strategy.type = DefaultRolloverStrategy
appender.CARBON_TRACE_LOGFILE.strategy.max = 20
# Appender config to put correlation Log.
appender.CORRELATION.type = RollingFile
appender.CORRELATION.name = CORRELATION
appender.CORRELATION.fileName = ${sys:carbon.home}/repository/logs/correlation.log
appender.CORRELATION.filePattern =${sys:carbon.home}/repository/logs/correlation-%d{MM-dd-yyyy}-%i.log.gz
appender.CORRELATION.layout.type = PatternLayout
appender.CORRELATION.layout.pattern = %d{yyyy-MM-dd HH:mm:ss,SSS}|%X{Correlation-ID}|%t|%m%n
appender.CORRELATION.policies.type = Policies
appender.CORRELATION.policies.time.type = TimeBasedTriggeringPolicy
appender.CORRELATION.policies.time.interval = 1
appender.CORRELATION.policies.time.modulate = true
appender.CORRELATION.policies.size.type = SizeBasedTriggeringPolicy
appender.CORRELATION.policies.size.size = 10MB
appender.CORRELATION.strategy.type = DefaultRolloverStrategy
appender.CORRELATION.strategy.max = 20
appender.CORRELATION.filter.threshold.type = ThresholdFilter
appender.CORRELATION.filter.threshold.level = INFO
appender.ERROR_LOGFILE.type = RollingFile
appender.ERROR_LOGFILE.name = ERROR_LOGFILE
appender.ERROR_LOGFILE.fileName = ${sys:carbon.home}/repository/logs/wso2-apigw-errors.log
appender.ERROR_LOGFILE.filePattern = ${sys:carbon.home}/repository/logs/wso2-apigw-errors-%d{MM-dd-yyyy}-%i.log.gz
appender.ERROR_LOGFILE.layout.type = PatternLayout
appender.ERROR_LOGFILE.layout.pattern = %d{ISO8601} [%X{ip}-%X{host}] [%t] %5p %c{1} %m%n
appender.ERROR_LOGFILE.policies.type = Policies
appender.ERROR_LOGFILE.policies.time.type = TimeBasedTriggeringPolicy
appender.ERROR_LOGFILE.policies.time.interval = 1
appender.ERROR_LOGFILE.policies.time.modulate = true
appender.ERROR_LOGFILE.policies.size.type = SizeBasedTriggeringPolicy
appender.ERROR_LOGFILE.policies.size.size = 10MB
appender.ERROR_LOGFILE.strategy.type = DefaultRolloverStrategy
appender.ERROR_LOGFILE.strategy.max = 20
appender.ERROR_LOGFILE.filter.threshold.type = ThresholdFilter
appender.ERROR_LOGFILE.filter.threshold.level = WARN
appender.CARBON_SYS_LOG.type = Syslog
appender.CARBON_SYS_LOG.name = CARBON_SYS_LOG
appender.CARBON_SYS_LOG.host = localhost
appender.CARBON_SYS_LOG.facility = USER
appender.CARBON_SYS_LOG.layout.type = PatternLayout
appender.CARBON_SYS_LOG.layout.pattern = [%d] %5p - %x %m {%c}%n
appender.CARBON_SYS_LOG.filter.threshold.type = ThresholdFilter
appender.CARBON_SYS_LOG.filter.threshold.level = DEBUG
appender.OPEN_TRACING.type = RollingFile
appender.OPEN_TRACING.name = OPEN_TRACING
appender.OPEN_TRACING.fileName = ${sys:carbon.home}/repository/logs/wso2-apimgt-open-tracing.log
appender.OPEN_TRACING.filePattern = ${sys:carbon.home}/repository/logs/wso2-apimgt-open-tracing-%d{MM-dd-yyyy}-%i.log.gz
appender.OPEN_TRACING.layout.type = PatternLayout
appender.OPEN_TRACING.layout.pattern = %d{HH:mm:ss,SSS} [%X{ip}-%X{host}] [%t] %5p %m%nn
appender.OPEN_TRACING.policies.type = Policies
appender.OPEN_TRACING.policies.time.type = TimeBasedTriggeringPolicy
appender.OPEN_TRACING.policies.time.interval = 1
appender.OPEN_TRACING.policies.time.modulate = true
appender.OPEN_TRACING.policies.size.type = SizeBasedTriggeringPolicy
appender.OPEN_TRACING.policies.size.size = 10MB
appender.OPEN_TRACING.strategy.type = DefaultRolloverStrategy
appender.OPEN_TRACING.strategy.max = 20
appender.OPEN_TRACING.filter.threshold.type = ThresholdFilter
appender.OPEN_TRACING.filter.threshold.level = TRACE
appender.TRACE_APPENDER.type = RollingFile
appender.TRACE_APPENDER.name = TRACE_APPENDER
appender.TRACE_APPENDER.fileName = ${sys:carbon.home}/repository/logs/wso2-apigw-trace.log
appender.TRACE_APPENDER.filePattern = ${sys:carbon.home}/repository/logs/wso2-apigw-trace-%d{MM-dd-yyyy}.log
appender.TRACE_APPENDER.layout.type = PatternLayout
appender.TRACE_APPENDER.layout.pattern = %d{HH:mm:ss,SSS} [%X{ip}-%X{host}] [%t] %5p %c{1} %m%n
appender.TRACE_APPENDER.policies.type = Policies
appender.TRACE_APPENDER.policies.time.type = TimeBasedTriggeringPolicy
appender.TRACE_APPENDER.policies.time.interval = 1
appender.TRACE_APPENDER.policies.time.modulate = true
appender.TRACE_APPENDER.strategy.type = DefaultRolloverStrategy
appender.TRACE_APPENDER.strategy.max = 20
appender.SERVICE_APPENDER.type = RollingFile
appender.SERVICE_APPENDER.name = SERVICE_APPENDER
appender.SERVICE_APPENDER.fileName = ${sys:carbon.home}/repository/logs/wso2-apigw-service.log
appender.SERVICE_APPENDER.filePattern = ${sys:carbon.home}/repository/logs/wso2-apigw-service-%i.log
appender.SERVICE_APPENDER.layout.type = PatternLayout
appender.SERVICE_APPENDER.layout.pattern = %d{ISO8601} [%X{ip}-%X{host}] [%t] %5p %c{1} %m%n
appender.SERVICE_APPENDER.policies.type = Policies
appender.SERVICE_APPENDER.policies.size.type = SizeBasedTriggeringPolicy
appender.SERVICE_APPENDER.policies.size.size=1000KB
appender.SERVICE_APPENDER.strategy.type = DefaultRolloverStrategy
appender.SERVICE_APPENDER.strategy.max = 10
appender.osgi.type = PaxOsgi
appender.osgi.name = PaxOsgi
appender.osgi.filter = *
loggers = AUDIT_LOG, trace-messages, org-apache-coyote, com-hazelcast, Owasp-CsrfGuard, org-apache-axis2-wsdl-codegen-writer-PrettyPrinter, org-apache-axis2-clustering, org-apache-catalina, org-apache-tomcat, org-wso2-carbon-apacheds, org-apache-directory-server-ldap, org-apache-directory-server-core-event, com-atomikos, org-quartz, org-apache-jackrabbit-webdav, org-apache-juddi, org-apache-commons-digester-Digester, org-apache-jasper-compiler-TldLocationsCache, org-apache-qpid, org-apache-qpid-server-Main, qpid-message, qpid-message-broker-listening, org-apache-tiles, org-apache-commons-httpclient, org-apache-solr, me-prettyprint-cassandra-hector-TimingLogger, org-apache-axis-enterprise, org-apache-directory-shared-ldap, org-apache-directory-server-ldap-handlers, org-apache-directory-shared-ldap-entry-DefaultServerAttribute, org-apache-directory-server-core-DefaultDirectoryService, org-apache-directory-shared-ldap-ldif-LdifReader, org-apache-directory-server-ldap-LdapProtocolHandler, org-apache-directory-server-core, org-apache-directory-server-ldap-LdapSession, DataNucleus, Datastore, Datastore-Schema, JPOX-Datastore, JPOX-Plugin, JPOX-MetaData, JPOX-Query, JPOX-General, JPOX-Enhancer, org-apache-hadoop-hive, hive, ExecMapper, ExecReducer, net-sf-ehcache-config-ConfigurationFactory, axis2Deployment, equinox, tomcat2, StAXDialectDetector, trace, synapse, synapse_transport, axis2, axis2_transport, org-wso2-carbon, hunsicker, thrift-publisher, service_logger, trace_logger, org-wso2-carbon-apimgt-gateway-mediators-BotDetectionMediator, wso2-callhome, correlation, JAGGERY_LOG, API_LOG
logger.API_LOG.name = API_LOG
logger.API_LOG.level = INFO
logger.API_LOG.appenderRef.API_LOGFILE.ref = API_LOGFILE
logger.API_LOG.additivity = false
logger.JAGGERY_LOG.name = JAGGERY
logger.JAGGERY_LOG.level = INFO
logger.AUDIT_LOG.name = AUDIT_LOG
logger.AUDIT_LOG.level = INFO
logger.AUDIT_LOG.appenderRef.AUDIT_LOGFILE.ref = AUDIT_LOGFILE
logger.AUDIT_LOG.additivity = false
logger.trace-messages.name = trace.messages
logger.trace-messages.level = TRACE
logger.trace-messages.appenderRef.CARBON_TRACE_LOGFILE.ref = CARBON_TRACE_LOGFILE
logger.org-apache-coyote.name = org.apache.coyote
logger.org-apache-coyote.level = WARN
logger.com-hazelcast.name = com.hazelcast
logger.com-hazelcast.level = ERROR
logger.Owasp-CsrfGuard.name = Owasp.CsrfGuard
logger.Owasp-CsrfGuard.level = WARN
logger.org-apache-axis2-wsdl-codegen-writer-PrettyPrinter.name = org.apache.axis2.wsdl.codegen.writer.PrettyPrinter
logger.org-apache-axis2-wsdl-codegen-writer-PrettyPrinter.level = ERROR
logger.org-apache-axis2-wsdl-codegen-writer-PrettyPrinter.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
logger.org-apache-axis2-clustering.name = org.apache.axis2.clustering
logger.org-apache-axis2-clustering.level = INFO
logger.org-apache-axis2-clustering.additivity = false
logger.org-apache.name = org.apache
logger.org-apache.level = INFO
logger.org-apache.additivity = false
logger.org-apache.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
logger.org-apache-catalina.name = org.apache.catalina
logger.org-apache-catalina.level = ERROR
logger.org-apache-tomcat.name = org.apache.tomcat
logger.org-apache-tomcat.level = INFO
logger.org-wso2-carbon-apacheds.name = org.wso2.carbon.apacheds
logger.org-wso2-carbon-apacheds.level = WARN
logger.org-apache-directory-server-ldap.name = org.apache.directory.server.ldap
logger.org-apache-directory-server-ldap.level = ERROR
logger.org-apache-directory-server-core-event.name = org.apache.directory.server.core.event
logger.org-apache-directory-server-core-event.level = WARN
logger.com-atomikos.name = com.atomikos
logger.com-atomikos.level = INFO
logger.com-atomikos.additivity = false
logger.com-atomikos.appenderRef.ATOMIKOS_LOGFILE.ref = ATOMIKOS_LOGFILE
logger.org-quartz.name = org.quartz
logger.org-quartz.level = WARN
logger.org-apache-jackrabbit-webdav.name = org.apache.jackrabbit.webdav
logger.org-apache-jackrabbit-webdav.level = WARN
logger.org-apache-juddi.name = org.apache.juddi
logger.org-apache-juddi.level = ERROR
logger.org-apache-commons-digester-Digester.name = org.apache.commons.digester.Digester
logger.org-apache-commons-digester-Digester.level = WARN
logger.org-apache-jasper-compiler-TldLocationsCache.name = org.apache.jasper.compiler.TldLocationsCache
logger.org-apache-jasper-compiler-TldLocationsCache.level = WARN
logger.org-apache-qpid.name = org.apache.qpid
logger.org-apache-qpid.level = WARN
logger.org-apache-qpid-server-Main.name = org.apache.qpid.server.Main
logger.org-apache-qpid-server-Main.level = INFO
logger.qpid-message.name = qpid.message
logger.qpid-message.level = WARN
logger.qpid-message-broker-listening.name = qpid.message.broker.listening
logger.qpid-message-broker-listening.level = INFO
logger.org-apache-tiles.name = org.apache.tiles
logger.org-apache-tiles.level = WARN
logger.org-apache-commons-httpclient.name = org.apache.commons.httpclient
logger.org-apache-commons-httpclient.level = ERROR
logger.org-apache-solr.name = org.apache.solr
logger.org-apache-solr.level = ERROR
logger.me-prettyprint-cassandra-hector-TimingLogger.name = me.prettyprint.cassandra.hector.TimingLogger
logger.me-prettyprint-cassandra-hector-TimingLogger.level = ERROR
logger.org-wso2.name = org.wso2
logger.org-wso2.level = INFO
logger.org-wso2-carbon.name = org.wso2.carbon
logger.org-wso2-carbon.level = INFO
logger.org-apache-axis-enterprise.name = org.apache.axis2.enterprise
logger.org-apache-axis-enterprise.level = FATAL
logger.org-apache-axis-enterprise.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
logger.org-apache-directory-shared-ldap.name = org.apache.directory.shared.ldap
logger.org-apache-directory-shared-ldap.level = WARN
logger.org-apache-directory-shared-ldap.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
logger.org-apache-directory-server-ldap-handlers.name = org.apache.directory.server.ldap.handlers
logger.org-apache-directory-server-ldap-handlers.level = WARN
logger.org-apache-directory-server-ldap-handlers.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
# Following are to remove false error messages from startup (IS)
logger.org-apache-directory-shared-ldap-entry-DefaultServerAttribute.name = org.apache.directory.shared.ldap.entry.DefaultServerAttribute
logger.org-apache-directory-shared-ldap-entry-DefaultServerAttribute.level = FATAL
logger.org-apache-directory-shared-ldap-entry-DefaultServerAttribute.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
logger.org-apache-directory-server-core-DefaultDirectoryService.name = org.apache.directory.server.core.DefaultDirectoryService
logger.org-apache-directory-server-core-DefaultDirectoryService.level = ERROR
logger.org-apache-directory-server-core-DefaultDirectoryService.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
logger.org-apache-directory-shared-ldap-ldif-LdifReader.name = org.apache.directory.shared.ldap.ldif.LdifReader
logger.org-apache-directory-shared-ldap-ldif-LdifReader.level = ERROR
logger.org-apache-directory-shared-ldap-ldif-LdifReader.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
logger.org-apache-directory-server-ldap-LdapProtocolHandler.name = org.apache.directory.server.ldap.LdapProtocolHandler
logger.org-apache-directory-server-ldap-LdapProtocolHandler.level = ERROR
logger.org-apache-directory-server-ldap-LdapProtocolHandler.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
logger.org-apache-directory-server-core.name = org.apache.directory.server.core
logger.org-apache-directory-server-core.level = ERROR
logger.org-apache-directory-server-core.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
logger.org-apache-directory-server-ldap-LdapSession.name = org.apache.directory.server.ldap.LdapSession
logger.org-apache-directory-server-ldap-LdapSession.level = Error
logger.org-apache-directory-server-ldap-LdapSession.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
logger.correlation.name = correlation
logger.correlation.level = INFO
logger.correlation.appenderRef.CORRELATION.ref = CORRELATION
logger.correlation.additivity = false
# Hive Related Log configurations
logger.DataNucleus.name = DataNucleus
logger.DataNucleus.level = ERROR
logger.Datastore.name = Datastore
logger.Datastore.level = ERROR
logger.Datastore-Schema.name = Datastore.Schema
logger.Datastore-Schema.level = ERROR
logger.JPOX-Datastore.name = JPOX.Datastore
logger.JPOX-Datastore.level = ERROR
logger.JPOX-Plugin.name = JPOX.Plugin
logger.JPOX-Plugin.level = ERROR
logger.JPOX-MetaData.name = JPOX.MetaData
logger.JPOX-MetaData.level = ERROR
logger.JPOX-Query.name = JPOX.Query
logger.JPOX-Query.level = ERROR
logger.JPOX-General.name = JPOX.General
logger.JPOX-General.level = ERROR
logger.JPOX-Enhancer.name = JPOX.Enhancer
logger.JPOX-Enhancer.level = ERROR
logger.org-apache-hadoop-hive.name = org.apache.hadoop.hive
logger.org-apache-hadoop-hive.level = WARN
logger.hive.name = hive
logger.hive.level = WARN
logger.ExecMapper.name = ExecMapper
logger.ExecMapper.level = WARN
logger.ExecReducer.name = ExecReducer
logger.ExecReducer.level = WARN
logger.net-sf-ehcache-config-ConfigurationFactory.name = net.sf.ehcache.config.ConfigurationFactory
logger.net-sf-ehcache-config-ConfigurationFactory.level = ERROR
logger.axis2Deployment.name = org.apache.axis2.deployment
logger.axis2Deployment.level = WARN
logger.equinox.name = org.eclipse.equinox
logger.equinox.level = FATAL
logger.tomcat2.name = tomcat
logger.tomcat2.level = FATAL
logger.StAXDialectDetector.name = org.apache.axiom.util.stax.dialect.StAXDialectDetector
logger.StAXDialectDetector.level = ERROR
logger.trace.name = tracer
logger.trace.level = TRACE
logger.trace.appenderRef.OPEN_TRACING.ref = OPEN_TRACING
logger.synapse.name = org.apache.synapse
logger.synapse.level = INFO
logger.synapse_transport.name = org.apache.synapse.transport
logger.synapse_transport.level = INFO
logger.axis2.name = org.apache.axis2
logger.axis2.level = INFO
logger.axis2_transport.name = org.apache.axis2.transport
logger.axis2_transport.level = INFO
logger.hunsicker.name = de.hunsicker.jalopy.io
logger.hunsicker.level = FATAL
logger.synapse-headers.name = org.apache.synapse.transport.http.headers
logger.synapse-headers.level = DEBUG
logger.synapse-wire.name = org.apache.synapse.transport.http.wire
logger.synapse-wire.level = DEBUG
logger.thrift-publisher.name = org.wso2.carbon.databridge.agent.thrift.AsyncDataPublisher
logger.thrift-publisher.level = WARN
logger.service_logger.name = SERVICE_LOGGER
logger.service_logger.level = INFO
logger.service_logger.additivity = false
logger.service_logger.appenderRef.SERVICE_APPENDER.ref = SERVICE_APPENDER
logger.wso2-callhome.name = org.wso2.callhome
logger.wso2-callhome.level = INFO
logger.trace_logger.name = TRACE_LOGGER
logger.trace_logger.level = INFO
logger.trace_logger.appenderRef.TRACE_APPENDER.ref = TRACE_APPENDER
# root loggers
rootLogger.level = ERROR
rootLogger.appenderRef.CARBON_CONSOLE.ref = CARBON_CONSOLE
rootLogger.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE
rootLogger.appenderRef.ERROR_LOGFILE.ref = ERROR_LOGFILE
rootLogger.appenderRef.PaxOsgi.ref = PaxOsgi
#rootLogger.appenderReg.CARBON_SYS_LOG.ref = CARBON_SYS_LOG
#rootLogger.appenderRef.syslog.ref = syslog
# bot detection feature appender
appender.BOTDATA_APPENDER.type = RollingFile
appender.BOTDATA_APPENDER.name = BOTDATA_APPENDER
appender.BOTDATA_APPENDER.fileName = ${sys:carbon.home}/repository/logs/wso2-BotDetectedData.log
appender.BOTDATA_APPENDER.filePattern = ${sys:carbon.home}/repository/logs/wso2-BotDetectedData-%d{MM-dd-yyyy}.log
appender.BOTDATA_APPENDER.layout.type = PatternLayout
appender.BOTDATA_APPENDER.layout.pattern = [%d] [%tenantId] %5p {%c} - %m%ex%n
appender.BOTDATA_APPENDER.policies.type = Policies
appender.BOTDATA_APPENDER.policies.time.type = TimeBasedTriggeringPolicy
appender.BOTDATA_APPENDER.policies.time.interval = 1
appender.BOTDATA_APPENDER.policies.time.modulate = true
appender.BOTDATA_APPENDER.policies.size.type = SizeBasedTriggeringPolicy
appender.BOTDATA_APPENDER.policies.size.size = 10MB
appender.BOTDATA_APPENDER.strategy.type = DefaultRolloverStrategy
appender.BOTDATA_APPENDER.strategy.max = 20
logger.org-wso2-carbon-apimgt-gateway-mediators-BotDetectionMediator.name = org.wso2.carbon.apimgt.gateway.mediators.BotDetectionMediator
logger.org-wso2-carbon-apimgt-gateway-mediators-BotDetectionMediator.level = INFO
logger.org-wso2-carbon-apimgt-gateway-mediators-BotDetectionMediator.appenderRef.BOTDATA_APPENDER.ref = BOTDATA_APPENDER
logger.org-wso2-carbon-apimgt-gateway-mediators-BotDetectionMediator.additivity = false
category.SERVICE_APPENDER._OpenService_ = TRACE_APPENDER, BOTDATA_APPENDER

View File

@ -0,0 +1,175 @@
ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ
Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой)
версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего
Правообладателю Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН
7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова,
д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу
https://www.emdev.ru/about (далее - Компания).
Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями»
(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения,
Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в
настоящем документе, в противном случае, он должен не использовать или не получать доступ
к Программному обеспечению.
1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ
a) ПО Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии
или редакции, исключительные права на которую принадлежат Правообладателю.
b) Правообладатель (Компания) ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные
права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ
для ЭВМ № 2021610848 от 19.01.2021 года.
c) Пользователь юридическое или физическое лицо, получившее через скачивание с сайта
https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО.
d) ИС интеллектуальная собственность закреплённое законом исключительное право, а также
личные неимущественные права авторов произведений на результат интеллектуальной деятельности.
e) Подписка это коммерческое предложение Правообладателя, состоящее из Лицензии на использование
ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка
включает предоставление Пользователю неисключительного права использования ПО, в том числе
получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение
патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается
Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается
для каждого Пользователя индивидуально в Сертификате.
f) Сертификат документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром),
подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное
обеспечение в ограниченном объёме и на определённый период времени.
g) Лицензия (простая (неисключительная) совокупность ограниченных прав использования ПО,
предоставленных Пользователю согласно условиям Подписки.
h) Библиотека совокупность подпрограмм и объектов, используемых для разработки программного
обеспечения.
i) Исходный код текст компьютерной программы на каком-либо языке программирования, состоящий
из одного или нескольких файлов, который может быть прочтён человеком.
j) Объектный код файл (часть машинного кода) с промежуточным представлением отдельного модуля
программы, полученный в результате обработки исходного кода, еще не связанный в полную программу.
Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый
продукт.
k) Некоммерческое использование индивидуальное личное использование Пользователем программного
обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации
возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая
выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения.
2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ
2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного
обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом
воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения
в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ.
2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит
неисключительный характер.
2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию,
лицензия на ограниченное использование Программного обеспечения.
2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования
имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан
обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения
вида лицензии с Базовой бесплатной версии на Подписки.
2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для
пробного использования программного обеспечения не ограничен.
2.6. Использование Пользователем настоящего программного обеспечения в целях разработки,
модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю,
без разрешения Правообладателя не допускается.
3. АВТОРСКОЕ ПРАВО.
3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение
и любые его копии принадлежат Правообладателю.
3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента,
к которому можно получить доступ с помощью Программного обеспечения, является собственностью
соответствующего владельца контента и защищается применимым законодательством об авторском
праве или другими законами и договорами об интеллектуальной собственности.
3.3. Условия использования Программного обеспечения.
Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь
придерживается следующих условий:
3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять
какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании
Программного обеспечения или на нем.
3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать,
расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать
Программное обеспечение.
3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования
ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне.
3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено
использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам.
4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС»
4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю
на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с
использованием Пользователем:
4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в
Программное обеспечение;
4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями
настоящего соглашения;
4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием,
или данными, не предоставленными Пользователю Правообладателем;
4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем.
5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ
ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ
И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ
ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ
И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ
ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО.
6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ.
НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ
ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ,
ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ;
ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ.
ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ
ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ;
КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ
ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ.
7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ:
Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия
(включая, но не ограничиваясь) по:
-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код)
Программного обеспечения;
-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный
код Программного обеспечения, за исключением тех изменений, которые вносятся средствами,
включёнными в Программное обеспечение и описанными непосредственно в документации к нему;
-созданию условий для использования Программного обеспечения лицами, не имеющими прав на
использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство
третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа
к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку;
-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию).
8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА.
8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из
лицензионных продуктов, используемых на законных основаниях, а
именно https://entaxy.ru/libs/licenses/root-aggregated.deps.
8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть
совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения.
8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться
Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения,
содержащих все изменения и дополнения программного обеспечения.
9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ.
9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым
программным обеспечением.
9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно
с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм
«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public.
9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий
пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя,
прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер
ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства
Российской Федерации.
10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ.
10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет
право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб,
недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий
пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере
2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения
исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy).
10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое
законодательство Российской Федерации.
10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным,
остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать
исполнять свои обязанности в соответствии с этими положениями.

View File

@ -0,0 +1,48 @@
# Настройка логгирования в entaxy
Нужен артефакт cef-logger-layout версии __1.0.1__.
Его требуется любым доступным способом задеплоить
в karaf/entaxy.
## Настройка лог-файла
В файл `<karaf-root>/etc/org.ops4j.pax.logging.cfg` необходимо добавить:
```
# CEF logger
log4j2.logger.AUDIT_FILE.name = AUDIT_LOGFILE
log4j2.logger.AUDIT_FILE.level = INFO
log4j2.logger.AUDIT_FILE.appenderRef.AUDIT_LOGFILE.ref = AuditCompositeLogger
log4j2.logger.AUDIT_FILE.additivity = false
log4j2.appender.AUDIT_LOGFILE.type = CEFAggregate
log4j2.appender.AUDIT_LOGFILE.name = AuditCompositeLogger
log4j2.appender.AUDIT_LOGFILE.children = CefFile
log4j2.appender.AUDIT_LOGFILE.filter.threshold.type = ThresholdFilter
log4j2.appender.AUDIT_LOGFILE.filter.threshold.level = INFO
log4j2.appender.AUDIT_LOGFILE_1.type = RollingRandomAccessFile
log4j2.appender.AUDIT_LOGFILE_1.name = CefFile
log4j2.appender.AUDIT_LOGFILE_1.append = true
log4j2.appender.AUDIT_LOGFILE_1.fileName = ${karaf.log}/cef-audit.log
log4j2.appender.AUDIT_LOGFILE_1.filePattern = ${karaf.log}/cef-audit-%d{MM-dd-yyyy}.log
log4j2.appender.AUDIT_LOGFILE_1.layout.type = CEFLayout
log4j2.appender.AUDIT_LOGFILE_1.layout.vendor = EMDEV
log4j2.appender.AUDIT_LOGFILE_1.layout.product = ENTAXY
log4j2.appender.AUDIT_LOGFILE_1.layout.productVersion = 1.1.10-SNAPSHOT
log4j2.appender.AUDIT_LOGFILE_1.policies.type = Policies
log4j2.appender.AUDIT_LOGFILE_1.policies.size.type = SizeBasedTriggeringPolicy
log4j2.appender.AUDIT_LOGFILE_1.policies.size.size = 10MB
log4j2.appender.AUDIT_LOGFILE_1.filter.threshold.type = ThresholdFilter
log4j2.appender.AUDIT_LOGFILE_1.filter.threshold.level = INFO
```
Здесь используется композитный логгер, так что при необходимости
можно добавить вывод в консоль в cef или json формате
по образцу того, как было сделано в wso2.
Логгируется:
- Вход/выход в hawtio
- Все команды JAAS в karaf
- Изменения бандлов и конфигурации в karaf.

View File

@ -0,0 +1,10 @@
# Установка
- Установите или просто скопируйте в deploy файл `cef-logger-layout-1.0.1.jar`
- Установите бандл `entaxy-audit-logging-1.0.1.jar` (`bundle:install mvn:ru.entaxy/entaxy-audit-logging/1.0.1`) и
запустите его (bundle:start <bundleid>)
- Замените файл `<entaxy-root>/system/io/hawt/hawtio-osgi/2.14.1/hawtio-osgi-2.14.1.war` на одноименный из сборки
с зависимостью от `entaxy-audit-logging` (лучше сразу подготовить сборку с ним - он включается в WEB-INF/lib)
Сконфигурируйте логгирование как описано в файле
`Logging-config.md` в этом репозитории.

View File

@ -0,0 +1,88 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>ru.entaxy.platform</groupId>
<artifactId>logging</artifactId>
<version>1.10.0</version>
</parent>
<groupId>ru.entaxy.platform.logging</groupId>
<artifactId>entaxy-audit</artifactId>
<packaging>bundle</packaging>
<name>ENTAXY :: LOGGING :: AUDIT</name>
<description>ENTAXY :: LOGGING :: AUDIT</description>
<properties>
<bundle.osgi.export.pkg>
ru.entaxy.audit*
</bundle.osgi.export.pkg>
</properties>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.eventadmin</artifactId>
<version>1.5.0</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<version>${osgi.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-Activator>ru.entaxy.audit.service.osgi.Activator</Bundle-Activator>
<DynamicImport-Package>*</DynamicImport-Package>
<Include-Resource>${project.build.directory}/classes/</Include-Resource>
</instructions>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>bundle</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,5 @@
<!-- -->
<configfile finalname="etc/ru.entaxy.audit.interpreter.jmx.cfg" override="true">
mvn:ru.entaxy.platform.logging/entaxy-audit/1.10.0/cfg/ru.entaxy.audit.interpreter.jmx
</configfile>
<!-- -->

View File

@ -0,0 +1,27 @@
###
# ~~~~~~licensing~~~~~~
# entaxy-audit
# ==========
# Copyright (C) 2020 - 2024 EmDev LLC
# ==========
# You may not use this file except in accordance with the License Terms of the Copyright
# Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
# rights to the Software and any copies are the property of the Copyright Holder. Unless
# it is explicitly allowed the Copyright Holder, the User is prohibited from using the
# Software for commercial purposes to provide services to third parties.
#
# The Copyright Holder hereby declares that the Software is provided on an "AS IS".
# Under no circumstances does the Copyright Holder guarantee or promise that the
# Software provided by him will be suitable or not suitable for the specific purposes
# of the User, that the Software will meet all commercial and personal subjective
# expectations of the User, that the Software will work properly, without technical
# errors, quickly and uninterruptedly.
#
# Under no circumstances shall the Copyright Holder or its Affiliates is not liable
# to the User for any direct or indirect losses of the User, his expenses or actual
# damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
# or damage to data, property, etc.
# ~~~~~~/licensing~~~~~~
###
topics.ignore=GETATTRIBUTE,GETMBEANINFO
topics.process=INVOKE

View File

@ -0,0 +1,31 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.data;
public enum Actions {
LOGIN,
LOGOUT
}

View File

@ -0,0 +1,147 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.data;
import ru.entaxy.audit.utils.AuditHelper;
public class AuditEvent {
private final String target;
private final String category;
private final String suser;
private final String duser;
private final String message;
private final Outcome outcome;
private final Severity severity;
private final String src;
public AuditEvent(String target, String category, String suser,
String duser, String message, Outcome outcome,
Severity severity, String src) {
this.target = target;
this.category = category;
this.suser = suser;
this.duser = duser;
this.message = message;
this.outcome = outcome;
this.severity = severity;
this.src = src;
}
public String getTarget() {
return target;
}
public String getCategory() {
return category;
}
public String getSuser() {
return suser;
}
public String getDuser() {
return duser;
}
public String getMessage() {
return message;
}
public Outcome getOutcome() {
return outcome;
}
public Severity getSeverity() {
return severity;
}
public String getSrc() {
return src;
}
public static class AuditLoggingEventBuilder {
private String target = AuditHelper.DEFAULT_TARGET;
private String category;
private String suser;
private String duser;
private String message;
private String src;
private Outcome outcome = Outcome.SUCCESS;
private Severity severity = AuditHelper.DEFAULT_SEVERITY;
public static AuditLoggingEventBuilder getInstance() {
return new AuditLoggingEventBuilder();
}
public AuditLoggingEventBuilder target(String target) {
this.target = target;
return this;
}
public AuditLoggingEventBuilder category(String category) {
this.category = category;
return this;
}
public AuditLoggingEventBuilder suser(String suser) {
this.suser = suser;
return this;
}
public AuditLoggingEventBuilder duser(String duser) {
this.duser = duser;
return this;
}
public AuditLoggingEventBuilder message(String message) {
this.message = message;
return this;
}
public AuditLoggingEventBuilder outcome(Outcome outcome) {
this.outcome = outcome;
return this;
}
public AuditLoggingEventBuilder severity(Severity severity) {
this.severity = severity;
return this;
}
public AuditLoggingEventBuilder src(String src) {
this.src = src;
return this;
}
public AuditEvent build() {
return new AuditEvent(target, category, suser, duser,
message, outcome, severity, src);
}
}
}

View File

@ -0,0 +1,39 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.data;
public enum Outcome {
SUCCESS("Success"), FAILURE("Failed");
private final String label;
Outcome(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
}

View File

@ -0,0 +1,40 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.data;
public enum Severity {
INFO(3), WARNING(8), IMPORTANT(6);
private final int value;
Severity(int i) {
this.value = i;
}
public int getValue() {
return value;
}
}

View File

@ -0,0 +1,53 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.service;
import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;
import org.osgi.service.event.Event;
import ru.entaxy.audit.data.AuditEvent;
import ru.entaxy.audit.data.Outcome;
public interface AuditService {
void onAudit(AuditEvent record);
void onLogin(String username, HttpServletRequest request, Outcome outcome);
void onLogout(String username, HttpServletRequest request);
void onOSGIEvent(Event event);
void onFileChange(Event event);
boolean interpret(Event event);
void setRequestAndSubject(Subject subject, HttpServletRequest request);
void setRequestAndUser(String user, HttpServletRequest request);
}

View File

@ -0,0 +1,38 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.service;
import ru.entaxy.audit.service.impl.AuditServiceImpl;
public class AuditServiceFactory {
private static final AuditServiceImpl INSTANCE = new AuditServiceImpl();
public static AuditService getAuditService() {
return INSTANCE;
}
}

View File

@ -0,0 +1,41 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.service;
import ru.entaxy.audit.data.AuditEvent;
public interface EventConverter {
default Class<? extends InterpretedEvent>[] getAllowedClasses() {
if (getClass().isAnnotationPresent(EventConverterInfo.class)) {
return getClass().getAnnotation(EventConverterInfo.class).classes();
}
return new Class[] {};
};
<T extends InterpretedEvent> AuditEvent convert(T event);
}

View File

@ -0,0 +1,40 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.service;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target(TYPE)
public @interface EventConverterInfo {
Class<? extends InterpretedEvent>[] classes();
}

View File

@ -0,0 +1,34 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.service;
import org.osgi.service.event.Event;
public interface EventInterpreter {
InterpretedEvent interpret(Event origin);
}

View File

@ -0,0 +1,43 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.service;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;
import ru.entaxy.audit.service.filter.EventRouter;
public class EventSubscriber implements EventHandler {
private final EventRouter eventRouter;
public EventSubscriber(EventRouter eventRouter) {
this.eventRouter = eventRouter;
}
@Override
public void handleEvent(Event event) {
eventRouter.consumeEvent(event);
}
}

View File

@ -0,0 +1,56 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.service;
import java.util.HashMap;
import java.util.Map;
import org.osgi.service.event.Event;
public class InterpretedEvent {
public enum EventResolution {
IGNORE,
PROCESS,
NONE
}
public Event originalEvent;
public EventResolution resolution = EventResolution.NONE;
protected Map<String, Object> eventEssense = new HashMap<>();
public InterpretedEvent(Event origin) {
this.originalEvent = origin;
eventEssense.put("event.topic", origin.getTopic());
}
public Map<String, Object> getEventEssense() {
return eventEssense;
}
}

View File

@ -0,0 +1,108 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.service.filter;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicLong;
import org.osgi.service.event.Event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.audit.service.AuditService;
public class EventRouter {
private final Queue<Event> events = new LinkedBlockingQueue<>(10_000);
private final AtomicLong counter = new AtomicLong(0);
private final AtomicLong consumed = new AtomicLong(0);
private final AtomicLong rejected = new AtomicLong(0);
private final ExecutorService executor = Executors.newFixedThreadPool(3,
(r) -> new Thread(r, "audit-logger-helper-thread #" + counter.getAndIncrement()));
private final AuditService auditService;
private static final Logger LOGGER = LoggerFactory.getLogger(EventRouter.class);
public EventRouter(AuditService service) {
this.auditService = service;
}
private boolean processEvent(Event event) {
if (event == null) {
return false;
}
if (event.getTopic().contains("EXECUTED") && event.getProperty("command") != null) {
auditService.onOSGIEvent(event);
return true;
} else {
// if it's a log event
if (event.getTopic().startsWith("org/osgi/service/log")) {
String bundleSymbolicName = (String) event.getProperty("bundle.symbolicname");
// if it's configuration update event
if (bundleSymbolicName != null && "org.apache.felix.fileinstall".equals(bundleSymbolicName)) {
Object message = event.getProperty("message");
if (message instanceof String) {
String messageText = (String) message;
if (messageText.contains("Updating")) {
auditService.onFileChange(event);
return true;
}
}
}
} else {
return auditService.interpret(event);
}
}
return false;
}
public String stats() {
return String.format("Consumed: %d, rejected: %d", consumed.get(), rejected.get());
}
public void consumeEvent(Event event) {
boolean added = events.offer(event);
if (added) {
executor.submit(() -> {
Event evt = events.poll();
if (processEvent(evt)) {
consumed.incrementAndGet();
} else {
rejected.incrementAndGet();
}
});
} else {
LOGGER.warn("Cannot consume event {}, queue is probably full", event);
}
}
public void stop() {
executor.shutdown();
events.clear();
}
}

View File

@ -0,0 +1,62 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.service.hawtio;
import org.osgi.service.component.annotations.Component;
import ru.entaxy.audit.data.AuditEvent;
import ru.entaxy.audit.data.Outcome;
import ru.entaxy.audit.data.Severity;
import ru.entaxy.audit.service.EventConverter;
import ru.entaxy.audit.service.EventConverterInfo;
import ru.entaxy.audit.service.InterpretedEvent;
@Component(service = EventConverter.class, immediate = true)
@EventConverterInfo(classes = {HawtioInterpretedEvent.class})
public class HawtioEventConverter implements EventConverter {
@Override
public <T extends InterpretedEvent> AuditEvent convert(T event) {
if (!(event instanceof HawtioInterpretedEvent))
return null;
HawtioInterpretedEvent hawtioEvent = (HawtioInterpretedEvent) event;
AuditEvent result = AuditEvent.AuditLoggingEventBuilder.getInstance()
.target("auth")
.outcome(hawtioEvent.isSuccessful ? Outcome.SUCCESS : Outcome.FAILURE)
.message(String.format("%s", hawtioEvent.getMessage()))
.severity(Severity.IMPORTANT)
.category(hawtioEvent.getAction())
.suser(hawtioEvent.getUser())
.src(hawtioEvent.getSrc())
.build();
return result;
}
}

View File

@ -0,0 +1,50 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.service.hawtio;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.event.Event;
import ru.entaxy.audit.service.EventInterpreter;
import ru.entaxy.audit.service.InterpretedEvent;
@Component(service = EventInterpreter.class, immediate = true, configurationPolicy = ConfigurationPolicy.OPTIONAL)
public class HawtioEventInterpreter implements EventInterpreter {
private static final String HAWTIO_AUDIT_TOPIC = "entaxy/hawtio/audit";
@Override
public InterpretedEvent interpret(Event origin) {
if (!HAWTIO_AUDIT_TOPIC.equals(origin.getTopic()))
return null;
return new HawtioInterpretedEvent(origin);
}
}

View File

@ -0,0 +1,74 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.service.hawtio;
import org.osgi.service.event.Event;
import ru.entaxy.audit.service.InterpretedEvent;
public class HawtioInterpretedEvent extends InterpretedEvent {
String action;
String message;
String user;
String src;
boolean isSuccessful;
public HawtioInterpretedEvent(Event origin) {
super(origin);
action = origin.getProperty("category").toString();
message = origin.getProperty("message").toString();
user = origin.getProperty("user").toString();
src = origin.getProperty("src").toString();
isSuccessful = (Boolean) origin.getProperty("result");
}
public String getAction() {
return action;
}
public String getMessage() {
return message;
}
public String getUser() {
return user;
}
public String getSrc() {
return src;
}
public boolean isSuccessful() {
return isSuccessful;
}
}

View File

@ -0,0 +1,143 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.service.impl;
import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;
import org.osgi.service.event.Event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.audit.data.AuditEvent;
import ru.entaxy.audit.data.Outcome;
import ru.entaxy.audit.service.AuditService;
import ru.entaxy.audit.service.InterpretedEvent;
import ru.entaxy.audit.utils.AuditHelper;
public class AuditServiceImpl implements AuditService {
private static final Logger LOG = LoggerFactory.getLogger(AuditServiceImpl.class);
private final WebLoginModule webLoginModule = new WebLoginModule();
private final OSGIEventModule osgiEventModule = new OSGIEventModule();
@Override
public void onAudit(AuditEvent record) {
throw new RuntimeException("Not implemented");
}
@Override
public void onLogin(String username, HttpServletRequest request, Outcome outcome) {
webLoginModule.onLogin(username, request, outcome);
}
@Override
public void onLogout(String username, HttpServletRequest request) {
webLoginModule.onLogout(username, request);
}
@Override
public void onOSGIEvent(Event event) {
osgiEventModule.onEvent(event);
}
@Override
public void onFileChange(Event event) {
osgiEventModule.onFileChange(event);
}
@Override
public boolean interpret(Event event) {
if (InterpreterService.INSTANCE == null)
return false;
InterpretedEvent result = InterpreterService.INSTANCE.interpret(event);
if (result == null) {
if (LOG.isTraceEnabled())
LOG.trace("Event from topic [{}] not interpreted", event.getTopic());
return false;
}
if (result.resolution.equals(InterpretedEvent.EventResolution.IGNORE)) {
if (LOG.isTraceEnabled())
LOG.trace("Event from topic [{}] IGNORED; interpreted as [{}] -> [{}]", event.getTopic(),
result.getClass().getName());
return false;
}
if (ConverterService.INSTANCE == null)
return false;
AuditEvent convertedEvent = ConverterService.INSTANCE.convert(result);
if (convertedEvent == null) {
if (LOG.isDebugEnabled())
LOG.debug("NOT CONVERTED: Event from topic [{}] interpreted as [{}]", event.getTopic(),
result.getClass().getName());
return false;
}
Subject subject = (Subject) event.getProperty("subject");
boolean processed = false;
String suser = "local";
String address = "localhost";
if (subject != null) {
suser = AuditHelper.findRemoteUser(subject);
address = AuditHelper.findAddress(subject);
}
AuditEvent auditEvent = AuditEvent.AuditLoggingEventBuilder.getInstance()
.category(convertedEvent.getCategory())
.duser(convertedEvent.getDuser())
.message(convertedEvent.getMessage())
.outcome(convertedEvent.getOutcome())
.severity(convertedEvent.getSeverity())
.src(convertedEvent.getSrc() != null ? convertedEvent.getSrc() : address)
.suser(convertedEvent.getSuser() != null ? convertedEvent.getSuser() : suser)
.target(convertedEvent.getTarget())
.build();
AuditHelper.log(auditEvent);
processed = true;
return processed;
}
@Override
public void setRequestAndSubject(Subject subject, HttpServletRequest request) {
webLoginModule.setMDC(subject, request);
}
@Override
public void setRequestAndUser(String user, HttpServletRequest request) {
webLoginModule.setMDC(user, request);
}
}

View File

@ -0,0 +1,101 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.service.impl;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;
import ru.entaxy.audit.data.AuditEvent;
import ru.entaxy.audit.service.EventConverter;
import ru.entaxy.audit.service.InterpretedEvent;
@Component(service = ConverterService.class, immediate = true)
public class ConverterService {
static public ConverterService INSTANCE = null;
protected Map<Class<? extends InterpretedEvent>, Set<EventConverter>> converters = new HashMap<>();
protected Object convertersLock = new Object();
@Activate
public void activate() {
INSTANCE = this;
}
@Deactivate
public void deactivate() {
INSTANCE = null;
}
@Reference(cardinality = ReferenceCardinality.MULTIPLE, policyOption = ReferencePolicyOption.GREEDY,
policy = ReferencePolicy.DYNAMIC, unbind = "removeConverter")
public void addInterpreter(EventConverter converter) {
synchronized (convertersLock) {
for (Class<? extends InterpretedEvent> clazz : converter.getAllowedClasses()) {
this.converters.putIfAbsent(clazz, new HashSet<>());
this.converters.get(clazz).add(converter);
}
}
}
public void removeConverter(EventConverter converter) {
synchronized (convertersLock) {
for (Class<? extends InterpretedEvent> clazz : converter.getAllowedClasses()) {
if (converters.containsKey(clazz))
converters.get(clazz).remove(converter);
}
}
}
public <T extends InterpretedEvent> AuditEvent convert(T event) {
AuditEvent result = null;
if (converters.containsKey(event.getClass())) {
for (EventConverter converter : converters.get(event.getClass())) {
try {
result = converter.convert(event);
} catch (Exception ignore) {
// NOOP
}
if (result != null)
break;
}
}
return result;
}
}

View File

@ -0,0 +1,91 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;
import org.osgi.service.event.Event;
import ru.entaxy.audit.service.EventInterpreter;
import ru.entaxy.audit.service.InterpretedEvent;
@Component(service = InterpreterService.class, immediate = true)
public class InterpreterService {
static public InterpreterService INSTANCE = null;
protected List<EventInterpreter> interpreters = new ArrayList<>();
protected Object interpretersLock = new Object();
@Activate
public void activate() {
INSTANCE = this;
}
@Deactivate
public void deactivate() {
INSTANCE = null;
}
@Reference(cardinality = ReferenceCardinality.MULTIPLE, policyOption = ReferencePolicyOption.GREEDY,
policy = ReferencePolicy.DYNAMIC, unbind = "removeInterpreter")
public void addInterpreter(EventInterpreter interpreter) {
synchronized (interpretersLock) {
if (!interpreters.contains(interpreter))
interpreters.add(interpreter);
}
}
public void removeInterpreter(EventInterpreter interpreter) {
synchronized (interpretersLock) {
interpreters.remove(interpreter);
}
}
public InterpretedEvent interpret(Event event) {
InterpretedEvent result = null;
for (EventInterpreter interpreter : interpreters) {
try {
result = interpreter.interpret(event);
} catch (Exception ignore) {
// NOOP
}
if (result != null)
break;
}
return result;
}
}

View File

@ -0,0 +1,117 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.service.impl;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.security.auth.Subject;
import org.osgi.service.event.Event;
import ru.entaxy.audit.data.AuditEvent;
import ru.entaxy.audit.data.Severity;
import ru.entaxy.audit.utils.AuditHelper;
import ru.entaxy.audit.utils.CommandWeight;
public class OSGIEventModule {
private Map<String, LongAdder> processedCommands = new ConcurrentHashMap<>();
private Map<String, LongAdder> skippedCommands = new ConcurrentHashMap<>();
private final Set<String> targets = new HashSet<String>() {{
add("jaas");
}};
private final static Pattern COMMAND_PATTERN = Pattern.compile("^(.+):([A-Za-z-]+)\\s?+(.+)?$");
private final static Pattern FILE_PATTERN = Pattern.compile("^Updating ([a-zA-Z]+)\\s+(from)?\\s?(.+)$");
public void onEvent(Event event) {
String command = (String) event.getProperty("command");
if (command == null) {
return;
}
Subject subject = (Subject) event.getProperty("subject");
boolean processed = false;
Matcher m = checkCommand(command);
if (m != null && subject != null) {
String suser = AuditHelper.findRemoteUser(subject);
String address = AuditHelper.findAddress(subject);
String target = m.group(1);
String commandName = m.group(2);
String arguments = m.group(3);
if (targets.contains(target)) {
AuditEvent auditEvent = AuditEvent.AuditLoggingEventBuilder.getInstance()
.target(target)
.suser(suser)
.src(address)
.category(commandName)
.severity(CommandWeight.getByTarget(target))
.message(arguments == null ? "" : arguments).build();
AuditHelper.log(auditEvent);
processed = true;
}
}
Map<String, LongAdder> target = processed ? processedCommands : skippedCommands;
target.computeIfAbsent(command, (s) -> new LongAdder()).increment();
}
private Matcher checkCommand(String command) {
Matcher m = COMMAND_PATTERN.matcher(command);
if (m.find()) {
return m;
}
return null;
}
public void onFileChange(Event event) {
String message = (String) event.getProperty("message");
Matcher m = FILE_PATTERN.matcher(message);
if (m.find()) {
String filename = m.group(3);
String changeSubject = m.group(1);
String target = "Update " + changeSubject;
if (changeSubject.equals("bundle") || changeSubject.equals("configuration")) {
AuditEvent auditEvent = AuditEvent.AuditLoggingEventBuilder.getInstance()
.target(target)
.suser("local")
.src("localhost")
.category(filename)
.severity(Severity.WARNING)
.message(message).build();
AuditHelper.log(auditEvent);
processedCommands.computeIfAbsent(target, (s) -> new LongAdder()).increment();
}
skippedCommands.computeIfAbsent(target, (s) -> new LongAdder()).increment();
}
}
}

View File

@ -0,0 +1,93 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.service.impl;
import org.slf4j.MDC;
import ru.entaxy.audit.data.AuditEvent;
import ru.entaxy.audit.utils.AuditHelper;
import ru.entaxy.audit.utils.Constants;
import ru.entaxy.audit.data.Outcome;
import ru.entaxy.audit.data.Severity;
import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class WebLoginModule {
public void onLogin(String username, HttpServletRequest request, Outcome outcome) {
String remoteAddress = requestRemoteAddress(request);
AuditEvent event = AuditEvent.AuditLoggingEventBuilder.getInstance()
.suser(username)
.outcome(outcome)
.severity(outcome == Outcome.SUCCESS ? Severity.INFO : Severity.WARNING)
.src(remoteAddress)
.category(outcome == Outcome.SUCCESS ? "Login success" : "Login failed")
.target("auth")
.build();
AuditHelper.log(event);
}
public void onLogout(String username, HttpServletRequest request) {
String remoteAddress = requestRemoteAddress(request);
AuditEvent event = AuditEvent.AuditLoggingEventBuilder.getInstance()
.suser(username)
.outcome(Outcome.SUCCESS)
.severity(Severity.INFO)
.src(remoteAddress)
.category("Logout")
.target("auth")
.build();
AuditHelper.log(event);
}
private static String requestRemoteAddress(HttpServletRequest request) {
return Optional.ofNullable(request.getHeader(Constants.X_FORWARDER_FOR))
.orElse(request.getRemoteHost());
}
public void setMDC(Subject subject, HttpServletRequest request) {
String remoteUser = AuditHelper.findRemoteUser(subject);
saveMDC(remoteUser, request);
}
public void setMDC(String username, HttpServletRequest request) {
saveMDC(username, request);
}
private void saveMDC(String username, HttpServletRequest request) {
Map<String, String> contextMap = MDC.getCopyOfContextMap();
if (contextMap == null) {
contextMap = new HashMap<>();
}
contextMap.put(Constants.HTTP_REQUEST_USER, username);
contextMap.put(Constants.HTTP_REQUEST_REMOTE_IP, requestRemoteAddress(request));
contextMap.put(Constants.HTTP_REQUEST_SERVER_IP, request.getServerName());
MDC.setContextMap(contextMap);
}
}

View File

@ -0,0 +1,140 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.service.jmx;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Modified;
import org.osgi.service.event.Event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.audit.service.EventInterpreter;
import ru.entaxy.audit.service.InterpretedEvent;
import ru.entaxy.audit.service.InterpretedEvent.EventResolution;
@Component(service = EventInterpreter.class, immediate = true, configurationPid = "ru.entaxy.audit.interpreter.jmx",
configurationPolicy = ConfigurationPolicy.OPTIONAL)
public class JMXEventInterpreter implements EventInterpreter {
private static final Logger LOG = LoggerFactory.getLogger(JMXEventInterpreter.class);
public static final String JMX_AUDIT_TOPIC_PREFIX = "javax/management/MBeanServer";
public static final String JMX_AUDIT_INVOKE_SUBTOPIC = "INVOKE";
protected static final String PROP_IGNORE_TOPICS = "topics.ignore";
protected static final String PROP_PROCESS_TOPICS = "topics.process";
protected List<String> topicsToIgnore = new ArrayList<>();
protected List<String> topicsToProcess = new ArrayList<>();
@Activate
public void activate(Map<String, Object> properties) {
parseProperties(properties);
}
@Modified
public void modified(Map<String, Object> properties) {
parseProperties(properties);
}
protected void parseProperties(Map<String, Object> properties) {
if (properties == null)
return;
if (LOG.isDebugEnabled())
LOG.debug("\n CONFIGURATION :: \n " + properties.toString());
if (properties.containsKey(PROP_IGNORE_TOPICS)) {
String ignoreTopics = (String) properties.get(PROP_IGNORE_TOPICS);
if (ignoreTopics == null)
topicsToIgnore = new ArrayList<>();
else {
topicsToIgnore = Arrays.asList(ignoreTopics.split(","));
}
} else {
topicsToIgnore = new ArrayList<>();
}
if (properties.containsKey(PROP_PROCESS_TOPICS)) {
String processTopics = (String) properties.get(PROP_PROCESS_TOPICS);
if (processTopics == null)
topicsToProcess = new ArrayList<>();
else {
topicsToProcess = Arrays.asList(processTopics.split(","));
}
} else {
topicsToProcess = new ArrayList<>();
}
}
@Override
public InterpretedEvent interpret(Event origin) {
if (!origin.getTopic().startsWith(JMX_AUDIT_TOPIC_PREFIX))
return null;
JMXInterpretedEvent result;
String subtopic = origin.getTopic().substring(JMX_AUDIT_TOPIC_PREFIX.length() + 1);
if (subtopic.startsWith(JMX_AUDIT_INVOKE_SUBTOPIC))
result = new JMXInvokeEvent(origin);
else
result = new JMXInterpretedEvent(origin);
result.subtopic = subtopic;
result.resolution = EventResolution.IGNORE;
if (!topicsToProcess.isEmpty()) {
for (String process : topicsToProcess)
if (result.subtopic.startsWith(process)) {
result.resolution = EventResolution.PROCESS;
break;
}
} else {
result.resolution = EventResolution.PROCESS;
}
for (String ignore : topicsToIgnore)
if (result.subtopic.startsWith(ignore)) {
result.resolution = EventResolution.IGNORE;
break;
}
return result;
}
}

View File

@ -0,0 +1,56 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.service.jmx;
import org.osgi.service.event.Event;
import ru.entaxy.audit.service.InterpretedEvent;
public class JMXInterpretedEvent extends InterpretedEvent {
protected String subtopic = null;
public JMXInterpretedEvent(Event origin) {
super(origin);
this.eventEssense.put("event.source", "jmx");
}
public JMXInterpretedEvent subtopic(String value) {
setSubtopic(value);
return this;
}
public String getSubtopic() {
return subtopic;
}
public void setSubtopic(String subtopic) {
this.subtopic = subtopic;
this.eventEssense.put("event.subtopic", this.subtopic);
}
}

View File

@ -0,0 +1,104 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.service.jmx;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import javax.management.ObjectName;
import org.osgi.service.event.Event;
public class JMXInvokeEvent extends JMXInterpretedEvent {
public static final String PROP_PARAMS = "params";
protected ObjectName objectName;
protected String methodName;
protected Object[] methodParams;
protected Map<String, Object> objectNameData = new HashMap<>();
public JMXInvokeEvent(Event origin) {
super(origin);
if (this.originalEvent.containsProperty(PROP_PARAMS)) {
Object[] data = (Object[]) this.originalEvent.getProperty(PROP_PARAMS);
setObjectName((ObjectName) data[0]);
setMethodName((String) data[1]);
setMethodParams((Object[]) data[2]);
}
}
protected void parseObjectName() {
this.objectNameData.clear();
this.objectNameData.put("jmx.domain", this.objectName.getDomain());
Hashtable<String, String> properties = this.objectName.getKeyPropertyList();
for (Map.Entry<String, String> entry : properties.entrySet()) {
this.objectNameData.put("jmx.property." + entry.getKey(), entry.getValue());
}
}
public ObjectName getObjectName() {
return objectName;
}
public void setObjectName(ObjectName objectName) {
this.objectName = objectName;
parseObjectName();
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
this.eventEssense.put("jmx.methodName", methodName);
}
public Object[] getMethodParams() {
return methodParams;
}
public void setMethodParams(Object[] methodParams) {
this.methodParams = methodParams;
}
@Override
public Map<String, Object> getEventEssense() {
Map<String, Object> result = new HashMap<>(super.getEventEssense());
result.putAll(this.objectNameData);
return result;
}
}

View File

@ -0,0 +1,115 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.service.osgi;
import java.util.Dictionary;
import java.util.Hashtable;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import ru.entaxy.audit.service.AuditService;
import ru.entaxy.audit.service.AuditServiceFactory;
import ru.entaxy.audit.service.EventSubscriber;
import ru.entaxy.audit.service.filter.EventRouter;
import ru.entaxy.audit.service.impl.AuditServiceImpl;
public class Activator implements BundleActivator {
private static final String LOGS_TOPIC = "org/osgi/service/*";
private static final String COMMANDS_TOPIC = "org/apache/karaf/shell/console/*";
private static final String JMX_AUDIT_TOPIC = "javax/management/MBeanServer/*";
private static final String HAWTIO_AUDIT_TOPIC = "entaxy/hawtio/audit";
private ServiceRegistration<?> listenerRegistration = null;
private ServiceRegistration<?> serviceRegistration = null;
private ServiceRegistration<?> commandRegistration = null;
private ServiceRegistration<?> jmxRegistration = null;
private ServiceRegistration<?> hawtioRegistration = null;
private ServiceRegistration<?> eventRouterRegistration = null;
private EventRouter eventRouter;
@Override
public void start(BundleContext bundleContext) throws Exception {
// System.err.println("I'm activating!");
AuditService auditService = AuditServiceFactory.getAuditService();
serviceRegistration =
bundleContext.registerService(AuditService.class.getName(), new AuditServiceImpl(), new Hashtable<>());
eventRouter = new EventRouter(auditService);
eventRouterRegistration = bundleContext.registerService(EventRouter.class, eventRouter, new Hashtable<>());
EventHandler logSubscriber = new EventSubscriber(eventRouter);
EventHandler commandsSubscriber = new EventSubscriber(eventRouter);
EventHandler jmxSubscriber = new EventSubscriber(eventRouter);
EventHandler hawtioSubscriber = new EventSubscriber(eventRouter);
Dictionary<String, Object> events = new Hashtable<>();
events.put(EventConstants.EVENT_TOPIC, LOGS_TOPIC);
listenerRegistration = bundleContext.registerService(EventHandler.class.getName(), logSubscriber, events);
Dictionary<String, Object> commandEvents = new Hashtable<>();
commandEvents.put(EventConstants.EVENT_TOPIC, COMMANDS_TOPIC);
commandRegistration =
bundleContext.registerService(EventHandler.class.getName(), commandsSubscriber, commandEvents);
Dictionary<String, Object> jmxEvents = new Hashtable<>();
jmxEvents.put(EventConstants.EVENT_TOPIC, JMX_AUDIT_TOPIC);
jmxRegistration =
bundleContext.registerService(EventHandler.class.getName(), jmxSubscriber, jmxEvents);
Dictionary<String, Object> hawtioEvents = new Hashtable<>();
hawtioEvents.put(EventConstants.EVENT_TOPIC, HAWTIO_AUDIT_TOPIC);
hawtioRegistration =
bundleContext.registerService(EventHandler.class.getName(), hawtioSubscriber, hawtioEvents);
}
@Override
public void stop(BundleContext bundleContext) throws Exception {
if (listenerRegistration != null) {
listenerRegistration.unregister();
}
if (commandRegistration != null) {
commandRegistration.unregister();
}
if (jmxRegistration != null) {
jmxRegistration.unregister();
}
if (serviceRegistration != null) {
serviceRegistration.unregister();
}
if (eventRouterRegistration != null) {
eventRouterRegistration.unregister();
}
if (eventRouter != null) {
eventRouter.stop();
}
}
}

View File

@ -0,0 +1,103 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.utils;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.audit.data.AuditEvent;
import ru.entaxy.audit.data.Severity;
import javax.security.auth.Subject;
import java.lang.reflect.Method;
import java.security.Principal;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
public class AuditHelper {
public static final String TARGET_ACTION = "action";
public static final Severity DEFAULT_SEVERITY = Severity.IMPORTANT;
public static final String DEFAULT_TARGET = TARGET_ACTION;
private static final Logger AUDIT = LoggerFactory.getLogger(Constants.LOG_FACILITY_NAME);
private static final Logger logger = LoggerFactory.getLogger(AuditHelper.class);
public static void log(AuditEvent event) {
JsonObject logRecord = new JsonObject();
logRecord.addProperty("isEmdevEvents", true);
logRecord.addProperty("typ", event.getTarget());
logRecord.addProperty("action", event.getCategory());
logRecord.addProperty("performedBy", event.getSuser());
JsonObject info = new JsonObject();
if (event.getSrc() != null) {
info.addProperty("src", event.getSrc());
}
if (event.getDuser() != null) {
info.addProperty("duser", event.getDuser());
}
info.addProperty("suser", event.getSuser());
info.addProperty("severity", event.getSeverity().getValue());
info.addProperty("msg", event.getMessage());
info.addProperty("outcome", event.getOutcome().getLabel());
logRecord.add("info", info);
AUDIT.info(logRecord.toString());
}
public static String findRemoteUser(Subject subject) {
return findAndProcessPrincipal(subject, "UserPrincipal", Principal::getName);
}
private static String findAndProcessPrincipal(Subject subject, String principalName, Function<Principal, String> mapping) {
Set<Principal> principals = subject.getPrincipals();
if (principals != null) {
Optional<String> userName = principals.stream()
.filter(p -> p.getClass().getSimpleName().startsWith(principalName)).findFirst()
.map(mapping);
return userName.orElse(null);
}
return null;
}
public static String findAddress(Subject subject) {
return findAndProcessPrincipal(subject, "ClientPrincipal", AuditHelper::getAddress);
}
private static String getAddress(Principal p) {
//We're assumiming to process Karaf's ClientPrincipal. We need method getAddress();
try {
Method m = p.getClass().getMethod("getAddress");
Object result = m.invoke(p);
return (String) result;
} catch (Throwable t) {
logger.error("Cannot get address from principal {}:", p, t);
return null;
}
}
}

View File

@ -0,0 +1,57 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.utils;
import ru.entaxy.audit.data.Severity;
public enum CommandWeight {
JAAS("jaas", Severity.IMPORTANT);
private final String target;
private final Severity severity;
CommandWeight(String target, Severity severity) {
this.target = target;
this.severity = severity;
}
public String getTarget() {
return target;
}
public Severity getSeverity() {
return severity;
}
public static Severity getByTarget(String target) {
for (CommandWeight value : values()) {
if (value.getTarget().equals(target)) {
return value.severity;
}
}
return Severity.INFO;
}
}

View File

@ -0,0 +1,38 @@
/*-
* ~~~~~~licensing~~~~~~
* entaxy-audit
* ==========
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
* rights to the Software and any copies are the property of the Copyright Holder. Unless
* it is explicitly allowed the Copyright Holder, the User is prohibited from using the
* Software for commercial purposes to provide services to third parties.
*
* The Copyright Holder hereby declares that the Software is provided on an "AS IS".
* Under no circumstances does the Copyright Holder guarantee or promise that the
* Software provided by him will be suitable or not suitable for the specific purposes
* of the User, that the Software will meet all commercial and personal subjective
* expectations of the User, that the Software will work properly, without technical
* errors, quickly and uninterruptedly.
*
* Under no circumstances shall the Copyright Holder or its Affiliates is not liable
* to the User for any direct or indirect losses of the User, his expenses or actual
* damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
* or damage to data, property, etc.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.audit.utils;
public class Constants {
public static final String X_FORWARDER_FOR = "X-Forwarder-For";
public static final String LOG_FACILITY_NAME = "AUDIT_LOGFILE";
public static final String HTTP_REQUEST_USER = "Audit-HTTP-Request-User";
public static final String HTTP_REQUEST_REMOTE_IP = "Audit-HTTP-Request-Remote-IP";
public static final String HTTP_REQUEST_SERVER_IP = "Audit-HTTP-Request-Server-IP";
private Constants() {}
}

View File

@ -0,0 +1,102 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>ru.entaxy.esb.platform.runtime</groupId>
<artifactId>base</artifactId>
<version>1.10.0</version>
</parent>
<groupId>ru.entaxy.platform</groupId>
<artifactId>logging</artifactId>
<packaging>pom</packaging>
<name>ENTAXY :: LOGGING</name>
<description>ENTAXY :: LOGGING</description>
<modules>
<module>cef-logger-layout</module>
<module>entaxy-audit</module>
</modules>
<profiles>
<profile>
<id>combine-logging-cfg</id>
<activation>
<activeByDefault>false</activeByDefault>
<file>
<exists>src/main/cfg/org.ops4j.pax.logging.cfg</exists>
</file>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-logging-from-underlying</id>
<phase>prepare-package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>ru.entaxy.esb.underlying</groupId>
<artifactId>entaxy-underlying-configuration</artifactId>
<version>${project.version}</version>
<type>cfg</type>
<classifier>org.ops4j.pax.logging</classifier>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/combine-logging</outputDirectory>
<destFileName>1.cfg</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<!--
combine org.ops4j.pax.logging from underlying with local one
-->
<execution>
<id>combine_logging_cfg</id>
<phase>prepare-package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<copy file="${project.build.directory}/attach-resources/resources/cfg/org.ops4j.pax.logging.cfg"
tofile="${project.build.directory}/combine-logging/2.cfg" />
<delete file="${project.build.directory}/attach-resources/resources/cfg/org.ops4j.pax.logging.cfg"/>
<concat destfile="${project.build.directory}/attach-resources/resources/cfg/org.ops4j.pax.logging.cfg"
force="yes">
<fileset dir="${project.build.directory}/combine-logging">
<include name="**/*.cfg"></include>
</fileset>
</concat>
<!-- copy file="${project.build.directory}/tmp/startup.properties"
tofile="${project.build.directory}/assembly/etc/startup.properties" / -->
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -0,0 +1,5 @@
<!-- -->
<configfile finalname="etc/org.ops4j.pax.logging.cfg" override="true">
mvn:ru.entaxy.platform/logging/1.10.0/cfg/org.ops4j.pax.logging
</configfile>
<!-- -->

View File

@ -0,0 +1,51 @@
###
# ~~~~~~licensing~~~~~~
# logging
# ==========
# Copyright (C) 2020 - 2024 EmDev LLC
# ==========
# You may not use this file except in accordance with the License Terms of the Copyright
# Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
# rights to the Software and any copies are the property of the Copyright Holder. Unless
# it is explicitly allowed the Copyright Holder, the User is prohibited from using the
# Software for commercial purposes to provide services to third parties.
#
# The Copyright Holder hereby declares that the Software is provided on an "AS IS".
# Under no circumstances does the Copyright Holder guarantee or promise that the
# Software provided by him will be suitable or not suitable for the specific purposes
# of the User, that the Software will meet all commercial and personal subjective
# expectations of the User, that the Software will work properly, without technical
# errors, quickly and uninterruptedly.
#
# Under no circumstances shall the Copyright Holder or its Affiliates is not liable
# to the User for any direct or indirect losses of the User, his expenses or actual
# damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
# or damage to data, property, etc.
# ~~~~~~/licensing~~~~~~
###
# Entaxy CEF logger
log4j2.logger.AUDIT_FILE.name = AUDIT_LOGFILE
log4j2.logger.AUDIT_FILE.level = INFO
log4j2.logger.AUDIT_FILE.appenderRef.AUDIT_LOGFILE.ref = AuditCompositeLogger
log4j2.logger.AUDIT_FILE.additivity = false
log4j2.appender.AUDIT_LOGFILE.type = CEFAggregate
log4j2.appender.AUDIT_LOGFILE.name = AuditCompositeLogger
log4j2.appender.AUDIT_LOGFILE.children = CefFile
log4j2.appender.AUDIT_LOGFILE.filter.threshold.type = ThresholdFilter
log4j2.appender.AUDIT_LOGFILE.filter.threshold.level = INFO
log4j2.appender.AUDIT_LOGFILE_1.type = RollingRandomAccessFile
log4j2.appender.AUDIT_LOGFILE_1.name = CefFile
log4j2.appender.AUDIT_LOGFILE_1.append = true
log4j2.appender.AUDIT_LOGFILE_1.fileName = ${karaf.log}/cef-audit.log
log4j2.appender.AUDIT_LOGFILE_1.filePattern = ${karaf.log}/cef-audit-%d{MM-dd-yyyy}.log
log4j2.appender.AUDIT_LOGFILE_1.layout.type = CEFLayout
log4j2.appender.AUDIT_LOGFILE_1.layout.vendor = EMDEV
log4j2.appender.AUDIT_LOGFILE_1.layout.product = ENTAXY
log4j2.appender.AUDIT_LOGFILE_1.layout.productVersion = 1.1.10-SNAPSHOT
log4j2.appender.AUDIT_LOGFILE_1.policies.type = Policies
log4j2.appender.AUDIT_LOGFILE_1.policies.size.type = SizeBasedTriggeringPolicy
log4j2.appender.AUDIT_LOGFILE_1.policies.size.size = 10MB
log4j2.appender.AUDIT_LOGFILE_1.filter.threshold.type = ThresholdFilter
log4j2.appender.AUDIT_LOGFILE_1.filter.threshold.level = INFO