RU2786352C1 - System and method for detecting a malicious script based on a set of hash codes - Google Patents

System and method for detecting a malicious script based on a set of hash codes Download PDF

Info

Publication number
RU2786352C1
RU2786352C1 RU2022107038A RU2022107038A RU2786352C1 RU 2786352 C1 RU2786352 C1 RU 2786352C1 RU 2022107038 A RU2022107038 A RU 2022107038A RU 2022107038 A RU2022107038 A RU 2022107038A RU 2786352 C1 RU2786352 C1 RU 2786352C1
Authority
RU
Russia
Prior art keywords
script
file
hash
hash codes
characters
Prior art date
Application number
RU2022107038A
Other languages
Russian (ru)
Inventor
Андрей Игоревич Калегин
Виталий Владимирович Бутузов
Дмитрий Николаевич Главатских
Денис Игоревич Паринов
Алексей Михайлович Романенко
Original Assignee
Акционерное общество "Лаборатория Касперского"
Filing date
Publication date
Application filed by Акционерное общество "Лаборатория Касперского" filed Critical Акционерное общество "Лаборатория Касперского"
Priority to US17/939,071 priority Critical patent/US20230297703A1/en
Priority to EP22202596.7A priority patent/EP4246352A1/en
Application granted granted Critical
Publication of RU2786352C1 publication Critical patent/RU2786352C1/en

Links

Images

Abstract

FIELD: information security.
SUBSTANCE: invention relates to the field of information security, in particular to a system and method for detecting malicious scripts. The effect is achieved by detecting malicious scripts or their parts written in a certain programming language by detecting a file containing a script, recognizing the script language using language recognition rules, generating a set of hash codes of the detected script and comparing the set of hash codes of the script with known sets. hash codes of malicious scripts.
EFFECT: improve the efficiency of detecting malicious scripts.
12 cl, 4 dwg

Description

Область техникиTechnical field

Изобретение относится к области информационной безопасности, а более конкретно к системам и способам выявления вредоносных скриптов.The invention relates to the field of information security, and more specifically to systems and methods for detecting malicious scripts.

Уровень техникиState of the art

Количество пользователей, количество компаний и разнообразие направлений их деятельности продолжает непрерывно расти. Одновременно увеличивается и количество создаваемых веб-сайтов и веб-страниц.The number of users, the number of companies and the diversity of their activities continues to grow continuously. At the same time, the number of created websites and web pages is also increasing.

Создание веб-страницы как наиболее простого инструмента для доступа к информации в сети Интернет предусматривает использование ресурсов компьютерной системы. Использование ресурсов все чаще реализуют при помощи скриптовых языков программирования (PHP, JavaScript, Python, Ruby и прочие).Creating a web page as the simplest tool for accessing information on the Internet involves the use of computer system resources. The use of resources is increasingly implemented using scripting programming languages (PHP, JavaScript, Python, Ruby, and others).

Скрипт – это программный код (сценарий), написанный на различных интерпретируемых языках программирования. Все скрипты выполняются с помощью внешней программы – интерпретатора. В отличие от исполняемых файлов, скрипты в большинстве своем существуют в виде текстовых файлов и могут быть прочитаны человеком. Вредоносные скрипты можно условно разделить на два вида. Первый вид включает скрипты, которые встраиваются в код веб-страниц, интерпретируются браузером и выполняют действия, заложенные злоумышленниками. Второй вид включает скрипты, которые предназначены для запуска на компьютере пользователя. Они исполняются компонентами операционной системы и имеют доступ к API (файловая система, процессы и т. д.).A script is a program code (script) written in various interpreted programming languages. All scripts are executed using an external program - an interpreter. Unlike executable files, scripts mostly exist as text files and can be read by humans. Malicious scripts can be roughly divided into two types. The first type includes scripts that are embedded in the code of web pages, interpreted by the browser, and perform actions laid down by attackers. The second type includes scripts that are designed to run on the user's computer. They are executed by operating system components and have access to APIs (file system, processes, etc.).

Существует много способов выявления вредоносных скриптов. Одним из эффективных способов является детальный анализ текста файлов веб-страницы.There are many ways to detect malicious scripts. One of the effective ways is to analyze the text of the web page files in detail.

В публикации US7707634B2 представлена система, в которой используют сигнатуры для обнаружения вредоносных скриптов. Сигнатуры создают на основании известных образцов вредоносных скриптов. Прежде чем использовать сигнатуру, текст, содержащий скрипт, подвергают нормализации. В ходе нормализации осуществляют поиск начала скрипта, приводят имена функций и переменных скрипта в форму, пригодную для использования сигнатур.Publication US7707634B2 presents a system that uses signatures to detect malicious scripts. Signatures are created based on known samples of malicious scripts. Before using the signature, the text containing the script is normalized. In the course of normalization, the beginning of the script is searched, the names of the functions and variables of the script are brought into a form suitable for using signatures.

Указанное решение частично осуществляет выявление вредоносных скриптов, но не позволяет эффективно решить задачу выявления обрезанных и частично поврежденных вредоносных скриптов, пересылаемых отличным от внедрения в веб-страницу способом.This solution partially detects malicious scripts, but does not effectively solve the problem of detecting truncated and partially damaged malicious scripts sent in a way other than embedding into a web page.

Раскрытие изобретенияDisclosure of invention

Изобретение предназначено для повышения эффективности выявления вредоносных скриптов. Технический результат настоящего изобретения заключается в обнаружении вредоносных скриптов или их частей, написанных на определенном языке программирования путем выявления файла, содержащего скрипт, распознавания языка скрипта при помощи правил распознавания языка, формирования набора хэш-кодов выявленного скрипта и сравнения набора хэш-кодов скрипта с известными наборами хэш-кодов вредоносных скриптов.The invention is intended to improve the efficiency of detecting malicious scripts. The technical result of the present invention is to detect malicious scripts or their parts written in a certain programming language by detecting a file containing a script, recognizing the script language using language recognition rules, generating a set of hash codes of the detected script and comparing the set of hash codes of the script with known ones. hash codes of malicious scripts.

В одном из вариантов реализации предоставляется способ выявления вредоносного скрипта на основании набора хэш-кодов, содержащий этапы, на которых применяют компьютер, чтобы выполнить операции, которые включают в себя этапы, на которых: обнаруживают файл, содержащий скрипт, путем анализа каждого файла из множества файлов, которые проверяют на наличие вредоносного кода; формируют сводку скрипта на основании обнаруженного файла; подсчитывают статические и динамические параметры, содержащиеся в сформированной сводке скрипта; распознают язык программирования скрипта на основании подсчитанных параметров сформированной сводки скрипта с использованием правил распознавания языка; обрабатывают обнаруженный файл на основании данных о распознанном языке программирования и данных об обнаруженном файле; формируют набор хэш-кодов на основании обработанного файла с использованием правил формирования хэш-кодов; выявляют вредоносный скрипт путем сравнения сформированного набора хэш-кодов с известными вредоносными наборами хэш-кодов из базы данных хэш-кодов скриптов.In one embodiment, a method is provided for detecting a malicious script based on a set of hash codes, comprising the steps of using a computer to perform operations that include the steps of: detecting a file containing the script by parsing each file in a set of files that are checked for malicious code; generating a script summary based on the detected file; counting static and dynamic parameters contained in the generated script summary; recognizing the programming language of the script based on the calculated parameters of the generated script summary using language recognition rules; processing the detected file based on the recognized programming language data and the detected file data; generating a set of hash codes based on the processed file using hash code generation rules; a malicious script is detected by comparing the generated set of hash codes with known malicious hash codes from the database of script hash codes.

В другом варианте реализации способа в результате анализа каждого файла из множества файлов, которые проверяют на наличие вредоносного кода, при помощи эвристических алгоритмов, созданных для поиска структурированных типов файлов, в которых наличие скриптов маловероятно, исключают найденные файлы из указанного множества файлов.In another embodiment of the method, as a result of analyzing each file from a set of files that check for malicious code, using heuristic algorithms designed to search for structured file types in which the presence of scripts is unlikely, the found files are excluded from the specified set of files.

Еще в одном варианте реализации способа формируют сводку скрипта путем выделения набора значимых байтов и набора исключенных байтов из обнаруженного файла.In yet another embodiment of the method, a script summary is generated by extracting a set of significant bytes and a set of excluded bytes from the detected file.

Еще в другом варианте реализации способа набор значимых байтов выделяют из обнаруженного файла путем фильтрации обнаруженного файла при помощи алгоритмов фильтрации. In yet another embodiment of the method, a set of significant bytes is extracted from the detected file by filtering the detected file using filtering algorithms.

В другом варианте реализации способа набор исключенных байтов получают путем удаления из обнаруженного файла набора значимых байтов.In another embodiment of the method, the set of excluded bytes is obtained by removing the set of significant bytes from the detected file.

Еще в одном варианте реализации способа под правилом распознавания языка понимают набор результатов работы деревьев решений, при наличии которого считают, что выявлен скрипт, написанный на определенном языке программирования.In another embodiment of the method, a language recognition rule is understood as a set of decision tree results, in the presence of which it is believed that a script written in a certain programming language has been detected.

Еще в другом варианте реализации способа набор значимых байтов выделяют из обнаруженного файла путем фильтрации обнаруженного файла при помощи алгоритмов фильтрации. In yet another embodiment of the method, a set of significant bytes is extracted from the detected file by filtering the detected file using filtering algorithms.

В другом варианте реализации способа обрабатывают обнаруженный файл путем: удаления всех символов, кроме видимых символов, из таблицы ASCII; символов переноса строк, пробелов, символов из таблицы Unicode, строк, содержащих комментарии и отдельные отмеченные строки, характерные для распознанного языка программирования; приведения текста к нижнему регистру; указания начала и окончания строковых констант, характерных для распознанного языка программирования.In another embodiment of the method, the detected file is processed by: removing all characters except visible characters from the ASCII table; line breaks, spaces, characters from the Unicode table, lines containing comments and individual marked lines that are specific to the recognized programming language; converting text to lowercase; specifying the start and end of string constants specific to the recognized programming language.

Еще в одном варианте реализации способа выполняют формирование набора хэш-кодов путем: разделения обработанного файла на конструкции, содержащие совокупность символов длиной от 4 до 10 символов; подсчета количества вхождений всех выявленных конструкций в обработанный файл; определения типа используемого хэш-кода с помощью правил формирования хэш-кодов; формирования набора хэш-кодов из хэш-кодов определенного типа.In another variant of the implementation of the method, a set of hash codes is generated by: dividing the processed file into structures containing a set of characters from 4 to 10 characters long; counting the number of occurrences of all identified constructs in the processed file; determining the type of hash code to be used using hash code generation rules; generating a set of hash codes from hash codes of a certain type.

В другом варианте реализации способа под правилом формирования хэш-кодов понимают набор условий, при выполнении которых используют определенный тип хэш-кода.In another embodiment of the method, a hash code generation rule is understood as a set of conditions under which a certain type of hash code is used.

Еще в другом варианте реализации способа под статическими параметрами сформированной сводки скрипта понимают перечень признаков, посчитанный на основе набора значимых байт, количества вхождений комментариев, строк, содержащих символьные выражения, конструкций, содержащих выражения, известных языков программирования скриптов.In another embodiment of the method, the static parameters of the generated script summary are understood as a list of features calculated on the basis of a set of significant bytes, the number of occurrences of comments, lines containing symbolic expressions, constructs containing expressions, known script programming languages.

В другом варианте реализации способа под динамическими параметрами сформированной сводки скрипта понимают перечень признаков, подсчитанный на основе количества вхождений каждого вида конструкций, содержащих совокупность символов, характерных для каждого языка программирования, в набор значимых байтов.In another embodiment of the method, the dynamic parameters of the generated script summary are understood as a list of features calculated based on the number of occurrences of each type of constructs containing a set of characters specific to each programming language in a set of significant bytes.

В одном из вариантов реализации предоставляется cистема, содержащая по меньшей мере один компьютер, включающий взаимодействующие между собой средства: средство обнаружения, средство подсчета, средство формирования, средство выявления, базу данных правил, базу данных хэш-кодов скриптов и хранящий машиночитаемые инструкции, при выполнении которых система выполняет выявление вредоносного скрипта на основании набора хэш-кодов согласно способу по любому из пп. 1-11.In one implementation, a system is provided that contains at least one computer, including means interacting with each other: a detection tool, a counting tool, a generation tool, a detection tool, a rules database, a script hash code database and storing machine-readable instructions, when executing which the system performs detection of a malicious script based on a set of hash codes according to the method according to any one of paragraphs. 1-11.

Краткое описание чертежейBrief description of the drawings

Фиг. 1 иллюстрирует пример файла, содержащего исходный код скрипта. Fig. 1 illustrates an example of a file containing script source code.

Фиг. 2 иллюстрирует структуру системы выявления вредоносного скрипта на основании набора хэш-кодов. Fig. 2 illustrates the structure of a malicious script detection system based on a set of hash codes.

Фиг. 3 иллюстрирует алгоритм функционирования системы выявления вредоносного скрипта на основании набора хэш-кодов. Fig. 3 illustrates the algorithm of the system for detecting a malicious script based on a set of hash codes.

Фиг. 4 представляет пример компьютерной системы общего назначения, персональный компьютер или сервер. Fig. 4 represents an example of a general purpose computer system, a personal computer or a server.

Хотя изобретение может иметь различные модификации и альтернативные формы, характерные признаки, показанные в качестве примера на чертежах, будут описаны подробно. Следует понимать, однако, что цель описания заключается не в ограничении изобретения конкретным его воплощением. Наоборот, целью описания является охват всех изменений, модификаций, входящих в рамки данного изобретения, как это определено в приложенной формуле.Although the invention may have various modifications and alternative forms, the characteristic features shown by way of example in the drawings will be described in detail. It should be understood, however, that the purpose of the description is not to limit the invention to a particular embodiment thereof. On the contrary, the purpose of the description is to cover all changes, modifications included in the scope of this invention, as defined in the attached claims.

Описание вариантов осуществления изобретенияDescription of embodiments of the invention

Объекты и признаки настоящего изобретения, способы для достижения этих объектов и признаков станут очевидными посредством отсылки к примерным вариантам осуществления. Однако настоящее изобретение не ограничивается примерными вариантами осуществления, раскрытыми ниже, оно может воплощаться в различных видах. Сущность, приведенная в описании, является ничем иным, как конкретными деталями, необходимыми для помощи специалисту в области техники в исчерпывающем понимании изобретения, и настоящее изобретение определяется в объеме приложенной формулы.The objects and features of the present invention, methods for achieving these objects and features will become apparent by reference to exemplary embodiments. However, the present invention is not limited to the exemplary embodiments disclosed below, but may be embodied in various forms. The gist of the description is nothing but the specific details necessary to assist a person skilled in the art in a thorough understanding of the invention, and the present invention is defined within the scope of the appended claims.

Введем ряд определений и понятий, которые будут использованы при описании вариантов осуществления изобретения.We introduce a number of definitions and concepts that will be used in describing embodiments of the invention.

Хэш-функцией называется алгоритм, конвертирующий строку произвольной длины (сообщение) в битовую строку фиксированной длины, называемой хэш-кодом, проверочной суммой или цифровым отпечатком. Во многих технологиях безопасности применяются односторонние функции шифрования, называемые также хэш-функциями. Основное назначение подобных функций – получение из сообщения произвольного размера его хэш-кода – значения фиксированного размера. Хэш-код может быть использован в качестве контрольной суммы исходного сообщения, обеспечивая таким образом (при использовании соответствующего протокола) контроль целостности информации (Брассар Ж. Современная криптология / Ж. Брассар – М.: ПОЛИМЕД, 1999. – 178 с.).A hash function is an algorithm that converts an arbitrary-length string (message) into a fixed-length bit string called a hash code, checksum, or fingerprint. Many security technologies use one-way encryption functions, also called hash functions. The main purpose of such functions is to obtain from the message an arbitrary size of its hash code - a value of a fixed size. The hash code can be used as a checksum of the original message, thus providing (when using the appropriate protocol) information integrity control (J. Brassard. Modern cryptology / J. Brassard - M.: POLYMED, 1999. - 178 p.).

Сценарий, скрипт (англ. script, scenario) - программа (особый вид программного кода), обычно написанная на некотором интерпретируемом (не на компилируемом) языке и содержащая отдельные команды-инструкции. Например, сценарий включается в текст веб-страницы в виде исходного кода и интерпретируется системой, установленной на компьютере удаленного пользователя, запросившего эту страницу. Scenario, script (English script, scenario) - a program (a special kind of program code), usually written in some interpreted (not compiled) language and containing separate instruction commands. For example, a script is included in the text of a web page in the form of source code and is interpreted by the system installed on the computer of the remote user who requested this page.

Java-сценарий (англ. Java script) - сценарий в виде текста на языке программирования Java или языке сценариев javascript, включаемый непосредственно в веб-страницу и загружаемый вместе с ней. Исполняется интерпретатором Jаvа, который встраивается практически в каждый современный браузер (Дорот В. Л., Новиков Ф. А., Толковый словарь современной компьютерной лексики. - 3-е из Д., перераб. и доп. - СПб.: БХВ-Петербург, 2004. - 608 с.: ил.).Java script (eng. Java script) - a script in the form of text in the Java programming language or javascript scripting language, included directly in a web page and loaded with it. It is performed by the Java interpreter, which is built into almost every modern browser (Dorot V. L., Novikov F. A., Explanatory Dictionary of Modern Computer Vocabulary. - 3rd from D., revised and added. - St. Petersburg: BHV-Petersburg , 2004. - 608 p.: ill.).

Злоумышленники используют возможность скриптов обращаться к ресурсам компьютерной системы во вредоносных целях. Существующие в настоящее время способы передачи данных позволяют замаскировать скрипт в файле любого типа и вынудить пользователя тем или иным способом его активировать. Для выявления скрипта известного языка программирования скриптов или его части используют систему выявления вредоносного скрипта на основании набора хэш-кодов. Фиг 1. иллюстрирует пример файла, содержащего исходный код скрипта. Файл, содержит скрипт 1, написанный на языке программирования Bash 110. Скрипты командной строки Bash — это наборы команд для командной строки Linux, которые можно вводить с клавиатуры, собранные в файлы и объединенные общей целью. При этом результаты работы команд могут представлять либо самостоятельную ценность, либо служить входными данными для других команд и файлов. Attackers use the ability of scripts to access computer system resources for malicious purposes. The currently existing data transfer methods allow you to mask the script in a file of any type and force the user to activate it in one way or another. To detect a script of a known script programming language or its part, a system for detecting a malicious script based on a set of hash codes is used. Fig 1. illustrates an example of a file containing the source code of the script. The file contains script 1 written in the Bash 110 programming language. Bash command-line scripts are sets of commands for the Linux command line that can be entered from the keyboard, collected in files and united by a common purpose. At the same time, the results of the work of commands can either be of independent value, or serve as input data for other commands and files.

Фиг 2. иллюстрирует структуру системы выявления вредоносного скрипта на основании набора хэш-кодов, которая включает в себя средство обнаружения 220, средство подсчета 230, средство формирования 240, средство выявления 250, базу данных правил 260, базу данных хэш-кодов скриптов 270. Fig. 2 illustrates the structure of a malicious script detection system based on a set of hash codes, which includes a detection engine 220 , a counting engine 230 , a generation engine 240 , a detection engine 250 , a rule database 260 , a script hash code database 270 .

Представленная на Фиг. 2 система является компьютерной системой, например, компьютером общего назначения, представленным на Фиг. 4 и обладающим аппаратным процессором и памятью. Упомянутая система содержит функциональные и/или аппаратные модули и средства 220-270, которые в свою очередь содержат инструкции для исполнения на аппаратном процессоре. Ниже описаны варианты реализации упомянутых модулей и средств 220-270 системы.Shown in FIG. 2 , the system is a computer system, such as the general purpose computer shown in FIG. 4 and having a hardware processor and memory. Said system contains functional and/or hardware modules and means 220 - 270 , which in turn contain instructions for execution on a hardware processor. The embodiments of said modules and means 220-270 of the system are described below .

Средство обнаружения 220 предназначено для обнаружения файла, содержащего скрипт. Средство обнаружения 220 выполняет обнаружение файла, содержащего скрипт, путем анализа каждого файла из множества файлов, в которых необходимо проверить наличие вредоносного кода 210. Множество файлов 210 может содержать различные файлы, с которыми взаимодействовал пользователь в том или ином виде, в том числе файлы веб-сайтов и веб-страниц, файлы электронных сообщений и т.д. Анализ выполняют при помощи эвристических алгоритмов, которые созданы для поиска структурированных типов файлов, в которых наличие скриптов маловероятно (например, исполняемые файлы в формате PE/ELF/MACHO, архивы, отдельные типы файлов-документов и т.д.). Найденные упомянутые файлы исключают из множества файлов 210, наличие вредоносного кода в которых необходимо проверить. Оставшиеся после исключения файлы считают файлами, которые могут содержать вредоносный код.The detection tool 220 is designed to detect a file containing a script. The detection tool 220 detects the file containing the script by parsing each file out of a plurality of files that need to be checked for malicious code 210 . The plurality of files 210 may contain various files that the user has interacted with in one form or another, including website and web page files, email message files, and so on. The analysis is performed using heuristic algorithms that are designed to search for structured file types in which the presence of scripts is unlikely (for example, executable files in PE/ELF/MACHO format, archives, certain types of document files, etc.). The mentioned files found are excluded from the set of files 210 , the presence of malicious code in which must be checked. The files remaining after the exclusion are considered files that may contain malicious code.

Помимо этого, средство обнаружения 220 предназначено для формирования сводки скрипта на основании обнаруженного файла и передачи данных об обнаруженном файле и данных о сформированной сводке скрипта средству подсчета 230. In addition, the finder 220 is configured to generate a script summary based on the detected file, and transmit data about the detected file and data about the generated script summary to the calculator 230 .

Средство обнаружения 220 формирует сводку скрипта путем выделения набора значимых байтов и набора исключенных байтов из обнаруженного файла. Далее на основе анализа выделенных наборов средство обнаружения 220 заполняет сводку скрипта. The finder 220 generates a script summary by extracting a set of significant bytes and a set of excluded bytes from the discovered file. Next, based on the analysis of the selected sets, the discoverer 220 populates the script summary.

Набор значимых байтов выделяют из обнаруженного файла путем фильтрации обнаруженного файла при помощи алгоритмов фильтрации. A set of significant bytes is extracted from the detected file by filtering the detected file using filtering algorithms.

Алгоритмы фильтрации включают в себя следующие действия:Filtering algorithms include the following actions:

• выделение части обнаруженного файла, которая предположительно содержит скрипт;• selection of the part of the detected file, which presumably contains the script;

• удаление всех символов, кроме видимых символов, из таблицы ASCII;• removal of all characters, except for visible characters, from the ASCII table;

• удаление символов переноса строк, пробела, символов из таблицы Unicode;• removal of line breaks, spaces, characters from the Unicode table;

• приведение текста к нижнему регистру;• reduction of the text to lower case;

• удаление строк, содержащих комментарии популярных языков программирования скриптов;• deletion of lines containing comments of popular script programming languages;

• удаление строк, содержащих выражение «произвольный текст $ произвольный текст и знак препинания»;• deleting lines containing the expression "arbitrary text $ arbitrary text and punctuation mark";

• удаление строк, содержащих непрерывные выражения (без пробелов, переносов, знаков препинания) длинной выше предельного значения символов. Предельное значение длины является настраиваемым параметром.• deletion of lines containing continuous expressions (without spaces, hyphens, punctuation marks) longer than the character limit. The length limit is a configurable setting.

Набор исключенных байтов получают путем удаления из обнаруженного файла набора значимых байтов. The set of excluded bytes is obtained by removing the set of significant bytes from the found file.

Сводка скрипта (англ. script summary) - это структура данных, подсчитанная на основании параметров обнаруженного файла, которая характеризует содержащийся в файле скрипт. Сводка скрипта содержит следующие данные:A script summary is a data structure calculated based on the parameters of a detected file that characterizes the script contained in the file. The script summary contains the following data:

• набор значимых байтов;• set of significant bytes;

• набор исключенных байтов;• set of excluded bytes;

• количество байтов в виде комментариев каждого шаблона из набора исключенных байтов;• the number of bytes in the form of comments of each template from the set of excluded bytes;

• размер массива, который занимает набор значимых байтов;• the size of the array, which occupies a set of significant bytes;

• количество строк, содержащих по крайней мере один значимый байт;• the number of lines containing at least one significant byte;

• количество строк, содержащих выражение «[произвольный текст (набор произвольных одного или более символов)]» или его часть;• the number of lines containing the expression "[arbitrary text (a set of arbitrary one or more characters)]" or part of it;

• количество строк, содержащих выражение «произвольный текст = произвольный текст» или его часть;• the number of lines containing the expression "arbitrary text = arbitrary text" or part of it;

• количество строк, содержащих выражение «$ = произвольный текст» или его часть;• the number of lines containing the expression "$ = arbitrary text" or part of it;

• количество конструкций, содержащих выражение «if произвольный текста - fi произвольный текст» или его часть;• the number of constructions containing the expression "if arbitrary text - fi arbitrary text" or part of it;

• количество конструкций, содержащих выражение «произвольный текст do произвольный текст» или его часть;• the number of constructions containing the expression "arbitrary text do arbitrary text" or part of it;

• количество конструкций, содержащих выражение «произвольный текст case – esac произвольный текст» или его часть;• number of constructions containing the expression "arbitrary text case - esac arbitrary text" or its part;

• количество конструкций, содержащих выражение «var произвольный текст» или его часть;• the number of constructions containing the expression "var arbitrary text" or part of it;

• количество конструкций, содержащих выражение «def произвольный текст» или его часть;• the number of constructions containing the expression "def arbitrary text" or part of it;

• количество конструкций, содержащих выражение «use произвольный текст» или его часть;• the number of constructions containing the expression "use arbitrary text" or part of it;

• количество конструкций, содержащих выражение «произвольное число: произвольное число» или его часть;• the number of constructions containing the expression "arbitrary number: arbitrary number" or part of it;

• количество строк, начинающихся с символа из латинского алфавита; • the number of lines starting with a character from the Latin alphabet;

• количество строк, содержащих только один символ «:» среди всех символов в строке;• the number of lines containing only one character ":" among all characters in the line;

• количество строк, в которых последним символом является символ «\»;• the number of lines in which the last character is the character "\";

• количество строк, в которых последним символом является символ «:»;• the number of lines in which the last character is the character ":";

• количество строк, в которых последним символом является символ «;»;• the number of lines in which the last character is the character ";";

• общее количество строк; • total number of lines;

• количество значимых строк;• number of significant lines;

• количество зачитанных из файла байтов; • the number of bytes read from the file;

• наличие набора шебанг символов «#!/bin/bash».• the presence of a set of shebang characters "#!/bin/bash".

Данные об обнаруженном файле включают сам файл и данные, полученные в результате его анализа.Data about the detected file includes the file itself and the data obtained as a result of its analysis.

Средство подсчета 230 предназначено для подсчета статических и динамических параметров сформированной сводки скрипта. Под статическими параметрами сформированной сводки скрипта понимают следующий перечень признаков:The calculator 230 is designed to calculate the static and dynamic parameters of the generated script summary. The static parameters of the generated script summary are the following list of features:

• энтропия массива, который занимает набор значимых байтов;• entropy of an array that occupies a set of significant bytes;

• количество вхождений каждого из возможных значимых байтов в массив, который занимает набор значимых байтов, поделенное на общее количество значимых байтов и помноженное на 1024;• the number of occurrences of each of the possible significant bytes in the array that occupies the set of significant bytes, divided by the total number of significant bytes and multiplied by 1024;

• количество исключенных комментариев каждого вида, поделенное на общее количество исключенных комментариев и помноженное на 1024;• the number of excluded comments of each type divided by the total number of excluded comments multiplied by 1024;

• наличие набора шебанг символов: 512, если да, 0 иначе;• the presence of a set of shebang characters: 512 if yes, 0 otherwise;

• количество строк, содержащих выражение «[произвольный текст]» или его часть, поделенное на количество значимых строк и помноженное на 1024;• the number of lines containing the expression "[free text]" or part of it, divided by the number of significant lines and multiplied by 1024;

• количество строк, содержащих выражение «произвольный текст = произвольный текст» или его часть, поделенное на количество значимых строк и помноженное на 1024;• the number of lines containing the expression "free text = free text" or part of it, divided by the number of significant lines and multiplied by 1024;

• количество строк, содержащих выражение «$ = произвольный текст» или его часть, поделенное на количество значимых строк и помноженное на 1024;• the number of lines containing the expression "$ = free text" or part of it, divided by the number of significant lines and multiplied by 1024;

• количество конструкций, содержащих выражение «if произвольный текста - fi произвольный текст» или его часть, поделенное на количество значимых строк и помноженное на 1024;• the number of structures containing the expression "if arbitrary text - fi arbitrary text" or its part, divided by the number of significant lines and multiplied by 1024;

• количество конструкций, содержащих выражение «произвольный текст do произвольный текст» или его часть, поделенное на количество значимых строк и помноженное на 1024;• the number of constructs containing the expression "arbitrary text do arbitrary text" or part of it, divided by the number of significant lines and multiplied by 1024;

• количество конструкций, содержащих выражение «произвольный текст case – esac произвольный текст» или его часть, поделенное на количество значимых строк и помноженное на 1024;• the number of structures containing the expression "arbitrary text case - esac arbitrary text" or part of it, divided by the number of significant lines and multiplied by 1024;

• количество конструкций, содержащих выражение «var произвольный текст» или его часть, поделенное на количество значимых строк и помноженное на 1024• the number of constructs containing the expression "var arbitrary text" or part of it, divided by the number of significant lines and multiplied by 1024

• количество конструкций, содержащих выражение «def произвольный текст» или его часть, поделенное на количество значимых строк и помноженное на 1024;• the number of constructs containing the expression "def arbitrary text" or part of it, divided by the number of significant lines and multiplied by 1024;

• количество конструкций, содержащих выражение «use произвольный текст» или его часть, поделенное на количество значимых строк и помноженное на 1024;• the number of constructs containing the expression "use free text" or part of it, divided by the number of significant lines and multiplied by 1024;

• количество конструкций, содержащих выражение «произвольное число: произвольное число» или его часть, поделенное на количество значимых строк и помноженное на 1024;• the number of constructs containing the expression "arbitrary number: arbitrary number" or part of it, divided by the number of significant lines and multiplied by 1024;

• количество строк, начинающихся с символа из латинского алфавита, поделенное на количество значимых строк и помноженное на 1024;• the number of lines starting with a character from the Latin alphabet, divided by the number of significant lines and multiplied by 1024;

• количество строк, содержащих только один символ «:» среди всех символов в строке, поделенное на количество значимых строк и помноженное на 1024;• the number of lines containing only one ":" character among all characters in the line, divided by the number of significant lines and multiplied by 1024;

• количество строк, в которых последним символом является символ «\»;• the number of lines in which the last character is the character "\";

• количество строк, в которых последним символом является символ «\», поделенное на количество значимых строк и помноженное на 1024;• the number of lines where the last character is "\" divided by the number of significant lines and multiplied by 1024;

• количество строк, в которых последним символом является символ «:», поделенное на количество значимых строк и помноженное на 1024;• the number of lines in which the last character is the character ":", divided by the number of significant lines and multiplied by 1024;

• количество строк, в которых последним символом является символ «;», поделенное на количество значимых строк и помноженное на 1024;• the number of lines in which the last character is the character ";", divided by the number of significant lines and multiplied by 1024;

• количество строк, начинающихся с символов латинского алфавита, поделенное на количество значимых строк и помноженное на 1024;• the number of lines beginning with Latin characters divided by the number of significant lines and multiplied by 1024;

Под динамическими параметрами сформированной сводки скрипта понимают количество вхождений каждого вида конструкций, содержащих совокупность символов, характерных для каждого языка программирования, в набор значимых байтов, поделенное на общее количество вхождений всех конструкций и помноженное на 1024. Для языка Bash, например, вычисляют количество вхождений в набор значимых байтов конструкций, содержащих совокупность символов из следующего динамического списка совокупностей символов: my$; $$; "${; $!; $?; $x; $#; $*; $@; $-; $_; $(; $0; $1; $2; $3; ./; ==; !=; <=; >=; =~; --; +r; +w; +x; -a; -b; -c; -e; -f; -g; -h; -i; -j; -k; -l; -m; -n; -o; -p; -q; -r; -s; -t; -u; -v; -w; -x; -y; -z; >>; <<; /bin; /boot; /dev; /etc; /opt; /X11; /sgml; /xml; /home; /lib; /media; /mnt; /opt; /proc; /root; /run; /sbin; /srv; /sys; /tmp; /usr; /bin; /include; /lib; /local; /sbin; /share; /src; /var; /cache; /lib; /lock; /log; /mail; /run; /spool; /mail; /tmp; breaksw; endsw; *); if; fi; then; else; elif; case; esac; [[; ]]; true; false; do; done; while; for; until; break; continue; select; function; if["$; if[$; if("$; if($; if[-d; if[!-d; if[-f; if[!-f; iftest; ;then; case"$; echo$; echo"$; sed-; grep-; ne-; while[$; ]do; whileread; test; apt; zypp; dnf; dig; chown; sync; chsh; chattr; puts; rm-; rm*; rpm; fold; rmdir; less; more; readelf; mv; pg_dump; popd; last; @echooff; @echoon; echooff; echoon; scp; pwd; logout; find; lsof; uuencode; yum; cat; clear; xmllint; stat; ssh-copy-i; Prints; printf; host; chmod; split; xxd; top; cd; od; sed; bind; whoami; ionice; touch; screen; diff; set; dirname; ifconfig; uniq; uname; cpio; eval; brew; awk; which; shopt; pkg; pdfunite; bunzip2; watch; ifconfig; bzip2; join; exec; ...; seq; xhost; bash; unalias; env; comm; node; ping; file; zcat; cowsay; tac; unzip; which; netstat; pstree; readlink; getent; lspci; /bin/sh; apropos; ssh; cd$; bar; ant; ipcs; ldd; vagrant; tail; .sh; tar; hostname; setarch; mate; kill; cut; alias; nohup; trap; chgrp; grep; wget; lshw; rev; locate; shred; sshpass; make; ssh-keygen; nslookup; tee; mktemp; shift; objdump; gunzip; mount; cron; stdbuf; pushd; groups; qstat; xargs; tmux; sudo; mkdir; strace; timex; mvn; tree; eof; eod; exit$; /dev/null; expect; ../; pkill; 2>&1; install; gcc; python; perl; java; .so; "$@"; http; ->; class; module; import; def; std::; var; function; usestrict; export; default; jquery; const; from; namespace; public; private; protected; interface; usewarnind; uselib; foreach; my$; eval; =>; package; sub; usevars; useparent; $self; <-; body{; typedef; @shift; window; microsoft; font; .PHONY; CMAKE_; PROJECT_; CTEST_; CPACK_; gem::; gem"; gemspec; docker; ENTRYPOINT; post; host:; user-agent; Accept:; DNT:; Content-Ty; Content-Le; Disass; PUSHBUTTON; COMBOBOX; LTEXT; CONTROL; EDITTEXT; EDITTEXT; IDS_; DS_; WS_; IDD_; <tr><td. Совокупности символов, характерных для определенного языка, обновляют при помощи методов машинного обучения и математической статистики. В первую очередь рассмотрению подлежат ключевые слова, выражения, названия или части названий функций, классов, переменных из популярных библиотек определенного языка программирования. The dynamic parameters of the generated script summary are understood as the number of occurrences of each type of constructs containing a set of characters characteristic of each programming language in the set of significant bytes, divided by the total number of occurrences of all constructs and multiplied by 1024. For the Bash language, for example, the number of occurrences in a set of meaningful bytes of constructs containing a set of characters from the following dynamic list of character sets: my$; $$; "${; $!; $?; $x; $#; $*; $@; $-; $_; $(; $0; $1; $2; $3; ./; ==; !=; <= ; >=; =~; --; +r; +w; +x; -a; -b; -c; -e; -f; -g; -h; -i; -j; -k; - l; -m; -n; -o; -p; -q; -r; -s; -t; -u; -v; -w; -x; -y; -z; >>; <<; /bin; /boot; /dev; /etc; /opt; /X11; /sgml; /xml; /home; /lib; /media; /mnt; /opt; /proc; /root; /run; /sbin ; /srv; /sys; /tmp; /usr; /bin; /include; /lib; /local; /sbin; /share; /src; /var; /cache; /lib; /lock; /log; / mail; /run; /spool; /mail; /tmp; breaksw; endsw; *); if; fi; then; else; elif; case; esac; [[; ]]; true; false; do; done; while ; for; until; break; continue; select; function; if["$; if[$; if("$; if($; if[-d; if[!-d; if[-f; if[!-f; iftest; ;then; case"$; echo$; echo"$; sed-; grep-; ne-; while[$; ]do; whileread; test; apt; zypp; dnf; dig; chown; sync; chsh; chattr; puts; rm-; rm*; rpm; fold; rmdir; less; more ; readelf; mv; pg_dump; popd; last; @echooff; @echoon; echooff; echoon; scp; pwd; logout; find; lsof; uuencode; yum; cat; clear; xmllint; stat; ssh-copy-i; Prints ; printf; host; chmod; split; xxd; top; cd; od; sed; bind; whoami; ionice; touch; screen; diff; set; dirname; ifconfig; uniq; uname; cpio; eval; brew; awk; which ; shopt; pkg; pdfunite; bunzip2; watch; ifconfig; bzip2; join; exec; ...; seq; xhost; bash; unalias; env; comm; node; ping; file; zcat; cowsay; tac; unzip; which ; netstat; pstree; readlink; getent; lspci; /bin/sh; apropos; ssh; cd$; bar; ant; ipcs; ldd; vagrant; tail; .sh; tar; hostname; setarch; mate; kill; cut; alias; nohup; trap; chgrp; grep; wget; lshw; rev; locate; shred; sshpass; make; ssh-keygen; nslookup; tee; mktemp; shift; objdump; gunzip; m ount; cron; stdbuf; pushd; groups; qstat; xargs; tmux; sudo; mkdir; strace; timex; mvn; tree; eof; eod; exit$; /dev/null; expect; ../; pkill; 2>&1;install;gcc; python perl; java; .so; "$@"; http; ->; class; module; import; def; std::; var; function; usestrict; export; default; jQuery; const; from; namespace; public; private; protected; interface; usewarnind; uselib; foreach; my$; eval; =>; package; sub; usevars; useparent; $self; <-; body{; typedef; @shift; window; microsoft; font; .PHONY; CMAKE_; PROJECT_; CTEST_; CPACK_; gem::; gem"; gemspec; docker; ENTRYPOINT; post; host:; user-agent; Accept:; DNT:; Content-Ty; Content-Le; Disass; PUSHBUTTON; COMBOBOX; LEXT; CONTROL; EDITTEXT; EDITTEXT; IDS_; DS_; WS_; IDD_; <tr><td. Sets of characters specific to a particular language are updated using machine learning methods and mathematical statistics. First of all, keywords, expressions, names or parts of names of functions, classes, variables from popular libraries are subject to consideration certain programming language.

Подсчет вхождений осуществляется путем вычисления значений скользящего хэш-кода (англ. rolling hash function) по набору значимых байтов. Оптимальным по сложности и скорости вычисления является последовательность байтов в 10 байт. Начиная с первого байта от последовательности байтов вычисляют упомянутый хэш-код. Затем смещают на один байт и уже со второго байта снова вычисляют от последовательности байтов упомянутый хэш-код. Далее повторяют упомянутое действие по всему набору значимых байтов. После этого подсчитывают количество вхождений хэш-кодов от упомянутых конструкций с точностью до попадания их в вероятностное множество Блума.The occurrences are counted by calculating the values of the rolling hash code (English rolling hash function) over a set of significant bytes. Optimal in terms of complexity and speed of calculation is a sequence of bytes of 10 bytes. Starting from the first byte from the byte sequence, said hash code is calculated. Then the hash code is shifted by one byte, and already from the second byte, the said hash code is again calculated from the byte sequence. Next, repeat the above action for the entire set of significant bytes. After that, the number of occurrences of hash codes from the mentioned structures is counted up to the accuracy of their falling into the Bloom's probabilistic set.

Помимо этого, средство подсчета 230 предназначено для распознавания языка программирования скрипта на основании подсчитанных параметров сформированной сводки скрипта с использованием правил распознавания языка из базы данных правил 260 и передачи данных об обнаруженном файле, данных о сформированной сводке скрипта и данных о распознанном языке программирования скрипта средству формирования 240. In addition, the calculator 230 is adapted to recognize the script programming language based on the calculated parameters of the generated script summary using the language recognition rules from the rule database 260 and transmit data about the detected file, data about the generated script summary and data about the recognized programming language of the script to the generation engine. 240 .

Распознавание языка программирования скрипта осуществляют при помощи методов машинного обучения. Подсчитанные параметры используют в качестве признаков, которые подают на вход предварительно обученных моделей машинного обучения в виде деревьев принятия решений (англ. decision tree).Recognition of the programming language of the script is carried out using machine learning methods. The calculated parameters are used as features that are fed to the input of pre-trained machine learning models in the form of decision trees.

В упомянутой модели машинного обучения используют пять шаблонов деревьев принятия решений для подтверждения языка программирования. Для каждого языка программирования формируют набор признаков и используют при обучении деревьев принятия решений. В результате обучения формируют пять деревьев принятия решений для одного языка. Результатом работы каждого дерева является подтверждение или отсутствие подтверждения того, написан ли рассматриваемый скрипт на текущем языке программирования. По результатам работы всех пяти деревьев принятия решения для подтверждения текущего языка программирования можно сделать окончательный вывод. Помимо наборов деревьев для подтверждения языка программирования скрипта создают деревья для подтверждения альтернативных языков, например, языка файла конфигурации (ini-файл), языка программирования PostScript (pdf-файл). Упомянутые деревья принятия решений используют для снижения ложных срабатываний.This machine learning model uses five decision tree patterns to validate a programming language. For each programming language, a set of features is formed and used to train decision trees. As a result of training, five decision trees are formed for one language. The result of each tree is confirmation or lack of confirmation of whether the script in question is written in the current programming language. Based on the results of the work of all five decision trees to confirm the current programming language, a final conclusion can be drawn. In addition to sets of trees for confirming the script programming language, trees are created for confirming alternative languages, for example, the language of the configuration file (ini file), the PostScript programming language (pdf file). These decision trees are used to reduce false positives.

Правило распознавания языка – набор результатов работы всех деревьев принятия решения для подтверждения языка программирования для распознавания всех языков, при наличии которых считают, что выявленный скрипт написан на определенном языке программирования.Language recognition rule - a set of results of the work of all decision trees for confirming a programming language for recognizing all languages, in the presence of which it is believed that the identified script was written in a certain programming language.

Примером правила распознавания языка является следующий набор результатов работы деревьев принятия решений: минимум 3 из 5 деревьев принятия решений для подтверждения одного языка программирования дали положительный результат; деревья принятия решения для подтверждения других языков дали не более 2 положительных результатов для каждого языка. При выполнении упомянутого набора условий считают, что выявленный скрипт написан на языке программирования, при распознавании которого дали положительный результат 3 из 5 деревьев принятия решений.An example of a language recognition rule is the following set of decision tree outcomes: at least 3 out of 5 decision trees to validate one programming language gave a positive result; decision trees to validate other languages yielded no more than 2 positive results for each language. When the above set of conditions is met, it is considered that the identified script is written in a programming language, upon recognition of which 3 out of 5 decision trees gave a positive result.

Другим примером правила распознавания языка является следующий набор результатов работы деревьев принятия решений: минимум 3 из 5 деревьев принятия решений для подтверждения одного языка решений дали положительный результат; деревья принятия решения для подтверждения других языков дали не более 2 положительных результатов для одного языка; минимум 4 из 5 деревьев принятия решений для распознавания одного альтернативного языка дали положительный результат. При выполнении упомянутого набора условий считают, что выявленный скрипт написан на альтернативном языке, при распознавании которого дали положительный результат 4 из 5 деревьев принятия решений.Another example of a language recognition rule is the following set of decision tree results: at least 3 out of 5 decision trees to validate one decision language yielded a positive result; decision trees to validate other languages gave no more than 2 positive results for one language; at least 4 out of 5 decision trees for recognizing one alternative language gave a positive result. When the above set of conditions is met, it is considered that the identified script is written in an alternative language, upon recognition of which 4 out of 5 decision trees gave a positive result.

Другим примером правила распознавания языка является следующий набор результатов работы деревьев принятия решений: минимум 3 из 5 деревьев принятия решений для подтверждения одного языка дали положительный результат; минимум 3 из 5 деревьев принятия решений для распознавания другого языка дали положительный результат. При выполнении упомянутого набора условий считают, что необходимо использовать дополнительное дерево принятия решения для уточнения результата деревьев принятия решений, которые дали положительный результат.Another example of a language recognition rule is the following set of decision tree results: at least 3 out of 5 decision trees for confirming one language gave a positive result; at least 3 out of 5 decision trees for recognizing another language gave a positive result. When the above set of conditions is met, it is considered that it is necessary to use an additional decision tree to refine the result of the decision trees that gave a positive result.

Средство формирования 240 предназначено для обработки обнаруженного файла на основании данных о распознанном языке программирования, преобразуя таким образом обнаруженный файл к определенному виду.The generator 240 is adapted to process the detected file based on the recognized programming language, thereby converting the detected file to a specific form.

Средство формирования 240 осуществляет обработку обнаруженного файла путем:Creator 240 processes the detected file by:

• удаления всех символов, кроме видимых символов из таблицы ASCII; символов переноса строк, пробелов, символов из таблицы Unicode; строк, содержащих комментарии и отдельные отмеченные строки, характерные для распознанного языка программирования;• removing all characters except visible characters from the ASCII table; line break characters, spaces, characters from the Unicode table; lines containing comments and individual marked lines specific to the recognized programming language;

• приведения текста к нижнему регистру;• converting text to lower case;

• указания начала и окончания строковых констант, характерных для распознанного языка программирования. • specifying the beginning and end of string constants specific to the recognized programming language.

Помимо этого, средство формирования 240 предназначено для формирования набора хэш-кодов на основании обработанного файла с использованием правил формирования хэш-кодов из базы данных правил 260 и передачи сформированного набора хэш-кодов средству выявления 250.In addition, generator 240 is configured to generate a hash code set based on the processed file using hash code generation rules from rule database 260 and pass the generated hash code set to finder 250 .

Средство формирования 240 выполняет формирование набора хэш-кодов путем выполнения следующего перечня действий: Generator 240 performs the generation of a set of hash codes by performing the following list of actions:

1) разделение обработанного файла на конструкции, содержащих совокупность символов длиной от 4 до 10 символов;1) division of the processed file into structures containing a set of characters from 4 to 10 characters long;

2) подсчета количества вхождений всех выявленных конструкций, содержащих совокупность символов длиной от 4 до 10 символов, в обработанный файл; например если обработанный файл представлен в виде символов "colacola", то в результате разделения на конструкции образуется следующий массив {cola: 2, colacola: 1, olacola: 1, lacola: 1, acola: 1, colac: 1, colaco: 1, colacol: 1};2) counting the number of occurrences of all identified constructs containing a set of characters with a length of 4 to 10 characters in the processed file; for example, if the processed file is represented as the characters "colacola", then as a result of division into constructs, the following array is formed {cola: 2, colacola: 1, olacola: 1, lacola: 1, acola: 1, colac: 1, colaco: 1, colacol: 1};

3) с помощью правил формирования хэш-кодов определения типа используемого хэш-кода;3) using the rules for generating hash codes to determine the type of hash code used;

4) формирования набора хэш-кодов из хэш-кодов определенного типа.4) generating a set of hash codes from hash codes of a certain type.

Подсчет количества вхождений каждого вида конструкций из всех языков программирования, содержащих совокупность символов длиной от 4 до 10 символов, в обработанный файл выполняют путем вычисления скользящего хэш-кода, построенного из частей файла, в виде последовательности байтов размером в 10 байт, где количество символов в совокупности символов имеет длину от 4 до 10 символов. Вычисляют количество вхождений хэш-кодов от упомянутых конструкций с точностью до попадания их в вероятностное множество Блума (размер которого совпадает с размером вероятностного множества Блума, использованного на этапе распознавания языка).The counting of the number of occurrences of each type of constructs from all programming languages containing a set of characters from 4 to 10 characters in length in the processed file is performed by calculating a sliding hash code built from parts of the file in the form of a byte sequence of 10 bytes, where the number of characters in character set has a length of 4 to 10 characters. The number of occurrences of the hash codes from the mentioned constructs is calculated up to their hit in the Bloom's probability set (the size of which coincides with the size of the Bloom's probability set used at the stage of language recognition).

Правило формирования хэш-кодов – это набор условий, при выполнении которых используют тот или иной тип хэш-кода. Подсчитанное количество вхождений является основным условием при создании правил формирования хэш-кодов. Примером правила формирования хэш-кодов является случай, когда количество вхождений ниже предельного значения. При выполнении этого набора условий при формировании набора хэш-кодов используют сокращенный тип хэш-кодов. Другим примером правила формирования хэш-кодов является случай, когда количество вхождений равно либо выше предельного значения. При выполнения этого набора условий при формировании набора хэш-кодов используют полноразмерный тип хэш-кодов. Предельное значение количества вхождений может быть определено статистически, эмпирически или задано экспертом, установлено в результате работы алгоритмов машинного обучения.A hash code generation rule is a set of conditions under which one or another type of hash code is used. The counted number of occurrences is the main condition for creating rules for generating hash codes. An example of a hash code generation rule is when the number of occurrences is below the limit. When this set of conditions is met, a shortened type of hash codes is used when generating a set of hash codes. Another example of a hash code generation rule is when the number of occurrences is equal to or greater than the limit value. When this set of conditions is met, the full-length hash code type is used when generating a set of hash codes. The limit value of the number of occurrences can be determined statistically, empirically or set by an expert, established as a result of the operation of machine learning algorithms.

Сокращенный тип хэш-кодов – это 64-битное значение, полученное из комбинации двух половин 128-битной хэш-функции murmur3 (англ. MurmurHash3 hash function) от обработанного файла.The shortened type of hash codes is a 64-bit value obtained from the combination of two halves of the 128-bit hash function murmur3 (eng. MurmurHash3 hash function) from the processed file.

Полноразмерный тип хэш-кодов – тип хэш-кодов, которые считают от пары «хэш-код от совокупности символов - количество вхождений упомянутого хэш-кода на этапе обработки обнаруженного файла при подсчете скользящих хэш-кодов», с использование алгоритма подсчета хэш-функций murmur 3, xor и косинусного расстояния. При этом если есть несколько пар с разными хэш-кодами, но одинаковым количеством вхождений, то для вычисления полноразмерного хэш-кода может быть использована только одна из этих пар. Full-length type of hash codes - type of hash codes that count from the pair "hash code from a set of characters - the number of occurrences of the mentioned hash code at the stage of processing the detected file when counting sliding hash codes", using the murmur hash calculation algorithm 3, xor and cosine distance. Moreover, if there are several pairs with different hash codes, but the same number of occurrences, then only one of these pairs can be used to calculate the full-length hash code.

Средство выявления 250 предназначено для выявления вредоносного скрипта путем сравнения сформированного набора хэш-кодов с известными вредоносными наборами хэш-кодов из базы данных хэш-кодов скриптов 270. Сравнение преимущественно осуществляют с использованием алгоритмов локально-чувствительно хэширования (Local sensitive hash function) и выявления минимального косинусного расстояния. В случае, если сформированный набор хэш-кодов схож с известными вредоносными наборами хэш-кодов, скрипт признают содержащим вредоносный код.The detection tool 250 is designed to detect a malicious script by comparing the generated hash code set with known malicious hash code sets from the script hash code database 270 . Comparison is mainly carried out using algorithms locally sensitive hashing (Local sensitive hash function) and detection of the minimum cosine distance. If the generated set of hash codes is similar to known malicious hash codes, the script is recognized as containing malicious code.

База данных правил 260 предназначена для хранения правил распознавания языка и правил формирования хэш-кодов. База данных хэш-кодов скриптов 270 предназначена для хранения известных хэш-кодов, наборов хэш-кодов известных скриптов, в том числе и вредоносных. В качестве базы данных правил 260 и базы данных хэш-кодов скриптов 270 могут быть использованы различные виды баз данных, а именно: иерархические (IMS, TDMS, System 2000), сетевые (Cerebrum, Сronospro, DBVist), реляционные (DB2, Informix, Microsoft SQL Server), объектно-ориентированные (Jasmine, Versant, POET), объектно-реляционные (Oracle Database, PostgreSQL, FirstSQL/J), функциональные и т.д. Правила могут быть созданы при помощи алгоритмов машинного обучения и автоматизированной обработки больших массивов данных.The rule database 260 is designed to store language recognition rules and hash code generation rules. The database of hash codes of scripts 270 is designed to store known hash codes, sets of hash codes of known scripts, including malicious ones. Various types of databases can be used as a database of rules 260 and a database of script hash codes 270 , namely: hierarchical (IMS, TDMS, System 2000), network (Cerebrum, Сronospro, DBVist), relational (DB2, Informix, Microsoft SQL Server), object-oriented (Jasmine, Versant, POET), object-relational (Oracle Database, PostgreSQL, FirstSQL/J), functional, etc. Rules can be created using machine learning algorithms and automated processing of large data sets.

Ниже представлены подробности реализации в упрощенном виде.Below are the implementation details in a simplified form.

Для скрипта 1 из файла 110, набор значимых байтов будет выглядеть следующим образом:For script 1 from file 110 , the set of significant bytes would look like this:

prog=$(basename$0ctl)admecho1>&2"$(basename$0)depricated,pleaseuse$proginthefuture"if[$#-lt2];thenecho"usage:$(basename$0)-[deu]user[...]"1>&2exit1fiflag=$1shiftfori;doargs="$flag$i"doneecho1>&2"executing:$prog$args"exec$prog$argsprog=$(basename$0ctl)admecho1>&2"$(basename$0)depricated,pleaseuse$proginthefuture"if[$#-lt2];thenecho"usage:$(basename$0)-[deu]user[...] "1>&2exit1fiflag=$1shiftfori;doargs="$flag$i"doneecho1>&2"executing:$prog$args"exec$prog$args

Для скрипта 1 сводка скрипта будет выглядеть следующим образом:For script 1, the summary of the script would look like this:

{{

commentsCount = {0, 0, 0, 0, 0, 0, 0, 0, 0}; commentsCount = {0, 0, 0, 0, 0, 0, 0, 0, 0};

cleanBytes = " prog=$(basename$0ctl)admecho1>&2"$(basename$0)depricated,pleaseuse$proginthefuture"if[$#-lt2];thenecho"usage:$(basename$0)-[deu]user[...]"1>&2exit1fiflag=$1shiftfori;doargs="$flag$i"doneecho1>&2"executing:$prog$args"exec$prog$args"; cleanBytes = " prog=$(basename$0ctl)admecho1>&2"$(basename$0)depricated,pleaseuse$proginthefuture"if[$#-lt2];thenecho"usage:$(basename$0)-[deu]user[. ..]"1>&2exit1fiflag=$1shiftfori;doargs="$flag$i"doneecho1>&2"executing:$prog$args"exec$prog$args";

cleanBytesCount = 230; cleanBytesCount = 230;

significantLinesCount = 13; significantLinesCount = 13;

linesCount = 13; linesCount = 13;

iniSectionsCount = 0; iniSectionsCount = 0;

assignmentsCount = 3; assignmentsCount = 3;

psAssignmentsCount = 0; psAssignmentsCount = 0;

ifFiCount = 1; ifFiCount = 1;

bashCycleCount = 1; bashCycleCount = 1;

caseEsacCount = 0; caseEsacCount = 0;

varCount = 0; varCount = 0;

defCount = 0; defCount = 0;

useCount = 0; useCount = 0;

timestampCount = 0; timestampCount = 0;

bytesRawRead = 293; bytesRawRead = 293;

linesStartedWithLetterCount = 13; linesStartedWithLetterCount = 13;

singleColonInLine = 2; singleColonInLine = 2;

lastSlashCount = 0; lastSlashCount = 0;

lastColonCount = 0; lastColonCount = 0;

lastSemicolonCount = 0; lastSemicolonCount = 0;

hasShebang = false; hasShebang = false;

}}

Полный набор признаков скрипта 1, передаваемого в модель машинного обучения для распознавания языка программирования Bash:Full feature set of script 1 passed to the machine learning model for recognition of the Bash programming language:

[4919, 0, 35, 4, 66, 0, 13, 0, 13, 13, 0, 0, 4, 8, 13, 0, 13, 22, 17, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 13, 13, 0, 0, 13, 0, 13, 0, 0, 0, 66, 13, 31, 26, 115, 31, 48, 26, 40, 0, 0, 22, 17, 31, 44, 26, 0, 48, 48, 40, 31, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 236, 0, 78, 78, 0, 0, 0, 0, 0, 1024, 157, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 8, 16, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 16, 0, 0, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 0, 8, 8, 8, 16, 24, 8, 0, 24, 8, 0, 0, 0, 0, 0, 0, 8, 0, 8, 0, 0, 0, 0, 8, 0, 8, 0, 0, 8, 0, 0, 0, 16, 0, 8, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 8, 0, 8, 0, 8, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 0, 16, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 8, 0, 0, 0, 16, 0, 0, 8, 0, 8, 0, 8, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 16, 8, 0, 0, 0, 24, 8, 0, 16, 0, 0, 0, 8, 0, 0, 0, 0, 8, 0, 0, 0, 0, 8, 16, 8, 0, 0, 8, 0, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 16, 8, 0, 0, 0, 0, 0, 0, 0, 8, 0, 8, 8, 0, 16, 8, 0, 0, 8, 0, 0, 8, 8, 0, 8, 8, 8, 0, 0, 0, 0, 0, 8, 0, 0, 0, 8, 24, 0, 0, 0, 0, 0, 8, 8, 8, 16, 0, 8, 8, 0, 0, 0, 0, 16, 0, 0, 8, 0, 0, 8, 0, 0, 0, 8, 0, 0, 8, 0, 0, 8, 0, 0, 8, 0, 0, 24, 8, 8, 0, 0, 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0,][4919, 0, 35, 4, 66, 0, 13, 0, 13, 13, 0, 0, 4, 8, 13, 0, 13, 22, 17, 0, 0, 0, 0, 0, 0 , 0, 8, 8, 0, 13, 13, 0, 0, 13, 0, 13, 0, 0, 0, 66, 13, 31, 26, 115, 31, 48, 26, 40, 0, 0 , 22, 17, 31, 44, 26, 0, 48, 48, 40, 31, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 236, 0, 78, 78, 0, 0, 0, 0, 0, 1024, 157, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0 , 0, 0, 0, 0, 8, 16, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0 , 0, 0, 8, 8, 0, 0, 0, 0, 16, 0, 0, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 0, 8, 8 , 8, 16, 24, 8, 0, 24, 8, 0, 0, 0, 0, 0, 0, 8, 0, 8, 0, 0, 0, 0, 8, 0, 8, 0, 0 , 8, 0, 0, 0, 16, 0, 8, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 8, 0, 8, 0, 8, 0 , 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 8, 0, 0, 0, 8 , 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 0, 16, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0 , 0, 8, 0, 8, 0, 0, 0, 16, 0, 0, 8, 0, 8, 0, 8, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0 , 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 16, 8, 0, 0, 0, 24, 8, 0, 16, 0, 0, 0, 8, 0, 0 , 0, 0, 8, 0, 0, 0, 0, 8, 16, 8, 0, 0, 8, 0, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 16, 8, 0, 0, 0, 0, 0, 0, 0, 8, 0, 8, 8, 0, 16, 8, 0, 0, 8, 0, 0, 8, 8, 0, 8, 8, 8, 0, 0, 0, 0, 0, 8, 0, 0, 0, 8, 24, 0, 0, 0, 0, 0, 8, 8, 8, 16, 0, 8, 8, 0, 0, 0, 0, 16, 0, 0, 8, 0, 0, 8, 0, 0, 0, 8, 0, 0, 8, 0, 0, 8, 0, 0, 8, 0, 0, 24, 8, 8, 0, 0, 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0,]

Все пять деревьев принятия решения для подтверждения языка Bash дали положительный результат. Пример реализации одного из деревьев: def dt_code(features_original):All five decision trees for Bash validation were positive. An example of the implementation of one of the trees: def dt_code(features_original):

features = [0] + [feature * 2 for feature in features_original]features = [0] + [feature * 2 for feature in features_original]

if features[76] <= 3: # CommentStyle.POWERSHELL_MULTILINE_COMMENTif features[76] <= 3: # CommentStyle.POWERSHELL_MULTILINE_COMMENT

if features[81] <= 178: # has_shebangif features[81] <= 178: # has_shebang

if features[79] <= 25: # assignment_shareif features[79] <= 25: # assignment_share

if features[31] <= 0: # >if features[31] <= 0: # >

if features[81] <= 50: # has_shebangif features[81] <= 50: # has_shebang

if features[357] <= 39: # -referenceif features[357] <= 39: # -reference

if features[14] <= 6: # -if features[14] <= 6: # -

if features[68] <= 94: # }if features[68] <= 94: # }

if features[400] <= 72: # breakif features[400] <= 72: # break

if features[14] <= 1: # -if features[14] <= 1: # -

if features[382] <= 61: # $pscultureif features[382] <= 61: # $psculture

if features[49] <= 73: # jif features[49] <= 73: # j

if features[424] <= 272: # $($if features[424] <= 272: # $($

if features[61] <= 250: # vif features[61] <= 250: # v

if features[387] <= 36: # [system.if features[387] <= 36: # [system.

if features[256] <= 128: # paramif features[256] <= 128: #param

if features[420] <= 82: # .psif features[420] <= 82: # .ps

if features[269] <= 49: # ]$if features[269] <= 49: # ]$

if features[12] <= 149: # +if features[12] <= 149: # +

if features[297] <= 298: # format-if features[297] <= 298: # format-

if features[324] <= 163: # able-if features[324] <= 163: # able-

if features[65] <= 106: # zif features[65] <= 106: #z

if features[367] <= 137: # ext.encodiif features[367] <= 137: # ext.encodi

if features[5] <= 10: # $if features[5] <= 10: # $

if features[216] <= 59: # -typeif features[216] <= 59: # -type

if features[244] <= 151: # byte[]if features[244] <= 151: # byte[]

if features[58] <= 201: # sif features[58] <= 201: # s

if features[367] <= 110: # ext.encodiif features[367] <= 110: # ext.encodi

if features[233] <= 120: # select-if features[233] <= 120: # select-

if features[212] <= 67: # @(if features[212] <= 67: # @(

if features[362] <= 155: # -ltif features[362] <= 155: # -lt

if features[37] <= 71: # ^if features[37] <= 71: # ^

if features[420] <= 38: # .psif features[420] <= 38: # .ps

if features[315] <= 21: # -notif features[315] <= 21: # -not

if features[16] <= 185: # /if features[16] <= 185: # /

if features[141] <= 74: # elseifif features[141] <= 74: # elseif

if features[245] <= 103: # ynamicparaif features[245] <= 103: # ynamicpara

if features[178] <= 100: # -xorif features[178] <= 100: # -xor

if features[43] <= 205: # dif features[43] <= 205: # d

if features[162] <= 107: # -bnotif features[162] <= 107: # -bnot

if features[319] <= 33: # -pathif features[319] <= 33: # -path

if features[92] <= 926: # last_colon_countif features[92] <= 926: # last_colon_count

if features[221] <= 72: # iexif features[221] <= 72: # iex

if features[95] <= 4: # -bxor$if features[95] <= 4: # -bxor$

if features[1] <= 5176: # entropyif features[1] <= 5176: # entropy

if features[209] <= 42: # >>if features[209] <= 42: # >>

if features[339] <= 60: # -asif features[339] <= 60: # -as

if features[219] <= 31: # @{if features[219] <= 31: # @{

if features[293] <= 158: # inif features[293] <= 158: # in

if features[18] <= 211: # 1if features[18] <= 211: # 1

if features[376] <= 7: # register-if features[376] <= 7: # register-

if features[251] <= 5: # -errorif features[251] <= 5: # -error

return [22482, 0]return [22482, 0]

else: # if features[251] > 5 # -errorelse: # if features[251] > 5 # -error

if features[286] <= 71: # [intptr]if features[286] <= 71: # [intptr]

if features[145] <= 29: # -and$if features[145] <= 29: # -and$

if features[377] <= 30: # -in$if features[377] <= 30: # -in$

if features[320] <= 19: # -matchif features[320] <= 19: # -match

return [2700, 0] ……return [2700, 0] ……

Все остальные деревья дали отрицательный результат. Сработало правило, таким образом, данный обнаруженный файл распознан как скрипт на языке Bash. Далее формируют обработанный файл, а затем набор хэш-кодов:All other trees tested negative. The rule was triggered, so this detected file is recognized as a Bash script. Next, the processed file is formed, and then a set of hash codes:

prog=$(basename$0ctl)admecho1>&2"$(basename$0)depricated,pleaseuse$proginthefuture"if[$echo"usage:$(basename$0)-[deu]user[...]"1>&2exit1fiflag=$1shiftfori;doargs="$flag$i"doneecho1>&2"executing:$prog$args"exec$prog$argsprog=$(basename$0ctl)admecho1>&2"$(basename$0)depricated,pleaseuse$proginthefuture"if[$echo"usage:$(basename$0)-[deu]user[...]"1>&2exit1fiflag= $1shiftfori;doargs="$flag$i"doneecho1>&2"executing:$prog$args"exec$prog$args

Полноразмерный хэш-код построить невозможно, поскольку не сработало правило, и пар (хэш-вхождение) найдено всего две: (830, 4), (69, 3). Соответственно, будет выполнено вычисление сокращенного типа хэш-кодов. И поскольку обработанный файл имеет незначительный размер, хэш-код будет один и равен 0xd43903d3f56d64c1.It is impossible to build a full-length hash code, since the rule did not work, and only two pairs (hash entry) were found: (830, 4), (69, 3). Accordingly, the calculation of the reduced type of hash codes will be performed. And since the processed file has a small size, the hash code will be one and equal to 0xd43903d3f56d64c1.

Фиг. 3 иллюстрирует алгоритм функционирования системы выявления вредоносного скрипта на основании набора хэш-кодов. На этапе 311 средство обнаружения 220 осуществляет обнаружение файла, содержащего скрипт. На этапе 312 средство обнаружения 220 осуществляет формирование сводки скрипта на основании обнаруженного файла и передает данные об обнаруженном файле и данные о сформированной сводке скрипта средству подсчета 230. На этапе 313 средство подсчета 230 осуществляет подсчет статических и динамических параметров сформированной сводки скрипта. На этапе 314 средство подсчета 230 осуществляет распознавание языка программирования скрипта на основании подсчитанных параметров сформированной сводки скрипта с использованием правил распознавания языка из базы данных правил 260 и передает данные об обнаруженном файле, данные о сформированной сводке скрипта и данные о распознанном языке программирования скрипта средству формирования 240. На этапе 315 средство формирования 240 осуществляет обработку обнаруженного файла на основании данных о распознанном языке программирования. На этапе 316 средство формирования 240 осуществляет формирование набора хэш-кодов на основании обработанного файла с использованием правил формирования хэш-кодов из базы данных правил 260, и передает сформированный набор хэш-кодов средству выявления 250. На этапе 317 средство выявления 250 проверяет, схож ли сформированный набор хэш-кодов с известными вредоносными наборами хэш-кодов из базы данных хэш-кодов скриптов 270. При наличии схожести с известными вредоносными наборами хэш-кодов на этапе 319 средство выявления 250 осуществляет выявление вредоносного скрипта. В противном случае на этапе 318 система завершает работу. Fig. 3 illustrates the algorithm of the system for detecting a malicious script based on a set of hash codes. At step 311 , the finder 220 detects the file containing the script. In step 312 , the finder 220 generates a script summary based on the detected file, and passes the detected file data and the generated script summary data to the enumerator 230 . In step 313 , the calculator 230 calculates the static and dynamic parameters of the generated script summary. In step 314 , the calculator 230 performs script programming language recognition based on the calculated parameters of the generated script summary using the language recognition rules from the rule database 260 , and transmits the detected file data, the generated script summary data, and the recognized script programming language data to the generating engine 240 . At step 315 , the generator 240 processes the detected file based on the recognized programming language. At step 316 , generator 240 generates a hash code set based on the processed file using hash code generation rules from rule database 260 , and passes the generated hash code set to detector 250 . At step 317 , the detection engine 250 checks whether the generated hash code set is similar to the known malicious hash code sets from the script hash code database 270 . If there is a similarity to known malicious hash codes, at step 319 the detection engine 250 detects the malicious script. Otherwise, at block 318 , the system exits.

Фиг. 4 представляет пример компьютерной системы общего назначения, персональный компьютер или сервер 20, содержащий центральный процессор 21, системную память 22 и системную шину 23, которая содержит разные системные компоненты, в том числе память, связанную с центральным процессором 21. Системная шина 23 реализована, как любая известная из уровня техники шинная структура, содержащая в свою очередь память шины или контроллер памяти шины, периферийную шину и локальную шину, которая способна взаимодействовать с любой другой шинной архитектурой. Системная память содержит постоянное запоминающее устройство (ПЗУ) 24, память с произвольным доступом (ОЗУ) 25. Основная система ввода/вывода (BIOS) 26, содержит основные процедуры, которые обеспечивают передачу информации между элементами персонального компьютера 20, например, в момент загрузки операционной системы с использованием ПЗУ 24. Fig. 4 shows an example of a general purpose computer system, a personal computer or server 20 ', comprising a central processing unit 21 ', system memory 22 ', and a system bus 23 ', which contains various system components including memory associated with the central processing unit 21 '. The system bus 23 is implemented as any bus structure known in the art, in turn comprising a bus memory or bus memory controller, a peripheral bus, and a local bus capable of interfacing with any other bus architecture. The system memory contains read-only memory (ROM) 24 , random access memory (RAM) 25 . The main input/output system (BIOS) 26 contains the basic procedures that ensure the transfer of information between the elements of a personal computer 20 , for example, at the time of booting the operating system using ROM 24 .

Персональный компьютер 20 в свою очередь содержит жёсткий диск 27 для чтения и записи данных, привод магнитных дисков 28 для чтения и записи на сменные магнитные диски 29 и оптический привод 30 для чтения и записи на сменные оптические диски 31, такие как CD-ROM, DVD-ROM и иные оптические носители информации. Жёсткий диск 27, привод магнитных дисков 28, оптический привод 30 соединены с системной шиной 23 через интерфейс жёсткого диска 32, интерфейс магнитных дисков 33 и интерфейс оптического привода 34 соответственно. Приводы и соответствующие компьютерные носители информации представляют собой энергонезависимые средства хранения компьютерных инструкций, структур данных, программных модулей и прочих данных персонального компьютера 20. The personal computer 20 , in turn, contains a hard disk 27 for reading and writing data, a magnetic disk drive 28 for reading and writing to removable magnetic disks 29 and an optical drive 30 for reading and writing to removable optical disks 31 , such as CD-ROM, DVD -ROM and other optical storage media. The hard disk 27 , the magnetic disk drive 28 , the optical drive 30 are connected to the system bus 23 via the hard disk interface 32 , the magnetic disk interface 33 , and the optical drive interface 34 , respectively. Drives and related computer storage media are non-volatile means of storing computer instructions, data structures, program modules, and other personal computer data 20 .

Настоящее описание раскрывает реализацию системы, которая использует жёсткий диск 27, сменный магнитный диск 29 и сменный оптический диск 31, но следует понимать, что возможно применение иных типов компьютерных носителей информации 56, которые способны хранить данные в доступной для чтения компьютером форме (твердотельные накопители, флеш карты памяти, цифровые диски, память с произвольным доступом (ОЗУ) и т.п.), которые подключены к системной шине 23 через контроллер 55.The present description discloses an implementation of a system that uses a hard disk 27 , a removable magnetic disk 29 and a removable optical disk 31 , but it should be understood that other types of computer storage media 56 that are capable of storing data in a computer-readable form (solid-state drives, flash memory cards, digital disks, random access memory (RAM), etc.), which are connected to the system bus 23 through the controller 55 .

Компьютер 20 имеет файловую систему 36, где хранится записанная операционная система 35, а также дополнительные программные приложения 37, другие программные модули 38 и данные программ 39. Пользователь имеет возможность вводить команды и информацию в персональный компьютер 20 посредством устройств ввода (клавиатуры 40, манипулятора «мышь» 42). Могут использоваться другие устройства ввода (не отображены): микрофон, джойстик, игровая консоль, сканер и т.п. Подобные устройства ввода по своему обычаю подключают к компьютерной системе 20 через последовательный порт 46, который в свою очередь подсоединён к системной шине, но могут быть подключены иным способом, например, при помощи параллельного порта, игрового порта или универсальной последовательной шины (USB). Монитор 47 или иной тип устройства отображения также подсоединён к системной шине 23 через интерфейс, такой как видеоадаптер 48. В дополнение к монитору 47, персональный компьютер может быть оснащён другими периферийными устройствами вывода (не отображены), например, колонками, принтером и т.п.The computer 20 has a file system 36 that stores the recorded operating system 35 as well as additional software applications 37 , other program modules 38 and program data 39 . The user has the ability to enter commands and information into the personal computer 20 through input devices (keyboard 40 , mouse 42 ). Other input devices (not shown) may be used: microphone, joystick, game console, scanner, etc. Such input devices are typically connected to the computer system 20 through a serial port 46 which is in turn connected to the system bus, but may be connected in other ways, such as through a parallel port, game port, or universal serial bus (USB). A monitor 47 or other type of display device is also connected to the system bus 23 via an interface such as a video adapter 48 '. In addition to the monitor 47 , the personal computer may be equipped with other peripheral output devices (not shown), such as speakers, a printer, etc.

Персональный компьютер 20 способен работать в сетевом окружении, при этом используется сетевое соединение с другим или несколькими удалёнными компьютерами 49. Удалённый компьютер (или компьютеры) 49 являются такими же персональными компьютерами или серверами, которые имеют большинство или все упомянутые элементы, отмеченные ранее при описании существа персонального компьютера 20, представленного на Фиг. 4. В вычислительной сети могут присутствовать также и другие устройства, например, маршрутизаторы, сетевые станции, пиринговые устройства или иные сетевые узлы. The personal computer 20 is capable of operating in a networked environment using a network connection to another or more remote computers 49 . The remote computer (or computers) 49 are the same personal computers or servers that have most or all of the elements mentioned earlier in the description of the nature of the personal computer 20 shown in FIG. 4 . Other devices may also be present in the computer network, such as routers, network stations, peer-to-peer devices, or other network nodes.

Сетевые соединения могут образовывать локальную вычислительную сеть (LAN) 50 и глобальную вычислительную сеть (WAN). Такие сети применяются в корпоративных компьютерных сетях, внутренних сетях компаний и, как правило, имеют доступ к сети Интернет. В LAN- или WAN-сетях персональный компьютер 20 подключён к локальной сети 50 через сетевой адаптер или сетевой интерфейс 51. При использовании сетей персональный компьютер 20 может использовать модем 54 или иные средства обеспечения связи с глобальной вычислительной сетью, такой как Интернет. Модем 54, который является внутренним или внешним устройством, подключён к системной шине 23 посредством последовательного порта 46. Следует уточнить, что сетевые соединения являются лишь примерными и не обязаны отображать точную конфигурацию сети, т.е. в действительности существуют иные способы установления соединения техническими средствами связи одного компьютера с другим.The network connections may form a local area network (LAN) 50 and a wide area network (WAN). Such networks are used in corporate computer networks, internal networks of companies and, as a rule, have access to the Internet. In LAN or WAN networks, the personal computer 20 is connected to the local network 50 via a network adapter or network interface 51 . When using networks, personal computer 20 may use a modem 54 or other means to communicate with a wide area network, such as the Internet. Modem 54 , which is an internal or external device, is connected to system bus 23 via serial port 46 . It should be clarified that network connections are only indicative and are not required to represent the exact network configuration, i.e. in fact, there are other ways to establish a connection by technical means of communication from one computer to another.

В заключение следует отметить, что приведённые в описании сведения являются примерами, которые не ограничивают объем настоящего изобретения, определённого формулой.In conclusion, it should be noted that the information given in the description are examples that do not limit the scope of the present invention defined by the formula.

Claims (19)

1. Способ выявления вредоносного скрипта на основании набора хэш-кодов, содержащий этапы, на которых применяют компьютер, чтобы выполнить операции, которые включают в себя этапы, на которых:1. A method for detecting a malicious script based on a set of hash codes, comprising steps in which a computer is used to perform operations, which include steps in which: а) обнаруживают файл, содержащий скрипт, путем анализа каждого файла из множества файлов, которые проверяют на наличие вредоносного кода;a) detecting a file containing a script by analyzing each file from a plurality of files, which are checked for the presence of malicious code; б) формируют сводку скрипта на основании обнаруженного файла;b) generating a script summary based on the detected file; в) подсчитывают статические и динамические параметры, содержащиеся в сформированной сводке скрипта;c) calculate the static and dynamic parameters contained in the generated script summary; г) распознают язык программирования скрипта на основании подсчитанных параметров сформированной сводки скрипта с использованием правил распознавания языка;d) recognizing the programming language of the script based on the calculated parameters of the generated script summary using language recognition rules; д) обрабатывают обнаруженный файл на основании данных о распознанном языке программирования и данных об обнаруженном файле;e) processing the detected file based on the recognized programming language data and the detected file data; е) формируют набор хэш-кодов на основании обработанного файла с использованием правил формирования хэш-кодов;f) generating a set of hash codes based on the processed file using hash code generation rules; ж) выявляют вредоносный скрипт путем сравнения сформированного набора хэш-кодов с известными вредоносными наборами хэш-кодов из базы данных хэш-кодов скриптов.g) detecting a malicious script by comparing the generated set of hash codes with known malicious hash codes from the database of script hash codes. 2. Способ по п. 1, в котором в результате анализа каждого файла из множества файлов, которые проверяют на наличие вредоносного кода, при помощи эвристических алгоритмов, созданных для поиска структурированных типов файлов, в которых наличие скриптов маловероятно, исключают найденные файлы из указанного множества файлов.2. The method according to claim 1, in which, as a result of analyzing each file from a set of files that are checked for malicious code, using heuristic algorithms designed to search for structured file types in which the presence of scripts is unlikely, the found files are excluded from the specified set files. 3. Способ по п. 1, в котором формируют сводку скрипта путем выделения набора значимых байтов и набора исключенных байтов из обнаруженного файла.3. The method according to claim 1, which generates a summary of the script by extracting a set of significant bytes and a set of excluded bytes from the detected file. 4. Способ по п. 3, в котором набор значимых байтов выделяют из обнаруженного файла путем фильтрации обнаруженного файла при помощи алгоритмов фильтрации.4. The method of claim 3, wherein the set of significant bytes is extracted from the detected file by filtering the detected file using filtering algorithms. 5. Способ п. 4, в котором набор исключенных байтов получают путем удаления из обнаруженного файла набора значимых байтов. 5. The method of claim 4, wherein the set of excluded bytes is obtained by removing the set of significant bytes from the detected file. 6. Способ по п. 1, в котором под правилом распознавания языка понимают набор результатов работы деревьев решений, при наличии которого считают, что выявлен скрипт, написанный на определенном языке программирования.6. The method according to claim 1, in which the language recognition rule is understood as a set of decision tree results, in the presence of which it is considered that a script written in a certain programming language has been detected. 7. Способ по п. 1, в котором обрабатывают обнаруженный файл путем: удаления всех символов, кроме видимых символов, из таблицы ASCII; символов переноса строк, пробелов, символов из таблицы Unicode, строк, содержащих комментарии и отдельные отмеченные строки, характерные для распознанного языка программирования; приведения текста к нижнему регистру; указания начала и окончания строковых констант, характерных для распознанного языка программирования. 7. The method according to p. 1, which process the detected file by: removing all characters except visible characters from the ASCII table; line breaks, spaces, characters from the Unicode table, lines containing comments and individual marked lines that are specific to the recognized programming language; converting text to lower case; specifying the start and end of string constants specific to the recognized programming language. 8. Способ по п. 1, в котором выполняют формирование набора хэш-кодов путем: разделения обработанного файла на конструкции, содержащие совокупность символов длиной от 4 до 10 символов; подсчета количества вхождений всех выявленных конструкций в обработанный файл; определения типа используемого хэш-кода с помощью правил формирования хэш-кодов; формирования набора хэш-кодов из хэш-кодов определенного типа.8. The method according to p. 1, which perform the formation of a set of hash codes by: dividing the processed file into structures containing a set of characters from 4 to 10 characters long; counting the number of occurrences of all identified constructs in the processed file; determining the type of hash code to be used using hash code generation rules; generating a set of hash codes from hash codes of a certain type. 9. Способ по. 1, в котором под правилом формирования хэш-кодов понимают набор условий, при выполнении которых используют определенный тип хэш-кода.9. Method according to. 1, in which a hash code generation rule is understood as a set of conditions under which a certain type of hash code is used. 10. Способ по п. 1, в котором под статическими параметрами сформированной сводки скрипта понимают перечень признаков, посчитанный на основе набора значимых байт, количества вхождений комментариев, строк, содержащих символьные выражения, конструкций, содержащих выражения, известных языков программирования скриптов.10. The method according to claim 1, in which the static parameters of the generated script summary are understood as a list of features calculated based on a set of significant bytes, the number of occurrences of comments, lines containing symbolic expressions, constructs containing expressions, known script programming languages. 11. Способ по п. 1, в котором под динамическими параметрами сформированной сводки скрипта понимают перечень признаков, подсчитанный на основе количества вхождений каждого вида конструкций, содержащих совокупность символов, характерных для каждого языка программирования, в набор значимых байтов.11. The method according to claim 1, in which the dynamic parameters of the generated script summary are understood as a list of features calculated based on the number of occurrences of each type of constructs containing a set of characters specific to each programming language in a set of significant bytes. 12. Система, содержащая по меньшей мере один компьютер, включающий взаимодействующие между собой средства: средство обнаружения, средство подсчета, средство формирования, средство выявления, базу данных правил, базу данных хэш-кодов скриптов и хранящий машиночитаемые инструкции, при выполнении которых система выполняет выявление вредоносного скрипта на основании набора хэш-кодов согласно способу по любому из пп. 1-11.12. A system containing at least one computer, including means interacting with each other: a detection tool, a counting tool, a generation tool, a detection tool, a rules database, a script hash code database and storing machine-readable instructions, upon execution of which the system performs detection malicious script based on a set of hash codes according to the method according to any one of paragraphs. 1-11.
RU2022107038A 2022-03-17 2022-03-17 System and method for detecting a malicious script based on a set of hash codes RU2786352C1 (en)

Priority Applications (2)

Application Number Priority Date Filing Date Title
US17/939,071 US20230297703A1 (en) 2022-03-17 2022-09-07 System and method for detecting a harmful script based on a set of hash codes
EP22202596.7A EP4246352A1 (en) 2022-03-17 2022-10-19 System and method for detecting a harmful script based on a set of hash codes

Publications (1)

Publication Number Publication Date
RU2786352C1 true RU2786352C1 (en) 2022-12-20

Family

ID=

Citations (7)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
US20040181677A1 (en) * 2003-03-14 2004-09-16 Daewoo Educational Foundation Method for detecting malicious scripts using static analysis
US7707634B2 (en) * 2004-01-30 2010-04-27 Microsoft Corporation System and method for detecting malware in executable scripts according to its functionality
RU2613535C1 (en) * 2015-11-20 2017-03-16 Илья Самуилович Рабинович Method for detecting malicious software and elements
RU2634178C1 (en) * 2016-10-10 2017-10-24 Акционерное общество "Лаборатория Касперского" Method of detecting harmful composite files
WO2018060461A1 (en) * 2016-09-30 2018-04-05 AVAST Software s.r.o. Detecting malicious scripts
RU2659738C1 (en) * 2017-09-29 2018-07-03 Акционерное общество "Лаборатория Касперского" System and method of detecting malicious script
EP2823406B1 (en) * 2012-03-07 2020-08-26 Google LLC Uniquely identifying script files

Patent Citations (7)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
US20040181677A1 (en) * 2003-03-14 2004-09-16 Daewoo Educational Foundation Method for detecting malicious scripts using static analysis
US7707634B2 (en) * 2004-01-30 2010-04-27 Microsoft Corporation System and method for detecting malware in executable scripts according to its functionality
EP2823406B1 (en) * 2012-03-07 2020-08-26 Google LLC Uniquely identifying script files
RU2613535C1 (en) * 2015-11-20 2017-03-16 Илья Самуилович Рабинович Method for detecting malicious software and elements
WO2018060461A1 (en) * 2016-09-30 2018-04-05 AVAST Software s.r.o. Detecting malicious scripts
RU2634178C1 (en) * 2016-10-10 2017-10-24 Акционерное общество "Лаборатория Касперского" Method of detecting harmful composite files
RU2659738C1 (en) * 2017-09-29 2018-07-03 Акционерное общество "Лаборатория Касперского" System and method of detecting malicious script

Similar Documents

Publication Publication Date Title
US10838844B2 (en) Static feature extraction from structured files
Laskov et al. Static detection of malicious JavaScript-bearing PDF documents
US8037535B2 (en) System and method for detecting malicious executable code
JP6530786B2 (en) System and method for detecting malicious elements of web pages
TWI498752B (en) Extracting information from unstructured data and mapping the information to a structured schema using the naive bayesian probability model
CN109271780B (en) Method, system, and computer readable medium for machine learning malware detection model
JP4711949B2 (en) Method and system for detecting malware in macros and executable scripts
JP5572763B2 (en) Website scanning apparatus and method
US11841950B2 (en) Real-time javascript classifier
US20040181677A1 (en) Method for detecting malicious scripts using static analysis
US20130074198A1 (en) Methods and systems to fingerprint textual information using word runs
US20190222586A1 (en) Method and system of decentralized malware identification
US10528731B1 (en) Detecting malicious program code using similarity of hashed parsed trees
WO2020263271A1 (en) Methods, devices and systems for the detection of obfuscated code in application software files
Shobha et al. Code clone detection—a systematic review
Studiawan et al. Automatic event log abstraction to support forensic investigation
Chai et al. Invoke-deobfuscation: AST-based and semantics-preserving deobfuscation for PowerShell scripts
RU2786352C1 (en) System and method for detecting a malicious script based on a set of hash codes
RU2583712C2 (en) System and method of detecting malicious files of certain type
JP6194180B2 (en) Text mask device and text mask program
EP4246352A1 (en) System and method for detecting a harmful script based on a set of hash codes
US11789982B2 (en) Order independent data categorization, indication, and remediation across realtime datasets of live service environments
US20230297703A1 (en) System and method for detecting a harmful script based on a set of hash codes
WO2020090077A1 (en) Information processing device, information processing method, and information processing program
Tak et al. Lognroll: discovering accurate log templates by iterative filtering