Searching for Random

As I was "casually" surfing the web I stumbled upon some PHP files with random names. It turns out that these files are backdoors created by a hacking tool, which might warrant a post on its own later. The problem is that you can't really search for random data in a similar fashion as you can do with Google Dorks for specific files. So given a bunch of files, how would you find the ones with random names? In this post, I'll outline a statistical approach (#AI, #MachineLearning, #BigData, ...) I managed to use with some success to find multiple active and useable backdoors online. That being said, it's only a first step and far from perfect, any input on possible improvements is appreciated!

Motivating example

To shine some more light on what I mean, here is an example:
Which of these five files have a random name?

  • readertest.php
  • fkzptcdrrj.php
  • timeserver.php
  • datatables.php
  • fileserver.php

For anyone that knows English, this is pretty obvious, it's fkzptcdrrj.php.
While it's easy to tell in this case, how would you program a general solution for finding this file?

Specification

In the specific case of this malware, there are some things we know. The filename, excluding extension, is ten characters long and only lowercase letters. This is based on observations, I still haven't found the exact generating function for the names. 

Method

My first idea was to try some machine learning solution to detect English but I didn't like that solution. Firstly, it would fail for non-English names like "configuraracceso.php", "MotDePasse.php", etc. Secondly, it might also break for names with special characters like "edit_user.php", "wp-login.php", etc.

Since my wife is a librarian and a professional in data retrieval, I started by asking her. Understandably, she was a bit stumped at my request to find random names. However, before soon she recommended looking for names with "unlikely patterns".

Happily, I have created my own database with lots of file names that I use to uncover these unlikely patterns. The idea was to use this to create a Markov Chain with transition probabilities between characters in the names. Then finally, for each name, calculate the probability for the corresponding path in the chain. The names with the lowest probability are the "unlikely patterns".

To generate the Markov Chain I used approximately 16,000 unique file names of variable length converted to lowercase.

Example

If we have the files "abc", "aaa", and "aac" we construct the following chain. We start with "abc" where we have one "a b" transition and one "b c" transition, then "aaa" with two "a a" transition and finally "aac" with one "a a" and one "a c" transition. Now, for "a" there is a 1/5 chance the next character is "b", 3/5 it is "a" and a 1/5 that it is "c".

Results

Starting with the Markov Chain, the transitions seem to make sense. "f  i" is very popular at about 18% (any file name with "file" in the name will add to this), while "f  v" is very unlikely at 0.02%. Below is the Markov Chain for the likely name "fileserver".

Markov chain for the word

The top five most "likely" ten letter names results were:

  1. fileserver.php (8.2e-08)
  2. datatables.php (7.1e-08), 
  3. controller.php (7.0e-08),
  4. icontainer.php (1.9e-08),
  5. convention.php (1.8e-08).

And for the key results, the most "unlikely" names (slightly changed to preserve anonymity for victims):

  1. u5xvnsnvdn.php (1.42e-24)
  2. wp-dk1ugc4.php (4.3e-21)
  3. fkzptcdrrj.php (1.23e-20)
  4. wp-z0czikm.php (1.6e-19)
  5. wp-05qvpwb.php (2.4e-19)

I am very happy with these results! All top five results are from hacked servers. fkzptcdrrj.php was executable allowing for RCE. Actually, 1,2,4, and 5 are all from the same hacked server.

The seventh most unlikely pattern was an active web shell from the same malware authors that anyone could use on the infected server, as shown in the figure below.

Web shell with random name

Discussion

While I think these results were surprisingly good I'm sure there is much room for improvement. Even continuing on the Markov Chain model there are many parameters. Should everything be converted to lowercase? Should only unique names be used? If the target length is 10, should only names of this length be used?

Looking at more than the top 5 results, there are quite a lot of false positives (non-random names) like "logoff_wtd", "notify_vtm", "bookflight". The first two are combinations of words and other data. "bookflight" is interesting as it is a combination of two normal English words, but the "k  f" transition is quite rare (1%). Some names arguably seem random, like "esp8266h2o", unless you know that "ESP8266" is a microchip. So perhaps including some word lists or knowledge databases could help eliminate false positives.

Almost eveyone I've told about this to have mentioned ENTROPY! "Just calculate the entropy", "find the name with highest entropy", etc. But this is really not straight forward. Sometimes a simplified version is used for passwords where entropy can be calculated as E = L * log2(R), where L is the length and R the size of the character set. This doesn't really help us in deciding if "admin" or "fkzpt" has the highest entropy, as the have the same length and possible same character set [a-z]. I believe the core problem is that we need to know the distribution of file names before entropy can be applied. Please let me know if you have a good idea on this track! 

Conclusion

Markov chains are pretty good at finding probable patterns and consequently also non-patterns or randomness. Furthermore, multiple of the random files I found were indeed malicious with some even providing RCE on the infected servers.

 


Write your comment!

Comments

AM !8567b3b233e9 No. 1419 >>1421 2022-09-19 08:55:19
> This doesn't really help us in deciding if "admin" or "fkzpt" has the highest entropy.

Not if you consider letters separately, but you could split the word into n-grams (2- or 3- grams could be enough), and then compare by their entropy instead. "ad" should be a much more common 2-gram than "fk" in most popular languages.
Benjamin ## Admin !d2782292df32 No. 1421 2022-09-24 10:49:34
>>1419
Awesome idea AM! :)

For the total probability of a filename, I'm simply taking the product of each ngram in the filename divided by the total weighted ngrams in the dataset. This seems to work but maybe there is a more correct method to do it?

Looking at the bigrams the results are very similar with pretty much the same top lists for both common and uncommon. I guess this makes sense as bigrams and transition probabilities between individual characters are similar. The most common bigrams are "er" (423/13140) and "on" (284/13140). Indeed you are correct that "ad" (86/13140) is much more common than "fk" (1/13140), nice!

Trigrams also give similar results but perhaps a bit more false positives. For example, "subscriber" is the third most unlikely result. Most common trigrams are "ion", "con", and "tio", which makes sense too.

In practice, it would probably be useful to complement/filter the results w.r.t. to popular dictionaries.


yasu313 No. 1422 2022-10-19 20:26:09
good job bejamin :D
Hisssssssss There No. 4834 2024-02-05 16:04:05
Holle this is 6est
Leonjsj No. 9231 2025-11-08 16:46:54
Как и многие наши украинцы искал как уехать в Польшу и заработать денег.
Перечитал массу интернет страниц, пересмотрел много фильмов на Youtube, но больше всего мне понравился сайт hochuvpolshu.com.
На нем я нашел несколько вариантов для работы, вычитал отзывы и опыт тех мужчин и женщин,
которые делятся своим опытом жизни в Польше. Так же узнал как сделать документы.
И всегда это на одной сайте.
Вот одна из свежих и интересных статей:
http://www.theadultstories.net/memberlist.php?mode=viewprofile&u=43497
http://www.forum.jehovih.ru/viewtopic.php?t=591
http://www.alkwet.com/vb/showthread.php?t=29958&p=87087#post87087
http://www.daenemark-freunde.de/viewtopic.php?t=3485
http://rockportcivicleague.org/forum/viewtopic.php?t=1360761
Leonfep No. 9233 2025-11-08 18:56:47
Как и многие наши сограждане искал как поехать в Польшу и найти работу.
Перечитал массу интернет страниц, пересмотрел много фильмов на Youtube, но больше всего мне понравился сайт hochuvpolshu.com.
На нем я нашел несколько вариантов для работы, вычитал отзывы и опыт тех мужчин и женщин,
которые делятся своим опытом жизни в Польше. Так же узнал как сделать документы.
И всегда это на одной сайте.
Вот одна из свежих и интересных статей:
http://www.alkwet.com/vb/showthread.php?t=29786&p=85113#post85113
http://www.alkwet.com/vb/showthread.php?t=29763&p=85072#post85072
http://www.daenemark-freunde.de/viewtopic.php?t=3499
http://cpmayencos.org/mercadillo/viewtopic.php?f=41&t=1247
http://havanahubfl.com/forum/index.php/topic,112.new.html#new
Irinxtd No. 9235 2025-11-12 00:22:19
Pressa - украинское СМИ с огромной историей. Мы на рынке Украины предоставляем услуги более 12 лет, и за это время нас читает более 500 000 посетителей в месяц.
С нашими СМИ сотрудничают Самые мощные украинские Средства массовой информации и бренды, но важно не это. Мы считаемся частной онлайн газетой и пишем Сочные и новые новости для своих читателей.
Ежедневно появляется более 50 актуальных новостей и Украине и Мире.
Самые горячие новости наданный момент:
http://buteyko.pro/memberlist.php?mode=viewprofile&u=4866
http://www.c-strike.fakaheda.eu/forum/viewthread.php?thread_id=3112
http://bbs.epaqi.com/forum.php?mod=viewthread&tid=117186&extra=
http://epaqi.com/forum.php?mod=viewthread&tid=117227&pid=120489&page=4&extra=#pid120489
http://www.mordheim.labibliotecanegra.net/viewtopic.php?f=9&t=433

Также подписавшись на нашей сайт Вы будете потреблять стабильно проверенную и интересную информацию, по этому нажимайтесь "подписаться" и следите за нашими публикациями.
Irinofd No. 9237 2025-11-12 01:25:51
Pressa - украинское СМИ с большущей историей. Мы на рынке Украины предлагаем услуги свыше 12 лет, и за это время Pressa изучает более 500 000 посетителей в месяц.
С нашей газетой сотрудничают Самые мощные украинские Средства массовой информации и бренды, но важно не это. Мы являемся не заангажированной онлайн газетой и выкладываем горячие и свежие выдержки для своих пользователей.
Каждый день выходит более 50 горячих статей и Украине и Мире.
Самые горячие новости насейчас:
http://www.c-strike.fakaheda.eu/forum/viewthread.php?thread_id=3070
http://www.alkwet.com/vb/showthread.php?t=35010&p=94082#post94082
http://rockportcivicleague.org/forum/viewtopic.php?t=1375152
http://buteyko.pro/memberlist.php?mode=viewprofile&u=4880
http://cpmayencos.org/mercadillo/viewtopic.php?f=24&t=1487

Также подписавшись на нашу газету Вы будете читать Каждый день важную и интересную информацию, по этому нажимайтесь "подписаться" и следите за нашими новостями.
Vilianaoqf No. 9239 2025-11-12 11:52:12
Інформаційне агентство NewsToday – відоме в Україні інформаційне агентство з величезною історією. Аудиторія нашого веб-сайту стійко перевищує 100 000 унікальних користувачів на місяць. відвідувачі статей агенції завжди будуть в курсі всіх топових новостей політичного та економічного життя України та світу.
Агентство займає важливе місце на ринку за кількістю генерації своїх матеріалів – понад 100 на день . Частину ви можете вивчити у відкритому доступі на даному сайті.
Ось гарячі з них.
http://epaqi.com/forum.php?mod=viewthread&tid=117068&extra=
http://www.alkwet.com/vb/showthread.php?t=31827&p=89704#post89704
http://epaqi.com/forum.php?mod=viewthread&tid=117069&pid=120247&page=4&extra=#pid120247
http://cpmayencos.org/mercadillo/viewtopic.php?f=28&t=1418
http://www.alkwet.com/vb/showthread.php?t=31860&p=89738#post89738

Серед наших клієнтів – провідні українські новини, політичні партії, найбільші українські бізнес-структури та консалтингові компанії. Наші огляди виходять двома мовами – українською та російською, що дозволяє нам обслуговувати іноземних клієнтів – ЗМІ, посольства та комерційні компанії.
Підписуйтесь на нас і будьте завжди в курсі важливих новостей.
Vilianazgm No. 9241 2025-11-12 12:45:24
Інформаційне агентство NewsToday – топове в Україні інформаційне агентство з величезною історією. Аудиторія нашого сайту стабільно перевищує 100 000 унікальних читачів на місяць. відвідувачі матеріалів агенції завжди будуть в курсі всіх цікавих подій політичного та економічного життя України та світу.
Агентство займає топове місце на ринку за кількістю створення особистих новостей – понад 100 на день . Частину ви можете вивчити у загальному доступі на цьому сайті.
Ось топові з них.
http://www.c-strike.fakaheda.eu/forum/viewthread.php?thread_id=2933
http://www.alkwet.com/vb/showthread.php?t=32520&p=90747#post90747
http://www.alkwet.com/vb/showthread.php?t=31869&p=89747#post89747
http://epaqi.com/forum.php?mod=viewthread&tid=117067&extra=
http://sedemo5.b-pay.net/?q=blog/social-logins-made-simple&page=343#comment-36631

Серед наших клієнтів – провідні українські новини, політичні партії, найбільші українські бізнес-структури та консалтингові компанії. Наші статті виходять двома мовами – українською та російською, що дозволяє нам обслуговувати іноземних клієнтів – ЗМІ, посольства та комерційні компанії.
Підписуйтесь на нас і будьте завжди в курсі топових новостей.
Robwwm No. 9244 2025-11-14 23:26:35
Сайт езотерики - це місце, де об'єднані духовні звичаї, напрями та віри, як нерозривні частки Єдиного. Тут є все для тих, хто шукає божественність людей і ви будете уражені тим, скільки пізнань приховано за його стовпцями.
Цей езотеричний ресурс - посилення співтворчості багатьох людей, для кого шлях душевного процесу став цінністю життя.
Тут прагне відшукає відповідь, а знаючий готов надати своїм Знанням.
Ми запрошуємо Вас приєднатися до тих, хто тут і зараз робить нову реальність. Публікуйте свої статті, ставте питання фахівцям та наставникам, спілкуйтесь на форумі. Діліться компетентністю і сприяйте іншим людям на їхньому шляху.
http://telstar.gtaserv.ru/viewtopic.php?f=1135&t=5511
http://www.fabetghislain.free.fr/Pages/phpBB2/viewtopic.php?p=108955#108955
http://cpmayencos.org/mercadillo/viewtopic.php?f=25&t=1867
http://www.alkwet.com/vb/showthread.php?t=172181&p=408915#post408915
http://dragonsgate.awardspace.us/viewtopic.php?f=27&t=6293
Robtci No. 9246 2025-11-15 00:39:43
Платформа езотерики - це місце, де об'єднані моральні принципи, напрями та релігії, як єдині частки Єдиного. Тут є все для тих, хто шукає духовність людей і ви будете здивовані тим, скільки знань приховано за його сторінками.
Цей езотеричний проект - робота співтворчості багатьох людей, для кого шлях душевного розвитку став метою життя.
Тут розшукуючий відшукає відповідь, а знаючий бажає надати своїм Знанням.
Ми запрошуємо Вас приєднатися до тих, хто тут і зараз творить нову реальність. Публікуйте свої матеріали, ставте питання фахівцям та учителям, спілкуйтесь на форумі. Діліться компетентністю і сприяйте іншим людям на їхньому шляху.
http://www.alkwet.com/vb/showthread.php?t=172176&p=408903#post408903
http://cpmayencos.org/mercadillo/viewtopic.php?f=29&t=1837
http://bh-rp.g6.cz/viewtopic.php?f=35&t=626
http://telstar.gtaserv.ru/viewtopic.php?f=223&t=5529
http://users.atw.hu/mtm-site/viewtopic.php?p=3317#3317
Viktorisyj No. 9248 2025-11-15 23:16:08
BitMarkNews distinguishes itself for several compelling reasons. Here's why you should contemplate subscribing:
Prompt and Applicable Reporting: We understand the value of your time. Our team of seasoned reporters works incessantly to bring you news as it happens, guaranteeing that you're always in the know.
Broad Coverage: From civic developments and economic shifts to cultural happenings and technological breakthroughs, BitMarkNews offers broad reporting of a spectrum of topics. Our concentration is not just on Canada but on major worldwide events, offering a holistic view of the world.
http://www.dragonfly-trimarans.org/phpBB/viewtopic.php?t=10974
http://www.alkwet.com/vb/showthread.php?t=191076&p=454220#post454220
http://www.c-strike.fakaheda.eu/forum/viewthread.php?thread_id=4323
http://www.alkwet.com/vb/showthread.php?t=193268&p=466782#post466782
http://www.alkwet.com/vb/showthread.php?t=190432&p=443132#post443132
Viktoriphy No. 9250 2025-11-16 01:12:40
BitMarkNews is exceptional for several persuasive reasons. Here's why you should ponder subscribing:
Punctual and Pertinent Reporting: We grasp the worth of your time. Our crew of seasoned journalists works incessantly to bring you news as it happens, guaranteeing that you're always aware.
Extensive Coverage: From governmental advancements and financial movements to artistic happenings and academic breakthroughs, BitMarkNews offers wide-ranging analysis of a spectrum of topics. Our concentration is not just on Canada but on significant worldwide events, supplying a comprehensive perspective of the world.
http://sedemo5.b-pay.net/?q=blog/social-logins-made-simple&page=351#comment-38771
http://pdlspd.listbb.ru/viewtopic.php?f=2&t=4528
http://www.alkwet.com/vb/showthread.php?t=191977&p=460782#post460782
http://www.c-strike.fakaheda.eu/forum/viewthread.php?thread_id=4302
http://www.dragonfly-trimarans.org/phpBB/viewtopic.php?t=10869