xdpw icon indicating copy to clipboard operation
xdpw copied to clipboard

How can the issue with false positive be solved?

Open tinyBigGAMES opened this issue 6 years ago • 35 comments

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?

tinyBigGAMES avatar Sep 22 '19 15:09 tinyBigGAMES

@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 avatar Sep 22 '19 16:09 Mazdaywik

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

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

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

Mazdaywik avatar Sep 22 '19 16:09 Mazdaywik

@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 avatar Sep 22 '19 18:09 vtereshkov

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

vtereshkov avatar Sep 22 '19 18:09 vtereshkov

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

vtereshkov avatar Sep 22 '19 19:09 vtereshkov

@vtereshkov, @Mazdaywik coolness. Thanks.

tinyBigGAMES avatar Sep 22 '19 20:09 tinyBigGAMES

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

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

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

Mazdaywik avatar Sep 22 '19 20:09 Mazdaywik

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

vtereshkov avatar Sep 22 '19 21:09 vtereshkov

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

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

Mazdaywik avatar Sep 23 '19 08:09 Mazdaywik

@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 avatar Sep 25 '19 21:09 vtereshkov

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

vtereshkov avatar Sep 25 '19 21:09 vtereshkov

@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 avatar Sep 25 '19 23:09 tinyBigGAMES

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

tinyBigGAMES avatar Sep 26 '19 00:09 tinyBigGAMES

@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 avatar Sep 26 '19 00:09 vtereshkov

@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?

vtereshkov avatar Sep 26 '19 00:09 vtereshkov

xdpw_delphi10x.zip

Changes I made. Maybe I messed something up.

tinyBigGAMES avatar Sep 26 '19 00:09 tinyBigGAMES

@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.

vtereshkov avatar Sep 26 '19 00:09 vtereshkov

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

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

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

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

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

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

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

Mazdaywik avatar Sep 28 '19 08:09 Mazdaywik

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

vtereshkov avatar Sep 28 '19 10:09 vtereshkov

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

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

Mazdaywik avatar Sep 28 '19 11:09 Mazdaywik

@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.

vtereshkov avatar Sep 29 '19 20:09 vtereshkov

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

tinyBigGAMES avatar Sep 29 '19 20:09 tinyBigGAMES

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.

vtereshkov avatar Sep 30 '19 23:09 vtereshkov

@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.

tinyBigGAMES avatar Oct 01 '19 03:10 tinyBigGAMES

@tinyBigGAMES please contact me at [email protected]

vtereshkov avatar Oct 01 '19 10:10 vtereshkov

@vtereshkov Great, thanks. Check your email.

tinyBigGAMES avatar Oct 01 '19 20:10 tinyBigGAMES

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!

tinyBigGAMES avatar Oct 06 '19 18:10 tinyBigGAMES

@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.

vtereshkov avatar Oct 06 '19 18:10 vtereshkov

@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

tinyBigGAMES avatar Oct 06 '19 19:10 tinyBigGAMES

@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.

vtereshkov avatar Oct 06 '19 20:10 vtereshkov