Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can the issue with false positive be solved? #4

Open
tinyBigGAMES opened this issue Sep 22, 2019 · 35 comments
Open

How can the issue with false positive be solved? #4

tinyBigGAMES opened this issue Sep 22, 2019 · 35 comments

Comments

@tinyBigGAMES
Copy link

Every compile for me, Windows defender chews on the EXE and removes it. How is this fixed? Do you have to update the generated EXE header or submit to the antivirus companies as false positive?

@Mazdaywik
Copy link

@tinyBigGAMES, write to Microsoft’s technical support about false positive. I use fork of other Pascal compiler (BTPC) and one time wrote to technical support of Kaspersky antivirus.

@Mazdaywik
Copy link

Mazdaywik commented Sep 22, 2019

@vtereshkov, на сколько я себе представляю, антивирусы ругаются на BTPC из-за того, что в исполнимом файле только одна секция, и она одновременно исполнимая и доступная для записи. По хорошему, нужно сделать секцию кода read only и executable и секцию данных, доступную для записи и без прав на исполнение.

Но мне категорически лень этим заниматься. Студенты одну лабу терпят. Тем более, что доступен форк для Linux, которым они с удовольствием пользуются. Ну, кроме макинтошников, которым по любому приходится ставить виртуалку. А, кстати, это задача на курсовую. Надо написать студентам, тем, кто ещё не выбрал тему курсовой. Может, кто возьмётся перенести на Макось.

Если у Вас только одна секция с кодом и правами на запись, то подумайте, чтобы это исправить.

@vtereshkov
Copy link
Owner

vtereshkov commented Sep 22, 2019

@tinyBigGAMES I just add the compiler folder to the exclusions of Windows Defender and then recompile everything I need. As for the AVG antivirus, I have reported the false positive result to the vendor. I don't know what and when they have done, but now I observe no problems with it.
Unfortunately, this is a very common problem for amateur compiler developers, and I don't know a better way to solve it.

@vtereshkov
Copy link
Owner

vtereshkov commented Sep 22, 2019

@Mazdaywik Увы, это было бы слишком просто. У меня отдельные секции кода, данных и импорта. Секция кода для чтения и исполнения, секция данных для чтения и записи.
Боюсь, в свете вот этого обсуждения проблема оказывается несколько сложнее. У меня, например, из всех программ-примеров антивирус AVG ругался только на одну. Это явно признак какой-то мудрёной эвристики антивируса.

@vtereshkov
Copy link
Owner

@tinyBigGAMES Anyway I have just reported false positive results to Microsoft.

@tinyBigGAMES
Copy link
Author

tinyBigGAMES commented Sep 22, 2019

@vtereshkov, @Mazdaywik coolness. Thanks.

@Mazdaywik
Copy link

Спасибо за пояснения. Стало быть, переделывать компилятор, чтобы он использовал две секции, или, хотя бы, одну но константную секцию кода, смысла мало.

Ну тогда ладно. Всё равно у нас большинство студентов пользуется Линуксом, а те, кто пользуется Windows’ом, добавят в исключения.

У меня однажды репозиторий с форком Btpc GitHub забанил. Пришлось им написать, что это ложноположительное срабатывание. Разбанили.

@vtereshkov
Copy link
Owner

@Mazdaywik С BeRo у меня вообще сейчас большие проблемы: McAfee остервенело съедает всё немедленно после скачивания, не позволяя добавить в исключения. А с недавних пор в Google Chrome появился какой-то собственный антивирус, так что архив BeRo я уже не могу даже скачать с GitHub.
С моим компилятором дела обстоят несколько лучше: McAfee не жалуется, проблема с AVG вроде бы решилась, VirusTotal показывает срабатывание 6 антивирусов из 69. На всякий случай на GitHub я всегда выкладываю версию исполняемого файла, скомпилированную Free Pascal, а не самим XD Pascal.

@Mazdaywik
Copy link

У меня тоже оказались проблемы с BeRo: не удаётся скачать с https://bmstu-iu9.github.io/compiler-labs/. Спасибо за наблюдение!

А совет собрать начальную версию при помощи Free Pascal и выложить её — хороший. Ближе к началу следующего семестра так и сделаю. Сейчас лень.

@vtereshkov
Copy link
Owner

@tinyBigGAMES Could you please try again with the latest compiler version and the latest Windows Defender definitions (https://www.microsoft.com/en-us/wdsi/defenderupdates)? It seems that Microsoft has fixed something. The most interesting case is to compile not only the compiler and samples, but also some other programs (e.g. modified samples or something completely new). Of course, clear the Windows Defender exclusions list before you try.

@vtereshkov
Copy link
Owner

@Mazdaywik А начальный курс информатики в Бауманке до сих пор основан на Паскале? Поэтому и первую лабу вы строите на Паскале? Или просто внутренности компилятора Паскаля выглядят понятнее, чем компилятора C?

@tinyBigGAMES
Copy link
Author

tinyBigGAMES commented Sep 25, 2019

@vtereshkov YES. Something has changed now. The only thing that Defender grabbed was the inserr.pas example for some reason. Otherwise, everything else worked for me. Before nothing would last for over a second, then it would be gobbled up. So progress, yes. Good stuff.

  1. I am in the market for a pascal compiler that I can use in a game project that I'm working on and hoping that xdpw can work for me. It will be a lightweight IDE/compiler/game engine.

  2. I'm thinking of adding {$L} or something where you can add a library path where all the .inc files can be group and kept in a single location, and this will prevent from having abs path in the {$I} direction. I have not checked yet, can {$I} handle relative paths, such as {$I ....\libs\source.inc}?

{$L libs}
{$L projects\inc}

During compilation, the compiler will search those paths for example, if it can not find it by default. Should not be too hard to add, right?

  1. I am happy that you have support for linking to DLLs as the engine will be in the form of a DLL. I have to adjust to STDCALL conventions.

@tinyBigGAMES
Copy link
Author

Hmm... I modified the source to compile under Delphi 10.3.2, now any EXE produced will be gobbled up by Defender, sigh.

@vtereshkov
Copy link
Owner

@tinyBigGAMES

  1. After you compile XDPW under Delphi 10, do the EXEs compiled by XDPW run properly if the folder is in the exclusion list of Windows Defender? Have you overcome all problems with Unicode? If so, the EXEs produced by XDPW should be exactly (bitwise) identical to those compiled by the default XDPW version. If they differ, the compiler has been incorrectly ported to a Unicode version of Delphi.

  2. All paths in the $I directive are now relative to the folder from which you run XDPW. Of course you can add a "search path" in some new directive.

@vtereshkov
Copy link
Owner

@tinyBigGAMES By the way, the submission results (https://www.microsoft.com/en-us/wdsi/submission/0ea89577-5aec-4b37-a733-6b075b30d4fa) show that even inserr.exe (compiled by the default XDPW version) is "not malware". Are you sure you have updated all the definitions?

@tinyBigGAMES
Copy link
Author

tinyBigGAMES commented Sep 26, 2019

xdpw_delphi10x.zip

Changes I made. Maybe I messed something up.

@vtereshkov
Copy link
Owner

@tinyBigGAMES Unfortunately I don't have Delphi 10 at hand. It is better to compare binaries produced by the two versions of XDPW: the default one and the one compiled by Delphi 10. For example, are the sort.exe's identical or not? If identical, then the Windows Defender behavior must also be identical when running both versions of sort.exe.

@Mazdaywik
Copy link

@Mazdaywik А начальный курс информатики в Бауманке до сих пор основан на Паскале? Поэтому и первую лабу вы строите на Паскале? Или просто внутренности компилятора Паскаля выглядят понятнее, чем компилятора C?

@vtereshkov Зависит от кафедры. Я учился на машиностроительной специальности (СМ5) и у нас был Паскаль (Delphi). Как сейчас у машиностроительных специальностей, я не знаю.

На кафедре, где я преподаю, (ИУ9) Паскаль вообще не изучается. Изучаются Scheme и Си (первый семестр первого курса), Go, C++ и Java (второй семестр первого курса), ещё на третьем курсе изучается Scala. Первая лабораторная по компиляторам посвящена Паскалю, потому что есть сравнительно простые самоприменимые компиляторы Паскаля: P5 и BeRo.

На первой лекции рассказываются основные определения, T-диаграммы и в том числе раскрутка компилятора. Т.е. фактически материала для практических занятий ещё не прочитано. Поэтому автор курса, он же лектор, Скоробогатов придумал дать лабораторную работу на модификацию достаточно простого компилятора. Такими компиляторами оказались компиляторы Паскаля. Тем более, что с Паскалем многие знакомы, а то не знаком — легко разбирается.

Можешь посмотреть задания к первой лабораторной и исходники P5 и Btpc (его, наверное, ты смотрел):

https://bmstu-iu9.github.io/compiler-labs/

За две пары студенты легко справляются с этими заданиями.

@vtereshkov
Copy link
Owner

@Mazdaywik Да, задания посмотрел: многие из них даже не на уровне синтаксиса, а на уровне лексики. И наконец-то прочитал записку к проекту по портированию BeRo на Linux. Внутренности BeRo оказались ещё страшнее, чем мне казалось. Кстати, там я почерпнул ещё одну идею утихомирить Windows Defender - сделать полностью корректную DOS-заглушку. Увы, и это не помогло.

@Mazdaywik
Copy link

А ещё в BeRo знаки : и .. взаимозаменяемые.

Ещё у меня один студент оптимизировал компилятор P5. Ну где-то раза в три оптимизировал. Потом поищу записку и пришлю, если не забуду.

@vtereshkov
Copy link
Owner

@tinyBigGAMES After having submitted several subsequent versions of xdpw.exe to Microsoft for analysis, I for the first time observe that a minor change to the executable file does not cause a new conflict with Windows Defender. This hopefully means that the Defender's exclusions are now based on some more general code patterns than just a bit-by-bit copy of the file, so that future modifications of the compiler will not require resubmitting it. Currently the Defender's definitions are at version 1.303.479.0.

@tinyBigGAMES
Copy link
Author

@vtereshkov Ok, cool. Will check it out. Many thanks!

@vtereshkov
Copy link
Owner

The latest version of xdpw.exe again causes a false alarm, but now with another sort of "trojan". Microsoft claims that their Windows Defender "uses artificial intelligence (AI) to identify new and emerging malware". As such, there is no other way than just submitting as many examples as we can to help their AI learn the code patterns.

@tinyBigGAMES
Copy link
Author

@vtereshkov How can I contact you privately? I want to send you some src that from it we may be able to figure this out.

@vtereshkov
Copy link
Owner

@tinyBigGAMES please contact me at vtereshkov@mail.ru

@tinyBigGAMES
Copy link
Author

@vtereshkov Great, thanks. Check your email.

@tinyBigGAMES
Copy link
Author

tinyBigGAMES commented Oct 6, 2019

Happy to report that now ALL the samples compile and run without issue on

Windows 10:

  • Version 1903
  • Build 18362.388

Windows Defender:

  • Antimalware Client Version: 4.18.1909.6
  • Engine Version: 1.1.16400.2
  • Antivirus Version: 1.303.1042.0
  • Antispyware Version: 1.303.1042.0

I see you added some more stuff to the header. NICE!

@vtereshkov
Copy link
Owner

@tinyBigGAMES Yes, the probability of false alarms has decreased, but it's not the end of the story. I still observe false alarms with AVG and sometimes with Acronis and Avast. Now I'm working on the import section structure.

@tinyBigGAMES
Copy link
Author

@vtereshkov Ahh ok understand.

Ok, so I got the code to compile under Delphi 2009+, and the generated EXEs all work for me also. I use conditional defines in Common.inc, which xdpw does not yet support so that compilation will stop at line 43, unfortunately. If you know of another way to handle lines 42-50 in common.inc so all three compilers can work from a single source, let me know.
xdpw_d2009.zip

@vtereshkov
Copy link
Owner

@tinyBigGAMES probably you can add new definitions to system.inc:

AnsiChar = Char;
PAnsiChar = PChar;
ShortString = string;  

and then remove the $IFDEFs.
Anyway, I still think that the false positive problem needs further investigation.

@tinyBigGAMES
Copy link
Author

tinyBigGAMES commented Oct 6, 2019

Have delph (or freepascal) and xdpw compile this program

{$APPTYPE CONSOLE}
program test;
begin
end.

compare the differences. I still think by having a full and complete win32 EXE header will make some difference (whatever sections Delphi creates, for example) make sure xdpw has it too and see what happens.

Here you can see how an empty exe compare. If Delphi/freepascal version does not trigger the virus scanner, this becomes your baseline to work from.

@vtereshkov
Copy link
Owner

After having modified the code generator, I observe that the false alarm probability gets even lower.

@tinyBigGAMES
Copy link
Author

NICE!

@vtereshkov
Copy link
Owner

It is curious that professional compilers also suffer from the false alarm problem: https://golang.org/doc/faq#virus

@vtereshkov
Copy link
Owner

@tinyBigGAMES I have tried your GamePascal. Great work! But anyway, it is not free from the false alarm problems. Windows Defender behaves differently in different environments:

  • On my local computer, I get no false alarms.
  • On VirusTotal, TiledBitmap.exe is detected as infected. (Moreover, all the GamePascal examples are detected as infected by Acronis, a rather popular antivirus in Russia.)

image

  • On Microsoft Security website, StatementFor.exe is detected as infected. I suppose that by the time you check it, they will have removed this detection, but the removal usually means that they just add the file hash to their exclusion list.

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants